sequoia_cryptoki/selector.rs
1//! Types related to token and key selectors.
2
3use crate::Token;
4use crate::objects::Backend;
5
6/// Returns true if a value matches a restriction.
7///
8/// The value is compared to the restriction as is. If that doesn't
9/// match, the value is hex encoded and compared to the restriction.
10fn eq_raw_or_hex(field: &str, value: Option<&[u8]>, restriction: Option<&str>) -> bool {
11 tracer!(false, "cmp_raw_and_hex");
12
13 t!("Checking {}: have restriction: {:?}, value: {:02x?} ({:?})",
14 field, restriction, value, value.map(|v| String::from_utf8_lossy(v)));
15
16 let matches = match (value, restriction) {
17 (Some(value), Some(restriction)) => {
18 if restriction.as_bytes() == value {
19 t!("Raw value matches restriction.");
20 true
21 } else if value.len() * 2 == restriction.len()
22 && restriction.chars()
23 .all(|c| c.is_ascii_hexdigit())
24 {
25 // Try doing a hex comparison.
26 t!("Restriction appears to be hex, trying hex comparison.");
27
28 // XXX: Avoid allocating memory.
29
30 // The (current) implementation of the Rust standard
31 // library's eq_ignore_ascii_case lowercases the
32 // characters. Avoid the conversion by using
33 // lower-case hex.
34 let value_hex = value.iter()
35 .map(|x| format!("{:02x}", x))
36 .collect::<Vec<String>>()
37 .join("");
38
39 restriction.eq_ignore_ascii_case(&value_hex)
40 } else {
41 false
42 }
43 }
44 (None, Some(_)) => {
45 // The object doesn't have a value, but we have a
46 // restriction: not a match.
47 t!("Restriction, but no value => no match");
48 false
49 }
50 (_, None) => {
51 // We don't have a restriction: always a match.
52 t!("No restriction => match");
53 true
54 }
55 };
56
57 matches
58}
59
60/// Selects tokens with the specified identifier.
61#[derive(Debug, Clone)]
62pub struct TokenSelector {
63 /// Selects the named backend.
64 ///
65 /// Backends are usually specified by their full path, e.g.,
66 /// `/usr/lib/x86_64-linux-gnu/libykcs11.so.2`. This matches on
67 /// the full path, on the filename, the filename with each
68 /// trailing component stripped, i.e., `libykcs11.so.2`,
69 /// `libykcs11.so`, and `libykcs11`, and the filename with any
70 /// initial `lib` prefix and all trailing components striped,
71 /// i.e., `ykcs11`.
72 pub backend: Option<String>,
73
74 /// Selects the token in the specified slot.
75 pub slot: Option<u64>,
76
77 /// Selects tokens with the specified label.
78 ///
79 /// The user normally sets the token's label when it is
80 /// initialized.
81 ///
82 /// The value of the restriction is compared to both the token's
83 /// raw label and the label encoded in hex. This allows matching
84 /// labels with non-printable characters.
85 pub token_label: Option<String>,
86
87 /// Selects tokens with the specified serial number.
88 ///
89 /// The serial number is set when the token is initialized.
90 ///
91 /// The value of the restriction is compared to both the token's
92 /// raw serial number and the serial number encoded in hex. This
93 /// allows matching serial numbers with non-printable characters.
94 pub token_serial_number: Option<String>,
95}
96
97impl TokenSelector {
98 /// Returns an unconstrained `TokenSelector`.
99 ///
100 /// This matches all tokens.
101 pub fn unconstrained() -> Self {
102 Self {
103 backend: None,
104 slot: None,
105 token_label: None,
106 token_serial_number: None,
107 }
108 }
109
110 /// Returns the argument and value as a string, e.g., `--slot 1`.
111 pub fn args(&self) -> String {
112 let mut parts = Vec::with_capacity(2);
113
114 if let Some(value) = self.backend.as_ref() {
115 parts.push("--backend");
116 parts.push(value);
117 }
118 let slot_;
119 if let Some(value) = self.slot {
120 parts.push("--slot");
121 slot_ = format!("{}", value);
122 parts.push(&slot_[..]);
123 }
124 if let Some(value) = self.token_label.as_ref() {
125 parts.push("--token-label");
126 parts.push(value);
127 }
128 if let Some(value) = self.token_serial_number.as_ref() {
129 parts.push("--token-serial-number");
130 parts.push(value);
131 }
132
133 if parts.is_empty() {
134 "<empty selector>".to_string()
135 } else {
136 parts.join(" ")
137 }
138 }
139
140 /// Returns `true` if the selector has any restrictions on the
141 /// backend.
142 ///
143 /// A selector without restrictions matches everything.
144 pub fn has_backend_restrictions(&self) -> bool {
145 self.backend.is_some()
146 }
147
148 /// Returns `true` if the selector has any restrictions on the
149 /// token.
150 ///
151 /// A selector without restrictions matches everything.
152 pub fn has_token_restrictions(&self) -> bool {
153 self.slot.is_some()
154 || self.token_label.is_some()
155 || self.token_serial_number.is_some()
156 }
157
158 /// Returns `true` if the selector has any restrictions.
159 ///
160 /// A selector without restrictions matches everything.
161 pub fn has_restrictions(&self) -> bool {
162 self.has_backend_restrictions()
163 || self.has_token_restrictions()
164 }
165
166 /// Returns the backend restriction, if any.
167 pub fn backend(&self) -> Option<&str> {
168 self.backend.as_deref()
169 }
170
171 /// Returns `true` if the selector matches the `backend`.
172 ///
173 /// If the selector does not restrict the backend, then this
174 /// returns `true`.
175 pub fn backend_matches(&self, backend: &Backend) -> bool {
176 if let Some(backend_restriction) = self.backend() {
177 backend.is_lib(backend_restriction)
178 } else {
179 // No selector = no restriction.
180 true
181 }
182 }
183
184 /// Returns the slot restriction, if any.
185 pub fn slot(&self) -> Option<u64> {
186 self.slot
187 }
188
189 /// Returns `true` if the selector matches the specified slot.
190 ///
191 /// If the selector does not restrict the slot, then this returns
192 /// `true`.
193 pub fn slot_matches(&self, slot: u64) -> bool {
194 if let Some(slot_restriction) = self.slot() {
195 slot_restriction == slot
196 } else {
197 // Label not specified. No restriction.
198 true
199 }
200 }
201
202 /// Returns the token label restriction, if any.
203 pub fn token_label(&self) -> Option<&str> {
204 self.token_label.as_deref()
205 }
206
207 /// Returns `true` if the selector matches the specified token's
208 /// label.
209 ///
210 /// If the selector does not restrict the token's label, then this
211 /// returns `true`.
212 ///
213 /// The value of the restriction is compared to both the object's
214 /// raw label and the label encoded in hex. This allows matching
215 /// labels with non-printable characters.
216 pub fn token_label_matches(&self, label: &str) -> bool {
217 eq_raw_or_hex("token label",
218 Some(label.as_bytes()),
219 self.token_label())
220 }
221
222 /// Returns the token's serial number restriction, if any.
223 pub fn token_serial_number(&self) -> Option<&str> {
224 self.token_serial_number.as_deref()
225 }
226
227 /// Returns `true` if the selector matches the specified token's
228 /// serial number.
229 ///
230 /// If the selector does not restrict the token's serial number,
231 /// then this returns `true`.
232 ///
233 /// The value of the restriction is compared to both the token's
234 /// raw serial number and the serial number encoded in hex. This
235 /// allows matching on serial numbers with non-printable
236 /// characters.
237 pub fn token_serial_number_matches(&self, serial_number: &str) -> bool {
238 eq_raw_or_hex("token serial number",
239 Some(serial_number.as_bytes()),
240 self.token_serial_number())
241 }
242}
243
244impl From<&Token> for TokenSelector {
245 fn from(token: &Token) -> TokenSelector {
246 TokenSelector {
247 backend: Some(token.backend().lib_str.clone()),
248 slot: None,
249 token_label: Some(token.info().label().to_string()),
250 token_serial_number: Some(token.info().serial_number().to_string()),
251 }
252 }
253}
254
255/// Selects keys with the specified identifier.
256#[derive(Debug, Clone)]
257pub struct KeySelector {
258 /// Selects a token.
259 pub token: TokenSelector,
260
261 /// Selects keys with the specified unique ID.
262 ///
263 /// An object's ID corresponds to its unique ID attribute, which
264 /// was introduced in PKCS#11 3.0 in 2020.
265 ///
266 /// The value of the restriction is compared to both the key's raw
267 /// unique ID and the unique ID encoded in hex. This allows
268 /// matching unique IDs with non-printable characters.
269 ///
270 /// If a key does not have a unique ID, then it doesn't match a
271 /// restriction on the key's unique ID.
272 pub key_unique_id: Option<String>,
273
274 /// Selects keys with the specified label.
275 ///
276 /// An key's label correspond to its label attribute, which is
277 /// normally set by the user when the key is created.
278 ///
279 /// The value of the restriction is compared to both the key's raw
280 /// label and the label encoded in hex. This allows matching
281 /// labels with non-printable characters.
282 ///
283 /// If a key does not have a label, then it doesn't match a
284 /// restriction on the label.
285 pub key_label: Option<String>,
286
287 /// Selects keys with the specified ID.
288 ///
289 /// An object's ID is usually set by the application when the key
290 /// is created.
291 ///
292 /// The value of the restriction is compared to both the key's raw
293 /// ID and the ID encoded in hex. This allows matching IDs with
294 /// non-printable characters.
295 ///
296 /// If a key does not have an ID, then it doesn't match a
297 /// restriction on the key's ID.
298 pub key_id: Option<String>,
299
300 /// Selects keys with the specified URL.
301 ///
302 /// An object's URL is usually set by the application when the key
303 /// is created.
304 ///
305 /// The value of the restriction is compared to both the key's raw
306 /// URL and the URL encoded in hex. This allows matching URLs
307 /// with non-printable characters.
308 ///
309 /// If a key does not have a URL, then it doesn't match a
310 /// restriction on the key's URL.
311 pub key_url: Option<String>,
312}
313
314impl From<&Token> for KeySelector {
315 fn from(token: &Token) -> KeySelector {
316 KeySelector {
317 token: token.into(),
318 key_unique_id: None,
319 key_label: None,
320 key_id: None,
321 key_url: None,
322 }
323 }
324}
325
326impl KeySelector {
327 /// Returns an unconstrained `KeySelector`.
328 ///
329 /// This matches all keys on all tokens.
330 pub fn unconstrained() -> Self {
331 Self {
332 token: TokenSelector::unconstrained(),
333 key_unique_id: None,
334 key_label: None,
335 key_id: None,
336 key_url: None,
337 }
338 }
339
340 /// Creates a `KeySelector` from a `TokenSelector`.
341 pub fn from_token_selector(selector: TokenSelector) -> Self {
342 Self {
343 token: selector,
344 key_unique_id: None,
345 key_label: None,
346 key_id: None,
347 key_url: None,
348 }
349 }
350
351 /// Creates a `KeySelector` for a specific label.
352 pub fn from_key_label(key_label: impl Into<String>) -> Self {
353 Self {
354 token: TokenSelector {
355 backend: None,
356 slot: None,
357 token_serial_number: None,
358 token_label: None,
359 },
360 key_unique_id: None,
361 key_label: Some(key_label.into()),
362 key_id: None,
363 key_url: None,
364 }
365 }
366
367 /// Creates a `KeySelector` for a specific key ID.
368 pub fn from_key_id(key_id: impl Into<String>) -> Self {
369 Self {
370 token: TokenSelector {
371 backend: None,
372 slot: None,
373 token_serial_number: None,
374 token_label: None,
375 },
376 key_unique_id: None,
377 key_label: None,
378 key_id: Some(key_id.into()),
379 key_url: None,
380 }
381 }
382
383 /// Returns `true` if the selector has any restrictions on the
384 /// backend.
385 ///
386 /// A selector without restrictions matches all backends.
387 pub fn has_backend_restrictions(&self) -> bool {
388 self.token.has_backend_restrictions()
389 }
390
391 /// Returns `true` if the selector has any restrictions on the
392 /// token.
393 ///
394 /// A selector without restrictions matches all tokens.
395 pub fn has_token_restrictions(&self) -> bool {
396 self.token.has_token_restrictions()
397 }
398
399 /// Returns `true` if the selector has any restrictions on the
400 /// key.
401 ///
402 /// A selector without restrictions matches all keys.
403 pub fn has_key_restrictions(&self) -> bool {
404 self.key_unique_id.is_some()
405 || self.key_label.is_some()
406 || self.key_id.is_some()
407 || self.key_url.is_some()
408 }
409
410 /// Returns `true` if the selector has any restrictions.
411 ///
412 /// A selector without restrictions matches everything.
413 pub fn has_restrictions(&self) -> bool {
414 self.has_backend_restrictions()
415 || self.has_token_restrictions()
416 || self.has_key_restrictions()
417 }
418
419 /// Returns the backend restriction, if any.
420 pub fn backend(&self) -> Option<&str> {
421 self.token.backend()
422 }
423
424 /// Returns `true` if the selector matches the `backend`.
425 ///
426 /// If the selector does not restrict the backend, this returns
427 /// `true`.
428 pub fn backend_matches(&self, backend: &Backend) -> bool {
429 self.token.backend_matches(backend)
430 }
431
432 /// Returns the slot restriction, if any.
433 pub fn slot(&self) -> Option<u64> {
434 self.token.slot()
435 }
436
437 /// Returns `true` if the selector matches the specified slot.
438 ///
439 /// If the selector does not restrict the slot, this returns
440 /// `true`.
441 pub fn slot_matches(&self, slot: u64) -> bool {
442 self.token.slot_matches(slot)
443 }
444
445 /// Returns the token label restriction, if any.
446 pub fn token_label(&self) -> Option<&str> {
447 self.token.token_label()
448 }
449
450 /// Returns `true` if the selector matches the specified token's
451 /// label.
452 ///
453 /// If the selector does not restrict the token's label, this
454 /// returns `true`.
455 pub fn token_label_matches(&self, label: &str) -> bool {
456 self.token.token_label_matches(label)
457 }
458
459 /// Returns the token serial number restriction, if any.
460 pub fn token_serial_number(&self) -> Option<&str> {
461 self.token.token_serial_number()
462 }
463
464 /// Returns `true` if the selector matches the specified token's
465 /// serial number.
466 ///
467 /// If the selector does not restrict the token's serial number,
468 /// this returns `true`.
469 pub fn token_serial_number_matches(&self, serial_number: &str) -> bool {
470 self.token.token_serial_number_matches(serial_number)
471 }
472
473 /// Returns the key unique ID restriction, if any.
474 pub fn key_unique_id(&self) -> Option<&str> {
475 self.key_unique_id.as_deref()
476 }
477
478 /// Returns `true` if the selector matches the specified key's
479 /// unique ID.
480 ///
481 /// If the selector does not restrict the key's unique ID, this
482 /// returns `true`.
483 ///
484 /// The value is compared to the restriction as is. If that
485 /// doesn't match, the value is hex encoded and compared to the
486 /// restriction. This allows matching on unique IDs with
487 /// non-printable characters.
488 pub fn key_unique_id_matches(&self, key_unique_id: Option<&[u8]>) -> bool {
489 eq_raw_or_hex("key unique ID",
490 key_unique_id.as_deref(), self.key_unique_id())
491 }
492
493 /// Returns the key label restriction, if any.
494 pub fn key_label(&self) -> Option<&str> {
495 self.key_label.as_deref()
496 }
497
498 /// Returns `true` if the selector matches the specified key's
499 /// label.
500 ///
501 /// If the selector does not restrict the key's label, then this
502 /// returns `true`.
503 ///
504 /// The value is compared to the restriction as is. If that
505 /// doesn't match, the value is hex encoded and compared to the
506 /// restriction. This allows matching on labels with
507 /// non-printable characters.
508 pub fn key_label_matches(&self, key_label: Option<&[u8]>) -> bool {
509 eq_raw_or_hex("key label", key_label.as_deref(), self.key_label())
510 }
511
512 /// Returns the key ID restriction, if any.
513 pub fn key_id(&self) -> Option<&str> {
514 self.key_id.as_deref()
515 }
516
517 /// Returns `true` if the selector matches the specified key ID.
518 ///
519 /// If the selector does not restrict the key ID, then this
520 /// returns `true`.
521 ///
522 /// The value is compared to the restriction as is. If that
523 /// doesn't match, the value is hex encoded and compared to the
524 /// restriction. This allows matching on key IDs with
525 /// non-printable characters.
526 pub fn key_id_matches(&self, key_id: Option<&[u8]>) -> bool {
527 eq_raw_or_hex("key ID", key_id.as_deref(), self.key_id())
528 }
529
530 /// Returns the key URL restriction, if any.
531 pub fn key_url(&self) -> Option<&str> {
532 self.key_url.as_deref()
533 }
534
535 /// Returns `true` if the selector matches the specified key URL.
536 ///
537 /// If the selector does not restrict the key URL, then this
538 /// returns `true`.
539 ///
540 /// The value is compared to the restriction as is. If that
541 /// doesn't match, the value is hex encoded and compared to the
542 /// restriction. This allows matching on URLs with non-printable
543 /// characters.
544 pub fn key_url_matches(&self, key_url: Option<&[u8]>) -> bool {
545 eq_raw_or_hex("key URL", key_url.as_deref(), self.key_url())
546 }
547
548 /// Returns the argument and value as a string, e.g., "--slot 1".
549 pub fn args(&self) -> String {
550 let mut parts = Vec::with_capacity(2);
551
552 if let Some(value) = self.token.backend.as_ref() {
553 parts.push("--backend");
554 parts.push(value);
555 }
556 let slot_;
557 if let Some(value) = self.token.slot {
558 parts.push("--slot");
559 slot_ = format!("{}", value);
560 parts.push(&slot_[..]);
561 }
562 if let Some(value) = self.token.token_serial_number.as_ref() {
563 parts.push("--token-serial-number");
564 parts.push(value);
565 }
566 if let Some(value) = self.token.token_label.as_ref() {
567 parts.push("--token-label");
568 parts.push(value);
569 }
570 if let Some(value) = self.key_unique_id.as_ref() {
571 parts.push("--key-unique-id");
572 parts.push(value);
573 }
574 if let Some(value) = self.key_label.as_ref() {
575 parts.push("--key-label");
576 parts.push(value);
577 }
578 if let Some(value) = self.key_id.as_ref() {
579 parts.push("--key-id");
580 parts.push(value);
581 }
582 if let Some(value) = self.key_url.as_ref() {
583 parts.push("--key-url");
584 parts.push(value);
585 }
586
587 if parts.is_empty() {
588 "<empty selector>".to_string()
589 } else {
590 parts.join(" ")
591 }
592 }
593}