cryptex 2.1.1

Cryptex uses system keyrings to store and retrieve secrets or a local file
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
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
#![deny(
    warnings,
    unsafe_code,
    unused_import_braces,
    unused_qualifications,
    trivial_casts,
    trivial_numeric_casts
)]

use clap::{Arg, ArgMatches, Command};
use colored::Colorize;

// ── Imports used only when at least one active backend is compiled in ─────────

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use std::fs::File;

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use std::io::{self, IsTerminal, Read, Write};

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use std::path::PathBuf;

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use zeroize::Zeroize;

// ── Shared backend imports ────────────────────────────────────────────────────

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use cryptex::{KeyRing, KeyRingSecret};

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
use std::collections::BTreeMap;

// ── OS keyring ────────────────────────────────────────────────────────────────

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring};

#[cfg(all(target_os = "macos", feature = "macos-keychain"))]
use cryptex::macos::MacOsKeyRing as OsKeyRing;

#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
use cryptex::linux::LinuxOsKeyRing as OsKeyRing;

#[cfg(all(target_os = "windows", feature = "windows-credentials"))]
use cryptex::windows::WindowsOsKeyRing as OsKeyRing;

// ── YubiHSM ───────────────────────────────────────────────────────────────────

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
use cryptex::NewKeyRing;

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
use cryptex::yubihsm::YubiHsmKeyRing;

// ─────────────────────────────────────────────────────────────────────────────

fn main() {
    let matches = Command::new("cryptex")
        .version(env!("CARGO_PKG_VERSION"))
        .author("Michael Lodder")
        .about("Platform-independent CLI for storing and retrieving secrets from secure keyrings")
        .arg(
            Arg::new("keyring")
                .long("keyring")
                .short('k')
                .value_name("TYPE")
                .global(true)
                .help("Keyring backend to use: 'os' (default) or 'yubihsm'"),
        )
        .subcommand(
            Command::new("get")
                .about("Retrieve a secret by ID")
                .arg(
                    Arg::new("SERVICE")
                        .help("Service name (OS) or connection string (yubihsm)")
                        .required(true)
                        .index(1),
                )
                .arg(
                    Arg::new("ID")
                        .help("The secret ID. If omitted, read from STDIN")
                        .required(false)
                        .index(2),
                ),
        )
        .subcommand(
            Command::new("set")
                .about("Save a secret by ID")
                .arg(
                    Arg::new("SERVICE")
                        .help("Service name (OS) or connection string (yubihsm)")
                        .required(true)
                        .index(1),
                )
                .arg(
                    Arg::new("ID")
                        .help("The secret ID")
                        .required(true)
                        .index(2),
                )
                .arg(
                    Arg::new("SECRET")
                        .help("The secret value. If omitted, read from STDIN")
                        .required(false)
                        .index(3),
                ),
        )
        .subcommand(
            Command::new("delete")
                .about("Delete a secret by ID")
                .arg(
                    Arg::new("SERVICE")
                        .help("Service name (OS) or connection string (yubihsm)")
                        .required(true)
                        .index(1),
                )
                .arg(
                    Arg::new("ID")
                        .help("The secret ID. If omitted, read from STDIN")
                        .required(false)
                        .index(2),
                ),
        )
        .subcommand(
            Command::new("peek")
                .about("Inspect OS keyring entries without full retrieval (OS backends only)")
                .arg(
                    Arg::new("ID")
                        .help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)")
                        .required(false)
                        .index(1),
                ),
        )
        .subcommand(
            Command::new("list")
                .about("List secret IDs. For 'os': lists all. For 'yubihsm': requires a connection string.")
                .arg(
                    Arg::new("SERVICE")
                        .help("Connection string (required for 'yubihsm')")
                        .required(false)
                        .index(1),
                ),
        )
        .get_matches();

    dispatch(&matches);
}

fn dispatch(matches: &ArgMatches) {
    let keyring_type = matches
        .get_one::<String>("keyring")
        .map(|s| s.as_str())
        .unwrap_or("os");

    match keyring_type {
        "yubihsm" => {
            #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
            dispatch_yubihsm(matches);
            #[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))]
            die::<()>(
                "YubiHSM support is not compiled in. \
                 Enable the 'yubihsm-usb' or 'yubihsm-http' feature.",
            );
        }
        "os" => dispatch_os(matches),
        other => die::<()>(&format!(
            "Unknown keyring type '{}'. Valid options: os, yubihsm",
            other
        )),
    }
}

// ── OS keyring dispatch ───────────────────────────────────────────────────────

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn dispatch_os(matches: &ArgMatches) {
    if let Some(m) = matches.subcommand_matches("get") {
        os_get(m);
    } else if let Some(m) = matches.subcommand_matches("set") {
        os_set(m);
    } else if let Some(m) = matches.subcommand_matches("delete") {
        os_delete(m);
    } else if let Some(m) = matches.subcommand_matches("peek") {
        os_peek(m);
    } else if matches.subcommand_matches("list").is_some() {
        os_list();
    } else {
        die::<()>("Please specify a command: get | set | delete | peek | list");
    }
}

#[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"),
)))]
fn dispatch_os(_matches: &ArgMatches) {
    die::<()>(
        "No OS keyring available for this platform/feature combination. \
         Use '--keyring yubihsm' or enable a platform keyring feature.",
    );
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_get(matches: &ArgMatches) {
    let mut keyring = os_open(matches);
    let id = get_id(matches, true);
    let secret = keyring
        .get_secret(&id)
        .unwrap_or_else(|e| die::<KeyRingSecret>(&e.to_string()));
    io::stdout().write_all(secret.as_slice()).unwrap();
    io::stdout().flush().unwrap();
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_set(matches: &ArgMatches) {
    let mut keyring = os_open(matches);
    let id = matches.get_one::<String>("ID").map(|s| s.as_str()).unwrap();
    let mut secret = read_input(matches, "SECRET", true);
    keyring
        .set_secret(id, &secret)
        .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e)));
    secret.zeroize();
    println!("{}", "Success".green());
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_delete(matches: &ArgMatches) {
    let mut keyring = os_open(matches);
    let id = get_id(matches, true);
    keyring
        .delete_secret(&id)
        .unwrap_or_else(|e| die::<()>(&e.to_string()));
    println!("{}", "Success".green());
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_peek(matches: &ArgMatches) {
    let id = get_id(matches, false);
    let secrets = OsKeyRing::peek_secret(&id)
        .unwrap_or_else(|e| die::<Vec<(String, KeyRingSecret)>>(&e.to_string()));
    if secrets.len() == 1 && !id.is_empty() {
        io::stdout().write_all(secrets[0].1.as_slice()).unwrap();
        io::stdout().flush().unwrap();
        println!();
    } else {
        for s in secrets {
            print!("{} -> ", s.0);
            io::stdout().write_all(s.1.as_slice()).unwrap();
            println!();
            io::stdout().flush().unwrap();
        }
    }
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_list() {
    let secret_names = OsKeyRing::list_secrets()
        .unwrap_or_else(|e| die::<Vec<BTreeMap<String, String>>>(&e.to_string()));
    for s in secret_names {
        println!("{:?}", s);
    }
}

#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> {
    let service = matches
        .get_one::<String>("SERVICE")
        .map(|s| s.as_str())
        .unwrap();
    get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e)))
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
))]
fn os_open(matches: &ArgMatches) -> OsKeyRing {
    let service = matches
        .get_one::<String>("SERVICE")
        .map(|s| s.as_str())
        .unwrap();
    get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e)))
}

// ── YubiHSM dispatch ─────────────────────────────────────────────────────────

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn dispatch_yubihsm(matches: &ArgMatches) {
    if let Some(m) = matches.subcommand_matches("get") {
        yubihsm_get(m);
    } else if let Some(m) = matches.subcommand_matches("set") {
        yubihsm_set(m);
    } else if let Some(m) = matches.subcommand_matches("delete") {
        yubihsm_delete(m);
    } else if let Some(m) = matches.subcommand_matches("list") {
        yubihsm_list(m);
    } else if matches.subcommand_matches("peek").is_some() {
        die::<()>("The 'peek' command is not supported for the YubiHSM backend.");
    } else {
        die::<()>("Please specify a command: get | set | delete | list");
    }
}

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn yubihsm_open(matches: &ArgMatches) -> YubiHsmKeyRing {
    let connstr = matches
        .get_one::<String>("SERVICE")
        .map(|s| s.as_str())
        .unwrap_or_else(|| die("A YubiHSM connection string is required as the SERVICE argument"));
    YubiHsmKeyRing::new(connstr)
        .unwrap_or_else(|e| die(&format!("Failed to connect to YubiHSM: {}", e)))
}

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn yubihsm_get(matches: &ArgMatches) {
    let mut ring = yubihsm_open(matches);
    let id = get_id(matches, true);
    let secret = ring
        .get_secret(&id)
        .unwrap_or_else(|e| die::<KeyRingSecret>(&e.to_string()));
    io::stdout().write_all(secret.as_slice()).unwrap();
    io::stdout().flush().unwrap();
}

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn yubihsm_set(matches: &ArgMatches) {
    let mut ring = yubihsm_open(matches);
    let id = matches.get_one::<String>("ID").map(|s| s.as_str()).unwrap();
    let mut secret = read_input(matches, "SECRET", true);
    ring.set_secret(id, &secret)
        .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e)));
    secret.zeroize();
    println!("{}", "Success".green());
}

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn yubihsm_delete(matches: &ArgMatches) {
    let mut ring = yubihsm_open(matches);
    let id = get_id(matches, true);
    ring.delete_secret(&id)
        .unwrap_or_else(|e| die::<()>(&e.to_string()));
    println!("{}", "Success".green());
}

#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
fn yubihsm_list(matches: &ArgMatches) {
    let ring = yubihsm_open(matches);
    let entries = ring
        .list_hsm_secrets()
        .unwrap_or_else(|e| die::<Vec<BTreeMap<String, String>>>(&e.to_string()));
    for entry in entries {
        println!("{:?}", entry);
    }
}

// ── Shared helpers ────────────────────────────────────────────────────────────

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
fn get_id(matches: &ArgMatches, read_stdin: bool) -> String {
    let bytes = read_input(matches, "ID", read_stdin);
    String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8"))
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec<u8> {
    match matches.get_one::<String>(name).map(|s| s.as_str()) {
        Some(text) => match get_file(text) {
            Some(file) => match File::open(file.as_path()) {
                Ok(mut f) => read_stream(&mut f),
                Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())),
            },
            None => text.as_bytes().to_vec(),
        },
        None => {
            if io::stdin().is_terminal() {
                if read_stdin {
                    rpassword::prompt_password("Enter Secret: ")
                        .unwrap()
                        .as_bytes()
                        .to_vec()
                } else {
                    Vec::new()
                }
            } else {
                let mut f = io::stdin();
                read_stream(&mut f)
            }
        }
    }
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
fn read_stream<R: Read>(f: &mut R) -> Vec<u8> {
    let mut bytes = Vec::new();
    let mut buffer = [0u8; 4096];
    loop {
        match f.read(&mut buffer) {
            Ok(0) => break,
            Ok(n) => bytes.extend_from_slice(&buffer[..n]),
            Err(_) => break,
        }
    }
    bytes
}

#[cfg(any(
    all(target_os = "macos", feature = "macos-keychain"),
    all(target_os = "windows", feature = "windows-credentials"),
    all(target_os = "linux", feature = "linux-secret-service"),
    feature = "yubihsm-usb",
    feature = "yubihsm-http",
))]
fn get_file(name: &str) -> Option<PathBuf> {
    let mut file = PathBuf::from(name);
    if file.as_path().is_file() {
        let metadata = file
            .as_path()
            .symlink_metadata()
            .expect("symlink_metadata call failed");
        if metadata.file_type().is_symlink() {
            match file.as_path().read_link() {
                Ok(f) => file = f,
                Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)),
            }
        }
        Some(file)
    } else {
        None
    }
}

fn die<R>(final_message: &str) -> R {
    eprintln!("{}", final_message.red());
    std::process::exit(1);
}