Debian Codegraph @

third_party/rust/authenticator/src/crypto/mod.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::ctap2::commands::client_pin::PinUvAuthTokenPermission;
6 use crate::ctap2::commands::get_info::AuthenticatorInfo;
7 use crate::errors::AuthenticatorError;
8 use crate::{ctap2::commands::CommandError, transport::errors::HIDError};
9 use serde::{
10 de::{Error as SerdeError, MapAccess, Unexpected, Visitor},
11 Deserialize, Deserializer, Serialize, Serializer,
12 };
13 use serde_bytes::ByteBuf;
14 use std::convert::TryFrom;
15 use std::fmt;
16
17 #[cfg(feature = "crypto_nss")]
18 mod nss;
19 #[cfg(feature = "crypto_nss")]
20 use nss as backend;
21
22 #[cfg(feature = "crypto_openssl")]
23 mod openssl;
24 #[cfg(feature = "crypto_openssl")]
25 use self::openssl as backend;
26
27 #[cfg(feature = "crypto_dummy")]
28 mod dummy;
29 #[cfg(feature = "crypto_dummy")]
30 use dummy as backend;
31
32 use backend::{
33 decrypt_aes_256_cbc_no_pad, ecdhe_p256_raw, encrypt_aes_256_cbc_no_pad, gen_p256, hmac_sha256,
34 random_bytes, sha256,
35 };
36
37 mod der;
38
39 pub use backend::ecdsa_p256_sha256_sign_raw;
40
41 pub struct PinUvAuthProtocol(Box<dyn PinProtocolImpl + Send + Sync>);
42 impl PinUvAuthProtocol {
43 pub fn id(&self) -> u64 {
44 self.0.protocol_id()
45 }
46 pub fn encapsulate(&self, peer_cose_key: &COSEKey) -> Result<SharedSecret, CryptoError> {
47 self.0.encapsulate(peer_cose_key)
48 }
49 }
50
51 /// The output of `PinUvAuthProtocol::encapsulate` is supposed to be used with the same
52 /// PinProtocolImpl. So we stash a copy of the calling PinUvAuthProtocol in the output SharedSecret.
53 /// We need a trick here to tell the compiler that every PinProtocolImpl we define will implement
54 /// Clone.
55 trait ClonablePinProtocolImpl {
56 fn clone_box(&self) -> Box<dyn PinProtocolImpl + Send + Sync>;
57 }
58
59 impl<T> ClonablePinProtocolImpl for T
60 where
61 T: 'static + PinProtocolImpl + Clone + Send + Sync,
62 {
63 fn clone_box(&self) -> Box<dyn PinProtocolImpl + Send + Sync> {
64 Box::new(self.clone())
65 }
66 }
67
68 impl Clone for PinUvAuthProtocol {
69 fn clone(&self) -> Self {
70 PinUvAuthProtocol(self.0.as_ref().clone_box())
71 }
72 }
73
74 /// CTAP 2.1, Section 6.5.4. PIN/UV Auth Protocol Abstract Definition
75 trait PinProtocolImpl: ClonablePinProtocolImpl {
76 fn protocol_id(&self) -> u64;
77 fn initialize(&self);
78 fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, CryptoError>;
79 fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError>;
80 fn authenticate(&self, key: &[u8], message: &[u8]) -> Result<Vec<u8>, CryptoError>;
81 fn kdf(&self, z: &[u8]) -> Result<Vec<u8>, CryptoError>;
82 fn encapsulate(&self, peer_cose_key: &COSEKey) -> Result<SharedSecret, CryptoError> {
83 // [CTAP 2.1]
84 // encapsulate(peerCoseKey) → (coseKey, sharedSecret) | error
85 // 1) Let sharedSecret be the result of calling ecdh(peerCoseKey). Return any
86 // resulting error.
87 // 2) Return (getPublicKey(), sharedSecret)
88 //
89 // ecdh(peerCoseKey) → sharedSecret | error
90 // Parse peerCoseKey as specified for getPublicKey, below, and produce a P-256
91 // point, Y. If unsuccessful, or if the resulting point is not on the curve, return
92 // error. Calculate xY, the shared point. (I.e. the scalar-multiplication of the
93 // peer's point, Y, with the local private key agreement key.) Let Z be the
94 // 32-byte, big-endian encoding of the x-coordinate of the shared point. Return
95 // kdf(Z).
96
97 match peer_cose_key.alg {
98 // There is no COSEAlgorithm for ECDHE with the KDF used here. Section 6.5.6. of CTAP
99 // 2.1 says to use value -25 (= ECDH_ES_HKDF256) even though "this is not the algorithm
100 // actually used".
101 COSEAlgorithm::ECDH_ES_HKDF256 => (),
102 other => return Err(CryptoError::UnsupportedAlgorithm(other)),
103 }
104
105 let peer_cose_ec2_key = match peer_cose_key.key {
106 COSEKeyType::EC2(ref key) => key,
107 _ => return Err(CryptoError::UnsupportedKeyType),
108 };
109
110 let peer_spki = peer_cose_ec2_key.der_spki()?;
111
112 let (shared_point, client_public_sec1) = ecdhe_p256_raw(&peer_spki)?;
113
114 let client_cose_ec2_key =
115 COSEEC2Key::from_sec1_uncompressed(Curve::SECP256R1, &client_public_sec1)?;
116
117 let client_cose_key = COSEKey {
118 alg: COSEAlgorithm::ECDH_ES_HKDF256,
119 key: COSEKeyType::EC2(client_cose_ec2_key),
120 };
121
122 let shared_secret = SharedSecret {
123 pin_protocol: PinUvAuthProtocol(self.clone_box()),
124 key: self.kdf(&shared_point)?,
125 inputs: PublicInputs {
126 peer: peer_cose_key.clone(),
127 client: client_cose_key,
128 },
129 };
130
131 Ok(shared_secret)
132 }
133 }
134
135 impl TryFrom<&AuthenticatorInfo> for PinUvAuthProtocol {
136 type Error = CommandError;
137
138 fn try_from(info: &AuthenticatorInfo) -> Result<Self, Self::Error> {
139 // CTAP 2.1, Section 6.5.5.4
140 // "If there are multiple mutually supported protocols, and the platform
141 // has no preference, it SHOULD select the one listed first in
142 // pinUvAuthProtocols."
143 if let Some(pin_protocols) = &info.pin_protocols {
144 for proto_id in pin_protocols.iter() {
145 match proto_id {
146 1 => return Ok(PinUvAuthProtocol(Box::new(PinUvAuth1 {}))),
147 2 => return Ok(PinUvAuthProtocol(Box::new(PinUvAuth2 {}))),
148 _ => continue,
149 }
150 }
151 } else {
152 match info.max_supported_version() {
153 crate::ctap2::commands::get_info::AuthenticatorVersion::U2F_V2 => {
154 return Err(CommandError::UnsupportedPinProtocol)
155 }
156 crate::ctap2::commands::get_info::AuthenticatorVersion::FIDO_2_0 => {
157 return Ok(PinUvAuthProtocol(Box::new(PinUvAuth1 {})))
158 }
159 crate::ctap2::commands::get_info::AuthenticatorVersion::FIDO_2_1_PRE
160 | crate::ctap2::commands::get_info::AuthenticatorVersion::FIDO_2_1 => {
161 return Ok(PinUvAuthProtocol(Box::new(PinUvAuth2 {})))
162 }
163 }
164 }
165 Err(CommandError::UnsupportedPinProtocol)
166 }
167 }
168
169 impl fmt::Debug for PinUvAuthProtocol {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.debug_struct("PinUvAuthProtocol")
172 .field("id", &self.id())
173 .finish()
174 }
175 }
176
177 /// CTAP 2.1, Section 6.5.6.
178 #[derive(Copy, Clone)]
179 pub struct PinUvAuth1;
180
181 impl PinProtocolImpl for PinUvAuth1 {
182 fn protocol_id(&self) -> u64 {
183 1
184 }
185
186 fn initialize(&self) {}
187
188 fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, CryptoError> {
189 // [CTAP 2.1]
190 // encrypt(key, demPlaintext) → ciphertext
191 // Return the AES-256-CBC encryption of plaintext using an all-zero IV. (No padding is
192 // performed as the size of plaintext is required to be a multiple of the AES block
193 // length.)
194 encrypt_aes_256_cbc_no_pad(key, None, plaintext)
195 }
196
197 fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError> {
198 // [CTAP 2.1]
199 // decrypt(key, demCiphertext) → plaintext | error
200 // If the size of ciphertext is not a multiple of the AES block length, return error.
201 // Otherwise return the AES-256-CBC decryption of ciphertext using an all-zero IV.
202 decrypt_aes_256_cbc_no_pad(key, None, ciphertext)
203 }
204
205 fn authenticate(&self, key: &[u8], message: &[u8]) -> Result<Vec<u8>, CryptoError> {
206 // [CTAP 2.1]
207 // authenticate(key, message) → signature
208 // Return the first 16 bytes of the result of computing HMAC-SHA-256 with the given
209 // key and message.
210 let mut hmac = hmac_sha256(key, message)?;
211 hmac.truncate(16);
212 Ok(hmac)
213 }
214
215 fn kdf(&self, z: &[u8]) -> Result<Vec<u8>, CryptoError> {
216 // kdf(Z) → sharedSecret
217 // Return SHA-256(Z)
218 sha256(z)
219 }
220 }
221
222 /// CTAP 2.1, Section 6.5.7.
223 #[derive(Copy, Clone)]
224 pub struct PinUvAuth2;
225
226 impl PinProtocolImpl for PinUvAuth2 {
227 fn protocol_id(&self) -> u64 {
228 2
229 }
230
231 fn initialize(&self) {}
232
233 fn encrypt(&self, key: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, CryptoError> {
234 // [CTAP 2.1]
235 // encrypt(key, demPlaintext) → ciphertext
236 // 1. Discard the first 32 bytes of key. (This selects the AES-key portion of the
237 // shared secret.)
238 // 2. Let iv be a 16-byte, random bytestring.
239 // 3. Let ct be the AES-256-CBC encryption of demPlaintext using key and iv. (No
240 // padding is performed as the size of demPlaintext is required to be a multiple of
241 // the AES block length.)
242 // 4. Return iv || ct.
243 if key.len() != 64 {
244 return Err(CryptoError::LibraryFailure);
245 }
246 let key = &key[32..64];
247
248 let iv = random_bytes(16)?;
249 let mut ct = encrypt_aes_256_cbc_no_pad(key, Some(&iv), plaintext)?;
250
251 let mut out = iv;
252 out.append(&mut ct);
253 Ok(out)
254 }
255
256 fn decrypt(&self, key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError> {
257 // decrypt(key, demCiphertext) → plaintext | error
258 // 1. Discard the first 32 bytes of key. (This selects the AES-key portion of the
259 // shared secret.)
260 // 2. If demCiphertext is less than 16 bytes in length, return an error
261 // 3. Split demCiphertext after the 16th byte to produce two subspans, iv and ct.
262 // 4. Return the AES-256-CBC decryption of ct using key and iv.
263 if key.len() < 64 || ciphertext.len() < 16 {
264 return Err(CryptoError::LibraryFailure);
265 }
266 let key = &key[32..64];
267 let (iv, ct) = ciphertext.split_at(16);
268 decrypt_aes_256_cbc_no_pad(key, Some(iv), ct)
269 }
270
271 fn authenticate(&self, key: &[u8], message: &[u8]) -> Result<Vec<u8>, CryptoError> {
272 // authenticate(key, message) → signature
273 // 1. If key is longer than 32 bytes, discard the excess. (This selects the HMAC-key
274 // portion of the shared secret. When key is the pinUvAuthToken, it is exactly 32
275 // bytes long and thus this step has no effect.)
276 // 2. Return the result of computing HMAC-SHA-256 on key and message.
277 if key.len() < 32 {
278 return Err(CryptoError::LibraryFailure);
279 }
280 let key = &key[0..32];
281 hmac_sha256(key, message)
282 }
283
284 fn kdf(&self, z: &[u8]) -> Result<Vec<u8>, CryptoError> {
285 // kdf(Z) → sharedSecret
286 // return HKDF-SHA-256(salt, Z, L = 32, info = "CTAP2 HMAC key") ||
287 // HKDF-SHA-256(salt, Z, L = 32, info = "CTAP2 AES key")
288 // where salt = [0u8; 32].
289 //
290 // From Section 2 of RFC 5869, we have
291 // HKDF(salt, Z, 32, info) =
292 // HKDF-Expand(HKDF-Extract(salt, Z), info || 0x01)
293 //
294 // And for HKDF-SHA256 both Extract and Expand are instantiated with HMAC-SHA256.
295
296 let prk = hmac_sha256(&[0u8; 32], z)?;
297 let mut shared_secret = hmac_sha256(&prk, "CTAP2 HMAC key\x01".as_bytes())?;
298 shared_secret.append(&mut hmac_sha256(&prk, "CTAP2 AES key\x01".as_bytes())?);
299 Ok(shared_secret)
300 }
301 }
302
303 #[derive(Clone, Debug)]
304 struct PublicInputs {
305 client: COSEKey,
306 peer: COSEKey,
307 }
308
309 #[derive(Clone, Debug)]
310 pub struct SharedSecret {
311 pub pin_protocol: PinUvAuthProtocol,
312 key: Vec<u8>,
313 inputs: PublicInputs,
314 }
315
316 impl SharedSecret {
317 pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CryptoError> {
318 self.pin_protocol.0.encrypt(&self.key, plaintext)
319 }
320 pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError> {
321 self.pin_protocol.0.decrypt(&self.key, ciphertext)
322 }
323 pub fn decrypt_pin_token(
324 &self,
325 permissions: PinUvAuthTokenPermission,
326 encrypted_pin_token: &[u8],
327 ) -> Result<PinUvAuthToken, CryptoError> {
328 let pin_token = self.decrypt(encrypted_pin_token)?;
329 Ok(PinUvAuthToken {
330 pin_protocol: self.pin_protocol.clone(),
331 pin_token,
332 permissions,
333 })
334 }
335 pub fn authenticate(&self, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
336 self.pin_protocol.0.authenticate(&self.key, message)
337 }
338 pub fn client_input(&self) -> &COSEKey {
339 &self.inputs.client
340 }
341 pub fn peer_input(&self) -> &COSEKey {
342 &self.inputs.peer
343 }
344
345 #[cfg(test)]
346 pub fn new_test(
347 pin_protocol: PinUvAuthProtocol,
348 key: Vec<u8>,
349 client_input: COSEKey,
350 peer_input: COSEKey,
351 ) -> Self {
352 Self {
353 pin_protocol,
354 key,
355 inputs: PublicInputs {
356 client: client_input,
357 peer: peer_input,
358 },
359 }
360 }
361 }
362
363 #[derive(Clone, Debug)]
364 pub struct PinUvAuthToken {
365 pub pin_protocol: PinUvAuthProtocol,
366 pin_token: Vec<u8>,
367 pub permissions: PinUvAuthTokenPermission,
368 }
369
370 impl PinUvAuthToken {
371 pub fn derive(self, message: &[u8]) -> Result<PinUvAuthParam, CryptoError> {
372 let pin_auth = self.pin_protocol.0.authenticate(&self.pin_token, message)?;
373 Ok(PinUvAuthParam {
374 pin_auth,
375 pin_protocol: self.pin_protocol,
376 permissions: self.permissions,
377 })
378 }
379 }
380
381 #[derive(Clone, Debug)]
382 pub struct PinUvAuthParam {
383 pin_auth: Vec<u8>,
384 pub pin_protocol: PinUvAuthProtocol,
385 #[allow(dead_code)] // Not yet used
386 permissions: PinUvAuthTokenPermission,
387 }
388
389 impl PinUvAuthParam {
390 pub(crate) fn create_empty() -> Self {
391 let pin_protocol = PinUvAuthProtocol(Box::new(PinUvAuth1 {}));
392 Self {
393 pin_auth: vec![],
394 pin_protocol,
395 permissions: PinUvAuthTokenPermission::empty(),
396 }
397 }
398
399 #[cfg(test)]
400 pub(crate) fn create_test(
401 pin_protocol: u64,
402 pin_auth: Vec<u8>,
403 permissions: PinUvAuthTokenPermission,
404 ) -> Self {
405 let pin_protocol = PinUvAuthProtocol::try_from(&AuthenticatorInfo {
406 pin_protocols: Some(vec![pin_protocol]),
407 ..Default::default()
408 })
409 .expect("Failed to create PIN protocol");
410 Self {
411 pin_auth,
412 pin_protocol,
413 permissions,
414 }
415 }
416 }
417
418 impl Serialize for PinUvAuthParam {
419 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
420 where
421 S: Serializer,
422 {
423 serde_bytes::serialize(&self.pin_auth[..], serializer)
424 }
425 }
426
427 /// A Curve identifier. You probably will never need to alter
428 /// or use this value, as it is set inside the Credential for you.
429 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
430 pub enum Curve {
431 // +---------+-------+----------+------------------------------------+
432 // | Name | Value | Key Type | Description |
433 // +---------+-------+----------+------------------------------------+
434 // | P-256 | 1 | EC2 | NIST P-256 also known as secp256r1 |
435 // | P-384 | 2 | EC2 | NIST P-384 also known as secp384r1 |
436 // | P-521 | 3 | EC2 | NIST P-521 also known as secp521r1 |
437 // | X25519 | 4 | OKP | X25519 for use w/ ECDH only |
438 // | X448 | 5 | OKP | X448 for use w/ ECDH only |
439 // | Ed25519 | 6 | OKP | Ed25519 for use w/ EdDSA only |
440 // | Ed448 | 7 | OKP | Ed448 for use w/ EdDSA only |
441 // +---------+-------+----------+------------------------------------+
442 /// Identifies this curve as SECP256R1 (X9_62_PRIME256V1 in OpenSSL)
443 SECP256R1 = 1,
444 /// Identifies this curve as SECP384R1
445 SECP384R1 = 2,
446 /// Identifies this curve as SECP521R1
447 SECP521R1 = 3,
448 /// Identifieds this as OKP X25519 for use w/ ECDH only
449 X25519 = 4,
450 /// Identifieds this as OKP X448 for use w/ ECDH only
451 X448 = 5,
452 /// Identifieds this as OKP Ed25519 for use w/ EdDSA only
453 Ed25519 = 6,
454 /// Identifieds this as OKP Ed448 for use w/ EdDSA only
455 Ed448 = 7,
456 }
457
458 impl Serialize for Curve {
459 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
460 where
461 S: Serializer,
462 {
463 serializer.serialize_i64(*self as i64)
464 }
465 }
466
467 impl TryFrom<i64> for Curve {
468 type Error = CryptoError;
469 fn try_from(i: i64) -> Result<Self, Self::Error> {
470 match i {
471 i if i == Curve::SECP256R1 as i64 => Ok(Curve::SECP256R1),
472 i if i == Curve::SECP384R1 as i64 => Ok(Curve::SECP384R1),
473 i if i == Curve::SECP521R1 as i64 => Ok(Curve::SECP521R1),
474 i if i == Curve::X25519 as i64 => Ok(Curve::X25519),
475 i if i == Curve::X448 as i64 => Ok(Curve::X448),
476 i if i == Curve::Ed25519 as i64 => Ok(Curve::Ed25519),
477 i if i == Curve::Ed448 as i64 => Ok(Curve::Ed448),
478 _ => Err(CryptoError::UnknownKeyType),
479 }
480 }
481 }
482 /// A COSE signature algorithm, indicating the type of key and hash type
483 /// that should be used.
484 /// see: https://www.iana.org/assignments/cose/cose.xhtml#table-algorithms
485 #[rustfmt::skip]
486 #[allow(non_camel_case_types)]
487 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
488 pub enum COSEAlgorithm {
489 // /// Identifies this key as ECDSA (recommended SECP256R1) with SHA256 hashing
490 // //#[serde(alias = "ECDSA_SHA256")]
491 // ES256 = -7, // recommends curve SECP256R1
492 // /// Identifies this key as ECDSA (recommended SECP384R1) with SHA384 hashing
493 // //#[serde(alias = "ECDSA_SHA384")]
494 // ES384 = -35, // recommends curve SECP384R1
495 // /// Identifies this key as ECDSA (recommended SECP521R1) with SHA512 hashing
496 // //#[serde(alias = "ECDSA_SHA512")]
497 // ES512 = -36, // recommends curve SECP521R1
498 // /// Identifies this key as RS256 aka RSASSA-PKCS1-v1_5 w/ SHA-256
499 // RS256 = -257,
500 // /// Identifies this key as RS384 aka RSASSA-PKCS1-v1_5 w/ SHA-384
501 // RS384 = -258,
502 // /// Identifies this key as RS512 aka RSASSA-PKCS1-v1_5 w/ SHA-512
503 // RS512 = -259,
504 // /// Identifies this key as PS256 aka RSASSA-PSS w/ SHA-256
505 // PS256 = -37,
506 // /// Identifies this key as PS384 aka RSASSA-PSS w/ SHA-384
507 // PS384 = -38,
508 // /// Identifies this key as PS512 aka RSASSA-PSS w/ SHA-512
509 // PS512 = -39,
510 // /// Identifies this key as EdDSA (likely curve ed25519)
511 // EDDSA = -8,
512 // /// Identifies this as an INSECURE RS1 aka RSASSA-PKCS1-v1_5 using SHA-1. This is not
513 // /// used by validators, but can exist in some windows hello tpm's
514 // INSECURE_RS1 = -65535,
515 INSECURE_RS1 = -65535, // RSASSA-PKCS1-v1_5 using SHA-1
516 RS512 = -259, // RSASSA-PKCS1-v1_5 using SHA-512
517 RS384 = -258, // RSASSA-PKCS1-v1_5 using SHA-384
518 RS256 = -257, // RSASSA-PKCS1-v1_5 using SHA-256
519 ES256K = -47, // ECDSA using secp256k1 curve and SHA-256
520 HSS_LMS = -46, // HSS/LMS hash-based digital signature
521 SHAKE256 = -45, // SHAKE-256 512-bit Hash Value
522 SHA512 = -44, // SHA-2 512-bit Hash
523 SHA384 = -43, // SHA-2 384-bit Hash
524 RSAES_OAEP_SHA_512 = -42, // RSAES-OAEP w/ SHA-512
525 RSAES_OAEP_SHA_256 = -41, // RSAES-OAEP w/ SHA-256
526 RSAES_OAEP_RFC_8017_default = -40, // RSAES-OAEP w/ SHA-1
527 PS512 = -39, // RSASSA-PSS w/ SHA-512
528 PS384 = -38, // RSASSA-PSS w/ SHA-384
529 PS256 = -37, // RSASSA-PSS w/ SHA-256
530 ES512 = -36, // ECDSA w/ SHA-512
531 ES384 = -35, // ECDSA w/ SHA-384
532 ECDH_SS_A256KW = -34, // ECDH SS w/ Concat KDF and AES Key Wrap w/ 256-bit key
533 ECDH_SS_A192KW = -33, // ECDH SS w/ Concat KDF and AES Key Wrap w/ 192-bit key
534 ECDH_SS_A128KW = -32, // ECDH SS w/ Concat KDF and AES Key Wrap w/ 128-bit key
535 ECDH_ES_A256KW = -31, // ECDH ES w/ Concat KDF and AES Key Wrap w/ 256-bit key
536 ECDH_ES_A192KW = -30, // ECDH ES w/ Concat KDF and AES Key Wrap w/ 192-bit key
537 ECDH_ES_A128KW = -29, // ECDH ES w/ Concat KDF and AES Key Wrap w/ 128-bit key
538 ECDH_SS_HKDF512 = -28, // ECDH SS w/ HKDF - generate key directly
539 ECDH_SS_HKDF256 = -27, // ECDH SS w/ HKDF - generate key directly
540 ECDH_ES_HKDF512 = -26, // ECDH ES w/ HKDF - generate key directly
541 ECDH_ES_HKDF256 = -25, // ECDH ES w/ HKDF - generate key directly
542 SHAKE128 = -18, // SHAKE-128 256-bit Hash Value
543 SHA512_256 = -17, // SHA-2 512-bit Hash truncated to 256-bits
544 SHA256 = -16, // SHA-2 256-bit Hash
545 SHA256_64 = -15, // SHA-2 256-bit Hash truncated to 64-bits
546 SHA1 = -14, // SHA-1 Hash
547 Direct_HKDF_AES256 = -13, // Shared secret w/ AES-MAC 256-bit key
548 Direct_HKDF_AES128 = -12, // Shared secret w/ AES-MAC 128-bit key
549 Direct_HKDF_SHA512 = -11, // Shared secret w/ HKDF and SHA-512
550 Direct_HKDF_SHA256 = -10, // Shared secret w/ HKDF and SHA-256
551 EDDSA = -8, // EdDSA
552 ES256 = -7, // ECDSA w/ SHA-256
553 Direct = -6, // Direct use of CEK
554 A256KW = -5, // AES Key Wrap w/ 256-bit key
555 A192KW = -4, // AES Key Wrap w/ 192-bit key
556 A128KW = -3, // AES Key Wrap w/ 128-bit key
557 A128GCM = 1, // AES-GCM mode w/ 128-bit key, 128-bit tag
558 A192GCM = 2, // AES-GCM mode w/ 192-bit key, 128-bit tag
559 A256GCM = 3, // AES-GCM mode w/ 256-bit key, 128-bit tag
560 HMAC256_64 = 4, // HMAC w/ SHA-256 truncated to 64 bits
561 HMAC256_256 = 5, // HMAC w/ SHA-256
562 HMAC384_384 = 6, // HMAC w/ SHA-384
563 HMAC512_512 = 7, // HMAC w/ SHA-512
564 AES_CCM_16_64_128 = 10, // AES-CCM mode 128-bit key, 64-bit tag, 13-byte nonce
565 AES_CCM_16_64_256 = 11, // AES-CCM mode 256-bit key, 64-bit tag, 13-byte nonce
566 AES_CCM_64_64_128 = 12, // AES-CCM mode 128-bit key, 64-bit tag, 7-byte nonce
567 AES_CCM_64_64_256 = 13, // AES-CCM mode 256-bit key, 64-bit tag, 7-byte nonce
568 AES_MAC_128_64 = 14, // AES-MAC 128-bit key, 64-bit tag
569 AES_MAC_256_64 = 15, // AES-MAC 256-bit key, 64-bit tag
570 ChaCha20_Poly1305 = 24, // ChaCha20/Poly1305 w/ 256-bit key, 128-bit tag
571 AES_MAC_128_128 = 25, // AES-MAC 128-bit key, 128-bit tag
572 AES_MAC_256_128 = 26, // AES-MAC 256-bit key, 128-bit tag
573 AES_CCM_16_128_128 = 30, // AES-CCM mode 128-bit key, 128-bit tag, 13-byte nonce
574 AES_CCM_16_128_256 = 31, // AES-CCM mode 256-bit key, 128-bit tag, 13-byte nonce
575 AES_CCM_64_128_128 = 32, // AES-CCM mode 128-bit key, 128-bit tag, 7-byte nonce
576 AES_CCM_64_128_256 = 33, // AES-CCM mode 256-bit key, 128-bit tag, 7-byte nonce
577 IV_GENERATION = 34, // For doing IV generation for symmetric algorithms.
578 }
579
580 impl Serialize for COSEAlgorithm {
581 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
582 where
583 S: Serializer,
584 {
585 serializer.serialize_i64(*self as i64)
586 }
587 }
588
589 impl<'de> Deserialize<'de> for COSEAlgorithm {
590 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
591 where
592 D: Deserializer<'de>,
593 {
594 struct COSEAlgorithmVisitor;
595
596 impl<'de> Visitor<'de> for COSEAlgorithmVisitor {
597 type Value = COSEAlgorithm;
598
599 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
600 formatter.write_str("a signed integer")
601 }
602
603 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
604 where
605 E: SerdeError,
606 {
607 COSEAlgorithm::try_from(v).map_err(|_| {
608 SerdeError::invalid_value(Unexpected::Signed(v), &"valid COSEAlgorithm")
609 })
610 }
611 }
612
613 deserializer.deserialize_any(COSEAlgorithmVisitor)
614 }
615 }
616
617 impl TryFrom<i64> for COSEAlgorithm {
618 type Error = CryptoError;
619 fn try_from(i: i64) -> Result<Self, Self::Error> {
620 match i {
621 i if i == COSEAlgorithm::RS512 as i64 => Ok(COSEAlgorithm::RS512),
622 i if i == COSEAlgorithm::RS384 as i64 => Ok(COSEAlgorithm::RS384),
623 i if i == COSEAlgorithm::RS256 as i64 => Ok(COSEAlgorithm::RS256),
624 i if i == COSEAlgorithm::ES256K as i64 => Ok(COSEAlgorithm::ES256K),
625 i if i == COSEAlgorithm::HSS_LMS as i64 => Ok(COSEAlgorithm::HSS_LMS),
626 i if i == COSEAlgorithm::SHAKE256 as i64 => Ok(COSEAlgorithm::SHAKE256),
627 i if i == COSEAlgorithm::SHA512 as i64 => Ok(COSEAlgorithm::SHA512),
628 i if i == COSEAlgorithm::SHA384 as i64 => Ok(COSEAlgorithm::SHA384),
629 i if i == COSEAlgorithm::RSAES_OAEP_SHA_512 as i64 => {
630 Ok(COSEAlgorithm::RSAES_OAEP_SHA_512)
631 }
632 i if i == COSEAlgorithm::RSAES_OAEP_SHA_256 as i64 => {
633 Ok(COSEAlgorithm::RSAES_OAEP_SHA_256)
634 }
635 i if i == COSEAlgorithm::RSAES_OAEP_RFC_8017_default as i64 => {
636 Ok(COSEAlgorithm::RSAES_OAEP_RFC_8017_default)
637 }
638 i if i == COSEAlgorithm::PS512 as i64 => Ok(COSEAlgorithm::PS512),
639 i if i == COSEAlgorithm::PS384 as i64 => Ok(COSEAlgorithm::PS384),
640 i if i == COSEAlgorithm::PS256 as i64 => Ok(COSEAlgorithm::PS256),
641 i if i == COSEAlgorithm::ES512 as i64 => Ok(COSEAlgorithm::ES512),
642 i if i == COSEAlgorithm::ES384 as i64 => Ok(COSEAlgorithm::ES384),
643 i if i == COSEAlgorithm::ECDH_SS_A256KW as i64 => Ok(COSEAlgorithm::ECDH_SS_A256KW),
644 i if i == COSEAlgorithm::ECDH_SS_A192KW as i64 => Ok(COSEAlgorithm::ECDH_SS_A192KW),
645 i if i == COSEAlgorithm::ECDH_SS_A128KW as i64 => Ok(COSEAlgorithm::ECDH_SS_A128KW),
646 i if i == COSEAlgorithm::ECDH_ES_A256KW as i64 => Ok(COSEAlgorithm::ECDH_ES_A256KW),
647 i if i == COSEAlgorithm::ECDH_ES_A192KW as i64 => Ok(COSEAlgorithm::ECDH_ES_A192KW),
648 i if i == COSEAlgorithm::ECDH_ES_A128KW as i64 => Ok(COSEAlgorithm::ECDH_ES_A128KW),
649 i if i == COSEAlgorithm::ECDH_SS_HKDF512 as i64 => Ok(COSEAlgorithm::ECDH_SS_HKDF512),
650 i if i == COSEAlgorithm::ECDH_SS_HKDF256 as i64 => Ok(COSEAlgorithm::ECDH_SS_HKDF256),
651 i if i == COSEAlgorithm::ECDH_ES_HKDF512 as i64 => Ok(COSEAlgorithm::ECDH_ES_HKDF512),
652 i if i == COSEAlgorithm::ECDH_ES_HKDF256 as i64 => Ok(COSEAlgorithm::ECDH_ES_HKDF256),
653 i if i == COSEAlgorithm::SHAKE128 as i64 => Ok(COSEAlgorithm::SHAKE128),
654 i if i == COSEAlgorithm::SHA512_256 as i64 => Ok(COSEAlgorithm::SHA512_256),
655 i if i == COSEAlgorithm::SHA256 as i64 => Ok(COSEAlgorithm::SHA256),
656 i if i == COSEAlgorithm::SHA256_64 as i64 => Ok(COSEAlgorithm::SHA256_64),
657 i if i == COSEAlgorithm::SHA1 as i64 => Ok(COSEAlgorithm::SHA1),
658 i if i == COSEAlgorithm::Direct_HKDF_AES256 as i64 => {
659 Ok(COSEAlgorithm::Direct_HKDF_AES256)
660 }
661 i if i == COSEAlgorithm::Direct_HKDF_AES128 as i64 => {
662 Ok(COSEAlgorithm::Direct_HKDF_AES128)
663 }
664 i if i == COSEAlgorithm::Direct_HKDF_SHA512 as i64 => {
665 Ok(COSEAlgorithm::Direct_HKDF_SHA512)
666 }
667 i if i == COSEAlgorithm::Direct_HKDF_SHA256 as i64 => {
668 Ok(COSEAlgorithm::Direct_HKDF_SHA256)
669 }
670 i if i == COSEAlgorithm::EDDSA as i64 => Ok(COSEAlgorithm::EDDSA),
671 i if i == COSEAlgorithm::ES256 as i64 => Ok(COSEAlgorithm::ES256),
672 i if i == COSEAlgorithm::Direct as i64 => Ok(COSEAlgorithm::Direct),
673 i if i == COSEAlgorithm::A256KW as i64 => Ok(COSEAlgorithm::A256KW),
674 i if i == COSEAlgorithm::A192KW as i64 => Ok(COSEAlgorithm::A192KW),
675 i if i == COSEAlgorithm::A128KW as i64 => Ok(COSEAlgorithm::A128KW),
676 i if i == COSEAlgorithm::A128GCM as i64 => Ok(COSEAlgorithm::A128GCM),
677 i if i == COSEAlgorithm::A192GCM as i64 => Ok(COSEAlgorithm::A192GCM),
678 i if i == COSEAlgorithm::A256GCM as i64 => Ok(COSEAlgorithm::A256GCM),
679 i if i == COSEAlgorithm::HMAC256_64 as i64 => Ok(COSEAlgorithm::HMAC256_64),
680 i if i == COSEAlgorithm::HMAC256_256 as i64 => Ok(COSEAlgorithm::HMAC256_256),
681 i if i == COSEAlgorithm::HMAC384_384 as i64 => Ok(COSEAlgorithm::HMAC384_384),
682 i if i == COSEAlgorithm::HMAC512_512 as i64 => Ok(COSEAlgorithm::HMAC512_512),
683 i if i == COSEAlgorithm::AES_CCM_16_64_128 as i64 => {
684 Ok(COSEAlgorithm::AES_CCM_16_64_128)
685 }
686 i if i == COSEAlgorithm::AES_CCM_16_64_256 as i64 => {
687 Ok(COSEAlgorithm::AES_CCM_16_64_256)
688 }
689 i if i == COSEAlgorithm::AES_CCM_64_64_128 as i64 => {
690 Ok(COSEAlgorithm::AES_CCM_64_64_128)
691 }
692 i if i == COSEAlgorithm::AES_CCM_64_64_256 as i64 => {
693 Ok(COSEAlgorithm::AES_CCM_64_64_256)
694 }
695 i if i == COSEAlgorithm::AES_MAC_128_64 as i64 => Ok(COSEAlgorithm::AES_MAC_128_64),
696 i if i == COSEAlgorithm::AES_MAC_256_64 as i64 => Ok(COSEAlgorithm::AES_MAC_256_64),
697 i if i == COSEAlgorithm::ChaCha20_Poly1305 as i64 => {
698 Ok(COSEAlgorithm::ChaCha20_Poly1305)
699 }
700 i if i == COSEAlgorithm::AES_MAC_128_128 as i64 => Ok(COSEAlgorithm::AES_MAC_128_128),
701 i if i == COSEAlgorithm::AES_MAC_256_128 as i64 => Ok(COSEAlgorithm::AES_MAC_256_128),
702 i if i == COSEAlgorithm::AES_CCM_16_128_128 as i64 => {
703 Ok(COSEAlgorithm::AES_CCM_16_128_128)
704 }
705 i if i == COSEAlgorithm::AES_CCM_16_128_256 as i64 => {
706 Ok(COSEAlgorithm::AES_CCM_16_128_256)
707 }
708 i if i == COSEAlgorithm::AES_CCM_64_128_128 as i64 => {
709 Ok(COSEAlgorithm::AES_CCM_64_128_128)
710 }
711 i if i == COSEAlgorithm::AES_CCM_64_128_256 as i64 => {
712 Ok(COSEAlgorithm::AES_CCM_64_128_256)
713 }
714 i if i == COSEAlgorithm::IV_GENERATION as i64 => Ok(COSEAlgorithm::IV_GENERATION),
715 i if i == COSEAlgorithm::INSECURE_RS1 as i64 => Ok(COSEAlgorithm::INSECURE_RS1),
716 _ => Err(CryptoError::UnknownAlgorithm),
717 }
718 }
719 }
720
721 /// A COSE Elliptic Curve Public Key. This is generally the provided credential
722 /// that an authenticator registers, and is used to authenticate the user.
723 #[derive(Clone, Debug, PartialEq, Eq)]
724 pub struct COSEEC2Key {
725 /// The curve that this key references.
726 pub curve: Curve,
727 /// The key's public X coordinate.
728 pub x: Vec<u8>,
729 /// The key's public Y coordinate.
730 pub y: Vec<u8>,
731 }
732
733 impl COSEEC2Key {
734 // The SEC 1 uncompressed point format is "0x04 || x coordinate || y coordinate".
735 // See Section 2.3.3 of "SEC 1: Elliptic Curve Cryptography" https://www.secg.org/sec1-v2.pdf.
736 pub fn from_sec1_uncompressed(curve: Curve, key: &[u8]) -> Result<Self, CryptoError> {
737 if !(curve == Curve::SECP256R1 && key.len() == 65) {
738 return Err(CryptoError::UnsupportedCurve(curve));
739 }
740 if key[0] != 0x04 {
741 return Err(CryptoError::MalformedInput);
742 }
743 let key = &key[1..];
744 let (x, y) = key.split_at(key.len() / 2);
745 Ok(COSEEC2Key {
746 curve,
747 x: x.to_vec(),
748 y: y.to_vec(),
749 })
750 }
751
752 pub fn der_spki(&self) -> Result<Vec<u8>, CryptoError> {
753 if self.curve != Curve::SECP256R1 {
754 return Err(CryptoError::UnsupportedCurve(self.curve));
755 }
756
757 // SubjectPublicKeyInfo
758 der::sequence(&[
759 // algorithm: AlgorithmIdentifier
760 &der::sequence(&[
761 // algorithm
762 &der::object_id(der::OID_EC_PUBLIC_KEY_BYTES)?,
763 // parameters
764 &der::object_id(der::OID_SECP256R1_BYTES)?,
765 ])?,
766 // subjectPublicKey
767 &der::bit_string(
768 // SEC 1 uncompressed format
769 &[&[0x04], self.x.as_slice(), self.y.as_slice()].concat(),
770 )?,
771 ])
772 }
773 }
774
775 /// A Octet Key Pair (OKP).
776 /// The other version uses only the x-coordinate as the y-coordinate is
777 /// either to be recomputed or not needed for the key agreement operation ('OKP').
778 #[derive(Clone, Debug, PartialEq, Eq)]
779 pub struct COSEOKPKey {
780 /// The curve that this key references.
781 pub curve: Curve,
782 /// The key's public X coordinate.
783 pub x: Vec<u8>,
784 }
785
786 impl COSEOKPKey {
787 pub fn der_spki(&self) -> Result<Vec<u8>, CryptoError> {
788 if self.curve != Curve::Ed25519 {
789 return Err(CryptoError::UnsupportedCurve(self.curve));
790 }
791
792 // SubjectPublicKeyInfo
793 der::sequence(&[
794 // algorithm: AlgorithmIdentifier
795 &der::sequence(&[
796 // algorithm
797 &der::object_id(der::OID_ED25519_BYTES)?,
798 // parameters
799 // (absent as per RFC 8410)
800 ])?,
801 // subjectPublicKey
802 &der::bit_string(
803 // RFC 8410
804 self.x.as_slice(),
805 )?,
806 ])
807 }
808 }
809
810 /// A COSE RSA PublicKey. This is a provided credential from a registered authenticator.
811 #[derive(Clone, Debug, PartialEq, Eq)]
812 pub struct COSERSAKey {
813 /// An RSA modulus
814 pub n: Vec<u8>,
815 /// An RSA exponent
816 pub e: Vec<u8>,
817 }
818
819 impl COSERSAKey {
820 pub fn der_spki(&self) -> Result<Vec<u8>, CryptoError> {
821 // SubjectPublicKeyInfo
822 der::sequence(&[
823 // algorithm: AlgorithmIdentifier
824 &der::sequence(&[
825 // algorithm
826 &der::object_id(der::OID_RSA_ENCRYPTION_BYTES)?,
827 // parameters
828 &der::null()?,
829 ])?,
830 // subjectPublicKey
831 &der::bit_string(
832 // RFC 4055 RSAPublicKey
833 &der::sequence(&[&der::integer(&self.n)?, &der::integer(&self.e)?])?,
834 )?,
835 ])
836 }
837 }
838
839 // https://tools.ietf.org/html/rfc8152#section-13
840 #[allow(non_camel_case_types)]
841 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
842 pub enum COSEKeyTypeId {
843 // Reserved is invalid
844 // Reserved = 0,
845 /// Octet Key Pair
846 OKP = 1,
847 /// Elliptic Curve Keys w/ x- and y-coordinate
848 EC2 = 2,
849 /// RSA
850 RSA = 3,
851 }
852
853 impl Serialize for COSEKeyTypeId {
854 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
855 where
856 S: Serializer,
857 {
858 serializer.serialize_i64(*self as i64)
859 }
860 }
861
862 impl TryFrom<i64> for COSEKeyTypeId {
863 type Error = CryptoError;
864 fn try_from(i: i64) -> Result<Self, Self::Error> {
865 match i {
866 i if i == COSEKeyTypeId::OKP as i64 => Ok(COSEKeyTypeId::OKP),
867 i if i == COSEKeyTypeId::EC2 as i64 => Ok(COSEKeyTypeId::EC2),
868 i if i == COSEKeyTypeId::RSA as i64 => Ok(COSEKeyTypeId::RSA),
869 _ => Err(CryptoError::UnknownKeyType),
870 }
871 }
872 }
873
874 /// The type of Key contained within a COSE value. You should never need
875 /// to alter or change this type.
876 #[allow(non_camel_case_types)]
877 #[derive(Clone, Debug, PartialEq, Eq)]
878 pub enum COSEKeyType {
879 /// Identifies this as an Elliptic Curve EC2 key
880 EC2(COSEEC2Key),
881 /// Identifies this as an Elliptic Curve octet key pair
882 OKP(COSEOKPKey),
883 /// Identifies this as an RSA key
884 RSA(COSERSAKey),
885 }
886
887 /// A COSE Key as provided by the Authenticator. You should never need
888 /// to alter or change these values.
889 #[derive(Clone, Debug, PartialEq, Eq)]
890 pub struct COSEKey {
891 /// COSE signature algorithm, indicating the type of key and hash type
892 /// that should be used.
893 pub alg: COSEAlgorithm,
894 /// The public key
895 pub key: COSEKeyType,
896 }
897
898 impl COSEKey {
899 /// Generates a new key pair for the specified algorithm.
900 /// Returns an PKCS#8 encoding of the private key, and the public key as a COSEKey.
901 pub fn generate(alg: COSEAlgorithm) -> Result<(Vec<u8>, Self), CryptoError> {
902 if alg != COSEAlgorithm::ES256 && alg != COSEAlgorithm::ECDH_ES_HKDF256 {
903 return Err(CryptoError::UnsupportedAlgorithm(alg));
904 }
905 let (private, public) = gen_p256()?;
906 let cose_ec2_key = COSEEC2Key::from_sec1_uncompressed(Curve::SECP256R1, &public)?;
907 let public = COSEKey {
908 alg,
909 key: COSEKeyType::EC2(cose_ec2_key),
910 };
911 Ok((private, public))
912 }
913
914 pub fn der_spki(&self) -> Result<Vec<u8>, CryptoError> {
915 match &self.key {
916 COSEKeyType::EC2(ec2_key) => ec2_key.der_spki(),
917 COSEKeyType::OKP(okp_key) => okp_key.der_spki(),
918 COSEKeyType::RSA(rsa_key) => rsa_key.der_spki(),
919 }
920 }
921 }
922
923 impl<'de> Deserialize<'de> for COSEKey {
924 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
925 where
926 D: Deserializer<'de>,
927 {
928 struct COSEKeyVisitor;
929
930 impl<'de> Visitor<'de> for COSEKeyVisitor {
931 type Value = COSEKey;
932
933 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
934 formatter.write_str("a map")
935 }
936
937 fn visit_map<M>(self, mut map: M) -> std::result::Result<Self::Value, M::Error>
938 where
939 M: MapAccess<'de>,
940 {
941 let mut key_type: Option<COSEKeyTypeId> = None;
942 let mut alg: Option<COSEAlgorithm> = None;
943 // OKP / EC2
944 let mut curve: Option<Curve> = None;
945 let mut x: Option<Vec<u8>> = None;
946 let mut y: Option<Vec<u8>> = None;
947
948 // RSA specific
949 let mut n: Option<Vec<u8>> = None;
950 let mut e: Option<Vec<u8>> = None;
951
952 while let Some(key) = map.next_key()? {
953 // See https://www.iana.org/assignments/cose/cose.xhtml#key-type-parameters
954 match key {
955 1 => {
956 if key_type.is_some() {
957 return Err(SerdeError::duplicate_field("key_type"));
958 }
959 let value: i64 = map.next_value()?;
960 let val = COSEKeyTypeId::try_from(value).map_err(|_| {
961 SerdeError::custom(format!("unsupported key_type {value}"))
962 })?;
963 key_type = Some(val);
964 }
965 3 => {
966 if alg.is_some() {
967 return Err(SerdeError::duplicate_field("alg"));
968 }
969 let value: i64 = map.next_value()?;
970 let val = COSEAlgorithm::try_from(value).map_err(|_| {
971 SerdeError::custom(format!("unsupported algorithm {value}"))
972 })?;
973 alg = Some(val);
974 }
975 -1 => match key_type {
976 None => return Err(SerdeError::missing_field("key_type")),
977 Some(COSEKeyTypeId::OKP) | Some(COSEKeyTypeId::EC2) => {
978 if curve.is_some() {
979 return Err(SerdeError::duplicate_field("curve"));
980 }
981 let value: i64 = map.next_value()?;
982 let val = Curve::try_from(value).map_err(|_| {
983 SerdeError::custom(format!("unsupported curve {value}"))
984 })?;
985 curve = Some(val);
986 }
987 Some(COSEKeyTypeId::RSA) => {
988 if n.is_some() {
989 return Err(SerdeError::duplicate_field("n"));
990 }
991 let value: ByteBuf = map.next_value()?;
992 n = Some(value.to_vec());
993 }
994 },
995 -2 => match key_type {
996 None => return Err(SerdeError::missing_field("key_type")),
997 Some(COSEKeyTypeId::OKP) | Some(COSEKeyTypeId::EC2) => {
998 if x.is_some() {
999 return Err(SerdeError::duplicate_field("x"));
1000 }
1001 let value: ByteBuf = map.next_value()?;
1002 x = Some(value.to_vec());
1003 }
1004 Some(COSEKeyTypeId::RSA) => {
1005 if e.is_some() {
1006 return Err(SerdeError::duplicate_field("e"));
1007 }
1008 let value: ByteBuf = map.next_value()?;
1009 e = Some(value.to_vec());
1010 }
1011 },
1012 -3 if key_type == Some(COSEKeyTypeId::EC2) => {
1013 if y.is_some() {
1014 return Err(SerdeError::duplicate_field("y"));
1015 }
1016 let value: ByteBuf = map.next_value()?;
1017 y = Some(value.to_vec());
1018 }
1019 other => {
1020 return Err(SerdeError::custom(format!("unexpected field: {other}")));
1021 }
1022 };
1023 }
1024
1025 let key_type = key_type.ok_or_else(|| SerdeError::missing_field("key_type (1)"))?;
1026 let alg = alg.ok_or_else(|| SerdeError::missing_field("alg (3)"))?;
1027
1028 let res = match key_type {
1029 COSEKeyTypeId::OKP => {
1030 let curve = curve.ok_or_else(|| SerdeError::missing_field("curve (-1)"))?;
1031 let x = x.ok_or_else(|| SerdeError::missing_field("x (-2)"))?;
1032 COSEKeyType::OKP(COSEOKPKey { curve, x })
1033 }
1034 COSEKeyTypeId::EC2 => {
1035 let curve = curve.ok_or_else(|| SerdeError::missing_field("curve (-1)"))?;
1036 let x = x.ok_or_else(|| SerdeError::missing_field("x (-2)"))?;
1037 let y = y.ok_or_else(|| SerdeError::missing_field("y (-3)"))?;
1038 COSEKeyType::EC2(COSEEC2Key { curve, x, y })
1039 }
1040 COSEKeyTypeId::RSA => {
1041 let n = n.ok_or_else(|| SerdeError::missing_field("n (-1)"))?;
1042 let e = e.ok_or_else(|| SerdeError::missing_field("e (-2)"))?;
1043 COSEKeyType::RSA(COSERSAKey { e, n })
1044 }
1045 };
1046 Ok(COSEKey { alg, key: res })
1047 }
1048 }
1049
1050 deserializer.deserialize_bytes(COSEKeyVisitor)
1051 }
1052 }
1053
1054 impl Serialize for COSEKey {
1055 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1056 where
1057 S: Serializer,
1058 {
1059 match &self.key {
1060 COSEKeyType::OKP(key) => {
1061 serialize_map!(
1062 serializer,
1063 &1 => &COSEKeyTypeId::OKP,
1064 &3 => &self.alg,
1065 &-1 => &key.curve,
1066 &-2 => &serde_bytes::Bytes::new(&key.x),
1067 )
1068 }
1069 COSEKeyType::EC2(key) => {
1070 serialize_map!(
1071 serializer,
1072 &1 => &COSEKeyTypeId::EC2,
1073 &3 => &self.alg,
1074 &-1 => &key.curve,
1075 &-2 => &serde_bytes::Bytes::new(&key.x),
1076 &-3 => &serde_bytes::Bytes::new(&key.y),
1077 )
1078 }
1079 COSEKeyType::RSA(key) => {
1080 serialize_map!(
1081 serializer,
1082 &1 => &COSEKeyTypeId::RSA,
1083 &3 => &self.alg,
1084 &-1 => &serde_bytes::Bytes::new(&key.n),
1085 &-2 => &serde_bytes::Bytes::new(&key.e),
1086 )
1087 }
1088 }
1089 }
1090 }
1091
1092 /// Errors that can be returned from COSE functions.
1093 #[derive(Debug, Clone, PartialEq, Serialize)]
1094 pub enum CryptoError {
1095 // DecodingFailure,
1096 LibraryFailure,
1097 MalformedInput,
1098 // MissingHeader,
1099 // UnexpectedHeaderValue,
1100 // UnexpectedTag,
1101 // UnexpectedType,
1102 // Unimplemented,
1103 // VerificationFailed,
1104 // SigningFailed,
1105 // InvalidArgument,
1106 UnknownKeyType,
1107 UnknownSignatureScheme,
1108 UnknownAlgorithm,
1109 WrongSaltLength,
1110 UnsupportedAlgorithm(COSEAlgorithm),
1111 UnsupportedCurve(Curve),
1112 UnsupportedKeyType,
1113 Backend(String),
1114 }
1115
1116 impl From<CryptoError> for CommandError {
1117 fn from(e: CryptoError) -> Self {
1118 CommandError::Crypto(e)
1119 }
1120 }
1121
1122 impl From<CryptoError> for AuthenticatorError {
1123 fn from(e: CryptoError) -> Self {
1124 AuthenticatorError::HIDError(HIDError::Command(CommandError::Crypto(e)))
1125 }
1126 }
1127
1128 pub struct U2FRegisterAnswer<'a> {
1129 pub certificate: &'a [u8],
1130 pub signature: &'a [u8],
1131 }
1132
1133 // We will only return MalformedInput here
1134 pub fn parse_u2f_der_certificate(data: &[u8]) -> Result<U2FRegisterAnswer, CryptoError> {
1135 // So we don't panic below, when accessing individual bytes
1136 if data.len() < 4 {
1137 return Err(CryptoError::MalformedInput);
1138 }
1139 // Check if it is a SEQUENCE
1140 if data[0] != 0x30 {
1141 return Err(CryptoError::MalformedInput);
1142 }
1143
1144 // This algorithm is taken from mozilla-central/security/nss/lib/mozpkix/lib/pkixder.cpp
1145 // The short form of length is a single byte with the high order bit set
1146 // to zero. The long form of length is one byte with the high order bit
1147 // set, followed by N bytes, where N is encoded in the lowest 7 bits of
1148 // the first byte.
1149 let end = if (data[1] & 0x80) == 0 {
1150 2 + data[1] as usize
1151 } else if data[1] == 0x81 {
1152 // The next byte specifies the length
1153
1154 if data[2] < 128 {
1155 // Not shortest possible encoding
1156 // Forbidden by DER-format
1157 return Err(CryptoError::MalformedInput);
1158 }
1159 3 + data[2] as usize
1160 } else if data[1] == 0x82 {
1161 // The next 2 bytes specify the length
1162 let l = u16::from_be_bytes([data[2], data[3]]);
1163 if l < 256 {
1164 // Not shortest possible encoding
1165 // Forbidden by DER-format
1166 return Err(CryptoError::MalformedInput);
1167 }
1168 4 + l as usize
1169 } else {
1170 // We don't support lengths larger than 2^16 - 1.
1171 return Err(CryptoError::MalformedInput);
1172 };
1173
1174 if data.len() < end {
1175 return Err(CryptoError::MalformedInput);
1176 }
1177
1178 Ok(U2FRegisterAnswer {
1179 certificate: &data[0..end],
1180 signature: &data[end..],
1181 })
1182 }
1183
1184 #[cfg(all(test, not(feature = "crypto_dummy")))]
1185 mod test {
1186 use std::convert::TryFrom;
1187
1188 #[cfg(feature = "crypto_nss")]
1189 use super::backend::{ecdsa_p256_sha256_sign_raw, test_ecdsa_p256_sha256_verify_raw};
1190 use super::{
1191 backend::hmac_sha256, backend::sha256, backend::test_ecdh_p256_raw, COSEAlgorithm, COSEKey,
1192 Curve, PinProtocolImpl, PinUvAuth1, PinUvAuth2, PinUvAuthProtocol, PublicInputs,
1193 SharedSecret,
1194 };
1195 use crate::crypto::{COSEEC2Key, COSEKeyType, COSEOKPKey, COSERSAKey};
1196 use crate::ctap2::attestation::AAGuid;
1197 use crate::ctap2::commands::client_pin::Pin;
1198 use crate::ctap2::commands::get_info::{
1199 tests::AAGUID_RAW, AuthenticatorOptions, AuthenticatorVersion,
1200 };
1201 use crate::util::decode_hex;
1202 use crate::AuthenticatorInfo;
1203 use serde_cbor::de::from_slice;
1204
1205 // Extracted from RFC 8410 Example 10.1
1206 const SAMPLE_ED25519_KEY: &[u8] = &[
1207 0x19, 0xbf, 0x44, 0x09, 0x69, 0x84, 0xcd, 0xfe, 0x85, 0x41, 0xba, 0xc1, 0x67, 0xdc, 0x3b,
1208 0x96, 0xc8, 0x50, 0x86, 0xaa, 0x30, 0xb6, 0xb6, 0xcb, 0x0c, 0x5c, 0x38, 0xad, 0x70, 0x31,
1209 0x66, 0xe1,
1210 ];
1211
1212 const SAMPLE_P256_X: &[u8] = &[
1213 0xfc, 0x9e, 0xd3, 0x6f, 0x7c, 0x1a, 0xa9, 0x15, 0xce, 0x3e, 0xa1, 0x77, 0xf0, 0x75, 0x67,
1214 0xf0, 0x7f, 0x16, 0xf9, 0x47, 0x9d, 0x95, 0xad, 0x8e, 0xd4, 0x97, 0x1d, 0x33, 0x05, 0xe3,
1215 0x1a, 0x80,
1216 ];
1217 const SAMPLE_P256_Y: &[u8] = &[
1218 0x50, 0xb7, 0x33, 0xaf, 0x8c, 0x0b, 0x0e, 0xe1, 0xda, 0x8d, 0xe0, 0xac, 0xf9, 0xd8, 0xe1,
1219 0x32, 0x82, 0xf0, 0x63, 0xb7, 0xb3, 0x0d, 0x73, 0xd4, 0xd3, 0x2c, 0x9a, 0xad, 0x6d, 0xfa,
1220 0x8b, 0x27,
1221 ];
1222
1223 const SAMPLE_RSA_MODULUS: &[u8] = &[
1224 0xd4, 0xd2, 0x53, 0xed, 0x7a, 0x69, 0xb1, 0x84, 0xc9, 0xfb, 0x70, 0x30, 0x0c, 0x51, 0xb1,
1225 0x8f, 0x89, 0x6c, 0xb1, 0x31, 0x6d, 0x87, 0xbe, 0xe1, 0xc7, 0xf7, 0xb0, 0x4f, 0xe7, 0x27,
1226 0xa7, 0xb7, 0x7c, 0x55, 0x20, 0x37, 0xa8, 0xac, 0x40, 0xf4, 0xbc, 0x59, 0xc4, 0x92, 0x8f,
1227 0x13, 0x5b, 0x5e, 0xa7, 0x18, 0x05, 0xcc, 0xd7, 0x9c, 0xfb, 0x88, 0x6c, 0xf1, 0xbc, 0x6b,
1228 0x1b, 0x8d, 0xb7, 0x8d, 0x2d, 0xaa, 0xcb, 0xee, 0xdb, 0xab, 0x49, 0x36, 0x77, 0xe5, 0xd1,
1229 0x84, 0xa1, 0x40, 0x3f, 0xf6, 0xf7, 0x98, 0x6c, 0xaa, 0x24, 0x48, 0x30, 0x44, 0xdc, 0x68,
1230 0xbd, 0x9e, 0x74, 0x37, 0xaf, 0x27, 0x12, 0x90, 0x74, 0x0d, 0x9e, 0x3c, 0xa5, 0x3a, 0x1d,
1231 0xb8, 0x54, 0x92, 0xd4, 0x6d, 0x1f, 0xf9, 0x39, 0xb8, 0x1d, 0x8a, 0x5e, 0xbe, 0x12, 0xbd,
1232 0xe2, 0x9c, 0xf2, 0x5a, 0x48, 0x5d, 0x71, 0x2c, 0x71, 0x72, 0x6d, 0xd2, 0xcb, 0x37, 0xb1,
1233 0xe6, 0x2f, 0x76, 0x43, 0xda, 0xca, 0x44, 0x30, 0x7b, 0x28, 0xe7, 0xe4, 0xec, 0xa9, 0xc9,
1234 0x1a, 0x5f, 0xe5, 0x51, 0x03, 0x25, 0x60, 0x7c, 0x5a, 0x69, 0x12, 0x4d, 0x50, 0xfd, 0xb2,
1235 0xb8, 0x6e, 0x13, 0xb2, 0x92, 0xda, 0x0e, 0x31, 0xc9, 0xf1, 0x9c, 0xde, 0x17, 0x63, 0xe4,
1236 0xcb, 0xac, 0xd5, 0xee, 0x84, 0x06, 0xde, 0x67, 0x2d, 0xb8, 0xd2, 0xe1, 0x4b, 0xbb, 0x49,
1237 0xea, 0x45, 0xd4, 0xa1, 0x7f, 0x46, 0xf2, 0xd6, 0x0c, 0x05, 0x9d, 0x1d, 0x1a, 0x99, 0x41,
1238 0x20, 0x5e, 0x1a, 0xa4, 0xcc, 0x21, 0x44, 0x58, 0x8b, 0xcd, 0x98, 0xe4, 0x3d, 0x53, 0x20,
1239 0xfc, 0xfc, 0x7b, 0x9f, 0x43, 0x35, 0xfb, 0x38, 0x37, 0x23, 0xd0, 0x76, 0xe3, 0x3d, 0x4f,
1240 0x89, 0x9b, 0x89, 0x32, 0x81, 0x89, 0xed, 0x58, 0xc0, 0x80, 0x18, 0x83, 0x5b, 0xaf, 0x5a,
1241 0xa5,
1242 ];
1243
1244 #[test]
1245 fn test_rsa_key_to_der_spki() {
1246 // $ ascii2der | xxd -i
1247 // SEQUENCE {
1248 // SEQUENCE {
1249 // # rsaEncryption
1250 // OBJECT_IDENTIFIER { 1.2.840.113549.1.1.1 }
1251 // NULL {}
1252 // }
1253 // BIT_STRING {
1254 // `00`
1255 // SEQUENCE {
1256 // INTEGER { `00d4d253ed7a69b184c9fb70300c51b18f896cb1316d87bee1c7f7b04fe727a7b77c552037a8ac40f4bc59c4928f135b5ea71805ccd79cfb886cf1bc6b1b8db78d2daacbeedbab493677e5d184a1403ff6f7986caa24483044dc68bd9e7437af271290740d9e3ca53a1db85492d46d1ff939b81d8a5ebe12bde29cf25a485d712c71726dd2cb37b1e62f7643daca44307b28e7e4eca9c91a5fe5510325607c5a69124d50fdb2b86e13b292da0e31c9f19cde1763e4cbacd5ee8406de672db8d2e14bbb49ea45d4a17f46f2d60c059d1d1a9941205e1aa4cc2144588bcd98e43d5320fcfc7b9f4335fb383723d076e33d4f899b89328189ed58c08018835baf5aa5` }
1257 // INTEGER { 65537 }
1258 // }
1259 // }
1260 // }
1261 let expected: &[u8] = &[
1262 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
1263 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a,
1264 0x02, 0x82, 0x01, 0x01, 0x00, 0xd4, 0xd2, 0x53, 0xed, 0x7a, 0x69, 0xb1, 0x84, 0xc9,
1265 0xfb, 0x70, 0x30, 0x0c, 0x51, 0xb1, 0x8f, 0x89, 0x6c, 0xb1, 0x31, 0x6d, 0x87, 0xbe,
1266 0xe1, 0xc7, 0xf7, 0xb0, 0x4f, 0xe7, 0x27, 0xa7, 0xb7, 0x7c, 0x55, 0x20, 0x37, 0xa8,
1267 0xac, 0x40, 0xf4, 0xbc, 0x59, 0xc4, 0x92, 0x8f, 0x13, 0x5b, 0x5e, 0xa7, 0x18, 0x05,
1268 0xcc, 0xd7, 0x9c, 0xfb, 0x88, 0x6c, 0xf1, 0xbc, 0x6b, 0x1b, 0x8d, 0xb7, 0x8d, 0x2d,
1269 0xaa, 0xcb, 0xee, 0xdb, 0xab, 0x49, 0x36, 0x77, 0xe5, 0xd1, 0x84, 0xa1, 0x40, 0x3f,
1270 0xf6, 0xf7, 0x98, 0x6c, 0xaa, 0x24, 0x48, 0x30, 0x44, 0xdc, 0x68, 0xbd, 0x9e, 0x74,
1271 0x37, 0xaf, 0x27, 0x12, 0x90, 0x74, 0x0d, 0x9e, 0x3c, 0xa5, 0x3a, 0x1d, 0xb8, 0x54,
1272 0x92, 0xd4, 0x6d, 0x1f, 0xf9, 0x39, 0xb8, 0x1d, 0x8a, 0x5e, 0xbe, 0x12, 0xbd, 0xe2,
1273 0x9c, 0xf2, 0x5a, 0x48, 0x5d, 0x71, 0x2c, 0x71, 0x72, 0x6d, 0xd2, 0xcb, 0x37, 0xb1,
1274 0xe6, 0x2f, 0x76, 0x43, 0xda, 0xca, 0x44, 0x30, 0x7b, 0x28, 0xe7, 0xe4, 0xec, 0xa9,
1275 0xc9, 0x1a, 0x5f, 0xe5, 0x51, 0x03, 0x25, 0x60, 0x7c, 0x5a, 0x69, 0x12, 0x4d, 0x50,
1276 0xfd, 0xb2, 0xb8, 0x6e, 0x13, 0xb2, 0x92, 0xda, 0x0e, 0x31, 0xc9, 0xf1, 0x9c, 0xde,
1277 0x17, 0x63, 0xe4, 0xcb, 0xac, 0xd5, 0xee, 0x84, 0x06, 0xde, 0x67, 0x2d, 0xb8, 0xd2,
1278 0xe1, 0x4b, 0xbb, 0x49, 0xea, 0x45, 0xd4, 0xa1, 0x7f, 0x46, 0xf2, 0xd6, 0x0c, 0x05,
1279 0x9d, 0x1d, 0x1a, 0x99, 0x41, 0x20, 0x5e, 0x1a, 0xa4, 0xcc, 0x21, 0x44, 0x58, 0x8b,
1280 0xcd, 0x98, 0xe4, 0x3d, 0x53, 0x20, 0xfc, 0xfc, 0x7b, 0x9f, 0x43, 0x35, 0xfb, 0x38,
1281 0x37, 0x23, 0xd0, 0x76, 0xe3, 0x3d, 0x4f, 0x89, 0x9b, 0x89, 0x32, 0x81, 0x89, 0xed,
1282 0x58, 0xc0, 0x80, 0x18, 0x83, 0x5b, 0xaf, 0x5a, 0xa5, 0x02, 0x03, 0x01, 0x00, 0x01,
1283 ];
1284 let rsa_key = COSERSAKey {
1285 e: vec![1, 0, 1],
1286 n: SAMPLE_RSA_MODULUS.to_vec(),
1287 };
1288 let cose_key: COSEKey = COSEKey {
1289 alg: COSEAlgorithm::RS256,
1290 key: COSEKeyType::RSA(rsa_key),
1291 };
1292 let actual = cose_key.der_spki().expect("Failed to serialize to SPKI");
1293 assert_eq!(expected, &actual);
1294 }
1295
1296 #[test]
1297 fn test_rsa_key_to_cbor() {
1298 let key = COSERSAKey {
1299 e: vec![1, 0, 1],
1300 n: SAMPLE_RSA_MODULUS.to_vec(),
1301 };
1302 let cose_key: COSEKey = COSEKey {
1303 alg: COSEAlgorithm::RS256,
1304 key: COSEKeyType::RSA(key),
1305 };
1306 let cose_key_cbor = serde_cbor::to_vec(&cose_key).expect("Failed to serialize key");
1307 let actual = serde_cbor::from_slice(&cose_key_cbor).expect("Failed to deserialize key");
1308 assert_eq!(cose_key, actual);
1309 }
1310
1311 #[test]
1312 fn test_ec2_key_to_der_spki() {
1313 // $ ascii2der | xxd -i
1314 // SEQUENCE {
1315 // SEQUENCE {
1316 // # ecPublicKey
1317 // OBJECT_IDENTIFIER { 1.2.840.10045.2.1 }
1318 // # secp256r1
1319 // OBJECT_IDENTIFIER { 1.2.840.10045.3.1.7 }
1320 // }
1321 // BIT_STRING { `00` `04fc9ed36f7c1aa915ce3ea177f07567f07f16f9479d95ad8ed4971d3305e31a8050b733af8c0b0ee1da8de0acf9d8e13282f063b7b30d73d4d32c9aad6dfa8b27` }
1322 // }
1323 let expected = [
1324 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06,
1325 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xfc,
1326 0x9e, 0xd3, 0x6f, 0x7c, 0x1a, 0xa9, 0x15, 0xce, 0x3e, 0xa1, 0x77, 0xf0, 0x75, 0x67,
1327 0xf0, 0x7f, 0x16, 0xf9, 0x47, 0x9d, 0x95, 0xad, 0x8e, 0xd4, 0x97, 0x1d, 0x33, 0x05,
1328 0xe3, 0x1a, 0x80, 0x50, 0xb7, 0x33, 0xaf, 0x8c, 0x0b, 0x0e, 0xe1, 0xda, 0x8d, 0xe0,
1329 0xac, 0xf9, 0xd8, 0xe1, 0x32, 0x82, 0xf0, 0x63, 0xb7, 0xb3, 0x0d, 0x73, 0xd4, 0xd3,
1330 0x2c, 0x9a, 0xad, 0x6d, 0xfa, 0x8b, 0x27,
1331 ];
1332 let ec2_key = COSEEC2Key {
1333 curve: Curve::SECP256R1,
1334 x: SAMPLE_P256_X.to_vec(),
1335 y: SAMPLE_P256_Y.to_vec(),
1336 };
1337 let cose_key = COSEKey {
1338 alg: COSEAlgorithm::EDDSA,
1339 key: COSEKeyType::EC2(ec2_key),
1340 };
1341 let actual = cose_key.der_spki().expect("Failed to serialize key");
1342 assert_eq!(actual, expected);
1343 }
1344
1345 #[test]
1346 fn test_ec2_key_to_cbor() {
1347 let ec2_key = COSEEC2Key {
1348 curve: Curve::SECP256R1,
1349 x: SAMPLE_P256_X.to_vec(),
1350 y: SAMPLE_P256_Y.to_vec(),
1351 };
1352 let cose_key = COSEKey {
1353 alg: COSEAlgorithm::EDDSA,
1354 key: COSEKeyType::EC2(ec2_key),
1355 };
1356 let cose_key_cbor = serde_cbor::to_vec(&cose_key).expect("Failed to serialize key");
1357 let actual = serde_cbor::from_slice(&cose_key_cbor).expect("Failed to deserialize key");
1358 assert_eq!(cose_key, actual);
1359 }
1360
1361 #[test]
1362 fn test_okp_key_to_der_spki() {
1363 // RFC 8410 Example 10.1
1364 let expected = [
1365 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0x19, 0xbf,
1366 0x44, 0x09, 0x69, 0x84, 0xcd, 0xfe, 0x85, 0x41, 0xba, 0xc1, 0x67, 0xdc, 0x3b, 0x96,
1367 0xc8, 0x50, 0x86, 0xaa, 0x30, 0xb6, 0xb6, 0xcb, 0x0c, 0x5c, 0x38, 0xad, 0x70, 0x31,
1368 0x66, 0xe1,
1369 ];
1370 let okp_key = COSEOKPKey {
1371 curve: Curve::Ed25519,
1372 x: SAMPLE_ED25519_KEY.to_vec(),
1373 };
1374 let cose_key = COSEKey {
1375 alg: COSEAlgorithm::EDDSA,
1376 key: COSEKeyType::OKP(okp_key),
1377 };
1378 let actual = cose_key.der_spki().expect("Failed to serialize key");
1379 assert_eq!(actual, expected);
1380 }
1381
1382 #[test]
1383 fn test_okp_key_to_cbor() {
1384 let okp_key = COSEOKPKey {
1385 curve: Curve::Ed25519,
1386 x: SAMPLE_ED25519_KEY.to_vec(),
1387 };
1388 let cose_key = COSEKey {
1389 alg: COSEAlgorithm::EDDSA,
1390 key: COSEKeyType::OKP(okp_key),
1391 };
1392 let cose_key_cbor = serde_cbor::to_vec(&cose_key).expect("Failed to serialize key");
1393 let actual = serde_cbor::from_slice(&cose_key_cbor).expect("Failed to deserialize key");
1394 assert_eq!(cose_key, actual);
1395 }
1396
1397 #[test]
1398 fn test_parse_es256_serialize_key() {
1399 // Test values taken from https://github.com/Yubico/python-fido2/blob/master/test/test_cose.py
1400 let key_data = decode_hex("A5010203262001215820A5FD5CE1B1C458C530A54FA61B31BF6B04BE8B97AFDE54DD8CBB69275A8A1BE1225820FA3A3231DD9DEED9D1897BE5A6228C59501E4BCD12975D3DFF730F01278EA61C");
1401 let key: COSEKey = from_slice(&key_data).unwrap();
1402 assert_eq!(key.alg, COSEAlgorithm::ES256);
1403 if let COSEKeyType::EC2(ec2key) = &key.key {
1404 assert_eq!(ec2key.curve, Curve::SECP256R1);
1405 assert_eq!(
1406 ec2key.x,
1407 decode_hex("A5FD5CE1B1C458C530A54FA61B31BF6B04BE8B97AFDE54DD8CBB69275A8A1BE1")
1408 );
1409 assert_eq!(
1410 ec2key.y,
1411 decode_hex("FA3A3231DD9DEED9D1897BE5A6228C59501E4BCD12975D3DFF730F01278EA61C")
1412 );
1413 } else {
1414 panic!("Wrong key type!");
1415 }
1416
1417 let serialized = serde_cbor::to_vec(&key).expect("Failed to serialize key");
1418 assert_eq!(key_data, serialized);
1419 }
1420
1421 #[test]
1422 #[allow(non_snake_case)]
1423 fn test_shared_secret() {
1424 // Test values taken from https://github.com/Yubico/python-fido2/blob/main/tests/test_ctap2.py
1425 let EC_PRIV =
1426 decode_hex("7452E599FEE739D8A653F6A507343D12D382249108A651402520B72F24FE7684");
1427 let EC_PUB_X =
1428 decode_hex("44D78D7989B97E62EA993496C9EF6E8FD58B8B00715F9A89153DDD9C4657E47F");
1429 let EC_PUB_Y =
1430 decode_hex("EC802EE7D22BD4E100F12E48537EB4E7E96ED3A47A0A3BD5F5EEAB65001664F9");
1431 let DEV_PUB_X =
1432 decode_hex("0501D5BC78DA9252560A26CB08FCC60CBE0B6D3B8E1D1FCEE514FAC0AF675168");
1433 let DEV_PUB_Y =
1434 decode_hex("D551B3ED46F665731F95B4532939C25D91DB7EB844BD96D4ABD4083785F8DF47");
1435 let SHARED = decode_hex("c42a039d548100dfba521e487debcbbb8b66bb7496f8b1862a7a395ed83e1a1c");
1436 let TOKEN_ENC = decode_hex("7A9F98E31B77BE90F9C64D12E9635040");
1437 let TOKEN = decode_hex("aff12c6dcfbf9df52f7a09211e8865cd");
1438 let PIN_HASH_ENC = decode_hex("afe8327ce416da8ee3d057589c2ce1a9");
1439
1440 let client_ec2_key = COSEEC2Key {
1441 curve: Curve::SECP256R1,
1442 x: EC_PUB_X.clone(),
1443 y: EC_PUB_Y.clone(),
1444 };
1445
1446 let peer_ec2_key = COSEEC2Key {
1447 curve: Curve::SECP256R1,
1448 x: DEV_PUB_X,
1449 y: DEV_PUB_Y,
1450 };
1451
1452 // We are using `test_cose_ec2_p256_ecdh_sha256()` here, because we need a way to hand in
1453 // the private key which would be generated on the fly otherwise (ephemeral keys),
1454 // to predict the outputs
1455 let peer_spki = peer_ec2_key.der_spki().unwrap();
1456 let shared_point = test_ecdh_p256_raw(&peer_spki, &EC_PUB_X, &EC_PUB_Y, &EC_PRIV).unwrap();
1457 let shared_secret = SharedSecret {
1458 pin_protocol: PinUvAuthProtocol(Box::new(PinUvAuth1 {})),
1459 key: sha256(&shared_point).unwrap(),
1460 inputs: PublicInputs {
1461 client: COSEKey {
1462 alg: COSEAlgorithm::ES256,
1463 key: COSEKeyType::EC2(client_ec2_key),
1464 },
1465 peer: COSEKey {
1466 alg: COSEAlgorithm::ES256,
1467 key: COSEKeyType::EC2(peer_ec2_key),
1468 },
1469 },
1470 };
1471 assert_eq!(shared_secret.key, SHARED);
1472
1473 let token_enc = shared_secret.encrypt(&TOKEN).unwrap();
1474 assert_eq!(token_enc, TOKEN_ENC);
1475
1476 let token = shared_secret.decrypt(&TOKEN_ENC).unwrap();
1477 assert_eq!(token, TOKEN);
1478
1479 let pin = Pin::new("1234");
1480 let pin_hash_enc = shared_secret.encrypt(&pin.for_pin_token()).unwrap();
1481 assert_eq!(pin_hash_enc, PIN_HASH_ENC);
1482 }
1483
1484 #[test]
1485 fn test_pin_uv_auth2_kdf() {
1486 // We don't pull a complete HKDF implementation from the crypto backend, so we need to
1487 // check that PinUvAuth2::kdf makes the right sequence of HMAC-SHA256 calls.
1488 //
1489 // ```python
1490 // from cryptography.hazmat.primitives.kdf.hkdf import HKDF
1491 // from cryptography.hazmat.primitives import hashes
1492 // from cryptography.hazmat.backends import default_backend
1493 //
1494 // Z = b"\xFF" * 32
1495 //
1496 // hmac_key = HKDF(
1497 // algorithm=hashes.SHA256(),
1498 // length=32,
1499 // salt=b"\x00" * 32,
1500 // info=b"CTAP2 HMAC key",
1501 // ).derive(Z)
1502 //
1503 // aes_key = HKDF(
1504 // algorithm=hashes.SHA256(),
1505 // length=32,
1506 // salt=b"\x00" * 32,
1507 // info=b"CTAP2 AES key",
1508 // ).derive(Z)
1509 //
1510 // print((hmac_key+aes_key).hex())
1511 // ```
1512 let input = decode_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
1513 let expected = decode_hex("570B4ED82AA5DFB49DB79DBEAF4B315D8ABB1A9867B245F3367026987C0D47A17D9A93C39BAEC741D141C6238D8E1846DE323D8EED022CB397D19A73B98945E2");
1514 let output = PinUvAuth2 {}.kdf(&input).unwrap();
1515 assert_eq!(&expected, &output);
1516 }
1517
1518 #[test]
1519 fn test_hmac_sha256() {
1520 let key = "key";
1521 let message = "The quick brown fox jumps over the lazy dog";
1522 let expected =
1523 decode_hex("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8");
1524
1525 let result = hmac_sha256(key.as_bytes(), message.as_bytes()).expect("HMAC-SHA256 failed");
1526 assert_eq!(result, expected);
1527
1528 let key = "The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog";
1529 let message = "message";
1530 let expected =
1531 decode_hex("5597b93a2843078cbb0c920ae41dfe20f1685e10c67e423c11ab91adfc319d12");
1532
1533 let result = hmac_sha256(key.as_bytes(), message.as_bytes()).expect("HMAC-SHA256 failed");
1534 assert_eq!(result, expected);
1535 }
1536
1537 #[test]
1538 fn test_pin_encryption_and_hashing() {
1539 let pin = "1234";
1540
1541 let shared_secret = vec![
1542 0x82, 0xE3, 0xD8, 0x41, 0xE2, 0x5C, 0x5C, 0x13, 0x46, 0x2C, 0x12, 0x3C, 0xC3, 0xD3,
1543 0x98, 0x78, 0x65, 0xBA, 0x3D, 0x20, 0x46, 0x74, 0xFB, 0xED, 0xD4, 0x7E, 0xF5, 0xAB,
1544 0xAB, 0x8D, 0x13, 0x72,
1545 ];
1546 let expected_new_pin_enc = vec![
1547 0x70, 0x66, 0x4B, 0xB5, 0x81, 0xE2, 0x57, 0x45, 0x1A, 0x3A, 0xB9, 0x1B, 0xF1, 0xAA,
1548 0xD8, 0xE4, 0x5F, 0x6C, 0xE9, 0xB5, 0xC3, 0xB0, 0xF3, 0x2B, 0x5E, 0xCD, 0x62, 0xD0,
1549 0xBA, 0x3B, 0x60, 0x5F, 0xD9, 0x18, 0x31, 0x66, 0xF6, 0xC5, 0xFA, 0xF3, 0xE4, 0xDA,
1550 0x24, 0x81, 0x50, 0x2C, 0xD0, 0xCE, 0xE0, 0x15, 0x8B, 0x35, 0x1F, 0xC3, 0x92, 0x08,
1551 0xA7, 0x7C, 0xB2, 0x74, 0x4B, 0xD4, 0x3C, 0xF9,
1552 ];
1553 let expected_pin_auth = vec![
1554 0x8E, 0x7F, 0x01, 0x69, 0x97, 0xF3, 0xB0, 0xA2, 0x7B, 0xA4, 0x34, 0x7A, 0x0E, 0x49,
1555 0xFD, 0xF5,
1556 ];
1557
1558 let mut input = vec![0x00; 64];
1559 {
1560 let pin_bytes = pin.as_bytes();
1561 let (head, _) = input.split_at_mut(pin_bytes.len());
1562 head.copy_from_slice(pin_bytes);
1563 }
1564
1565 let new_pin_enc = PinUvAuth1 {}
1566 .encrypt(&shared_secret, &input)
1567 .expect("Failed to encrypt pin");
1568 assert_eq!(new_pin_enc, expected_new_pin_enc);
1569
1570 let pin_auth = PinUvAuth1 {}
1571 .authenticate(&shared_secret, &new_pin_enc)
1572 .expect("HMAC-SHA256 failed");
1573 assert_eq!(pin_auth[0..16], expected_pin_auth);
1574 }
1575
1576 #[test]
1577 fn test_pin_protocol() {
1578 let mut info = AuthenticatorInfo {
1579 versions: vec![AuthenticatorVersion::U2F_V2, AuthenticatorVersion::FIDO_2_0],
1580 extensions: vec![],
1581 aaguid: AAGuid(AAGUID_RAW),
1582 options: AuthenticatorOptions {
1583 platform_device: false,
1584 resident_key: true,
1585 client_pin: Some(false),
1586 user_presence: true,
1587 ..Default::default()
1588 },
1589 max_msg_size: Some(1200),
1590 pin_protocols: None,
1591 ..Default::default()
1592 };
1593
1594 // Valid pin_protocols
1595 info.pin_protocols = Some(vec![1, 2]);
1596 let pin = PinUvAuthProtocol::try_from(&info).unwrap();
1597 assert_eq!(pin.id(), 1); // The one listed first
1598
1599 // Invalid pin_protocols
1600 info.pin_protocols = Some(vec![0, 10]);
1601 PinUvAuthProtocol::try_from(&info).unwrap_err();
1602
1603 info.pin_protocols = None;
1604 // No PIN protocols. CTAP1 - not supported
1605 info.versions = vec![AuthenticatorVersion::U2F_V2];
1606 PinUvAuthProtocol::try_from(&info).unwrap_err();
1607
1608 // No PIN protocols. CTAP2.0 - Fallback to 1
1609 info.versions = vec![AuthenticatorVersion::U2F_V2, AuthenticatorVersion::FIDO_2_0];
1610 let pin = PinUvAuthProtocol::try_from(&info).unwrap();
1611 assert_eq!(pin.id(), 1);
1612
1613 // No PIN protocols. CTAP2.1 - Fallback to 2
1614 info.versions = vec![AuthenticatorVersion::FIDO_2_1];
1615 let pin = PinUvAuthProtocol::try_from(&info).unwrap();
1616 assert_eq!(pin.id(), 2);
1617
1618 // No PIN protocols. CTAP2.1_PRE - Fallback to 2
1619 info.versions = vec![
1620 AuthenticatorVersion::FIDO_2_0,
1621 AuthenticatorVersion::FIDO_2_1_PRE,
1622 ];
1623 let pin = PinUvAuthProtocol::try_from(&info).unwrap();
1624 assert_eq!(pin.id(), 2);
1625 }
1626
1627 #[test]
1628 #[cfg(feature = "crypto_nss")]
1629 fn test_sign() {
1630 let (good_private, good_public) =
1631 COSEKey::generate(COSEAlgorithm::ES256).expect("could not generate a key pair");
1632 let good_spki = match good_public.key {
1633 COSEKeyType::EC2(ref x) => x.der_spki().expect("could not serialize public key"),
1634 _ => unreachable!(),
1635 };
1636
1637 let good_data = vec![1, 2, 3, 4, 5, 6, 7, 8];
1638 let good_signature =
1639 ecdsa_p256_sha256_sign_raw(&good_private, &good_data).expect("could not sign");
1640 let good_signature2 =
1641 ecdsa_p256_sha256_sign_raw(&good_private, &good_data).expect("could not sign");
1642
1643 // Signing is randomized
1644 assert_ne!(good_signature, good_signature2);
1645
1646 // Good signature verifies
1647 assert!(test_ecdsa_p256_sha256_verify_raw(&good_spki, &good_signature, &good_data).is_ok());
1648
1649 // Wrong data does not verify
1650 let other_data = vec![0, 0, 0, 0, 5, 6, 7, 8];
1651 assert!(
1652 test_ecdsa_p256_sha256_verify_raw(&good_spki, &good_signature, &other_data).is_err()
1653 );
1654
1655 // Wrong signature does not verify
1656 let other_signature =
1657 ecdsa_p256_sha256_sign_raw(&good_private, &other_data).expect("could not sign");
1658 assert!(
1659 test_ecdsa_p256_sha256_verify_raw(&good_spki, &other_signature, &good_data).is_err()
1660 );
1661
1662 // Wrong key does not verify
1663 let (_, other_public) =
1664 COSEKey::generate(COSEAlgorithm::ES256).expect("could not generate a key pair");
1665 let other_spki = match other_public.key {
1666 COSEKeyType::EC2(ref x) => x.der_spki().expect("could not serialize public key"),
1667 _ => unreachable!(),
1668 };
1669 assert!(
1670 test_ecdsa_p256_sha256_verify_raw(&other_spki, &good_signature, &good_data).is_err()
1671 );
1672 }
1673 }