summaryrefslogtreecommitdiffstats
path: root/third_party/rust/authenticator/src/ctap2/commands/authenticator_config.rs
blob: f72640d701196f859902a7266503a66c8074a34c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use super::{Command, CommandError, PinUvAuthCommand, RequestCtap2, StatusCode};
use crate::{
    crypto::{PinUvAuthParam, PinUvAuthToken},
    ctap2::server::UserVerificationRequirement,
    errors::AuthenticatorError,
    transport::errors::HIDError,
    AuthenticatorInfo, FidoDevice,
};
use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
use serde_cbor::{de::from_slice, to_vec, Value};

#[derive(Debug, Clone, Deserialize)]
pub struct SetMinPINLength {
    /// Minimum PIN length in code points
    pub new_min_pin_length: Option<u64>,
    /// RP IDs which are allowed to get this information via the minPinLength extension.
    /// This parameter MUST NOT be used unless the minPinLength extension is supported.  
    pub min_pin_length_rpids: Option<Vec<String>>,
    /// The authenticator returns CTAP2_ERR_PIN_POLICY_VIOLATION until changePIN is successful.    
    pub force_change_pin: Option<bool>,
}

impl Serialize for SetMinPINLength {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map_len = 0;
        if self.new_min_pin_length.is_some() {
            map_len += 1;
        }
        if self.min_pin_length_rpids.is_some() {
            map_len += 1;
        }
        if self.force_change_pin.is_some() {
            map_len += 1;
        }

        let mut map = serializer.serialize_map(Some(map_len))?;
        if let Some(new_min_pin_length) = self.new_min_pin_length {
            map.serialize_entry(&0x01, &new_min_pin_length)?;
        }
        if let Some(min_pin_length_rpids) = &self.min_pin_length_rpids {
            map.serialize_entry(&0x02, &min_pin_length_rpids)?;
        }
        if let Some(force_change_pin) = self.force_change_pin {
            map.serialize_entry(&0x03, &force_change_pin)?;
        }
        map.end()
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AuthConfigCommand {
    EnableEnterpriseAttestation,
    ToggleAlwaysUv,
    SetMinPINLength(SetMinPINLength),
}

impl AuthConfigCommand {
    fn has_params(&self) -> bool {
        match self {
            AuthConfigCommand::EnableEnterpriseAttestation => false,
            AuthConfigCommand::ToggleAlwaysUv => false,
            AuthConfigCommand::SetMinPINLength(..) => true,
        }
    }
}

#[derive(Debug, Serialize)]
pub enum AuthConfigResult {
    Success(AuthenticatorInfo),
}

#[derive(Debug)]
pub struct AuthenticatorConfig {
    subcommand: AuthConfigCommand, // subCommand currently being requested
    pin_uv_auth_param: Option<PinUvAuthParam>, // First 16 bytes of HMAC-SHA-256 of contents using pinUvAuthToken.
}

impl AuthenticatorConfig {
    pub(crate) fn new(subcommand: AuthConfigCommand) -> Self {
        Self {
            subcommand,
            pin_uv_auth_param: None,
        }
    }
}

impl Serialize for AuthenticatorConfig {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Need to define how many elements are going to be in the map
        // beforehand
        let mut map_len = 1;
        if self.pin_uv_auth_param.is_some() {
            map_len += 2;
        }
        if self.subcommand.has_params() {
            map_len += 1;
        }

        let mut map = serializer.serialize_map(Some(map_len))?;

        match &self.subcommand {
            AuthConfigCommand::EnableEnterpriseAttestation => {
                map.serialize_entry(&0x01, &0x01)?;
            }
            AuthConfigCommand::ToggleAlwaysUv => {
                map.serialize_entry(&0x01, &0x02)?;
            }
            AuthConfigCommand::SetMinPINLength(params) => {
                map.serialize_entry(&0x01, &0x03)?;
                map.serialize_entry(&0x02, &params)?;
            }
        }

        if let Some(ref pin_uv_auth_param) = self.pin_uv_auth_param {
            map.serialize_entry(&0x03, &pin_uv_auth_param.pin_protocol.id())?;
            map.serialize_entry(&0x04, pin_uv_auth_param)?;
        }

        map.end()
    }
}

impl RequestCtap2 for AuthenticatorConfig {
    type Output = ();

    fn command(&self) -> Command {
        Command::AuthenticatorConfig
    }

    fn wire_format(&self) -> Result<Vec<u8>, HIDError> {
        let output = to_vec(&self).map_err(CommandError::Serializing)?;
        trace!("client subcommmand: {:04X?}", &output);
        Ok(output)
    }

    fn handle_response_ctap2<Dev>(
        &self,
        _dev: &mut Dev,
        input: &[u8],
    ) -> Result<Self::Output, HIDError>
    where
        Dev: FidoDevice,
    {
        if input.is_empty() {
            return Err(CommandError::InputTooSmall.into());
        }

        let status: StatusCode = input[0].into();

        if status.is_ok() {
            Ok(())
        } else {
            let msg = if input.len() > 1 {
                let data: Value = from_slice(&input[1..]).map_err(CommandError::Deserializing)?;
                Some(data)
            } else {
                None
            };
            Err(CommandError::StatusCode(status, msg).into())
        }
    }

    fn send_to_virtual_device<Dev: crate::VirtualFidoDevice>(
        &self,
        _dev: &mut Dev,
    ) -> Result<Self::Output, HIDError> {
        unimplemented!()
    }
}

impl PinUvAuthCommand for AuthenticatorConfig {
    fn set_pin_uv_auth_param(
        &mut self,
        pin_uv_auth_token: Option<PinUvAuthToken>,
    ) -> Result<(), AuthenticatorError> {
        let mut param = None;
        if let Some(token) = pin_uv_auth_token {
            // pinUvAuthParam (0x04): the result of calling
            // authenticate(pinUvAuthToken, 32×0xff || 0x0d || uint8(subCommand) || subCommandParams).
            let mut data = vec![0xff; 32];
            data.push(0x0D);
            match &self.subcommand {
                AuthConfigCommand::EnableEnterpriseAttestation => {
                    data.push(0x01);
                }
                AuthConfigCommand::ToggleAlwaysUv => {
                    data.push(0x02);
                }
                AuthConfigCommand::SetMinPINLength(params) => {
                    data.push(0x03);
                    data.extend(to_vec(params).map_err(CommandError::Serializing)?);
                }
            }
            param = Some(token.derive(&data).map_err(CommandError::Crypto)?);
        }
        self.pin_uv_auth_param = param;
        Ok(())
    }

    fn can_skip_user_verification(
        &mut self,
        authinfo: &AuthenticatorInfo,
        _uv_req: UserVerificationRequirement,
    ) -> bool {
        !authinfo.device_is_protected()
    }

    fn set_uv_option(&mut self, _uv: Option<bool>) {
        /* No-op */
    }

    fn get_pin_uv_auth_param(&self) -> Option<&PinUvAuthParam> {
        self.pin_uv_auth_param.as_ref()
    }

    fn get_rp_id(&self) -> Option<&String> {
        None
    }
}