Debian Codegraph @

third_party/rust/authenticator/src/ctap2/client_data.rs

raw
1 use super::commands::CommandError;
2 use crate::transport::errors::HIDError;
3 use base64::Engine;
4 use serde::de::{self, Deserializer, Error as SerdeError, MapAccess, Visitor};
5 use serde::{Deserialize, Serialize, Serializer};
6 use serde_json as json;
7 use sha2::{Digest, Sha256};
8 use std::fmt;
9
10 /// https://w3c.github.io/webauthn/#dom-collectedclientdata-tokenbinding
11 // tokenBinding, of type TokenBinding
12 //
13 // This OPTIONAL member contains information about the state of the Token
14 // Binding protocol [TokenBinding] used when communicating with the Relying
15 // Party. Its absence indicates that the client doesn’t support token
16 // binding.
17 //
18 // status, of type TokenBindingStatus
19 //
20 // This member is one of the following:
21 //
22 // supported
23 //
24 // Indicates the client supports token binding, but it was not
25 // negotiated when communicating with the Relying Party.
26 //
27 // present
28 //
29 // Indicates token binding was used when communicating with the
30 // Relying Party. In this case, the id member MUST be present.
31 //
32 // id, of type DOMString
33 //
34 // This member MUST be present if status is present, and MUST be a
35 // base64url encoding of the Token Binding ID that was used when
36 // communicating with the Relying Party.
37 #[derive(Debug, Clone, PartialEq, Eq)]
38 pub enum TokenBinding {
39 Present(String),
40 Supported,
41 }
42
43 impl Serialize for TokenBinding {
44 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
45 where
46 S: Serializer,
47 {
48 match *self {
49 TokenBinding::Supported => {
50 serialize_map!(
51 serializer,
52 &"status" => &"supported",
53 )
54 }
55 TokenBinding::Present(ref v) => {
56 serialize_map!(
57 serializer,
58 &"status" => "present",
59 // Verify here, that `v` is valid base64 encoded?
60 // base64::decode_config(&v, base64::URL_SAFE_NO_PAD);
61 // For now: Let the token do that.
62 &"id" => &v,
63 )
64 }
65 }
66 }
67 }
68
69 impl<'de> Deserialize<'de> for TokenBinding {
70 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71 where
72 D: Deserializer<'de>,
73 {
74 struct TokenBindingVisitor;
75
76 impl<'de> Visitor<'de> for TokenBindingVisitor {
77 type Value = TokenBinding;
78
79 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
80 formatter.write_str("a byte string")
81 }
82
83 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
84 where
85 M: MapAccess<'de>,
86 {
87 let mut id = None;
88 let mut status = None;
89
90 while let Some(key) = map.next_key()? {
91 match key {
92 "status" => {
93 status = Some(map.next_value()?);
94 }
95 "id" => {
96 id = Some(map.next_value()?);
97 }
98 k => {
99 return Err(M::Error::custom(format!("unexpected key: {k:?}")));
100 }
101 }
102 }
103
104 if let Some(stat) = status {
105 match stat {
106 "present" => {
107 if let Some(id) = id {
108 Ok(TokenBinding::Present(id))
109 } else {
110 Err(SerdeError::missing_field("id"))
111 }
112 }
113 "supported" => Ok(TokenBinding::Supported),
114 k => Err(M::Error::custom(format!("unexpected status key: {k:?}"))),
115 }
116 } else {
117 Err(SerdeError::missing_field("status"))
118 }
119 }
120 }
121
122 deserializer.deserialize_map(TokenBindingVisitor)
123 }
124 }
125
126 /// https://w3c.github.io/webauthn/#dom-collectedclientdata-type
127 // type, of type DOMString
128 //
129 // This member contains the string "webauthn.create" when creating new
130 // credentials, and "webauthn.get" when getting an assertion from an
131 // existing credential. The purpose of this member is to prevent certain
132 // types of signature confusion attacks (where an attacker substitutes one
133 // legitimate signature for another).
134 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
135 pub enum WebauthnType {
136 Create,
137 Get,
138 }
139
140 impl Serialize for WebauthnType {
141 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
142 where
143 S: Serializer,
144 {
145 match *self {
146 WebauthnType::Create => serializer.serialize_str("webauthn.create"),
147 WebauthnType::Get => serializer.serialize_str("webauthn.get"),
148 }
149 }
150 }
151
152 impl<'de> Deserialize<'de> for WebauthnType {
153 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
154 where
155 D: Deserializer<'de>,
156 {
157 struct WebauthnTypeVisitor;
158
159 impl<'de> Visitor<'de> for WebauthnTypeVisitor {
160 type Value = WebauthnType;
161
162 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
163 formatter.write_str("a string")
164 }
165
166 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
167 where
168 E: de::Error,
169 {
170 match v {
171 "webauthn.create" => Ok(WebauthnType::Create),
172 "webauthn.get" => Ok(WebauthnType::Get),
173 _ => Err(E::custom("unexpected webauthn_type")),
174 }
175 }
176 }
177
178 deserializer.deserialize_str(WebauthnTypeVisitor)
179 }
180 }
181
182 #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
183 pub struct Challenge(pub String);
184
185 impl Challenge {
186 pub fn new(input: Vec<u8>) -> Self {
187 let value = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(input);
188 Challenge(value)
189 }
190 }
191
192 impl From<Vec<u8>> for Challenge {
193 fn from(v: Vec<u8>) -> Challenge {
194 Challenge::new(v)
195 }
196 }
197
198 impl AsRef<[u8]> for Challenge {
199 fn as_ref(&self) -> &[u8] {
200 self.0.as_bytes()
201 }
202 }
203
204 pub type Origin = String;
205
206 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
207 pub struct CollectedClientData {
208 #[serde(rename = "type")]
209 pub webauthn_type: WebauthnType,
210 pub challenge: Challenge,
211 pub origin: Origin,
212 // It is optional, according to https://www.w3.org/TR/webauthn/#collectedclientdata-hash-of-the-serialized-client-data
213 // But we are serializing it, so we *have to* set crossOrigin (if not given, we have to set it to false)
214 // Thus, on our side, it is not optional. For deserializing, we provide a default (bool's default == False)
215 #[serde(rename = "crossOrigin", default)]
216 pub cross_origin: bool,
217 #[serde(rename = "tokenBinding", skip_serializing_if = "Option::is_none")]
218 pub token_binding: Option<TokenBinding>,
219 }
220
221 impl CollectedClientData {
222 pub fn hash(&self) -> Result<ClientDataHash, HIDError> {
223 // WebIDL's dictionary definition specifies that the order of the struct
224 // is exactly as the WebIDL specification declares it, with an algorithm
225 // for partial dictionaries, so that's how interop works for these
226 // things.
227 // See: https://heycam.github.io/webidl/#dfn-dictionary
228 let json = json::to_vec(&self).map_err(CommandError::Json)?;
229 let digest = Sha256::digest(json);
230 Ok(ClientDataHash(digest.into()))
231 }
232 }
233
234 #[derive(Clone, Debug, Eq, PartialEq)]
235 pub struct ClientDataHash(pub [u8; 32]);
236
237 impl PartialEq<[u8]> for ClientDataHash {
238 fn eq(&self, other: &[u8]) -> bool {
239 self.0.eq(other)
240 }
241 }
242
243 impl AsRef<[u8]> for ClientDataHash {
244 fn as_ref(&self) -> &[u8] {
245 &self.0
246 }
247 }
248
249 impl Serialize for ClientDataHash {
250 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
251 where
252 S: Serializer,
253 {
254 serializer.serialize_bytes(&self.0)
255 }
256 }
257
258 #[cfg(test)]
259 mod test {
260 use super::{Challenge, ClientDataHash, CollectedClientData, TokenBinding, WebauthnType};
261 use serde_json as json;
262
263 #[test]
264 fn test_token_binding_status() {
265 let tok = TokenBinding::Present("AAECAw".to_string());
266
267 let json_value = json::to_string(&tok).unwrap();
268 assert_eq!(json_value, "{\"status\":\"present\",\"id\":\"AAECAw\"}");
269
270 let tok = TokenBinding::Supported;
271
272 let json_value = json::to_string(&tok).unwrap();
273 assert_eq!(json_value, "{\"status\":\"supported\"}");
274 }
275
276 #[test]
277 fn test_webauthn_type() {
278 let t = WebauthnType::Create;
279
280 let json_value = json::to_string(&t).unwrap();
281 assert_eq!(json_value, "\"webauthn.create\"");
282
283 let t = WebauthnType::Get;
284 let json_value = json::to_string(&t).unwrap();
285 assert_eq!(json_value, "\"webauthn.get\"");
286 }
287
288 #[test]
289 fn test_collected_client_data_parsing() {
290 let original_str = "{\"type\":\"webauthn.create\",\"challenge\":\"AAECAw\",\"origin\":\"example.com\",\"crossOrigin\":false,\"tokenBinding\":{\"status\":\"present\",\"id\":\"AAECAw\"}}";
291 let parsed: CollectedClientData = serde_json::from_str(original_str).unwrap();
292 let expected = CollectedClientData {
293 webauthn_type: WebauthnType::Create,
294 challenge: Challenge::new(vec![0x00, 0x01, 0x02, 0x03]),
295 origin: String::from("example.com"),
296 cross_origin: false,
297 token_binding: Some(TokenBinding::Present("AAECAw".to_string())),
298 };
299 assert_eq!(parsed, expected);
300
301 let back_again = serde_json::to_string(&expected).unwrap();
302 assert_eq!(back_again, original_str);
303 }
304
305 #[test]
306 fn test_collected_client_data_defaults() {
307 let cross_origin_str = "{\"type\":\"webauthn.create\",\"challenge\":\"AAECAw\",\"origin\":\"example.com\",\"crossOrigin\":false,\"tokenBinding\":{\"status\":\"present\",\"id\":\"AAECAw\"}}";
308 let no_cross_origin_str = "{\"type\":\"webauthn.create\",\"challenge\":\"AAECAw\",\"origin\":\"example.com\",\"tokenBinding\":{\"status\":\"present\",\"id\":\"AAECAw\"}}";
309 let parsed: CollectedClientData = serde_json::from_str(no_cross_origin_str).unwrap();
310 let expected = CollectedClientData {
311 webauthn_type: WebauthnType::Create,
312 challenge: Challenge::new(vec![0x00, 0x01, 0x02, 0x03]),
313 origin: String::from("example.com"),
314 cross_origin: false,
315 token_binding: Some(TokenBinding::Present("AAECAw".to_string())),
316 };
317 assert_eq!(parsed, expected);
318
319 let back_again = serde_json::to_string(&expected).unwrap();
320 assert_eq!(back_again, cross_origin_str);
321 }
322
323 #[test]
324 fn test_collected_client_data() {
325 let client_data = CollectedClientData {
326 webauthn_type: WebauthnType::Create,
327 challenge: Challenge::new(vec![0x00, 0x01, 0x02, 0x03]),
328 origin: String::from("example.com"),
329 cross_origin: false,
330 token_binding: Some(TokenBinding::Present("AAECAw".to_string())),
331 };
332 assert_eq!(
333 client_data.hash().expect("failed to serialize client data"),
334 // echo -n '{"type":"webauthn.create","challenge":"AAECAw","origin":"example.com","crossOrigin":false,"tokenBinding":{"status":"present","id":"AAECAw"}}' | sha256sum -t
335 ClientDataHash([
336 0x75, 0x35, 0x35, 0x7d, 0x49, 0x6e, 0x33, 0xc8, 0x18, 0x7f, 0xea, 0x8d, 0x11, 0x32,
337 0x64, 0xaa, 0xa4, 0x52, 0x3e, 0x13, 0x40, 0x14, 0x9f, 0xbe, 0x00, 0x3f, 0x10, 0x87,
338 0x54, 0xc3, 0x2d, 0x80
339 ])
340 );
341 }
342 }