sequoia-cryptoki 0.2.0

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
#![allow(dead_code)]

use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, OnceLock};

use tempfile::TempDir;

use sequoia_openpgp as openpgp;
pub use openpgp::Result;
use openpgp::Cert;
use openpgp::crypto::PublicKeyAlgorithm;
use openpgp::policy::StandardPolicy;
use openpgp::types::HashAlgorithm;
use openpgp::types::SymmetricAlgorithm;
use openpgp::packet;
use openpgp::packet::key;

use sequoia_cryptoki::{
    Key,
    KeyCapability,
    TokenSelector,
    dicewords,

    // Some cryptoki imports.
    cryptoki::session::UserType,
    cryptoki::types::AuthPin,
};

mod backend;

/// The Giant Testsuite Lock.
static GTL: Mutex<()> = Mutex::new(());

pub const P: &StandardPolicy = &StandardPolicy::new();

pub const SO_PIN: &str = "123456";
pub const USER_PIN: &str = "1234";

pub const SO_PIN2: &str = "654321";
pub const USER_PIN2: &str = "4321";

pub struct SqCryptoki {
    pub ctx: &'static sequoia_cryptoki::Context,

    /// Serializes all tests.
    gtl_locked: MutexGuard<'static, ()>,

    now: std::time::SystemTime,
}

static BACKEND: OnceLock<(TempDir, sequoia_cryptoki::Context, Box<dyn backend::Backend>)>
    = OnceLock::new();

impl SqCryptoki {
    fn init() -> &'static (TempDir, sequoia_cryptoki::Context, Box<dyn backend::Backend>) {
        let b = BACKEND.get_or_init(|| {
            let state = TempDir::new()
                .expect("can create a temporary directory");

            let backend = backend::init(state.path());

            // Setup the environment.
            for (key, value) in backend.env() {
                // SAFETY: Not safe.  Godspeed.
                eprintln!("Setting ENV {}={}", key, value);
                unsafe {
                    std::env::set_var(key, value);
                }
            }

            let module = match std::env::var("SEQUOIA_CRYPTOKI_MODULE") {
                Ok(module) => module,
                Err(err) => {
                    panic!(
                        "SEQUOIA_CRYPTOKI_MODULE is not set (or invalid): {}.  \
                         Must be set to a PKCS#11 to run the test suite.  \
                         WARNING: any attached tokens will be reinitialized.",
                        err);
                }
            };
            eprintln!("Using PKCS#11 module {}", module);
            let ctx = sequoia_cryptoki::ContextBuilder::new()
                .disable_config_file()
                .add_module(module)
                .build()
                .unwrap();

            (state, ctx, backend)
        });

        b
    }

    fn context() -> &'static sequoia_cryptoki::Context {
        &Self::init().1
    }

    fn backend() -> &'static Box<dyn backend::Backend> {
        &Self::init().2
    }

    /// Allocates the next free slot.
    pub fn allocate_slot(&self) -> u64 {
        Self::backend().allocate_slot()
    }

    /// Creates a new SqCryptoki context in a new, emphemeral home
    /// directory.  The clock is set to the specified time.
    pub fn at(now: std::time::SystemTime) -> Self {
        let gtl_locked = loop {
            match GTL.lock() {
                Ok(lock) => break lock,
                Err(_) => GTL.clear_poison(),
            }
        };
        let ctx = Self::context();

        let config = SqCryptoki {
            ctx,
            gtl_locked,
            now,
        };

        config
    }

    /// Creates a new SqCryptoki context in a new, emphemeral home
    /// directory.  The clock is set to the current time.
    pub fn new() -> Self {
        // The current time.
        let mut now = std::time::SystemTime::now();
        let since_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap();
        now = now - std::time::Duration::new(0, since_epoch.subsec_nanos());

        Self::at(now)
    }

    pub fn finalize(self) -> Result<()> {
        Ok(())
    }

    pub fn algo_supported(algo: &sequoia_cryptoki::PublicKeyAlgorithm) -> bool {
        let backend = Self::backend();
        backend.algo_supported(algo)
    }

    /// Returns the current time.
    pub fn now(&self) -> std::time::SystemTime {
        self.now
    }

    /// Lists the tokens.
    pub fn try_token_list(&self) -> Result<()> {
        todo!()
    }

    /// Lists the tokens.
    pub fn token_list(&self) -> () {
        self.try_token_list()
            .expect("token list should have succeeded")
    }

    /// Initialize or reinitialize a token.
    pub fn try_token_init_(&self, token: TokenSelector,
                           label: Option<&str>, so_pin: &str,
                           pin: &str)
        -> Result<String>
    {
        let token = self.ctx.select_one_token(&token)?;

        let info = token.info();

        if info.token_initialized() {
            eprintln!("Token already initialized, reinitializing.");
        } else {
            eprintln!("Token not yet initialized.  \
                       Performing initial initialization.");
        }

        let new_token_label = label
            .map(|label| label.to_string())
            .unwrap_or_else(|| {
                dicewords::random_words(2).unwrap().join("-")
            });

        // Initialize (or reinitialize) the token.  This deletes all
        // non-indestructible objects!  If the token is uninitialized,
        // then this sets the SO PIN to the specified PIN.  If the token
        // is being reinitialized, the SO PIN must match the SO's PIN.
        // Afterwards, the user PIN is unset.
        let so_pin = AuthPin::new(so_pin.into());
        token.backend().context().init_token(
            token.slot().clone(), &so_pin, &new_token_label)?;

        let user_pin = AuthPin::new(pin.into());

        // Initialize the user PIN.
        let session = token.backend().context()
            .open_rw_session(token.slot().clone())?;
        session.login(UserType::So, Some(&so_pin))?;
        session.init_pin(&user_pin)?;
        drop(session);

        Ok(new_token_label)
    }

    /// Initialize a token.
    ///
    /// Returns the token's label.
    pub fn try_token_init(&self, slot: u64, label: Option<&str>, so_pin: &str,
                          pin: &str)
        -> Result<String>
    {
        let token = TokenSelector {
            backend: None,
            slot: Some(slot),
            token_label: None,
            token_serial_number: None,
        };

        self.try_token_init_(token, label, so_pin, pin)
    }

    /// Lists the tokens.
    ///
    /// Returns the token's label.
    pub fn token_init(&self, slot: u64, label: Option<&str>, so_pin: &str,
                      pin: &str)
        -> String
    {
        self.try_token_init(slot, label, so_pin, pin)
            .expect("token init should have succeeded")
    }

    /// Reinitializes a token.
    ///
    /// Returns the token's label.
    pub fn try_token_reinit(&self, token_label: &str,
                            so_pin: &str, pin: &str)
        -> Result<()>
    {
        let token = TokenSelector {
            backend: None,
            slot: None,
            token_label: Some(token_label.into()),
            token_serial_number: None,
        };

        self.try_token_init_(token, Some(token_label), so_pin, pin)?;
        Ok(())
    }

    /// Reinitializes a token.
    ///
    /// Returns the token's label.
    pub fn token_reinit(&self, token_label: &str,
                        so_pin: &str, pin: &str)
    {
        self.try_token_reinit(token_label, so_pin, pin)
            .expect("token reinit should have succeeded");
    }

    /// Generate a key.
    fn try_key_generate_intern(&self,
                               slot: u64,
                               key_label: Option<&str>,
                               algo: PublicKeyAlgorithm,
                               for_signing: bool,
                               profile: openpgp::Profile,
                               pin: &str)
                               -> Result<Key>
    {
        let token = self.ctx.select_one_token(&TokenSelector {
            backend: None,
            slot: Some(slot),
            token_label: None,
            token_serial_number: None,
        })?;

        if ! token.info().token_initialized() {
            return Err(anyhow::anyhow!(
                "Token not initialized.  Try running `sq-cryptoki token init` \
                 first."));
        }

        let session = token.open_rw_user_session(pin)?;

        match (algo, for_signing) {
            (PublicKeyAlgorithm::EdDSA, _) => {
                assert_eq!(for_signing, algo.for_signing());
		self.ctx.generate_eddsa(&session, token, None, key_label)
	    }
            (PublicKeyAlgorithm::Ed25519, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_ed25519(&session, token, profile,
                                          None, key_label)
            }
            (PublicKeyAlgorithm::Ed448, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_ed448(&session, token, profile,
                                        None, key_label)
            }
            (PublicKeyAlgorithm::MLDSA65_Ed25519, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_mldsa65_ed25519(&session, token, None,
                                                  profile, None, key_label)
            }
            (PublicKeyAlgorithm::MLDSA87_Ed448, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_mldsa87_ed448(&session, token, None,
                                                profile, None, key_label)
            }
            (PublicKeyAlgorithm::SLHDSA128s, _) => {
                assert!(for_signing);
                self.ctx.generate_slh_dsa_128s(&session, token, profile,
                                               None, key_label)
            }
            (PublicKeyAlgorithm::SLHDSA128f, _) => {
                assert!(for_signing);
                self.ctx.generate_slh_dsa_128f(&session, token, profile,
                                               None, key_label)
            }
            (PublicKeyAlgorithm::SLHDSA256s, _) => {
                assert!(for_signing);
                self.ctx.generate_slh_dsa_256s(&session, token, profile,
                                               None, key_label)
            }
            (PublicKeyAlgorithm::X25519, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_x25519(&session, token, profile,
                                         None, key_label)
            }
            (PublicKeyAlgorithm::X448, _) => {
                assert_eq!(for_signing, algo.for_signing());
                self.ctx.generate_x448(&session, token, profile,
                                       None, key_label)
            }
            (PublicKeyAlgorithm::RSAEncryptSign, _) => {
                if for_signing {
                    self.ctx.generate_rsa_for_signing(&session, token, profile,
                                                      3072, None, key_label)
                } else {
                    self.ctx.generate_rsa_for_encryption(&session, token, profile,
                                                         3072, None, key_label)
                }
            }
            (PublicKeyAlgorithm::MLKEM768_X25519, _) => {
                assert!(! for_signing);
                self.ctx.generate_mlkem768_x25519(&session, token, None,
                                                  profile,
                                                  None, key_label)
            }
            (PublicKeyAlgorithm::MLKEM1024_X448, _) => {
                assert!(! for_signing);
                self.ctx.generate_mlkem1024_x448(&session, token, None,
                                                 profile, None, key_label)
            }
            _ => panic!("{} not implemented", algo),
        }
    }

    /// Generate a key.
    pub fn try_key_generate(&self,
                            slot: u64,
                            key_label: Option<&str>,
                            algo: PublicKeyAlgorithm,
                            for_signing: bool,
                            profile: openpgp::Profile,
                            pin: &str)
                            -> Result<Key>
    {
        self.try_key_generate_intern(
            slot, key_label, algo, for_signing, profile, pin)
    }

    /// Generate a key.
    pub fn key_generate(&self,
                        slot: u64,
                        key_label: Option<&str>,
                        algo: PublicKeyAlgorithm,
                        for_signing: bool,
                        profile: openpgp::Profile,
                        pin: &str)
                        -> Key
    {
        self.try_key_generate(
            slot, key_label, algo, for_signing, profile, pin)
            .expect("key generate should have succeeded")
    }

    /// Try and generate a parameterized v4 Cv25519 key.
    pub fn try_legacy_cv25519_key_generate(&self,
                                           token_label: &str,
                                           hash_algo: Option<HashAlgorithm>,
                                           sym_algo: Option<SymmetricAlgorithm>,
                                           key_label: Option<&str>,
                                           pin: &str)
                                           -> Result<Key>
    {
        let token = self.ctx.select_one_token(&TokenSelector {
            backend: None,
            slot: None,
            token_label: Some(token_label.to_string()),
            token_serial_number: None,
        })?;

        if ! token.info().token_initialized() {
            return Err(anyhow::anyhow!(
                "Token not initialized.  Try running `sq-cryptoki token init` \
                 first."));
        }

        let session = token.open_rw_user_session(pin)?;

        self.ctx.generate_legacy_cv25519(&session, token, None,
                                         hash_algo, sym_algo,
                                         key_label)
    }

    /// Generate a parameterized v4 Cv25519 key.
    pub fn legacy_cv25519_key_generate(&self,
                                       token_label: &str,
                                       hash_algo: Option<HashAlgorithm>,
                                       sym_algo: Option<SymmetricAlgorithm>,
                                       key_label: Option<&str>,
                                       pin: &str)
                                       -> Key
    {
        self.try_legacy_cv25519_key_generate(
            token_label, hash_algo, sym_algo, key_label, pin)
            .expect("key generate should have succeeded")
    }

    /// Generate a composite key.
    pub fn try_composite_key_generate(&self,
                                      slot: u64,
                                      key_label: Option<&str>,
                                      algo: PublicKeyAlgorithm,
                                      for_signing: bool,
                                      profile: openpgp::Profile,
                                      pin: &str)
                                      -> Result<Key>
    {
        self.try_key_generate_intern(
            slot, key_label, algo, for_signing, profile, pin)
    }

    /// Generate a composite key.
    pub fn composite_key_generate(&self,
                                  slot: u64,
                                  key_label: Option<&str>,
                                  algo: PublicKeyAlgorithm,
                                  for_signing: bool,
                                  profile: openpgp::Profile,
                                  pin: &str)
                                  -> Key
    {
        self.try_composite_key_generate(
            slot, key_label, algo, for_signing, profile, pin)
            .expect("key generate should have succeeded")
    }

    /// Import a key.
    pub fn try_import(&self,
                      token_label1: &str,
                      pin1: &str,
                      token_label_pin2: Option<(&str, &str)>,
                      key: &packet::key::Key<key::SecretParts,
                                             key::UnspecifiedRole>,
                      key_capability: KeyCapability,
                      key_label: Option<&str>)
        -> Result<Key>
    {
        let token1 = self.ctx.select_one_token(&TokenSelector {
            backend: None,
            slot: None,
            token_label: Some(token_label1.to_string()),
            token_serial_number: None,
        })?;

        if ! token1.info().token_initialized() {
            return Err(anyhow::anyhow!(
                "Token not initialized.  Try running `sq-cryptoki token init` \
                 first."));
        }

        let session1 = token1.open_rw_user_session(pin1)?;

        let session2_;
        let session_token2 = if let Some((token_label2, pin2)) = token_label_pin2 {
            let token2 = self.ctx.select_one_token(&TokenSelector {
                backend: None,
                slot: None,
                token_label: Some(token_label2.to_string()),
                token_serial_number: None,
            })?;

            if ! token2.info().token_initialized() {
                return Err(anyhow::anyhow!(
                    "Token not initialized.  Try running `sq-cryptoki token init` \
                     first."));
            }

            session2_ = token2.open_rw_user_session(pin2)?;

            Some((&session2_, token2))
        } else {
            None
        };

        self.ctx.import(&session1, token1, session_token2,
                        key_label, key, key_capability)
    }

    /// Import a key.
    pub fn import(&self,
                  token_label1: &str,
                  pin1: &str,
                  token_label_pin2: Option<(&str, &str)>,
                  key: &packet::key::Key<key::SecretParts,
                                         key::UnspecifiedRole>,
                  key_capability: KeyCapability,
                  key_label: Option<&str>)
        -> Key
    {
        self.try_import(token_label1, pin1, token_label_pin2,
                        key, key_capability, key_label)
            .expect("can import")
    }

    /// Export a certificate.
    pub fn try_key_export(&self)
        -> Result<(HashMap<String, String>, Cert)>
    {
        todo!()
    }

    /// Export a certificate.
    pub fn key_export(&self)
        -> (HashMap<String, String>, Cert)
    {
        todo!()
    }

    /// Sign a message.
    pub fn try_key_sign(&self, _user_pin: &str)
        -> Result<()>
    {
        todo!()
    }

    /// Sign a message.
    pub fn key_sign(&self, _user_pin: &str)
        -> ()
    {
        todo!()
    }

    /// Decrypt a message.
    ///
    /// Returns the plaintext.
    pub fn try_key_decrypt(&self, _user_pin: &str)
        -> Result<()>
    {
        todo!()
    }

    /// Decrypt a message.
    ///
    /// Returns the plaintext.
    pub fn key_decrypt(&self, _user_pin: &str)
        -> ()
    {
        todo!()
    }
}

/// A prompter that always returns an error.
#[derive(Default)]
pub struct CancelPrompt(());

impl sequoia_cryptoki::Prompt for CancelPrompt {
    fn prompt_password(&self, _: &str) -> Result<openpgp::crypto::Password> {
        Err(anyhow::anyhow!("nope"))
    }
}