toride-ssh-key 0.1.0

SSH key lifecycle management: generation, inventory, installation, and repair
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! SSH key generation via ssh-keygen CLI and ssh-key crate for parsing.

use base64::Engine;

use crate::get_permissions;
use toride_ssh_core::SshPaths;
use toride_ssh_core::{
    CliRunner, Error, Fingerprint, KeyCreateParams, KeyFormat, KeySource, KeyType, Result, SshKey,
};

/// Minimum RSA key size accepted by OpenSSH.
const MIN_RSA_BITS: u32 = 1024;

/// Recommended RSA key size (doctor flags RSA-2048 as weak).
const RECOMMENDED_RSA_BITS: u32 = 3072;

/// Timeout for `ssh-add` to complete (e.g. waiting for passphrase prompt).
const SSH_ADD_TIMEOUT_SECS: u64 = 30;

/// Convert our [`KeyType`] to the ssh-keygen `-t` argument value.
fn key_type_to_cli_arg(kt: KeyType) -> &'static str {
    match kt {
        KeyType::Ed25519 => "ed25519",
        KeyType::Rsa { .. } => "rsa",
        KeyType::EcdsaP256 | KeyType::EcdsaP384 | KeyType::EcdsaP521 => "ecdsa",
        KeyType::Dsa => "dsa",
        KeyType::SkEd25519 => "sk-ssh-ed25519@openssh.com",
        KeyType::SkEcdsaP256 => "sk-ecdsa-sha2-nistp256@openssh.com",
    }
}

/// Build the `ssh-keygen` CLI argument list from creation parameters.
///
/// SECURITY NOTE: `-N` is only included for the *empty*-passphrase case. When a
/// passphrase is requested it is omitted entirely so `ssh-keygen` prompts for
/// it and reads it via `SSH_ASKPASS` (see [`generate_key`]) — the passphrase
/// never appears in `argv` or `/proc/<pid>/cmdline`, unlike the old
/// `-N <passphrase>` approach which exposed it to every local user via `ps` for
/// the lifetime of the ssh-keygen process.
fn build_keygen_args(params: &KeyCreateParams, private_path_str: &str) -> Vec<String> {
    let key_type_str = key_type_to_cli_arg(params.key_type);
    let passphrase_nonempty = params.passphrase.as_deref().is_some_and(|p| !p.is_empty());

    let mut args: Vec<String> = vec![
        "-t".to_owned(),
        key_type_str.to_owned(),
        "-f".to_owned(),
        private_path_str.to_owned(),
    ];
    // Only pin an empty passphrase (`-N ""`) when none was requested. When one
    // IS requested, omit `-N` so ssh-keygen prompts and reads it via
    // SSH_ASKPASS — never argv.
    if !passphrase_nonempty {
        args.push("-N".to_owned());
        args.push(String::new());
    }

    // RSA bit size — only accept values that OpenSSH actually supports.
    if let KeyType::Rsa { bits } = params.key_type
        && bits > 0
    {
        args.extend(["-b".to_owned(), bits.to_string()]);
    }

    // ECDSA curve size (via -b flag)
    if params.key_type == KeyType::EcdsaP256 {
        args.extend(["-b".to_owned(), "256".to_owned()]);
    }
    if params.key_type == KeyType::EcdsaP384 {
        args.extend(["-b".to_owned(), "384".to_owned()]);
    }
    if params.key_type == KeyType::EcdsaP521 {
        args.extend(["-b".to_owned(), "521".to_owned()]);
    }

    if let Some(ref comment) = params.comment {
        args.extend(["-C".to_owned(), comment.clone()]);
    }

    if let Some(rounds) = params.kdf_rounds {
        args.extend(["-a".to_owned(), rounds.to_string()]);
    }

    if params.touch_required {
        args.extend(["-O".to_owned(), "touch-required".to_owned()]);
    }

    if params.verify_required {
        args.extend(["-O".to_owned(), "verify-required".to_owned()]);
    }

    args
}

/// Generate a new SSH key pair.
#[expect(
    clippy::too_many_lines,
    reason = "orchestrates generation, permissions, agent, config"
)]
pub async fn generate_key(
    paths: &SshPaths,
    params: KeyCreateParams,
    runner: &dyn CliRunner,
) -> Result<SshKey> {
    let private_path = paths.ssh_dir().join(&params.name);
    let public_path = private_path.with_extension("pub");

    if private_path.exists() {
        return Err(Error::KeyExists(params.name.clone()));
    }

    if !runner.tool_exists("ssh-keygen") {
        return Err(Error::ToolNotFound("ssh-keygen".to_owned()));
    }

    // Validate RSA bit size early to give a clear error before calling ssh-keygen.
    if let KeyType::Rsa { bits } = params.key_type
        && bits > 0
        && bits < MIN_RSA_BITS
    {
        return Err(Error::KeyGenerationFailed(format!(
            "RSA bit size {bits} is below minimum {MIN_RSA_BITS}"
        )));
    }

    // Warn (but do not error) when RSA bits are below the recommended size.
    if let KeyType::Rsa { bits } = params.key_type
        && bits > 0
        && bits < RECOMMENDED_RSA_BITS
    {
        tracing::warn!(
            "RSA key size {bits} is below the recommended {RECOMMENDED_RSA_BITS} bits; \
             consider using at least {RECOMMENDED_RSA_BITS} bits or switching to Ed25519"
        );
    }

    let passphrase_nonempty = params.passphrase.as_deref().is_some_and(|p| !p.is_empty());

    let private_path_str = private_path
        .to_str()
        .ok_or_else(|| Error::KeyGenerationFailed("invalid key path".to_owned()))?;

    let args = build_keygen_args(&params, private_path_str);

    // When a passphrase is requested, ssh-keygen is invoked WITHOUT `-N` (see
    // `build_keygen_args`) so it prompts for it. Feed the passphrase via an
    // SSH_ASKPASS helper script so it is read from a temp file rather than
    // passed in argv — `-N <passphrase>` would expose it via `ps`/cmdline. The
    // handler's Drop removes the script as soon as the run completes.
    if passphrase_nonempty {
        let askpass =
            toride_ssh_agent::AskpassHandler::new(params.passphrase.as_deref().unwrap_or(""))?;
        let askpass_env = vec![
            (
                "SSH_ASKPASS".to_owned(),
                askpass.script_path().to_string_lossy().into_owned(),
            ),
            ("SSH_ASKPASS_REQUIRE".to_owned(), "force".to_owned()),
            ("DISPLAY".to_owned(), ":0".to_owned()),
        ];
        runner.run_with_env("ssh-keygen", args, askpass_env).await?;
    } else {
        runner.run("ssh-keygen", args).await?;
    }

    // Set file permissions and read the generated key in a blocking context
    // to avoid blocking the async runtime with synchronous filesystem ops.
    let private_path_clone = private_path.clone();
    // Only the Unix branch chmods the containing directory (no POSIX modes
    // elsewhere), so the binding exists solely on Unix.
    #[cfg(unix)]
    let ssh_dir = paths.ssh_dir().to_path_buf();

    let result = tokio::task::spawn_blocking(move || {
        // Set file permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Err(e) =
                std::fs::set_permissions(&ssh_dir, std::fs::Permissions::from_mode(0o700))
            {
                tracing::warn!("failed to set permissions on {}: {e}", ssh_dir.display());
            }
            if let Err(e) = std::fs::set_permissions(
                &private_path_clone,
                std::fs::Permissions::from_mode(0o600),
            ) {
                tracing::warn!(
                    "failed to set permissions on {}: {e}",
                    private_path_clone.display()
                );
            }
            if let Err(e) =
                std::fs::set_permissions(&public_path, std::fs::Permissions::from_mode(0o644))
            {
                tracing::warn!(
                    "failed to set permissions on {}: {e}",
                    public_path.display()
                );
            }
        }

        let permissions = get_permissions(&private_path_clone);

        let private_key_data = std::fs::read_to_string(&private_path_clone)
            .map_err(|e| Error::KeyParseFailed(format!("failed to read generated key: {e}")))?;

        let pk = ssh_key::PrivateKey::from_openssh(&private_key_data)
            .map_err(|e| Error::KeyParseFailed(format!("failed to parse generated key: {e}")))?;

        Ok::<_, Error>((permissions, pk, public_path.exists()))
    })
    .await
    .map_err(|e| Error::TaskFailed(format!("post-generation task failed: {e}")))??;

    let (permissions, pk, has_public_pair) = result;

    // Add to agent if requested
    if params.add_to_agent {
        add_key_to_agent(&private_path, runner).await?;
    }

    // Add to SSH config if requested.
    if params.add_to_config {
        let host_alias = params
            .config_host
            .as_deref()
            .unwrap_or(&params.name)
            .to_owned();
        let identity_value = format!("~/.ssh/{}", params.name);
        let config_service = toride_ssh_config::ConfigService::new(paths);
        config_service
            .edit(|ast| {
                toride_ssh_config::ConfigService::add_host(
                    ast,
                    &host_alias,
                    vec![
                        ("HostName".to_owned(), host_alias.clone()),
                        ("IdentityFile".to_owned(), identity_value),
                    ],
                )
            })
            .await?;
    }

    let public_key = pk.public_key();
    let fp = public_key.fingerprint(ssh_key::HashAlg::Sha256);
    let fingerprint = Some(Fingerprint {
        hash: base64::engine::general_purpose::STANDARD_NO_PAD.encode(fp.as_bytes()),
        key_type: params.key_type,
    });

    let comment_str = pk.comment().to_string();
    let comment = if comment_str.is_empty() {
        None
    } else {
        Some(comment_str)
    };

    Ok(SshKey {
        path: private_path,
        key_type: params.key_type,
        fingerprint,
        comment,
        encrypted: passphrase_nonempty,
        source: KeySource::Filesystem,
        permissions,
        has_public_pair,
        has_certificate: false,
        last_modified: None,
        used_by_hosts: Vec::new(),
        key_format: Some(KeyFormat::OpenSSH),
    })
}

/// Add a key to the SSH agent.
///
/// Delegates to [`CliRunner::run`] so the call is testable with
/// [`MockCliRunner`].  A `tokio::time::timeout` wraps the call so that a
/// stuck agent (e.g. waiting for a passphrase prompt that never arrives) does
/// not hang indefinitely.
async fn add_key_to_agent(private_path: &std::path::Path, runner: &dyn CliRunner) -> Result<()> {
    let path_str = private_path
        .to_str()
        .ok_or_else(|| Error::CommandFailed("key path is not valid UTF-8".to_owned()))?
        .to_owned();

    let args = vec![path_str];

    tokio::time::timeout(
        std::time::Duration::from_secs(SSH_ADD_TIMEOUT_SECS),
        runner.run("ssh-add", args),
    )
    .await
    .map_err(|_| {
        Error::CommandFailed(format!(
            "ssh-add timed out after {SSH_ADD_TIMEOUT_SECS} seconds"
        ))
    })??;

    Ok(())
}

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

    #[test]
    fn key_type_to_cli_arg_all_types() {
        assert_eq!(key_type_to_cli_arg(KeyType::Ed25519), "ed25519");
        assert_eq!(key_type_to_cli_arg(KeyType::Rsa { bits: 4096 }), "rsa");
        assert_eq!(key_type_to_cli_arg(KeyType::EcdsaP256), "ecdsa");
        assert_eq!(key_type_to_cli_arg(KeyType::EcdsaP384), "ecdsa");
        assert_eq!(key_type_to_cli_arg(KeyType::EcdsaP521), "ecdsa");
        assert_eq!(key_type_to_cli_arg(KeyType::Dsa), "dsa");
        assert_eq!(
            key_type_to_cli_arg(KeyType::SkEd25519),
            "sk-ssh-ed25519@openssh.com"
        );
        assert_eq!(
            key_type_to_cli_arg(KeyType::SkEcdsaP256),
            "sk-ecdsa-sha2-nistp256@openssh.com"
        );
    }

    #[test]
    fn build_keygen_args_ed25519_basic() {
        let params = KeyCreateParams {
            name: "id_ed25519".to_owned(),
            key_type: KeyType::Ed25519,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/home/user/.ssh/id_ed25519");
        assert_eq!(
            args[0..4],
            ["-t", "ed25519", "-f", "/home/user/.ssh/id_ed25519"]
        );
        assert_eq!(args[4..6], ["-N", ""]);
        assert!(!args.contains(&"-b".to_owned()));
        assert!(!args.contains(&"-C".to_owned()));
    }

    #[test]
    fn build_keygen_args_rsa_with_bits() {
        let params = KeyCreateParams {
            name: "id_rsa".to_owned(),
            key_type: KeyType::Rsa { bits: 4096 },
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-b".to_owned()));
        assert!(args.contains(&"4096".to_owned()));
    }

    #[test]
    fn build_keygen_args_with_comment() {
        let params = KeyCreateParams {
            name: "id_ed25519".to_owned(),
            key_type: KeyType::Ed25519,
            comment: Some("user@host".to_owned()),
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-C".to_owned()));
        assert!(args.contains(&"user@host".to_owned()));
    }

    #[test]
    fn build_keygen_args_with_passphrase() {
        let params = KeyCreateParams {
            name: "id_ed25519".to_owned(),
            key_type: KeyType::Ed25519,
            comment: None,
            passphrase: Some("secret".to_owned()),
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        // When a passphrase is requested, `-N` is OMITTED entirely so
        // ssh-keygen prompts and reads it via SSH_ASKPASS — neither `-N` nor
        // the passphrase value appears in argv.
        assert!(
            !args.contains(&"-N".to_owned()),
            "-N must be omitted when a passphrase is requested: {args:?}"
        );
        assert!(
            !args.iter().any(|a| a == "secret"),
            "passphrase leaked into ssh-keygen argv: {args:?}"
        );
    }

    /// Validate the `SSH_ASKPASS` key-generation path end-to-end with real
    /// `ssh-keygen`: generating WITHOUT `-N` while feeding the passphrase via
    /// an askpass helper yields an encrypted key OpenSSH can read with that
    /// passphrase (and rejects a wrong one). This is the load-bearing
    /// compatibility guarantee for the askpass path in [`generate_key`].
    /// Skips when `ssh-keygen` is not on PATH.
    #[test]
    fn askpass_keygen_is_openssh_compatible() {
        let ssh_keygen_present = std::process::Command::new("ssh-keygen")
            .arg("--help")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok();
        if !ssh_keygen_present {
            eprintln!("skipping: ssh-keygen not available");
            return;
        }
        let dir = tempfile::TempDir::new().expect("temp dir");
        let keypath = dir.path().join("askpass_key");
        let keypath_str = keypath.to_str().expect("utf-8 path");

        // Build an askpass helper mirroring AskpassHandler (echo the passphrase).
        let askpass_script = dir.path().join("askpass.sh");
        std::fs::write(&askpass_script, "#!/bin/sh\necho testpass\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&askpass_script, std::fs::Permissions::from_mode(0o700))
                .unwrap();
        }

        // Generate WITHOUT `-N` (the passphrase-case shape), reading the
        // passphrase via SSH_ASKPASS so it never enters argv.
        let generate = std::process::Command::new("ssh-keygen")
            .args(["-t", "ed25519", "-f", keypath_str, "-C", "askpass-test"])
            .env("SSH_ASKPASS", &askpass_script)
            .env("SSH_ASKPASS_REQUIRE", "force")
            .env("DISPLAY", ":0")
            .stdin(std::process::Stdio::null())
            .output()
            .expect("spawn ssh-keygen");
        assert!(
            generate.status.success(),
            "ssh-keygen askpass generate failed: {}",
            String::from_utf8_lossy(&generate.stderr)
        );

        // OpenSSH must derive the public key with the correct passphrase.
        let verify = std::process::Command::new("ssh-keygen")
            .args(["-y", "-P", "testpass", "-f", keypath_str])
            .output()
            .expect("spawn ssh-keygen verify");
        assert!(
            verify.status.success(),
            "ssh-keygen could not read askpass-generated key: {}",
            String::from_utf8_lossy(&verify.stderr)
        );
        assert!(
            String::from_utf8_lossy(&verify.stdout).starts_with("ssh-ed25519 "),
            "unexpected public key output"
        );

        // A wrong passphrase must be rejected.
        let wrong = std::process::Command::new("ssh-keygen")
            .args(["-y", "-P", "wrongpass", "-f", keypath_str])
            .output()
            .expect("spawn ssh-keygen wrong");
        assert!(
            !wrong.status.success(),
            "wrong passphrase unexpectedly accepted"
        );
    }

    #[test]
    fn build_keygen_args_with_kdf_rounds() {
        let params = KeyCreateParams {
            name: "id_ed25519".to_owned(),
            key_type: KeyType::Ed25519,
            comment: None,
            passphrase: Some("pass".to_owned()),
            kdf_rounds: Some(64),
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-a".to_owned()));
        assert!(args.contains(&"64".to_owned()));
    }

    #[test]
    fn build_keygen_args_ecdsa_p384() {
        let params = KeyCreateParams {
            name: "id_ecdsa".to_owned(),
            key_type: KeyType::EcdsaP384,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-b".to_owned()));
        assert!(args.contains(&"384".to_owned()));
    }

    #[test]
    fn build_keygen_args_ecdsa_p521() {
        let params = KeyCreateParams {
            name: "id_ecdsa".to_owned(),
            key_type: KeyType::EcdsaP521,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-b".to_owned()));
        assert!(args.contains(&"521".to_owned()));
    }

    #[test]
    fn build_keygen_args_touch_required() {
        let params = KeyCreateParams {
            name: "id_sk".to_owned(),
            key_type: KeyType::SkEd25519,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: true,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-O".to_owned()));
        assert!(args.contains(&"touch-required".to_owned()));
        assert!(!args.contains(&"verify-required".to_owned()));
    }

    #[test]
    fn build_keygen_args_verify_required() {
        let params = KeyCreateParams {
            name: "id_sk".to_owned(),
            key_type: KeyType::SkEd25519,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: true,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"-O".to_owned()));
        assert!(args.contains(&"verify-required".to_owned()));
        assert!(!args.contains(&"touch-required".to_owned()));
    }

    #[test]
    fn build_keygen_args_touch_and_verify_required() {
        let params = KeyCreateParams {
            name: "id_sk".to_owned(),
            key_type: KeyType::SkEcdsaP256,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: true,
            verify_required: true,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(args.contains(&"touch-required".to_owned()));
        assert!(args.contains(&"verify-required".to_owned()));
    }

    #[test]
    fn build_keygen_args_no_fido_options_when_false() {
        let params = KeyCreateParams {
            name: "id_ed25519".to_owned(),
            key_type: KeyType::Ed25519,
            comment: None,
            passphrase: None,
            kdf_rounds: None,
            add_to_agent: false,
            add_to_config: false,
            config_host: None,
            touch_required: false,
            verify_required: false,
        };
        let args = build_keygen_args(&params, "/tmp/key");
        assert!(!args.contains(&"touch-required".to_owned()));
        assert!(!args.contains(&"verify-required".to_owned()));
    }
}