passbox 2.0.8

A password store for agents, where a fingerprint releases one secret into one process
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
/* A wrap opened by a YubiKey instead of a passphrase.

The passphrase wrap is the one file in a synced store worth attacking, because it can be ground
offline by anyone holding a copy. This wrap has nothing to grind: the private half lives in the
token's secure element and the copy is inert without it in your hand. */

use age::cli_common::UiCallbacks;
use age::plugin::{Identity, IdentityPluginV1, Recipient, RecipientPluginV1};
use anyhow::{Context, Result, anyhow, bail};
use std::str::FromStr;

/* Two different names. The binary on PATH is `age-plugin-yubikey`, and the name inside a
recipient is `yubikey`, which is what the age plugin API matches on. Comparing a parsed
recipient against the binary name rejects every real token. */
const PLUGIN: &str = "age-plugin-yubikey";
const PLUGIN_NAME: &str = "yubikey";

/// Recipients look like `age1yubikey1...` and identities like `AGE-PLUGIN-YUBIKEY-1...`
pub fn recipient(text: &str) -> Result<Box<dyn age::Recipient + Send>> {
    let parsed = Recipient::from_str(text.trim())
        .map_err(|e| anyhow!("{text} is not an age recipient: {e}"))?;
    if parsed.plugin() != PLUGIN_NAME {
        bail!(
            "{} is a {} recipient, not a YubiKey one",
            text,
            parsed.plugin()
        );
    }
    let name = parsed.plugin().to_string();
    let plugin = RecipientPluginV1::new(&name, &[parsed], &[], UiCallbacks)
        .context("age-plugin-yubikey is not on PATH")?;
    Ok(Box::new(plugin))
}

/// Asks the plugin for whichever token is plugged in, so no identity file has to be kept
pub fn identity() -> Result<Box<dyn age::Identity>> {
    let found = Identity::default_for_plugin(PLUGIN_NAME)
        .map_err(|e| anyhow!("no YubiKey identity: {e}"))?;
    let plugin = IdentityPluginV1::new(PLUGIN_NAME, &[found], UiCallbacks)
        .context("age-plugin-yubikey is not on PATH")?;
    Ok(Box::new(plugin))
}

/* Offer rather than act. Installing software is a change to the user's machine, and this
particular binary goes on to handle key material, so it is not something to do quietly. */
pub fn offer_install() -> Result<()> {
    if installed() {
        return Ok(());
    }
    let brew = std::process::Command::new("brew").arg("--version").output();
    if brew.is_err() || !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        bail!("{PLUGIN} is not on PATH, install it with `brew install {PLUGIN}`");
    }

    eprintln!("passbox needs {PLUGIN} to talk to the token, and it is not installed.");
    eprintln!("It is the age plugin that holds the key in the YubiKey's secure element.");
    eprint!("Install it with Homebrew now? [y/N] ");
    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .context("could not read the answer")?;
    if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
        bail!("install it with `brew install {PLUGIN}` and run this again");
    }

    let status = std::process::Command::new("brew")
        .args(["install", PLUGIN])
        .status()
        .context("could not run brew")?;
    if !status.success() || !installed() {
        bail!("brew could not install {PLUGIN}");
    }
    Ok(())
}

/// None means ykman is missing or the applet could not be read
fn piv_info() -> Option<String> {
    let out = std::process::Command::new("ykman")
        .args(["piv", "info"])
        .output()
        .ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/* What the PIV applet already holds. OpenPGP is a separate applet on the same chip, so PGP keys
are never at risk, but a PIV slot in use is worth seeing before provisioning one. None means the
check could not run. */
pub fn piv_slots_in_use() -> Option<Vec<String>> {
    Some(
        piv_info()?
            .lines()
            .filter(|l| l.trim_start().starts_with("Slot "))
            .map(|l| l.trim().to_string())
            .collect(),
    )
}

/* age-plugin-yubikey authenticates with the PIV management key and supports TDES only, so an AES
key fails after the PIN prompt with an error naming neither the cause nor the token. Recent ykman
picks AES192 when it sets a management key, so this is the state a careful user lands in.
See https://github.com/str4d/age-plugin-yubikey/issues/92 */
pub fn management_key_is_supported() -> Result<()> {
    match piv_info() {
        // No ykman, so let the plugin speak for itself
        None => Ok(()),
        Some(info) => check_management_key(&info),
    }
}

fn check_management_key(info: &str) -> Result<()> {
    let Some(algorithm) = info
        .lines()
        .find_map(|l| l.trim().strip_prefix("Management key algorithm:"))
    else {
        return Ok(());
    };
    let algorithm = algorithm.trim();
    if algorithm.eq_ignore_ascii_case("TDES") {
        return Ok(());
    }
    const DEFAULT_TDES: &str = "010203040506070801020304050607080102030405060708";
    bail!(
        "the PIV management key is {algorithm}, and {PLUGIN} can only use TDES.\n\
         Firmware 5.7 sets {algorithm} on a new token and on a factory reset, so this\n\
         is the state a new YubiKey arrives in. Change it, which touches the PIV\n\
         applet only and leaves OpenPGP keys alone:\n\
         \n    ykman piv access change-management-key -a tdes -n {DEFAULT_TDES}\n"
    )
}

/* GPG's scdaemon opens the card exclusively and holds it, so it lands between the plugin's key
generation and its certificate write and the write comes back as an authentication error. The
card is released when scdaemon stops, and gpg-agent starts it again the next time GPG wants it. */
pub fn scdaemon_is_running() -> bool {
    std::process::Command::new("pgrep")
        .args(["-x", "scdaemon"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Stopping another program's daemon is not something to do quietly, so it is offered
pub fn offer_to_stop_scdaemon() -> Result<()> {
    if !scdaemon_is_running() {
        return Ok(());
    }

    eprintln!("GPG's scdaemon is running and is holding the smart card.");
    eprintln!("It takes the card back mid-generation, and the plugin fails with");
    eprintln!("an authentication error that names neither the cause nor the fix.");
    eprintln!("Stopping it frees the card. GPG starts it again on its next use,");
    eprintln!("and your OpenPGP keys and PIN are untouched either way.");
    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        bail!("stop it with `gpgconf --kill scdaemon` and run this again");
    }
    eprint!("Stop scdaemon for this step? [y/N] ");

    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .context("could not read the answer")?;
    if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
        bail!("stop it with `gpgconf --kill scdaemon` and run this again");
    }

    let status = std::process::Command::new("gpgconf")
        .args(["--kill", "scdaemon"])
        .status()
        .context("could not run gpgconf")?;
    if !status.success() || scdaemon_is_running() {
        bail!("scdaemon is still running, stop it with `gpgconf --kill scdaemon`");
    }
    Ok(())
}

/// A recipient on a plugged token, with the `Serial: ..., Slot: ...` line that tells tokens apart
#[derive(Debug, PartialEq)]
pub struct Plugged {
    pub recipient: String,
    pub serial: Option<String>,
}

/// Recipients already provisioned on every token plugged in
pub fn recipients() -> Result<Vec<Plugged>> {
    let out = std::process::Command::new(PLUGIN)
        .arg("--list")
        .output()
        .context("could not run age-plugin-yubikey")?;
    // A plugin error must not read as a blank token, or it sends the user into setup
    if !out.status.success() {
        bail!(
            "age-plugin-yubikey --list failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(parse_list(&String::from_utf8_lossy(&out.stdout)))
}

fn parse_list(out: &str) -> Vec<Plugged> {
    let mut found: Vec<Plugged> = Vec::new();
    let mut serial = None;
    for line in out.lines() {
        if let Some(at) = line.find("Serial:") {
            serial = Some(line[at..].trim().to_string());
        }
        let Some(recipient) = line
            .split_whitespace()
            .find(|w| w.starts_with("age1yubikey1"))
        else {
            continue;
        };
        if !found.iter().any(|p| p.recipient == recipient) {
            found.push(Plugged {
                recipient: recipient.to_string(),
                serial: serial.clone(),
            });
        }
    }
    found
}

/// Plugged recipients the store does not hold yet
pub fn not_added(plugged: Vec<Plugged>, stored: &[String]) -> Vec<Plugged> {
    plugged
        .into_iter()
        .filter(|p| !stored.contains(&p.recipient))
        .collect()
}

/// The one new token, or the pick from several, which needs a terminal to ask on
pub fn choose(
    mut found: Vec<Plugged>,
    seen: usize,
    terminal: bool,
    answer: impl FnOnce() -> Result<String>,
) -> Result<String> {
    if found.len() <= 1 {
        let token = found.pop().with_context(|| {
            if seen == 0 {
                "no YubiKey recipient found, is the token plugged in?".to_string()
            } else {
                format!(
                    "the {seen} plugged token(s) already open this store, \
                     plug in only the new one to set it up"
                )
            }
        })?;
        eprintln!("using {}", token.recipient);
        return Ok(token.recipient);
    }

    if !terminal {
        bail!("several new tokens are plugged in, pass the recipient to `passbox yubikey-add`");
    }
    eprintln!("Several tokens are plugged in and new to this store:");
    for (i, token) in found.iter().enumerate() {
        let serial = token.serial.as_deref().unwrap_or("serial unknown");
        eprintln!("  {}) {serial}  {}", i + 1, token.recipient);
    }
    eprint!("Which? [1-{}] ", found.len());
    let answer = answer()?;
    let pick = answer
        .trim()
        .parse::<usize>()
        .ok()
        .filter(|n| (1..=found.len()).contains(n))
        .with_context(|| format!("expected 1 to {}, got {}", found.len(), answer.trim()))?;
    Ok(found.swap_remove(pick - 1).recipient)
}

/// Provisioning a PIV slot changes the token, so it runs only when the user says so
pub fn generate() -> Result<()> {
    let status = std::process::Command::new(PLUGIN)
        .arg("--generate")
        .status()
        .context("could not run age-plugin-yubikey --generate")?;
    if !status.success() {
        bail!("age-plugin-yubikey --generate did not finish");
    }
    Ok(())
}

pub fn installed() -> bool {
    std::process::Command::new(PLUGIN)
        .arg("--version")
        .output()
        .is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_plain_x25519_recipient_is_refused() {
        let err = match recipient("age1yyc8rqn67hcupyasv6d0tdpghndh2nnkk599emt3z8cqzkhr5ccqg4xglx")
        {
            Ok(_) => panic!("an x25519 recipient was accepted as a YubiKey one"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains("not an age recipient"), "{err}");
    }

    /* The exact `ykman piv info` shape this has to read, from a 5.7.4 token */
    const AES_INFO: &str = "PIV version:              5.7.4\nPIN tries remaining:      3/3\nManagement key algorithm: AES192\nManagement key is stored on the YubiKey, protected by PIN.\n";

    #[test]
    fn an_aes_management_key_is_refused_with_the_fix() {
        let err = check_management_key(AES_INFO).unwrap_err().to_string();
        assert!(err.contains("AES192"), "{err}");
        assert!(err.contains("change-management-key -a tdes"), "{err}");
    }

    #[test]
    fn a_tdes_management_key_passes() {
        let info = AES_INFO.replace("AES192", "TDES");
        assert!(check_management_key(&info).is_ok());
    }

    #[test]
    fn an_unreadable_applet_does_not_block_the_plugin() {
        assert!(check_management_key("").is_ok());
        assert!(check_management_key("PIV version: 5.7.4\n").is_ok());
    }

    /* A real recipient from a provisioned token. The plugin name inside it is `yubikey`, not the
    binary name, and comparing against the binary rejected every genuine token. */
    #[test]
    fn a_real_yubikey_recipient_is_accepted() {
        const REAL: &str =
            "age1yubikey1q0vlphw7w6z47hqzfl8x950zv7hy66aed5amgcvyx8cu4rqcfh7fswwqa7n";
        let parsed = Recipient::from_str(REAL).expect("a valid yubikey recipient");
        assert_eq!(parsed.plugin(), PLUGIN_NAME);
    }

    /* The `--list` shape, two tokens of the same model told apart only by serial */
    const LIST: &str = "#       Serial: 111, Slot: 1\n#         Name: age identity 1\n#      Created: Mon, 1 Jan 2024\n#   PIN policy: Once\n# Touch policy: Always\nage1yubikey1aaa\n\n#       Serial: 222, Slot: 1\n#         Name: age identity 2\nage1yubikey1bbb\n";

    #[test]
    fn list_pairs_each_recipient_with_its_serial() {
        let found = parse_list(LIST);
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].recipient, "age1yubikey1aaa");
        assert_eq!(found[0].serial.as_deref(), Some("Serial: 111, Slot: 1"));
        assert_eq!(found[1].serial.as_deref(), Some("Serial: 222, Slot: 1"));
        assert!(parse_list("").is_empty());
    }

    #[test]
    fn stored_recipients_are_filtered_out() {
        let stored = |s: &[&str]| s.iter().map(|r| r.to_string()).collect::<Vec<_>>();

        let none = not_added(
            parse_list(LIST),
            &stored(&["age1yubikey1aaa", "age1yubikey1bbb"]),
        );
        assert!(none.is_empty());

        let one = not_added(parse_list(LIST), &stored(&["age1yubikey1aaa"]));
        assert_eq!(one.len(), 1);
        assert_eq!(one[0].recipient, "age1yubikey1bbb");

        let many = not_added(parse_list(LIST), &stored(&[]));
        assert_eq!(many.len(), 2);
    }

    #[test]
    fn list_skips_garbage_and_repeats() {
        assert!(parse_list("error: no smart card\n\x00\u{fffd}age1yubi\n").is_empty());
        let twice = parse_list("age1yubikey1aaa\n#  Serial: 1, Slot: 1\nage1yubikey1aaa\n");
        assert_eq!(
            twice,
            vec![Plugged {
                recipient: "age1yubikey1aaa".into(),
                serial: None
            }]
        );
    }

    fn plugged(names: &[&str]) -> Vec<Plugged> {
        names
            .iter()
            .map(|r| Plugged {
                recipient: r.to_string(),
                serial: None,
            })
            .collect()
    }

    fn never() -> Result<String> {
        panic!("one candidate or none must not ask")
    }

    #[test]
    fn choose_takes_the_one_new_token_without_asking() {
        let got = choose(plugged(&["age1yubikey1bbb"]), 2, false, never).unwrap();
        assert_eq!(got, "age1yubikey1bbb");
    }

    #[test]
    fn choose_with_nothing_names_why() {
        let none = choose(Vec::new(), 0, true, never).unwrap_err().to_string();
        assert!(none.contains("is the token plugged in"), "{none}");

        let stored = choose(Vec::new(), 2, true, never).unwrap_err().to_string();
        assert!(
            stored.contains("2 plugged token(s) already open"),
            "{stored}"
        );
    }

    #[test]
    fn choose_among_several_asks_only_on_a_terminal() {
        let two = || plugged(&["age1yubikey1aaa", "age1yubikey1bbb"]);
        let headless = choose(two(), 2, false, never).unwrap_err().to_string();
        assert!(headless.contains("pass the recipient"), "{headless}");

        let got = choose(two(), 2, true, || Ok("2\n".into())).unwrap();
        assert_eq!(got, "age1yubikey1bbb");

        for bad in ["0\n", "3\n", "b\n", ""] {
            let err = choose(two(), 2, true, || Ok(bad.into())).unwrap_err();
            assert!(
                err.to_string().contains("expected 1 to 2"),
                "{bad:?}: {err}"
            );
        }
    }

    #[test]
    fn nonsense_is_refused() {
        assert!(recipient("hello").err().is_some());
        assert!(recipient("").err().is_some());
    }
}