1use std::path::{Path, PathBuf};
19
20use crate::{Error, Result};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum KeyType {
25 #[default]
26 Ed25519,
27 Rsa,
29 Ecdsa,
31}
32
33impl KeyType {
34 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 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#[derive(Debug)]
66pub struct GeneratedKey {
67 pub public_key: String,
70 pub private_key_path: PathBuf,
71 pub public_key_path: PathBuf,
72 pub fingerprint: String,
75}
76
77pub 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
86fn 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
100pub fn generate_and_write(path: &Path, comment: &str) -> Result<GeneratedKey> {
111 generate_typed_and_write(path, comment, KeyType::Ed25519)
112}
113
114pub 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 .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#[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#[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
213pub 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
225pub 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
242pub fn ssh_command_for_key(private_key_path: &str) -> String {
246 gitpoulpi_core::repo_config::ssh_command_for_key(private_key_path)
247}
248
249pub fn ssh_dir() -> Result<PathBuf> {
251 default_key_path().map(|p| p.parent().map(Path::to_path_buf).unwrap_or_default())
252}
253
254pub fn profile_key_title(host: &str) -> String {
257 format!("GitPoulpi {host} {}", today_ymd())
258}
259
260fn 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
278pub 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
285pub 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 #[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 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 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 #[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 #[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}