sequoia-cryptoki 0.1.1

Library for working with PKCS#11 devices (cryptokis) from Sequoia
Documentation
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
//! Types related to token and key selectors.

use crate::Token;
use crate::objects::Backend;

/// Returns true if a value matches a restriction.
///
/// The value is compared to the restriction as is.  If that doesn't
/// match, the value is hex encoded and compared to the restriction.
fn eq_raw_or_hex(field: &str, value: Option<&[u8]>, restriction: Option<&str>) -> bool {
    tracer!(false, "cmp_raw_and_hex");

    t!("Checking {}: have restriction: {:?}, value: {:02x?} ({:?})",
       field, restriction, value, value.map(|v| String::from_utf8_lossy(v)));

    let matches = match (value, restriction) {
        (Some(value), Some(restriction)) => {
            if restriction.as_bytes() == value {
                t!("Raw value matches restriction.");
                true
            } else if value.len() * 2 == restriction.len()
                && restriction.chars()
                     .all(|c| c.is_ascii_hexdigit())
            {
                // Try doing a hex comparison.
                t!("Restriction appears to be hex, trying hex comparison.");

                // XXX: Avoid allocating memory.

                // The (current) implementation of the Rust standard
                // library's eq_ignore_ascii_case lowercases the
                // characters.  Avoid the conversion by using
                // lower-case hex.
                let value_hex = value.iter()
                    .map(|x| format!("{:02x}", x))
                    .collect::<Vec<String>>()
                    .join("");

                restriction.eq_ignore_ascii_case(&value_hex)
            } else {
                false
            }
        }
        (None, Some(_)) => {
            // The object doesn't have a value, but we have a
            // restriction: not a match.
            t!("Restriction, but no value => no match");
            false
        }
        (_, None) => {
            // We don't have a restriction: always a match.
            t!("No restriction => match");
            true
        }
    };

    matches
}

/// Selects tokens with the specified identifier.
#[derive(Debug, Clone)]
pub struct TokenSelector {
    /// Selects the named backend.
    ///
    /// Backends are usually specified by their full path, e.g.,
    /// `/usr/lib/x86_64-linux-gnu/libykcs11.so.2`.  This matches on
    /// the full path, on the filename, the filename with each
    /// trailing component stripped, i.e., `libykcs11.so.2`,
    /// `libykcs11.so`, and `libykcs11`, and the filename with any
    /// initial `lib` prefix and all trailing components striped,
    /// i.e., `ykcs11`.
    pub backend: Option<String>,

    /// Selects the token in the specified slot.
    pub slot: Option<u64>,

    /// Selects tokens with the specified label.
    ///
    /// The user normally sets the token's label when it is
    /// initialized.
    ///
    /// The value of the restriction is compared to both the token's
    /// raw label and the label encoded in hex.  This allows matching
    /// labels with non-printable characters.
    pub token_label: Option<String>,

    /// Selects tokens with the specified serial number.
    ///
    /// The serial number is set when the token is initialized.
    ///
    /// The value of the restriction is compared to both the token's
    /// raw serial number and the serial number encoded in hex.  This
    /// allows matching serial numbers with non-printable characters.
    pub token_serial_number: Option<String>,
}

impl TokenSelector {
    /// Returns an unconstrained `TokenSelector`.
    ///
    /// This matches all tokens.
    pub fn unconstrained() -> Self {
        Self {
            backend: None,
            slot: None,
            token_label: None,
            token_serial_number: None,
        }
    }

    /// Returns the argument and value as a string, e.g., `--slot 1`.
    pub fn args(&self) -> String {
        let mut parts = Vec::with_capacity(2);

        if let Some(value) = self.backend.as_ref() {
            parts.push("--backend");
            parts.push(value);
        }
        let slot_;
        if let Some(value) = self.slot {
            parts.push("--slot");
            slot_ = format!("{}", value);
            parts.push(&slot_[..]);
        }
        if let Some(value) = self.token_label.as_ref() {
            parts.push("--token-label");
            parts.push(value);
        }
        if let Some(value) = self.token_serial_number.as_ref() {
            parts.push("--token-serial-number");
            parts.push(value);
        }

        if parts.is_empty() {
            "<empty selector>".to_string()
        } else {
            parts.join(" ")
        }
    }

    /// Returns `true` if the selector has any restrictions on the
    /// backend.
    ///
    /// A selector without restrictions matches everything.
    pub fn has_backend_restrictions(&self) -> bool {
        self.backend.is_some()
    }

    /// Returns `true` if the selector has any restrictions on the
    /// token.
    ///
    /// A selector without restrictions matches everything.
    pub fn has_token_restrictions(&self) -> bool {
        self.slot.is_some()
            || self.token_label.is_some()
            || self.token_serial_number.is_some()
    }

    /// Returns `true` if the selector has any restrictions.
    ///
    /// A selector without restrictions matches everything.
    pub fn has_restrictions(&self) -> bool {
        self.has_backend_restrictions()
            || self.has_token_restrictions()
    }

    /// Returns the backend restriction, if any.
    pub fn backend(&self) -> Option<&str> {
        self.backend.as_deref()
    }

    /// Returns `true` if the selector matches the `backend`.
    ///
    /// If the selector does not restrict the backend, then this
    /// returns `true`.
    pub fn backend_matches(&self, backend: &Backend) -> bool {
        if let Some(backend_restriction) = self.backend() {
            backend.is_lib(backend_restriction)
        } else {
            // No selector = no restriction.
            true
        }
    }

    /// Returns the slot restriction, if any.
    pub fn slot(&self) -> Option<u64> {
        self.slot
    }

    /// Returns `true` if the selector matches the specified slot.
    ///
    /// If the selector does not restrict the slot, then this returns
    /// `true`.
    pub fn slot_matches(&self, slot: u64) -> bool {
        if let Some(slot_restriction) = self.slot() {
            slot_restriction == slot
        } else {
            // Label not specified.  No restriction.
            true
        }
    }

    /// Returns the token label restriction, if any.
    pub fn token_label(&self) -> Option<&str> {
        self.token_label.as_deref()
    }

    /// Returns `true` if the selector matches the specified token's
    /// label.
    ///
    /// If the selector does not restrict the token's label, then this
    /// returns `true`.
    ///
    /// The value of the restriction is compared to both the object's
    /// raw label and the label encoded in hex.  This allows matching
    /// labels with non-printable characters.
    pub fn token_label_matches(&self, label: &str) -> bool {
        eq_raw_or_hex("token label",
                      Some(label.as_bytes()),
                      self.token_label())
    }

    /// Returns the token's serial number restriction, if any.
    pub fn token_serial_number(&self) -> Option<&str> {
        self.token_serial_number.as_deref()
    }

    /// Returns `true` if the selector matches the specified token's
    /// serial number.
    ///
    /// If the selector does not restrict the token's serial number,
    /// then this returns `true`.
    ///
    /// The value of the restriction is compared to both the token's
    /// raw serial number and the serial number encoded in hex.  This
    /// allows matching on serial numbers with non-printable
    /// characters.
    pub fn token_serial_number_matches(&self, serial_number: &str) -> bool {
        eq_raw_or_hex("token serial number",
                      Some(serial_number.as_bytes()),
                      self.token_serial_number())
    }
}

impl From<&Token> for TokenSelector {
    fn from(token: &Token) -> TokenSelector {
        TokenSelector {
            backend: Some(token.backend().lib_str.clone()),
            slot: None,
            token_label: Some(token.info().label().to_string()),
            token_serial_number: Some(token.info().serial_number().to_string()),
        }
    }
}

/// Selects keys with the specified identifier.
#[derive(Debug, Clone)]
pub struct KeySelector {
    /// Selects a token.
    pub token: TokenSelector,

    /// Selects keys with the specified unique ID.
    ///
    /// An object's ID corresponds to its unique ID attribute, which
    /// was introduced in PKCS#11 3.0 in 2020.
    ///
    /// The value of the restriction is compared to both the key's raw
    /// unique ID and the unique ID encoded in hex.  This allows
    /// matching unique IDs with non-printable characters.
    ///
    /// If a key does not have a unique ID, then it doesn't match a
    /// restriction on the key's unique ID.
    pub key_unique_id: Option<String>,

    /// Selects keys with the specified label.
    ///
    /// An key's label correspond to its label attribute, which is
    /// normally set by the user when the key is created.
    ///
    /// The value of the restriction is compared to both the key's raw
    /// label and the label encoded in hex.  This allows matching
    /// labels with non-printable characters.
    ///
    /// If a key does not have a label, then it doesn't match a
    /// restriction on the label.
    pub key_label: Option<String>,

    /// Selects keys with the specified ID.
    ///
    /// An object's ID is usually set by the application when the key
    /// is created.
    ///
    /// The value of the restriction is compared to both the key's raw
    /// ID and the ID encoded in hex.  This allows matching IDs with
    /// non-printable characters.
    ///
    /// If a key does not have an ID, then it doesn't match a
    /// restriction on the key's ID.
    pub key_id: Option<String>,

    /// Selects keys with the specified URL.
    ///
    /// An object's URL is usually set by the application when the key
    /// is created.
    ///
    /// The value of the restriction is compared to both the key's raw
    /// URL and the URL encoded in hex.  This allows matching URLs
    /// with non-printable characters.
    ///
    /// If a key does not have a URL, then it doesn't match a
    /// restriction on the key's URL.
    pub key_url: Option<String>,
}

impl From<&Token> for KeySelector {
    fn from(token: &Token) -> KeySelector {
        KeySelector {
            token: token.into(),
            key_unique_id: None,
            key_label: None,
            key_id: None,
            key_url: None,
        }
    }
}

impl KeySelector {
    /// Returns an unconstrained `KeySelector`.
    ///
    /// This matches all keys on all tokens.
    pub fn unconstrained() -> Self {
        Self {
            token: TokenSelector::unconstrained(),
            key_unique_id: None,
            key_label: None,
            key_id: None,
            key_url: None,
        }
    }

    /// Creates a `KeySelector` from a `TokenSelector`.
    pub fn from_token_selector(selector: TokenSelector) -> Self {
        Self {
            token: selector,
            key_unique_id: None,
            key_label: None,
            key_id: None,
            key_url: None,
        }
    }

    /// Creates a `KeySelector` for a specific label.
    pub fn from_key_label(key_label: impl Into<String>) -> Self {
        Self {
            token: TokenSelector {
                backend: None,
                slot: None,
                token_serial_number: None,
                token_label: None,
            },
            key_unique_id: None,
            key_label: Some(key_label.into()),
            key_id: None,
            key_url: None,
        }
    }

    /// Creates a `KeySelector` for a specific key ID.
    pub fn from_key_id(key_id: impl Into<String>) -> Self {
        Self {
            token: TokenSelector {
                backend: None,
                slot: None,
                token_serial_number: None,
                token_label: None,
            },
            key_unique_id: None,
            key_label: None,
            key_id: Some(key_id.into()),
            key_url: None,
        }
    }

    /// Returns `true` if the selector has any restrictions on the
    /// backend.
    ///
    /// A selector without restrictions matches all backends.
    pub fn has_backend_restrictions(&self) -> bool {
        self.token.has_backend_restrictions()
    }

    /// Returns `true` if the selector has any restrictions on the
    /// token.
    ///
    /// A selector without restrictions matches all tokens.
    pub fn has_token_restrictions(&self) -> bool {
        self.token.has_token_restrictions()
    }

    /// Returns `true` if the selector has any restrictions on the
    /// key.
    ///
    /// A selector without restrictions matches all keys.
    pub fn has_key_restrictions(&self) -> bool {
        self.key_unique_id.is_some()
            || self.key_label.is_some()
            || self.key_id.is_some()
            || self.key_url.is_some()
    }

    /// Returns `true` if the selector has any restrictions.
    ///
    /// A selector without restrictions matches everything.
    pub fn has_restrictions(&self) -> bool {
        self.has_backend_restrictions()
            || self.has_token_restrictions()
            || self.has_key_restrictions()
    }

    /// Returns the backend restriction, if any.
    pub fn backend(&self) -> Option<&str> {
        self.token.backend()
    }

    /// Returns `true` if the selector matches the `backend`.
    ///
    /// If the selector does not restrict the backend, this returns
    /// `true`.
    pub fn backend_matches(&self, backend: &Backend) -> bool {
        self.token.backend_matches(backend)
    }

    /// Returns the slot restriction, if any.
    pub fn slot(&self) -> Option<u64> {
        self.token.slot()
    }

    /// Returns `true` if the selector matches the specified slot.
    ///
    /// If the selector does not restrict the slot, this returns
    /// `true`.
    pub fn slot_matches(&self, slot: u64) -> bool {
        self.token.slot_matches(slot)
    }

    /// Returns the token label restriction, if any.
    pub fn token_label(&self) -> Option<&str> {
        self.token.token_label()
    }

    /// Returns `true` if the selector matches the specified token's
    /// label.
    ///
    /// If the selector does not restrict the token's label, this
    /// returns `true`.
    pub fn token_label_matches(&self, label: &str) -> bool {
        self.token.token_label_matches(label)
    }

    /// Returns the token serial number restriction, if any.
    pub fn token_serial_number(&self) -> Option<&str> {
        self.token.token_serial_number()
    }

    /// Returns `true` if the selector matches the specified token's
    /// serial number.
    ///
    /// If the selector does not restrict the token's serial number,
    /// this returns `true`.
    pub fn token_serial_number_matches(&self, serial_number: &str) -> bool {
        self.token.token_serial_number_matches(serial_number)
    }

    /// Returns the key unique ID restriction, if any.
    pub fn key_unique_id(&self) -> Option<&str> {
        self.key_unique_id.as_deref()
    }

    /// Returns `true` if the selector matches the specified key's
    /// unique ID.
    ///
    /// If the selector does not restrict the key's unique ID, this
    /// returns `true`.
    ///
    /// The value is compared to the restriction as is.  If that
    /// doesn't match, the value is hex encoded and compared to the
    /// restriction.  This allows matching on unique IDs with
    /// non-printable characters.
    pub fn key_unique_id_matches(&self, key_unique_id: Option<&[u8]>) -> bool {
        eq_raw_or_hex("key unique ID",
                      key_unique_id.as_deref(), self.key_unique_id())
    }

    /// Returns the key label restriction, if any.
    pub fn key_label(&self) -> Option<&str> {
        self.key_label.as_deref()
    }

    /// Returns `true` if the selector matches the specified key's
    /// label.
    ///
    /// If the selector does not restrict the key's label, then this
    /// returns `true`.
    ///
    /// The value is compared to the restriction as is.  If that
    /// doesn't match, the value is hex encoded and compared to the
    /// restriction.  This allows matching on labels with
    /// non-printable characters.
    pub fn key_label_matches(&self, key_label: Option<&[u8]>) -> bool {
        eq_raw_or_hex("key label", key_label.as_deref(), self.key_label())
    }

    /// Returns the key ID restriction, if any.
    pub fn key_id(&self) -> Option<&str> {
        self.key_id.as_deref()
    }

    /// Returns `true` if the selector matches the specified key ID.
    ///
    /// If the selector does not restrict the key ID, then this
    /// returns `true`.
    ///
    /// The value is compared to the restriction as is.  If that
    /// doesn't match, the value is hex encoded and compared to the
    /// restriction.  This allows matching on key IDs with
    /// non-printable characters.
    pub fn key_id_matches(&self, key_id: Option<&[u8]>) -> bool {
        eq_raw_or_hex("key ID", key_id.as_deref(), self.key_id())
    }

    /// Returns the key URL restriction, if any.
    pub fn key_url(&self) -> Option<&str> {
        self.key_url.as_deref()
    }

    /// Returns `true` if the selector matches the specified key URL.
    ///
    /// If the selector does not restrict the key URL, then this
    /// returns `true`.
    ///
    /// The value is compared to the restriction as is.  If that
    /// doesn't match, the value is hex encoded and compared to the
    /// restriction.  This allows matching on URLs with non-printable
    /// characters.
    pub fn key_url_matches(&self, key_url: Option<&[u8]>) -> bool {
        eq_raw_or_hex("key URL", key_url.as_deref(), self.key_url())
    }

    /// Returns the argument and value as a string, e.g., "--slot 1".
    pub fn args(&self) -> String {
        let mut parts = Vec::with_capacity(2);

        if let Some(value) = self.token.backend.as_ref() {
            parts.push("--backend");
            parts.push(value);
        }
        let slot_;
        if let Some(value) = self.token.slot {
            parts.push("--slot");
            slot_ = format!("{}", value);
            parts.push(&slot_[..]);
        }
        if let Some(value) = self.token.token_serial_number.as_ref() {
            parts.push("--token-serial-number");
            parts.push(value);
        }
        if let Some(value) = self.token.token_label.as_ref() {
            parts.push("--token-label");
            parts.push(value);
        }
        if let Some(value) = self.key_unique_id.as_ref() {
            parts.push("--key-unique-id");
            parts.push(value);
        }
        if let Some(value) = self.key_label.as_ref() {
            parts.push("--key-label");
            parts.push(value);
        }
        if let Some(value) = self.key_id.as_ref() {
            parts.push("--key-id");
            parts.push(value);
        }
        if let Some(value) = self.key_url.as_ref() {
            parts.push("--key-url");
            parts.push(value);
        }

        if parts.is_empty() {
            "<empty selector>".to_string()
        } else {
            parts.join(" ")
        }
    }
}