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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
* Copyright (c) 2022 The NAMIB Project Developers.
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*
* SPDX-License-Identifier: MIT OR Apache-2.0
*/
//! Contains methods for [encrypting](encrypt_access_token), [decrypting](decrypt_access_token),
//! [signing](sign_access_token) and [verifying](verify_access_token) access tokens.
//!
//! **NOTE: The APIs in this module are experimental and likely to change in the future!**
//! This is due to the COSE support being very basic right now (e.g. only `CoseEncrypt0` instead of
//! `CoseEncrypt`) and due to the APIs needing to be "battle-tested" in active use.
//! Builders will also most likely be added as well due to a lot of optional arguments present
//! in the functions at the moment.
//!
//! In order to use any of these methods, you will need to provide a cipher which handles
//! the cryptographic operations by implementing both [`CoseCipherCommon`] (which sets
//! necessary headers) and either [`CoseEncrypt0Cipher`], [`CoseMac0Cipher`] or [`CoseSign1Cipher`],
//! depending on the intended operation. See the respective traits for details.
//!
//! # Example
//! The following shows how to create and sign an access token (assuming a cipher implementing
//! both [`CoseSign1Cipher`] and [`CoseCipherCommon`] exists in variable `cipher`):
//! ```
//! # use ciborium::value::Value;
//! # use coset::{Header, Label};
//! # use coset::cwt::{ClaimsSetBuilder, Timestamp};
//! # use coset::iana::{Algorithm, CwtClaimName};
//! # use dcaf::{ToCborMap, CoseCipherCommon, CoseSign1Cipher, sign_access_token, verify_access_token};
//! # use dcaf::common::cbor_values::{ByteString, ProofOfPossessionKey};
//! # use dcaf::common::cbor_values::ProofOfPossessionKey::PlainCoseKey;
//! # use dcaf::error::{AccessTokenError, CoseCipherError};
//! # struct FakeCrypto {}
//! #
//! # impl CoseCipherCommon for FakeCrypto {
//! # type Error = String;
//! #
//! # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
//! # // We have to later verify these headers really are used.
//! # if let Some(label) = unprotected_header.rest.iter().find(|x| x.0 == Label::Int(47)) {
//! # return Err(CoseCipherError::existing_header_label(&label.0));
//! # }
//! # if protected_header.alg != None {
//! # return Err(CoseCipherError::existing_header("alg"));
//! # }
//! # unprotected_header.rest.push((Label::Int(47), Value::Null));
//! # protected_header.alg = Some(coset::Algorithm::Assigned(Algorithm::Direct));
//! # Ok(())
//! # }
//! # }
//! #
//! # /// Implements basic operations from the [`CoseSign1Cipher`] trait without actually using any
//! # /// "real" cryptography.
//! # /// This is purely to be used for testing and obviously offers no security at all.
//! # impl CoseSign1Cipher for FakeCrypto {
//! # fn generate_signature(&mut self, data: &[u8]) -> Vec<u8> {
//! # data.to_vec()
//! # }
//! #
//! # fn verify_signature(&mut self, sig: &[u8], data: &[u8]) -> Result<(), CoseCipherError<Self::Error>> {
//! # if sig != self.generate_signature(data) {
//! # Err(CoseCipherError::VerificationFailure)
//! # } else {
//! # Ok(())
//! # }
//! # }
//! # }
//!
//! # let mut cipher = FakeCrypto {};
//! let key = ProofOfPossessionKey::KeyId(vec![0xDC, 0xAF]);
//! let claims = ClaimsSetBuilder::new()
//! .audience(String::from("coaps://rs.example.com"))
//! .issuer(String::from("coaps://as.example.com"))
//! .claim(CwtClaimName::Cnf, key.to_ciborium_value())
//! .build();
//! let token = sign_access_token(claims, &mut cipher, None, None, None)?;
//! assert!(verify_access_token(&token, &mut cipher, None).is_ok());
//! # Ok::<(), AccessTokenError<String>>(())
//! ```
use crateByteString;
use ;
use ClaimsSet;
use ;
use crate;
/// Provides common operations necessary for other COSE cipher types to function.
///
/// This needs to be implemented if [`CoseEncrypt0Cipher`], [`CoseSign1Cipher`], or
/// [`CoseMac0Cipher`] is to be implemented as well.
///
/// See the documentation of [`header`](CoseCipherCommon::header) for an example.
/// Provides basic operations for encrypting and decrypting COSE structures.
///
/// This will be used by [`encrypt_access_token`] and [`decrypt_access_token`] to apply the
/// corresponding cryptographic operations to the constructed token bytestring.
/// Since [`CoseCipherCommon`] also needs to be implemented, the
/// [`headers` method](CoseCipherCommon::header) can be used to set parameters this cipher requires
/// to be set. If you need to operate on other fields in the token than just the claims,
/// you can use the data type behind this trait for that.
/// The methods provided in this trait accept `&mut self` in case the structure behind it needs to
/// modify internal fields during any cryptographic operation.
///
/// # Example
/// For example, to simply implement the encryption operation as appending the `aad` to the
/// `plaintext` (which you **clearly should not do**, this is just for illustrative purposes),
/// and implementing `decrypt` by verifying that the AAD matches (same warning applies):
/// ```
/// # use coset::Header;
/// # use dcaf::{CoseCipherCommon, CoseEncrypt0Cipher};
/// # use dcaf::error::CoseCipherError;
/// # struct FakeCrypto {};
/// # impl CoseCipherCommon for FakeCrypto {
/// # type Error = String;
/// # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
/// # unimplemented!()
/// # }
/// # }
/// impl CoseEncrypt0Cipher for FakeCrypto {
/// fn encrypt(&mut self, data: &[u8], aad: &[u8]) -> Vec<u8> {
/// // We simply put AAD behind the data and call it a day.
/// let mut result: Vec<u8> = Vec::new();
/// result.append(&mut data.to_vec());
/// result.append(&mut aad.to_vec());
/// result
/// }
///
/// fn decrypt(&mut self, ciphertext: &[u8], aad: &[u8]) -> Result<Vec<u8>, CoseCipherError<Self::Error>> {
/// // Now we just split off the AAD we previously put at the end of the data.
/// // We return an error if it does not match.
/// if ciphertext.len() < aad.len() {
/// return Err(CoseCipherError::Other("Encrypted data must be at least as long as AAD!".to_string()));
/// }
/// let mut result: Vec<u8> = ciphertext.to_vec();
/// let aad_result = result.split_off(ciphertext.len() - aad.len());
/// if aad != aad_result {
/// Err(CoseCipherError::DecryptionFailure)
/// } else {
/// Ok(result)
/// }
/// }
/// }
///
/// let mut cipher = FakeCrypto{};
/// let data = vec![0xDC, 0xAF];
/// let aad = vec![42];
/// let encrypted = cipher.encrypt(&data, &aad);
/// assert_eq!(cipher.decrypt(&encrypted, &aad)?, data);
/// # Ok::<(), CoseCipherError<String>>(())
/// ```
/// Provides basic operations for signing and verifying COSE structures.
///
/// This will be used by [`sign_access_token`] and [`verify_access_token`] to apply the
/// corresponding cryptographic operations to the constructed token bytestring.
/// Since [`CoseCipherCommon`] also needs to be implemented, the
/// [`headers` method](CoseCipherCommon::header) can be used to set parameters this cipher requires
/// to be set. If you need to operate on other fields in the token than just the claims,
/// you can use the data type behind this trait for that.
/// The methods provided in this trait accept `&mut self` in case the structure behind it needs to
/// modify internal fields during any cryptographic operation.
///
/// # Example
/// For example, to simply implement the signing operation as the identity function
/// (which you **clearly should not do**, this is just for illustrative purposes):
/// ```
/// # use coset::Header;
/// # use dcaf::{CoseCipherCommon, CoseSign1Cipher};
/// # use dcaf::error::CoseCipherError;
/// # struct FakeSigner {};
/// # impl CoseCipherCommon for FakeSigner {
/// # type Error = String;
/// # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
/// # unimplemented!()
/// # }
/// # }
/// impl CoseSign1Cipher for FakeSigner {
/// fn generate_signature(&mut self, target: &[u8]) -> Vec<u8> {
/// target.to_vec()
/// }
///
/// fn verify_signature(&mut self, signature: &[u8], signed_data: &[u8]) -> Result<(), CoseCipherError<Self::Error>> {
/// if signature != self.generate_signature(signed_data) {
/// Err(CoseCipherError::VerificationFailure)
/// } else {
/// Ok(())
/// }
/// }
/// }
///
/// let mut signer = FakeSigner {};
/// let signature = signer.generate_signature(&vec![0xDC, 0xAF]);
/// assert!(signer.verify_signature(&signature, &vec![0xDC, 0xAF]).is_ok());
/// assert!(signer.verify_signature(&signature, &vec![0xDE, 0xAD]).is_err());
/// ```
/// Provides basic operations for generating and verifying MAC tags for COSE structures.
///
/// This trait is currently not used by any access token function.
///
/// # Example
/// For example, to simply implement the signing operation as the identity function
/// (which you **clearly should not do**, this is just for illustrative purposes):
/// ```
/// # use coset::Header;
/// # use dcaf::{CoseCipherCommon, CoseMac0Cipher, CoseSign1Cipher};
/// # use dcaf::error::CoseCipherError;
/// # struct FakeTagger {};
/// # impl CoseCipherCommon for FakeTagger {
/// # type Error = String;
/// # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
/// # unimplemented!()
/// # }
/// # }
/// impl CoseMac0Cipher for FakeTagger {
/// fn generate_tag(&mut self, target: &[u8]) -> Vec<u8> {
/// target.to_vec()
/// }
///
/// fn verify_tag(&mut self, tag: &[u8], signed_data: &[u8]) -> Result<(), CoseCipherError<Self::Error>> {
/// if tag != self.generate_tag(signed_data) {
/// Err(CoseCipherError::VerificationFailure)
/// } else {
/// Ok(())
/// }
/// }
/// }
///
/// let mut tagger = FakeTagger {};
/// let tag = tagger.generate_tag(&vec![0xDC, 0xAF]);
/// assert!(tagger.verify_tag(&tag, &vec![0xDC, 0xAF]).is_ok());
/// assert!(tagger.verify_tag(&tag, &vec![0xDE, 0xAD]).is_err());
/// ```
/// Creates new headers if `unprotected_header` or `protected_header` is `None`, respectively,
/// and passes them to the `cipher`'s `header` function, returning the mutated result.
/// Encrypts the given `claims` with the given headers and `aad` using `cipher` for cryptography,
/// returning the token as a serialized bytestring of the [`CoseEncrypt0`] structure.
///
/// # Errors
/// - When there's a [`CoseError`](coset::CoseError) while serializing the given `claims` to CBOR.
/// - When there's a [`CoseError`](coset::CoseError) while serializing the [`CoseEncrypt0`] structure.
///
/// # Example
/// For example, assuming we have a [`CoseEncrypt0Cipher`] in `cipher`,
/// have a [`ProofOfPossessionKey`](crate::common::cbor_values::ProofOfPossessionKey)
/// in `key` and want to associate this key with the access token we are about to create and encrypt:
/// ```
/// # use coset::cwt::ClaimsSetBuilder;
/// # use coset::Header;
/// # use coset::iana::CwtClaimName;
/// # use dcaf::{ToCborMap, CoseCipherCommon, CoseEncrypt0Cipher, decrypt_access_token, encrypt_access_token, sign_access_token, verify_access_token};
/// # use dcaf::common::cbor_values::{ByteString, ProofOfPossessionKey};
/// # use dcaf::error::{AccessTokenError, CoseCipherError};
/// # struct FakeCrypto {};
/// # impl CoseCipherCommon for FakeCrypto {
/// # type Error = String;
/// # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
/// # Ok(())
/// # }
/// # }
/// # impl CoseEncrypt0Cipher for FakeCrypto {
/// # fn encrypt(&mut self, data: &[u8], aad: &[u8]) -> Vec<u8> {
/// # let mut result: Vec<u8> = Vec::new();
/// # result.append(&mut data.to_vec());
/// # result.append(&mut aad.to_vec());
/// # result
/// # }
/// #
/// # fn decrypt(&mut self, ciphertext: &[u8], aad: &[u8]) -> Result<Vec<u8>, CoseCipherError<Self::Error>> {
/// # if ciphertext.len() < aad.len() {
/// # return Err(CoseCipherError::Other("Encrypted data must be at least as long as AAD!".to_string()));
/// # }
/// # let mut result: Vec<u8> = ciphertext.to_vec();
/// # let aad_result = result.split_off(ciphertext.len() - aad.len());
/// # if aad != aad_result {
/// # Err(CoseCipherError::DecryptionFailure)
/// # } else {
/// # Ok(result)
/// # }
/// # }
/// # }
/// # let mut cipher = FakeCrypto{};
/// # let key = ProofOfPossessionKey::KeyId(vec![0xDC, 0xAF]);
/// let claims = ClaimsSetBuilder::new()
/// .audience(String::from("coaps://rs.example.com"))
/// .issuer(String::from("coaps://as.example.com"))
/// .claim(CwtClaimName::Cnf, key.to_ciborium_value())
/// .build();
/// let token: ByteString = encrypt_access_token(claims.clone(), &mut cipher, None, None, None)?;
/// assert_eq!(decrypt_access_token(&token, &mut cipher, None)?, claims);
/// # Ok::<(), AccessTokenError<String>>(())
/// ```
/// Signs the given `claims` with the given headers and `aad` using `cipher` for cryptography,
/// returning the token as a serialized bytestring of the [`CoseSign1`] structure.
///
/// # Errors
/// - When there's a [`CoseError`](coset::CoseError) while serializing the given `claims` to CBOR.
/// - When there's a [`CoseError`](coset::CoseError) while serializing the [`CoseSign1`] structure.
///
/// # Example
/// For example, assuming we have a [`CoseSign1Cipher`] in `cipher`,
/// have a [`ProofOfPossessionKey`](crate::common::cbor_values::ProofOfPossessionKey)
/// in `key` and want to associate this key with the access token we are about to create and sign:
/// ```
/// # use coset::cwt::ClaimsSetBuilder;
/// # use coset::Header;
/// # use coset::iana::CwtClaimName;
/// # use dcaf::{ToCborMap, CoseCipherCommon, CoseSign1Cipher, encrypt_access_token, sign_access_token, verify_access_token};
/// # use dcaf::common::cbor_values::{ByteString, ProofOfPossessionKey};
/// # use dcaf::error::{AccessTokenError, CoseCipherError};
/// # struct FakeSigner {};
/// # impl CoseCipherCommon for FakeSigner {
/// # type Error = String;
/// # fn header(&self, unprotected_header: &mut Header, protected_header: &mut Header) -> Result<(), CoseCipherError<Self::Error>> {
/// # Ok(())
/// # }
/// # }
/// # impl CoseSign1Cipher for FakeSigner {
/// # fn generate_signature(&mut self, target: &[u8]) -> Vec<u8> {
/// # target.to_vec()
/// # }
/// # fn verify_signature(&mut self, signature: &[u8], signed_data: &[u8]) -> Result<(), CoseCipherError<Self::Error>> {
/// # if signature != self.generate_signature(signed_data) {
/// # Err(CoseCipherError::VerificationFailure)
/// # } else {
/// # Ok(())
/// # }
/// # }
/// # }
/// # let mut cipher = FakeSigner {};
/// # let key = ProofOfPossessionKey::KeyId(vec![0xDC, 0xAF]);
/// let claims = ClaimsSetBuilder::new()
/// .audience(String::from("coaps://rs.example.com"))
/// .issuer(String::from("coaps://as.example.com"))
/// .claim(CwtClaimName::Cnf, key.to_ciborium_value())
/// .build();
/// let token: ByteString = sign_access_token(claims, &mut cipher, None, None, None)?;
/// assert!(verify_access_token(&token, &mut cipher, None).is_ok());
/// # Ok::<(), AccessTokenError<String>>(())
/// ```
/// Returns the headers of the given signed ([`CoseSign1`]), MAC tagged ([`CoseMac0`]),
/// or encrypted ([`CoseEncrypt0`]) access token.
///
/// When the given `token` is neither a [`CoseEncrypt0`], [`CoseSign1`], nor a [`CoseMac0`]
/// structure, `None` is returned.
///
/// # Example
/// For example, say you have an access token saved in `token` and want to look at its headers:
/// ```
/// # use dcaf::common::cbor_values::ByteString;
/// # use dcaf::token::get_token_headers;
/// # let token = vec![
/// # 0x84, 0x4b, 0xa2, 0x1, 0x25, 0x4, 0x46, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0xa2, 0x5, 0x4d,
/// # 0x63, 0x68, 0x98, 0x99, 0x4f, 0xf0, 0xec, 0x7b, 0xfc, 0xf6, 0xd3, 0xf9, 0x5b, 0x18, 0x2f, 0xf6,
/// # 0x58, 0x20, 0xa1, 0x8, 0xa3, 0x1, 0x4, 0x2, 0x46, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x20,
/// # 0x51, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42,
/// # 0x71, 0x8, 0x58, 0x40, 0x84, 0x6a, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x31,
/// # 0x4b, 0xa2, 0x1, 0x25, 0x4, 0x46, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x45, 0x1, 0x2, 0x3, 0x4,
/// # 0x5, 0x58, 0x20, 0xa1, 0x8, 0xa3, 0x1, 0x4, 0x2, 0x46, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x20,
/// # 0x51, 0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c, 0x14, 0x91, 0xbe, 0x3a, 0x76, 0xdc, 0xea, 0x6c, 0x42,
/// # 0x71, 0x8];
/// if let Some((unprotected_header, protected_header)) = get_token_headers(&token) {
/// assert_eq!(protected_header.header.key_id, vec![0x84, 0x9b, 0x57, 0x86, 0x45, 0x7c])
/// } else {
/// unreachable!("Example token should be valid.")
/// }
/// ```
/// Verifies the given `token` and `aad` using `verifier` for cryptography,
/// returning an error in case it could not be verified.
///
/// NOTE: Protected headers are not verified as of now.
///
/// For an example, see the documentation of [`sign_access_token`].
///
/// # Errors
/// - When there's a [`CoseError`](coset::CoseError) while deserializing the given `token`
/// to a [`CoseSign1`] structure
/// (e.g., if it's not in fact a [`CoseSign1`] structure but rather something else).
/// - When there's a verification error coming from the `verifier`
/// (e.g., if the `token`'s data does not match its signature).
/// Decrypts the given `token` and `aad` using `cipher` for cryptography,
/// returning the decrypted `ClaimsSet`.
///
/// For an example, see the documentation of [`encrypt_access_token`].
///
/// # Errors
/// - When there's a [`CoseError`](coset::CoseError) while deserializing
/// the given `token` to a [`CoseEncrypt0`] structure
/// (e.g., if it's not in fact a [`CoseEncrypt0`] structure but rather something else).
/// - When there's a decryption error coming from the `cipher`.
/// - When the deserialized and decrypted [`CoseEncrypt0`] structure does not contain a valid
/// [`ClaimsSet`].