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 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 .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#[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#[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
214pub 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
226pub 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
243pub fn ssh_command_for_key(private_key_path: &str) -> String {
247 gitpoulpi_core::repo_config::ssh_command_for_key(private_key_path)
248}
249
250pub fn ssh_dir() -> Result<PathBuf> {
252 default_key_path().map(|p| p.parent().map(Path::to_path_buf).unwrap_or_default())
253}
254
255pub fn profile_key_title(host: &str) -> String {
258 format!("GitPoulpi {host} {}", today_ymd())
259}
260
261fn 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
279pub 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
286pub 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 #[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 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 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 #[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 #[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}