Skip to main content

gitpoulpi_hosting/
ssh_key.rs

1//! Generating an SSH key pair, in process.
2//!
3//! **Why not shell out to `ssh-keygen`.** It is not reliably installed
4//! (Windows ships the OpenSSH client as an optional feature that managed
5//! images often have off, and the binary on `PATH` may be Git for
6//! Windows', WSL's or none) and it is interactive by default. `ssh-key`
7//! produces the same OpenSSH-format files with no process and no prompt.
8//!
9//! **Ed25519 by default.** Short, fast, and accepted by both GitHub and
10//! GitLab. `ssh.key_type` can ask for RSA (4096 bits) or ECDSA (NIST
11//! P-256) instead, see [`KeyType`].
12//!
13//! **No passphrase.** A generated key is written unencrypted, as
14//! `ssh-keygen -N ""` would, because the point is a key an agent-less
15//! `git fetch` can use unattended. The file permissions below are what
16//! protects it; the docstring on [`generate_and_write`] says so.
17
18use std::path::{Path, PathBuf};
19
20use crate::{Error, Result};
21
22/// The kind of key to generate (`ssh.key_type`).
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum KeyType {
25    #[default]
26    Ed25519,
27    /// RSA, 4096 bits.
28    Rsa,
29    /// ECDSA over NIST P-256.
30    Ecdsa,
31}
32
33impl KeyType {
34    /// Reads the `ssh.key_type` setting; anything unknown is ed25519.
35    pub fn from_setting(value: &str) -> Self {
36        match value.trim().to_ascii_lowercase().as_str() {
37            "rsa" => Self::Rsa,
38            "ecdsa" => Self::Ecdsa,
39            _ => Self::Ed25519,
40        }
41    }
42
43    /// The name used in file names and messages.
44    pub fn name(self) -> &'static str {
45        match self {
46            Self::Ed25519 => "ed25519",
47            Self::Rsa => "rsa",
48            Self::Ecdsa => "ecdsa",
49        }
50    }
51
52    fn algorithm(self) -> ssh_key::Algorithm {
53        match self {
54            Self::Ed25519 => ssh_key::Algorithm::Ed25519,
55            Self::Rsa => ssh_key::Algorithm::Rsa { hash: None },
56            Self::Ecdsa => ssh_key::Algorithm::Ecdsa {
57                curve: ssh_key::EcdsaCurve::NistP256,
58            },
59        }
60    }
61}
62
63/// A freshly generated pair. The private half is held only long enough
64/// to be written; nothing in this crate sends it anywhere.
65#[derive(Debug)]
66pub struct GeneratedKey {
67    /// The `ssh-ed25519 AAAA... <comment>` line, which is what gets
68    /// uploaded.
69    pub public_key: String,
70    pub private_key_path: PathBuf,
71    pub public_key_path: PathBuf,
72    /// `SHA256:...`, for showing the user which key they just made and
73    /// for matching against what the host already has.
74    pub fingerprint: String,
75}
76
77/// The default key path, `~/.ssh/id_ed25519`, which is where ssh looks
78/// without being told.
79pub fn default_key_path() -> Result<PathBuf> {
80    let home = home_dir().ok_or_else(|| {
81        Error::Ssh("could not determine the home directory for ~/.ssh".to_string())
82    })?;
83    Ok(home.join(".ssh").join("id_ed25519"))
84}
85
86/// `dirs`-free home lookup. `HOME` is checked first (so a user who set it
87/// deliberately on Windows, MSYS or Git Bash gets the `.ssh` directory
88/// they use), then `USERPROFILE`, which ssh itself uses on Windows.
89fn home_dir() -> Option<PathBuf> {
90    for var in ["HOME", "USERPROFILE"] {
91        if let Some(value) = std::env::var_os(var) {
92            if !value.is_empty() {
93                return Some(PathBuf::from(value));
94            }
95        }
96    }
97    None
98}
99
100/// Generates an Ed25519 pair (see [`generate_typed_and_write`] for the others) and writes it to `path` and `path.pub`.
101///
102/// **The private key is written without a passphrase**, and is readable
103/// by anyone who can read the file. On Unix it is created `0600`; on
104/// Windows it inherits the directory's ACL (for a path under the user
105/// profile, the user and administrators).
106///
107/// Refuses to overwrite an existing key: replacing one would destroy
108/// access to every host it was registered with. The caller is told to
109/// pick another path or delete the old one deliberately.
110pub fn generate_and_write(path: &Path, comment: &str) -> Result<GeneratedKey> {
111    generate_typed_and_write(path, comment, KeyType::Ed25519)
112}
113
114/// [`generate_and_write`] for a chosen [`KeyType`].
115pub fn generate_typed_and_write(
116    path: &Path,
117    comment: &str,
118    key_type: KeyType,
119) -> Result<GeneratedKey> {
120    use ssh_key::{LineEnding, PrivateKey};
121
122    let public_path = public_path_for(path);
123    for existing in [path, &public_path] {
124        if existing.exists() {
125            return Err(Error::Ssh(format!(
126                "{} already exists; delete it or choose another path rather than \
127                 overwriting a key other hosts may still trust",
128                existing.display()
129            )));
130        }
131    }
132
133    let mut rng = ::ssh_key::rand_core::UnwrapErr(::ssh_key::getrandom::SysRng);
134    let mut key = PrivateKey::random(&mut rng, key_type.algorithm()).map_err(|e| {
135        Error::Ssh(format!(
136            "could not generate an {} key: {e}",
137            key_type.name()
138        ))
139    })?;
140    key.set_comment(comment);
141
142    let private_pem = key
143        // Always LF: an OpenSSH private key with CRLF line endings is
144        // rejected by ssh on every platform, Windows included.
145        .to_openssh(LineEnding::LF)
146        .map_err(|e| Error::Ssh(format!("could not encode the private key: {e}")))?;
147    let public_line = key
148        .public_key()
149        .to_openssh()
150        .map_err(|e| Error::Ssh(format!("could not encode the public key: {e}")))?;
151    let fingerprint = key
152        .public_key()
153        .fingerprint(ssh_key::HashAlg::Sha256)
154        .to_string();
155
156    if let Some(parent) = path.parent() {
157        std::fs::create_dir_all(parent)
158            .map_err(|e| Error::Ssh(format!("could not create {}: {e}", parent.display())))?;
159    }
160    write_private(path, private_pem.as_bytes())?;
161    std::fs::write(&public_path, format!("{public_line}\n"))
162        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", public_path.display())))?;
163
164    Ok(GeneratedKey {
165        public_key: public_line,
166        private_key_path: path.to_path_buf(),
167        public_key_path: public_path,
168        fingerprint,
169    })
170}
171
172fn public_path_for(path: &Path) -> PathBuf {
173    let mut name = path.as_os_str().to_os_string();
174    name.push(".pub");
175    PathBuf::from(name)
176}
177
178/// Writes the private key with the tightest permissions the platform
179/// offers: on Unix `0600`, set *at creation* (chmod afterwards leaves a
180/// window where the key is world-readable, and ssh refuses a group- or
181/// world-readable key).
182#[cfg(unix)]
183fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
184    use std::io::Write;
185    use std::os::unix::fs::OpenOptionsExt;
186
187    let mut file = std::fs::OpenOptions::new()
188        .write(true)
189        .create_new(true)
190        .mode(0o600)
191        .open(path)
192        .map_err(|e| Error::Ssh(format!("could not create {}: {e}", path.display())))?;
193    file.write_all(bytes)
194        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", path.display())))
195}
196
197/// Windows has no mode bits. The file inherits the ACL of its directory,
198/// which under the user profile is the user plus administrators --
199/// which is also exactly what `ssh-keygen` produces there, so this is
200/// not a weaker guarantee than the alternative.
201#[cfg(not(unix))]
202fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
203    use std::io::Write;
204
205    let mut file = std::fs::OpenOptions::new()
206        .write(true)
207        .create_new(true)
208        .open(path)
209        .map_err(|e| Error::Ssh(format!("could not create {}: {e}", path.display())))?;
210    file.write_all(bytes)
211        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", path.display())))
212}
213
214/// A default title for an uploaded key: the machine's name, so a user
215/// with keys from three machines can tell them apart on the host's
216/// settings page.
217pub fn default_key_title() -> String {
218    let host = std::env::var("COMPUTERNAME")
219        .or_else(|_| std::env::var("HOSTNAME"))
220        .ok()
221        .filter(|h| !h.trim().is_empty())
222        .unwrap_or_else(|| "unknown-host".to_string());
223    format!("gitpoulpi@{host}")
224}
225
226/// The private-key path a profile's generated key gets inside `ssh_dir`:
227/// `gitpoulpi_<profile id>_ed25519`. Per profile so two accounts on one
228/// host never share (or overwrite) a key.
229pub fn profile_key_path(ssh_dir: &Path, profile_id: &str) -> PathBuf {
230    let safe: String = profile_id
231        .chars()
232        .map(|c| {
233            if c.is_ascii_alphanumeric() || c == '-' {
234                c
235            } else {
236                '_'
237            }
238        })
239        .collect();
240    ssh_dir.join(format!("gitpoulpi_{safe}_ed25519"))
241}
242
243/// The `core.sshCommand` value that pins one private key for a repository
244/// (ADR-0008): `ssh -i "<key>" -o IdentitiesOnly=yes`. Backslashes become
245/// forward slashes, which git's `sh` accepts on Windows too.
246pub fn ssh_command_for_key(private_key_path: &str) -> String {
247    gitpoulpi_core::repo_config::ssh_command_for_key(private_key_path)
248}
249
250/// `~/.ssh`, where ssh looks for keys.
251pub fn ssh_dir() -> Result<PathBuf> {
252    default_key_path().map(|p| p.parent().map(Path::to_path_buf).unwrap_or_default())
253}
254
255/// The title a profile's key gets when the user does not type one:
256/// `GitPoulpi <host> <YYYY-MM-DD>`.
257pub fn profile_key_title(host: &str) -> String {
258    format!("GitPoulpi {host} {}", today_ymd())
259}
260
261/// Today's UTC date as `YYYY-MM-DD`, without a date crate (civil-from-days).
262fn today_ymd() -> String {
263    let secs = std::time::SystemTime::now()
264        .duration_since(std::time::UNIX_EPOCH)
265        .map_or(0, |d| d.as_secs() as i64);
266    let z = secs.div_euclid(86_400) + 719_468;
267    let era = z.div_euclid(146_097);
268    let doe = z.rem_euclid(146_097);
269    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
270    let y = yoe + era * 400;
271    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
272    let mp = (5 * doy + 2) / 153;
273    let d = doy - (153 * mp + 2) / 5 + 1;
274    let m = if mp < 10 { mp + 3 } else { mp - 9 };
275    let y = if m <= 2 { y + 1 } else { y };
276    format!("{y:04}-{m:02}-{d:02}")
277}
278
279/// `SHA256:...` of an OpenSSH public-key line, or `None` when it is not one.
280pub fn fingerprint_of(public_line: &str) -> Option<String> {
281    ssh_key::PublicKey::from_openssh(public_line.trim())
282        .ok()
283        .map(|k| k.fingerprint(ssh_key::HashAlg::Sha256).to_string())
284}
285
286/// Whether two public-key lines are the same key (the comment, which
287/// hosts rewrite, is ignored).
288pub fn same_public_key(a: &str, b: &str) -> bool {
289    let body = |s: &str| {
290        let mut it = s.split_whitespace();
291        Some((it.next()?.to_string(), it.next()?.to_string()))
292    };
293    matches!((body(a), body(b)), (Some(x), Some(y)) if x == y)
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    #[test]
301    fn the_key_type_setting_is_read_with_ed25519_as_the_fallback() {
302        assert_eq!(KeyType::from_setting("rsa"), KeyType::Rsa);
303        assert_eq!(KeyType::from_setting(" ECDSA "), KeyType::Ecdsa);
304        assert_eq!(KeyType::from_setting("ed25519"), KeyType::Ed25519);
305        assert_eq!(KeyType::from_setting("nonsense"), KeyType::Ed25519);
306    }
307
308    /// Every type produces files ssh can read back, of the type asked for.
309    #[test]
310    fn each_key_type_is_generated_as_asked() {
311        let dir = tempfile::tempdir().unwrap();
312        for (key_type, prefix, bits) in [
313            (KeyType::Ed25519, "ssh-ed25519 ", None),
314            (KeyType::Ecdsa, "ecdsa-sha2-nistp256 ", None),
315            (KeyType::Rsa, "ssh-rsa ", Some(4096)),
316        ] {
317            let path = dir.path().join(format!("k_{}", key_type.name()));
318            let key = generate_typed_and_write(&path, "c", key_type).unwrap();
319            assert!(key.public_key.starts_with(prefix), "{}", key.public_key);
320            assert!(path.is_file() && public_path_for(&path).is_file());
321            let private = std::fs::read_to_string(&path).unwrap();
322            let parsed = ssh_key::PrivateKey::from_openssh(&private).unwrap();
323            assert_eq!(
324                parsed.public_key().to_openssh().unwrap(),
325                key.public_key,
326                "the private file matches the public line"
327            );
328            if let (Some(bits), Some(rsa)) = (bits, parsed.public_key().key_data().rsa()) {
329                assert_eq!(rsa.n().as_positive_bytes().unwrap().len() * 8, bits);
330            }
331        }
332    }
333
334    #[test]
335    fn the_ssh_command_pins_one_key() {
336        assert_eq!(
337            ssh_command_for_key(r"C:\Users\me\.ssh\k"),
338            r#"ssh -i "C:/Users/me/.ssh/k" -o IdentitiesOnly=yes"#
339        );
340    }
341
342    #[test]
343    fn profile_paths_titles_and_fingerprints() {
344        let p = profile_key_path(Path::new("/h/.ssh"), "gitlab-self-managed-2");
345        assert!(p.ends_with("gitpoulpi_gitlab-self-managed-2_ed25519"));
346        assert!(profile_key_path(Path::new("/h"), "a/b c").ends_with("gitpoulpi_a_b_c_ed25519"));
347        let t = profile_key_title("gitlab.example.com");
348        assert!(t.starts_with("GitPoulpi gitlab.example.com 20"), "{t}");
349        let dir = tempfile::tempdir().unwrap();
350        let k = generate_and_write(&dir.path().join("k"), "c").unwrap();
351        assert_eq!(
352            fingerprint_of(&k.public_key).as_deref(),
353            Some(k.fingerprint.as_str())
354        );
355        assert!(same_public_key(
356            &k.public_key,
357            &format!(
358                "{} other",
359                k.public_key
360                    .split(' ')
361                    .take(2)
362                    .collect::<Vec<_>>()
363                    .join(" ")
364            )
365        ));
366        assert!(!same_public_key("ssh-ed25519 AAA", "ssh-ed25519 BBB"));
367        assert_eq!(fingerprint_of("garbage"), None);
368    }
369
370    #[test]
371    fn a_generated_key_is_a_usable_openssh_pair() {
372        let dir = tempfile::tempdir().unwrap();
373        let path = dir.path().join("keys").join("id_ed25519");
374
375        let key = generate_and_write(&path, "gitpoulpi@test").unwrap();
376
377        assert!(key.public_key.starts_with("ssh-ed25519 "));
378        assert!(key.public_key.ends_with("gitpoulpi@test"));
379        assert!(key.fingerprint.starts_with("SHA256:"));
380        assert_eq!(key.public_key_path, path.with_extension("pub"));
381
382        let private = std::fs::read_to_string(&path).unwrap();
383        assert!(private.starts_with("-----BEGIN OPENSSH PRIVATE KEY-----"));
384        assert!(
385            !private.contains('\r'),
386            "an OpenSSH private key with CRLF is rejected by ssh everywhere"
387        );
388
389        // The written public file must be the same line that gets
390        // uploaded, or the host trusts a key the machine does not have.
391        let public_file = std::fs::read_to_string(&key.public_key_path).unwrap();
392        assert_eq!(public_file.trim_end(), key.public_key);
393
394        // And it must round-trip through a real parser, not just look
395        // right.
396        let parsed = ssh_key::PublicKey::from_openssh(&key.public_key).unwrap();
397        assert_eq!(parsed.algorithm(), ssh_key::Algorithm::Ed25519);
398    }
399
400    #[test]
401    fn two_generated_keys_are_different() {
402        let dir = tempfile::tempdir().unwrap();
403        let a = generate_and_write(&dir.path().join("a"), "a").unwrap();
404        let b = generate_and_write(&dir.path().join("b"), "b").unwrap();
405        assert_ne!(a.public_key, b.public_key);
406        assert_ne!(a.fingerprint, b.fingerprint);
407    }
408
409    /// Overwriting a key revokes access to every host that trusts it,
410    /// with no undo.
411    #[test]
412    fn an_existing_key_is_never_overwritten() {
413        let dir = tempfile::tempdir().unwrap();
414        let path = dir.path().join("id_ed25519");
415        let first = generate_and_write(&path, "first").unwrap();
416
417        let err = generate_and_write(&path, "second").unwrap_err();
418        assert!(err.to_string().contains("already exists"), "{err}");
419        assert_eq!(
420            std::fs::read_to_string(&first.public_key_path)
421                .unwrap()
422                .trim_end(),
423            first.public_key,
424            "the original key must be untouched"
425        );
426    }
427
428    /// A stray `id_ed25519.pub` with no private half still means "there
429    /// is something here"; clobbering it would leave a public key that
430    /// no private key matches.
431    #[test]
432    fn a_lone_public_key_also_blocks_generation() {
433        let dir = tempfile::tempdir().unwrap();
434        let path = dir.path().join("id_ed25519");
435        std::fs::write(path.with_extension("pub"), "ssh-ed25519 AAAA old\n").unwrap();
436        assert!(generate_and_write(&path, "new").is_err());
437    }
438
439    #[cfg(unix)]
440    #[test]
441    fn the_private_key_is_not_readable_by_anyone_else() {
442        use std::os::unix::fs::PermissionsExt;
443        let dir = tempfile::tempdir().unwrap();
444        let path = dir.path().join("id_ed25519");
445        generate_and_write(&path, "test").unwrap();
446        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
447        assert_eq!(mode & 0o077, 0, "ssh refuses a group/world-readable key");
448    }
449}