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 key = PrivateKey::random(&mut rand_core::OsRng, key_type.algorithm()).map_err(|e| {
134        Error::Ssh(format!(
135            "could not generate an {} key: {e}",
136            key_type.name()
137        ))
138    })?;
139    key.set_comment(comment);
140
141    let private_pem = key
142        // Always LF: an OpenSSH private key with CRLF line endings is
143        // rejected by ssh on every platform, Windows included.
144        .to_openssh(LineEnding::LF)
145        .map_err(|e| Error::Ssh(format!("could not encode the private key: {e}")))?;
146    let public_line = key
147        .public_key()
148        .to_openssh()
149        .map_err(|e| Error::Ssh(format!("could not encode the public key: {e}")))?;
150    let fingerprint = key
151        .public_key()
152        .fingerprint(ssh_key::HashAlg::Sha256)
153        .to_string();
154
155    if let Some(parent) = path.parent() {
156        std::fs::create_dir_all(parent)
157            .map_err(|e| Error::Ssh(format!("could not create {}: {e}", parent.display())))?;
158    }
159    write_private(path, private_pem.as_bytes())?;
160    std::fs::write(&public_path, format!("{public_line}\n"))
161        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", public_path.display())))?;
162
163    Ok(GeneratedKey {
164        public_key: public_line,
165        private_key_path: path.to_path_buf(),
166        public_key_path: public_path,
167        fingerprint,
168    })
169}
170
171fn public_path_for(path: &Path) -> PathBuf {
172    let mut name = path.as_os_str().to_os_string();
173    name.push(".pub");
174    PathBuf::from(name)
175}
176
177/// Writes the private key with the tightest permissions the platform
178/// offers: on Unix `0600`, set *at creation* (chmod afterwards leaves a
179/// window where the key is world-readable, and ssh refuses a group- or
180/// world-readable key).
181#[cfg(unix)]
182fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
183    use std::io::Write;
184    use std::os::unix::fs::OpenOptionsExt;
185
186    let mut file = std::fs::OpenOptions::new()
187        .write(true)
188        .create_new(true)
189        .mode(0o600)
190        .open(path)
191        .map_err(|e| Error::Ssh(format!("could not create {}: {e}", path.display())))?;
192    file.write_all(bytes)
193        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", path.display())))
194}
195
196/// Windows has no mode bits. The file inherits the ACL of its directory,
197/// which under the user profile is the user plus administrators --
198/// which is also exactly what `ssh-keygen` produces there, so this is
199/// not a weaker guarantee than the alternative.
200#[cfg(not(unix))]
201fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
202    use std::io::Write;
203
204    let mut file = std::fs::OpenOptions::new()
205        .write(true)
206        .create_new(true)
207        .open(path)
208        .map_err(|e| Error::Ssh(format!("could not create {}: {e}", path.display())))?;
209    file.write_all(bytes)
210        .map_err(|e| Error::Ssh(format!("could not write {}: {e}", path.display())))
211}
212
213/// A default title for an uploaded key: the machine's name, so a user
214/// with keys from three machines can tell them apart on the host's
215/// settings page.
216pub fn default_key_title() -> String {
217    let host = std::env::var("COMPUTERNAME")
218        .or_else(|_| std::env::var("HOSTNAME"))
219        .ok()
220        .filter(|h| !h.trim().is_empty())
221        .unwrap_or_else(|| "unknown-host".to_string());
222    format!("gitpoulpi@{host}")
223}
224
225/// The private-key path a profile's generated key gets inside `ssh_dir`:
226/// `gitpoulpi_<profile id>_ed25519`. Per profile so two accounts on one
227/// host never share (or overwrite) a key.
228pub fn profile_key_path(ssh_dir: &Path, profile_id: &str) -> PathBuf {
229    let safe: String = profile_id
230        .chars()
231        .map(|c| {
232            if c.is_ascii_alphanumeric() || c == '-' {
233                c
234            } else {
235                '_'
236            }
237        })
238        .collect();
239    ssh_dir.join(format!("gitpoulpi_{safe}_ed25519"))
240}
241
242/// The `core.sshCommand` value that pins one private key for a repository
243/// (ADR-0008): `ssh -i "<key>" -o IdentitiesOnly=yes`. Backslashes become
244/// forward slashes, which git's `sh` accepts on Windows too.
245pub fn ssh_command_for_key(private_key_path: &str) -> String {
246    gitpoulpi_core::repo_config::ssh_command_for_key(private_key_path)
247}
248
249/// `~/.ssh`, where ssh looks for keys.
250pub fn ssh_dir() -> Result<PathBuf> {
251    default_key_path().map(|p| p.parent().map(Path::to_path_buf).unwrap_or_default())
252}
253
254/// The title a profile's key gets when the user does not type one:
255/// `GitPoulpi <host> <YYYY-MM-DD>`.
256pub fn profile_key_title(host: &str) -> String {
257    format!("GitPoulpi {host} {}", today_ymd())
258}
259
260/// Today's UTC date as `YYYY-MM-DD`, without a date crate (civil-from-days).
261fn today_ymd() -> String {
262    let secs = std::time::SystemTime::now()
263        .duration_since(std::time::UNIX_EPOCH)
264        .map_or(0, |d| d.as_secs() as i64);
265    let z = secs.div_euclid(86_400) + 719_468;
266    let era = z.div_euclid(146_097);
267    let doe = z.rem_euclid(146_097);
268    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
269    let y = yoe + era * 400;
270    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
271    let mp = (5 * doy + 2) / 153;
272    let d = doy - (153 * mp + 2) / 5 + 1;
273    let m = if mp < 10 { mp + 3 } else { mp - 9 };
274    let y = if m <= 2 { y + 1 } else { y };
275    format!("{y:04}-{m:02}-{d:02}")
276}
277
278/// `SHA256:...` of an OpenSSH public-key line, or `None` when it is not one.
279pub fn fingerprint_of(public_line: &str) -> Option<String> {
280    ssh_key::PublicKey::from_openssh(public_line.trim())
281        .ok()
282        .map(|k| k.fingerprint(ssh_key::HashAlg::Sha256).to_string())
283}
284
285/// Whether two public-key lines are the same key (the comment, which
286/// hosts rewrite, is ignored).
287pub fn same_public_key(a: &str, b: &str) -> bool {
288    let body = |s: &str| {
289        let mut it = s.split_whitespace();
290        Some((it.next()?.to_string(), it.next()?.to_string()))
291    };
292    matches!((body(a), body(b)), (Some(x), Some(y)) if x == y)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn the_key_type_setting_is_read_with_ed25519_as_the_fallback() {
301        assert_eq!(KeyType::from_setting("rsa"), KeyType::Rsa);
302        assert_eq!(KeyType::from_setting(" ECDSA "), KeyType::Ecdsa);
303        assert_eq!(KeyType::from_setting("ed25519"), KeyType::Ed25519);
304        assert_eq!(KeyType::from_setting("nonsense"), KeyType::Ed25519);
305    }
306
307    /// Every type produces files ssh can read back, of the type asked for.
308    #[test]
309    fn each_key_type_is_generated_as_asked() {
310        let dir = tempfile::tempdir().unwrap();
311        for (key_type, prefix, bits) in [
312            (KeyType::Ed25519, "ssh-ed25519 ", None),
313            (KeyType::Ecdsa, "ecdsa-sha2-nistp256 ", None),
314            (KeyType::Rsa, "ssh-rsa ", Some(4096)),
315        ] {
316            let path = dir.path().join(format!("k_{}", key_type.name()));
317            let key = generate_typed_and_write(&path, "c", key_type).unwrap();
318            assert!(key.public_key.starts_with(prefix), "{}", key.public_key);
319            assert!(path.is_file() && public_path_for(&path).is_file());
320            let private = std::fs::read_to_string(&path).unwrap();
321            let parsed = ssh_key::PrivateKey::from_openssh(&private).unwrap();
322            assert_eq!(
323                parsed.public_key().to_openssh().unwrap(),
324                key.public_key,
325                "the private file matches the public line"
326            );
327            if let (Some(bits), Some(rsa)) = (bits, parsed.public_key().key_data().rsa()) {
328                assert_eq!(rsa.n.as_positive_bytes().unwrap().len() * 8, bits);
329            }
330        }
331    }
332
333    #[test]
334    fn the_ssh_command_pins_one_key() {
335        assert_eq!(
336            ssh_command_for_key(r"C:\Users\me\.ssh\k"),
337            r#"ssh -i "C:/Users/me/.ssh/k" -o IdentitiesOnly=yes"#
338        );
339    }
340
341    #[test]
342    fn profile_paths_titles_and_fingerprints() {
343        let p = profile_key_path(Path::new("/h/.ssh"), "gitlab-self-managed-2");
344        assert!(p.ends_with("gitpoulpi_gitlab-self-managed-2_ed25519"));
345        assert!(profile_key_path(Path::new("/h"), "a/b c").ends_with("gitpoulpi_a_b_c_ed25519"));
346        let t = profile_key_title("gitlab.example.com");
347        assert!(t.starts_with("GitPoulpi gitlab.example.com 20"), "{t}");
348        let dir = tempfile::tempdir().unwrap();
349        let k = generate_and_write(&dir.path().join("k"), "c").unwrap();
350        assert_eq!(
351            fingerprint_of(&k.public_key).as_deref(),
352            Some(k.fingerprint.as_str())
353        );
354        assert!(same_public_key(
355            &k.public_key,
356            &format!(
357                "{} other",
358                k.public_key
359                    .split(' ')
360                    .take(2)
361                    .collect::<Vec<_>>()
362                    .join(" ")
363            )
364        ));
365        assert!(!same_public_key("ssh-ed25519 AAA", "ssh-ed25519 BBB"));
366        assert_eq!(fingerprint_of("garbage"), None);
367    }
368
369    #[test]
370    fn a_generated_key_is_a_usable_openssh_pair() {
371        let dir = tempfile::tempdir().unwrap();
372        let path = dir.path().join("keys").join("id_ed25519");
373
374        let key = generate_and_write(&path, "gitpoulpi@test").unwrap();
375
376        assert!(key.public_key.starts_with("ssh-ed25519 "));
377        assert!(key.public_key.ends_with("gitpoulpi@test"));
378        assert!(key.fingerprint.starts_with("SHA256:"));
379        assert_eq!(key.public_key_path, path.with_extension("pub"));
380
381        let private = std::fs::read_to_string(&path).unwrap();
382        assert!(private.starts_with("-----BEGIN OPENSSH PRIVATE KEY-----"));
383        assert!(
384            !private.contains('\r'),
385            "an OpenSSH private key with CRLF is rejected by ssh everywhere"
386        );
387
388        // The written public file must be the same line that gets
389        // uploaded, or the host trusts a key the machine does not have.
390        let public_file = std::fs::read_to_string(&key.public_key_path).unwrap();
391        assert_eq!(public_file.trim_end(), key.public_key);
392
393        // And it must round-trip through a real parser, not just look
394        // right.
395        let parsed = ssh_key::PublicKey::from_openssh(&key.public_key).unwrap();
396        assert_eq!(parsed.algorithm(), ssh_key::Algorithm::Ed25519);
397    }
398
399    #[test]
400    fn two_generated_keys_are_different() {
401        let dir = tempfile::tempdir().unwrap();
402        let a = generate_and_write(&dir.path().join("a"), "a").unwrap();
403        let b = generate_and_write(&dir.path().join("b"), "b").unwrap();
404        assert_ne!(a.public_key, b.public_key);
405        assert_ne!(a.fingerprint, b.fingerprint);
406    }
407
408    /// Overwriting a key revokes access to every host that trusts it,
409    /// with no undo.
410    #[test]
411    fn an_existing_key_is_never_overwritten() {
412        let dir = tempfile::tempdir().unwrap();
413        let path = dir.path().join("id_ed25519");
414        let first = generate_and_write(&path, "first").unwrap();
415
416        let err = generate_and_write(&path, "second").unwrap_err();
417        assert!(err.to_string().contains("already exists"), "{err}");
418        assert_eq!(
419            std::fs::read_to_string(&first.public_key_path)
420                .unwrap()
421                .trim_end(),
422            first.public_key,
423            "the original key must be untouched"
424        );
425    }
426
427    /// A stray `id_ed25519.pub` with no private half still means "there
428    /// is something here"; clobbering it would leave a public key that
429    /// no private key matches.
430    #[test]
431    fn a_lone_public_key_also_blocks_generation() {
432        let dir = tempfile::tempdir().unwrap();
433        let path = dir.path().join("id_ed25519");
434        std::fs::write(path.with_extension("pub"), "ssh-ed25519 AAAA old\n").unwrap();
435        assert!(generate_and_write(&path, "new").is_err());
436    }
437
438    #[cfg(unix)]
439    #[test]
440    fn the_private_key_is_not_readable_by_anyone_else() {
441        use std::os::unix::fs::PermissionsExt;
442        let dir = tempfile::tempdir().unwrap();
443        let path = dir.path().join("id_ed25519");
444        generate_and_write(&path, "test").unwrap();
445        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
446        assert_eq!(mode & 0o077, 0, "ssh refuses a group/world-readable key");
447    }
448}