cryptex 3.0.0

Store and retrieve secrets in OS keyrings, encrypted SQLite or Turso files, in-memory and browser keyrings, or under a YubiHSM 2 or Nitrokey 3
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
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/

#[cfg(any(
    feature = "encrypted-vfs",
    feature = "memory",
    feature = "turso-encrypted-io"
))]
mod cipher;

mod keyringsecret;

/// A keyring in a bundled SQLite database whose pages cryptex encrypts.
#[cfg(feature = "encrypted-vfs")]
pub mod encrypted_vfs;
#[cfg(any(
    feature = "file",
    feature = "encrypted-vfs",
    feature = "memory",
    feature = "turso",
    feature = "turso-encrypted-io"
))]
pub mod file_common;
#[cfg(feature = "indexeddb")]
pub mod indexeddb;
#[cfg(any(
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
    feature = "nitrokey"
))]
pub mod kms;
/// The Linux Secret Service (GNOME Keyring, KWallet) keyring.
#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
pub mod linux;
/// The macOS Keychain keyring.
#[cfg(all(target_os = "macos", feature = "macos-keychain"))]
pub mod macos;
#[cfg(feature = "memory")]
pub mod memory;
#[cfg(all(feature = "encrypted-vfs", not(feature = "fips")))]
pub mod migrate;
/// A keyring keyed by a Nitrokey 3 (or any FIDO2 key) through `hmac-secret`.
#[cfg(feature = "nitrokey")]
pub mod nitrokey;
#[cfg(feature = "turso-opfs")]
pub mod opfs;
#[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))]
mod page_cipher;
#[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))]
mod page_header;
#[cfg(any(
    feature = "encrypted-vfs",
    feature = "turso",
    feature = "turso-encrypted-io",
    feature = "turso-opfs"
))]
mod page_store;
/// A keyring in a SQLCipher database.
#[cfg(feature = "file")]
pub mod sqlcipher;
#[cfg(any(feature = "file", feature = "encrypted-vfs"))]
mod sqlite_common;
#[cfg(feature = "turso")]
pub mod turso;
#[cfg(any(feature = "turso", feature = "turso-encrypted-io"))]
mod turso_common;
#[cfg(feature = "turso-encrypted-io")]
pub mod turso_encrypted_io;
#[cfg(feature = "turso")]
mod turso_web;
#[cfg(feature = "web-storage")]
pub mod web_storage;
#[cfg(any(feature = "turso-opfs", feature = "turso"))]
mod web_time;
/// The Windows Credential Manager keyring.
#[cfg(all(target_os = "windows", feature = "windows-credentials"))]
pub mod windows;
#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
pub mod yubihsm;

#[cfg(all(target_os = "macos", feature = "macos-keychain"))]
#[cfg_attr(docsrs, doc(cfg(all(target_os = "macos", feature = "macos-keychain"))))]
pub use self::macos::MacOsKeyRing as OsKeyRing;

#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(target_os = "linux", feature = "linux-secret-service")))
)]
pub use self::linux::LinuxOsKeyRing as OsKeyRing;

#[cfg(all(target_os = "windows", feature = "windows-credentials"))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(target_os = "windows", feature = "windows-credentials")))
)]
pub use self::windows::WindowsOsKeyRing as OsKeyRing;

use std::collections::BTreeMap;

/// The result type every keyring returns.
pub type Result<T> = std::result::Result<T, crate::error::KeyRingError>;

pub use keyringsecret::*;

#[cfg(any(
    all(target_os = "linux", feature = "linux-secret-service"),
    all(target_os = "macos", feature = "macos-keychain"),
))]
use uzers::{get_current_username, get_effective_username};

/// Return the OS keyring if available
#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
))]
#[cfg_attr(
    docsrs,
    doc(cfg(any(
        all(target_os = "macos", feature = "macos-keychain"),
        all(target_os = "windows", feature = "windows-credentials"),
    )))
)]
pub fn get_os_keyring(service: &str) -> Result<OsKeyRing> {
    OsKeyRing::new(service)
}

/// Return the OS keyring if available
#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(target_os = "linux", feature = "linux-secret-service")))
)]
pub fn get_os_keyring(service: &str) -> Result<OsKeyRing<'_>> {
    OsKeyRing::new(service)
}

#[cfg(not(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "file",
    feature = "encrypted-vfs",
    feature = "memory",
    feature = "turso",
    feature = "turso-encrypted-io",
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
    feature = "nitrokey",
)))]
compile_error!("no keyring implementation is selected or available for this platform");

// Backends that need native OS APIs, C libraries or USB devices. They are
// rejected on wasm targets so the build fails with a clear message instead of
// a wall of linker errors.
#[cfg(all(
    target_family = "wasm",
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "yubihsm-usb",
        feature = "yubihsm-http",
        feature = "nitrokey",
        feature = "linux-secret-service",
        feature = "macos-keychain",
        feature = "windows-credentials",
    )
))]
compile_error!(
    "the file, encrypted-vfs, yubihsm, nitrokey and OS keyring backends are not available on wasm; \
     use the memory, web-storage, indexeddb, turso-opfs or turso features instead"
);

// Browser-only features asked for by a non-browser target.
#[cfg(all(
    not(all(target_arch = "wasm32", target_os = "unknown")),
    any(
        feature = "web-storage",
        feature = "indexeddb",
        feature = "turso-opfs",
        feature = "js"
    )
))]
compile_error!(
    "the web-storage, indexeddb, turso-opfs and js features require wasm32-unknown-unknown"
);

#[cfg(any(
    all(target_os = "linux", feature = "linux-secret-service"),
    all(target_os = "macos", feature = "macos-keychain"),
))]
fn get_username() -> String {
    fn fallback_username() -> String {
        whoami::username().unwrap_or_else(|_| String::from("unknown"))
    }

    fn get_current_user() -> String {
        match get_current_username() {
            Some(s) => s.into_string().unwrap_or_else(|_| fallback_username()),
            None => fallback_username(),
        }
    }

    match get_effective_username() {
        Some(s) => s.into_string().unwrap_or_else(|_| get_current_user()),
        None => get_current_user(),
    }
}

/// Whether the SQLCipher keyring (the `file` feature) is compiled in.
#[cfg(feature = "file")]
pub const fn allows_file() -> bool {
    true
}

/// Whether the SQLCipher keyring (the `file` feature) is compiled in.
#[cfg(not(feature = "file"))]
pub const fn allows_file() -> bool {
    false
}

/// Default Argon2 memory cost, in KiB blocks, for file-backed keyrings.
#[cfg(all(
    not(test),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_memory_cost() -> u32 {
    32 * 1024
}

/// Default Argon2 memory cost, in KiB blocks, for file-backed keyring tests.
#[cfg(all(
    test,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_memory_cost() -> u32 {
    argon2::Params::DEFAULT_M_COST
}

/// Default Argon2 thread/time cost for file-backed keyrings.
#[cfg(all(
    not(test),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_threads() -> u32 {
    3
}

/// Default Argon2 thread/time cost for file-backed keyring tests.
#[cfg(all(
    test,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_threads() -> u32 {
    argon2::Params::DEFAULT_T_COST
}

/// Default Argon2 parallelism cost for file-backed keyrings.
#[cfg(all(
    not(test),
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_parallel() -> u32 {
    2
}

/// Default Argon2 parallelism cost for file-backed keyring tests.
#[cfg(all(
    test,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
pub const fn default_parallel() -> u32 {
    argon2::Params::DEFAULT_P_COST
}

/// Default PBKDF2-HMAC-SHA256 iteration count for `fips` builds, and the
/// lowest count a new key may use (OWASP's 2023 guidance).
#[cfg(all(not(test), feature = "fips"))]
pub const fn default_iterations() -> u32 {
    600_000
}

/// Default PBKDF2-HMAC-SHA256 iteration count for `fips` build tests.
#[cfg(all(test, feature = "fips"))]
pub const fn default_iterations() -> u32 {
    1_000
}

/// A trait for all key rings
pub trait KeyRing: Send + Sync {
    /// Fetch the secret stored under `id`.
    fn get_secret<S: AsRef<str>>(&mut self, id: S) -> Result<KeyRingSecret>;

    /// Store `secret` under `id`, replacing any secret already there.
    fn set_secret<S: AsRef<str>, B: AsRef<[u8]>>(&mut self, id: S, secret: B) -> Result<()>;

    /// Remove the secret stored under `id`.
    fn delete_secret<S: AsRef<str>>(&mut self, id: S) -> Result<()>;
}

/// Modification of [`KeyRing`] trait suitable for trait Objects. Implementers
/// should use this trait and [`KeyRing`] will be implemented automatically
pub trait DynKeyRing: Send + Sync {
    /// Fetch the secret stored under `id`.
    fn get_secret(&mut self, id: &str) -> Result<KeyRingSecret>;

    /// Store `secret` under `id`, replacing any secret already there.
    fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()>;

    /// Remove the secret stored under `id`.
    fn delete_secret(&mut self, id: &str) -> Result<()>;
}

impl<D: DynKeyRing> KeyRing for D {
    fn get_secret<S: AsRef<str>>(&mut self, id: S) -> Result<KeyRingSecret> {
        DynKeyRing::get_secret(self, id.as_ref())
    }

    fn set_secret<S: AsRef<str>, B: AsRef<[u8]>>(&mut self, id: S, secret: B) -> Result<()> {
        DynKeyRing::set_secret(self, id.as_ref(), secret.as_ref())
    }

    fn delete_secret<S: AsRef<str>>(&mut self, id: S) -> Result<()> {
        DynKeyRing::delete_secret(self, id.as_ref())
    }
}

/// A KeyRing that can be created from a service name
pub trait NewKeyRing: Sized {
    /// Open the keyring. For OS keyrings `service` is the service name; for
    /// file keyrings it is a connection string, and the keyring lives in
    /// `~/.cryptex`.
    fn new<S: AsRef<str>>(service: S) -> Result<Self>;
}

/// A Keyring that allows inspecting the identifiers
pub trait PeekableKeyRing {
    /// Every entry matching `id`, a comma-separated list of `name=value`
    /// filters, as `(description, secret)` pairs. An empty `id` matches all.
    fn peek_secret<S: AsRef<str>>(id: S) -> Result<Vec<(String, KeyRingSecret)>>;
}

/// A Keyring that allows listing the identifiers
pub trait ListKeyRing {
    /// The attributes of every entry, without their secrets.
    fn list_secrets() -> Result<Vec<BTreeMap<String, String>>>;
}

#[cfg(all(
    test,
    any(
        feature = "file",
        feature = "encrypted-vfs",
        feature = "memory",
        feature = "turso",
        feature = "turso-encrypted-io"
    )
))]
mod tests {
    use super::*;

    #[test]
    fn test_defaults_use_argon2_defaults() {
        assert_eq!(default_memory_cost(), argon2::Params::DEFAULT_M_COST);
        assert_eq!(default_threads(), argon2::Params::DEFAULT_T_COST);
        assert_eq!(default_parallel(), argon2::Params::DEFAULT_P_COST);
    }
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
pub(crate) fn parse_peek_criteria(id: &str) -> BTreeMap<String, String> {
    let mut result = BTreeMap::new();
    if !id.is_empty() {
        for pair in id.split(',') {
            if let Some((key, value)) = pair.split_once('=') {
                result.insert(key.to_string(), value.to_string());
            }
        }
    }
    result
}