kryoptic-lib 1.5.3

A PKCS #11 software token written in Rust
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
// Copyright 2023 Simo Sorce
// See LICENSE.txt file for terms

use std::ffi::CString;
use std::fs::{create_dir_all, remove_dir_all, OpenOptions};
use std::io::Write;
use std::sync::Once;
use std::thread;
use std::time::Duration;

#[cfg(feature = "log")]
use crate::log;

use crate::misc::*;
use crate::storage::StorageDBInfo;
use crate::*;

use hex;

#[macro_use]
mod util;
use util::*;

mod json_objects;
mod token;

const TESTDIR: &str = "test/kryoptic";
const SO_PIN: &str = "12345678";
const USER_PIN: &str = "12345678";
const TOKEN_LABEL: &str = "INTERNAL TEST TOKEN";

/* note that the following concoction to sync threads is not entirely race free
 * as it assumes all tests initialize before all of the others complete. */
static FINI: RwLock<u64> = RwLock::new(0);
static SYNC: RwLock<u64> = RwLock::new(0);

static INIT: Once = Once::new();
fn test_initialize() -> Option<RwLockWriteGuard<'static, u64>> {
    #[cfg(feature = "log")]
    log::test_init();

    let mut winner: Option<RwLockWriteGuard<u64>> = None;
    INIT.call_once(|| {
        /* ignore failure to remove */
        let _ = remove_dir_all(TESTDIR);
        create_dir_all(TESTDIR).unwrap();

        winner = Some(FINI.write().unwrap());
    });
    winner
}

struct Slots {
    id: CK_ULONG,
}

static SLOTS: RwLock<Slots> = RwLock::new(Slots { id: 0 });

pub fn check_test_slot_busy(slot: CK_SLOT_ID) -> bool {
    let state = match STATE.rlock() {
        Ok(r) => r,
        Err(_) => return false,
    };

    match state.get_slot(slot) {
        Ok(_) => true,
        Err(_) => false,
    }
}

struct TestToken<'a> {
    slot: CK_SLOT_ID,
    name: String,
    dbtype: String,
    dbargs: String,
    finalize: Option<RwLockWriteGuard<'a, u64>>,
    sync: Option<RwLockReadGuard<'a, u64>>,
    session: CK_SESSION_HANDLE,
    session_rw: bool,
    dedup: Option<crate::config::ObjectsDedup>,
}

impl TestToken<'_> {
    fn new<'a>(name: String) -> TestToken<'a> {
        let (dbtype, dbargs) = Self::get_default_db(&name);

        Self::new_type(String::from(dbtype), dbargs, name)
    }

    fn new_type<'a>(
        dbtype: String,
        dbargs: String,
        name: String,
    ) -> TestToken<'a> {
        let mut slots = SLOTS.write().unwrap();
        slots.id += 1;
        while check_test_slot_busy(slots.id) {
            slots.id += 1;
        }

        let finalizer = test_initialize();

        TestToken {
            slot: slots.id,
            name: name,
            dbtype: dbtype,
            dbargs: dbargs,
            finalize: finalizer,
            sync: Some(SYNC.read().unwrap()),
            session: CK_INVALID_HANDLE,
            session_rw: false,
            dedup: None,
        }
    }

    fn setup_db<'a>(&mut self, import: Option<&'a str>) {
        let so_pin = SO_PIN.as_bytes().to_vec();
        let user_pin = USER_PIN.as_bytes().to_vec();
        let mut label = TOKEN_LABEL.as_bytes().to_vec();
        label.resize(32, 0x20);
        /* Init a brand new token */
        let mut token =
            Token::new(&self.dbtype, Some(self.dbargs.clone())).unwrap();
        token.initialize(&so_pin, &label).unwrap();
        token.login(CKU_SO, &so_pin);
        token.set_pin(CKU_USER, &user_pin, &vec![0u8; 0]).unwrap();
        token.logout();
        token.login(CKU_USER, &user_pin);

        match import {
            Some(s) => {
                let test_data = json_objects::JsonObjects::load(s).unwrap();
                let mut tstore = json_objects::TransferStorage::new();
                test_data.prime_store(&mut tstore).unwrap();

                let objects = tstore.search(&[]).unwrap();
                for obj in objects {
                    token
                        .insert_object(CK_INVALID_HANDLE, obj.clone())
                        .unwrap();
                }
            }
            None => (),
        };
    }

    fn get_slot(&self) -> CK_SLOT_ID {
        self.slot
    }

    fn make_config_file(
        &self,
        confname: &str,
        mechs: Option<Vec<String>>,
        dedup: Option<crate::config::ObjectsDedup>,
    ) {
        let mut conf = config::Config::new();
        let mut slot =
            config::Slot::with_db(&self.dbtype, Some(self.dbargs.clone()));
        slot.slot = u32::try_from(self.get_slot()).unwrap();
        slot.mechanisms = mechs;
        slot.objects_dedup = dedup;
        conf.add_slot(slot).unwrap();
        let data = toml::to_string(&conf).unwrap();
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(confname)
            .unwrap();
        file.write_all(data.as_bytes()).unwrap();
    }

    fn make_init_string(&self) -> String {
        let confname = format!("{}/{}.conf", TESTDIR, self.name);
        self.make_config_file(&confname, None, self.dedup);
        format!("kryoptic_conf={}", confname)
    }

    fn make_init_args(reserved: Option<String>) -> CK_C_INITIALIZE_ARGS {
        CK_C_INITIALIZE_ARGS {
            CreateMutex: None,
            DestroyMutex: None,
            LockMutex: None,
            UnlockMutex: None,
            flags: 0,
            pReserved: match reserved {
                Some(r) => void_ptr!(CString::new(r).unwrap().into_raw()),
                None => std::ptr::null_mut(),
            },
        }
    }

    fn finalize(&mut self) {
        self.logout();
        self.close_session();
        if self.finalize.is_none() {
            self.sync = None;
            /* wait until we can read, which means the winner finalized the module */
            drop(FINI.read().unwrap());
        } else {
            self.sync = None;

            /* wait for all others to complete */
            loop {
                /* This needs to use try_write() because a queued write lock
                 * may actually block read() attempts, which would cause
                 * tests to deadlock, sleeps between attempts. */
                thread::sleep(Duration::from_millis(5));
                match SYNC.try_write() {
                    Ok(lock) => {
                        drop(lock);
                        break;
                    }
                    Err(_) => (),
                }
            }

            let ret = fn_finalize(std::ptr::null_mut());
            assert_eq!(ret, CKR_OK);
            /* winner finalized and completed the tests */
            self.finalize = None;
        }
    }

    #[allow(unreachable_code)]
    fn get_default_db(name: &str) -> (&'static str, String) {
        let default_db = match std::env::var("KRYOPTIC_TESTS_DEFAULT_DB") {
            Ok(var) => var,
            Err(_) => String::from("sqlitedb"),
        };

        match default_db.as_str() {
            #[cfg(feature = "nssdb")]
            "nssdb" => (
                storage::nssdb::DBINFO.dbtype(),
                format!("configDir={}/{}/", TESTDIR, name),
            ),
            #[cfg(feature = "sqlitedb")]
            "sqlitedb" => (
                storage::sqlite::DBINFO.dbtype(),
                format!("{}/{}.sql", TESTDIR, name),
            ),
            x => panic!("Unknown database {}", x),
        }
    }

    fn initialized_with_dedup<'a>(
        name: &'a str,
        import: Option<&'a str>,
        dedup: Option<crate::config::ObjectsDedup>,
    ) -> TestToken<'a> {
        let mut td = Self::new(String::from(name));
        td.dedup = dedup;
        td.setup_db(import);

        let mut args = Self::make_init_args(Some(td.make_init_string()));
        let args_ptr = &mut args as *mut CK_C_INITIALIZE_ARGS;
        let ret = fn_initialize(args_ptr as *mut std::ffi::c_void);
        assert!(ret == CKR_OK || ret == CKR_CRYPTOKI_ALREADY_INITIALIZED);

        /* By default we force relaxed behavior so tests can access
         * data to check results */
        #[cfg(feature = "fips")]
        set_fips_behavior(
            td.get_slot(),
            config::FipsBehavior {
                keys_always_sensitive: false,
            },
        );

        td
    }

    fn initialized<'a>(
        name: &'a str,
        import: Option<&'a str>,
    ) -> TestToken<'a> {
        Self::initialized_with_dedup(name, import, None)
    }

    fn get_session(&mut self, rw: bool) -> CK_SESSION_HANDLE {
        if self.session != CK_INVALID_HANDLE {
            if rw == self.session_rw {
                return self.session;
            }
            self.close_session();
        }
        let mut flags = CKF_SERIAL_SESSION;
        if rw {
            flags |= CKF_RW_SESSION;
        };
        let ret = fn_open_session(
            self.get_slot(),
            flags,
            std::ptr::null_mut(),
            None,
            &mut self.session,
        );
        assert_eq!(ret, CKR_OK);
        self.session
    }

    fn login(&mut self) {
        let pin = "12345678";
        let ret = fn_login(
            self.session,
            CKU_USER,
            pin.as_ptr() as *mut _,
            pin.len() as CK_ULONG,
        );
        assert_eq!(ret, CKR_OK);
    }

    fn logout(&self) {
        if self.session != CK_INVALID_HANDLE {
            fn_logout(self.session);
        }
    }

    fn close_session(&mut self) {
        if self.session != CK_INVALID_HANDLE {
            let ret = fn_close_session(self.session);
            assert_eq!(ret, CKR_OK);
            self.session = CK_INVALID_HANDLE;
        }
    }
}

mod random;

mod login;

mod attrs;

mod objects;

mod init;

mod mechs;

#[cfg(feature = "aes")]
mod aes;

#[cfg(feature = "chacha20")]
mod chacha20;

#[cfg(feature = "rsa")]
mod rsa;

mod session;

#[cfg(feature = "ecdsa")]
mod ecc;

#[cfg(feature = "ec_montgomery")]
mod ec_montgomery;

#[cfg(feature = "ecdh")]
mod ecdh;

#[cfg(feature = "ecdh")]
mod ecdh_vectors;

#[cfg(feature = "eddsa")]
mod eddsa;

#[cfg(feature = "ffdh")]
mod ffdh;

#[cfg(feature = "hash")]
mod hashes;

mod signatures;

mod keys;

#[cfg(feature = "sp800_108")]
mod kdf_vectors;

mod kdfs;

#[cfg(feature = "hmac")]
mod mac_vectors;

#[cfg(feature = "ike")]
mod ike;

#[cfg(feature = "aes")]
mod aes_kw_vectors;

#[cfg(feature = "tlskdf")]
mod tls;

#[cfg(feature = "simplekdf")]
mod simplekdf;

#[cfg(feature = "nssdb")]
mod nssdb;

mod combined;

#[cfg(feature = "mlkem")]
mod mlkem;

#[cfg(feature = "mldsa")]
mod mldsa;

#[cfg(all(
    feature = "slhdsa",
    any(not(feature = "fips"), feature = "ossl400")
))]
mod slhdsa;

mod pkcs11;

#[cfg(feature = "hotp")]
mod hotp;