Skip to main content

ssh_key/
dot_ssh.rs

1//! `~/.ssh` support.
2
3use crate::{PrivateKey, PublicKey, Result};
4use core::fmt::{self, Debug};
5use std::{
6    env,
7    fs::{self, ReadDir},
8    path::{Path, PathBuf},
9};
10
11#[cfg(feature = "sha2")]
12use crate::Fingerprint;
13
14#[cfg(doc)]
15use crate::Error;
16
17/// `~/.ssh` directory support (or similarly structured directories).
18#[derive(Clone, Eq, PartialEq)]
19pub struct DotSsh {
20    path: PathBuf,
21}
22
23impl DotSsh {
24    /// Open `~/.ssh` if the home directory can be located.
25    ///
26    /// Returns `None` if the home directory couldn't be located.
27    #[must_use]
28    pub fn new() -> Option<Self> {
29        #[allow(deprecated, reason = "TODO MSRV: Rust 1.86 un-deprecates this")]
30        env::home_dir().map(|path| Self::open(path.join(".ssh")))
31    }
32
33    /// Open a `~/.ssh`-structured directory.
34    ///
35    /// Does not verify that the directory exists or has the right file permissions.
36    ///
37    /// Attempts to canonicalize the path once opened.
38    pub fn open(path: impl Into<PathBuf>) -> Self {
39        let path = path.into();
40        Self {
41            path: path.canonicalize().unwrap_or(path),
42        }
43    }
44
45    /// Get the path to the `~/.ssh` directory (or whatever [`DotSsh::open`] was called with).
46    #[must_use]
47    pub fn path(&self) -> &Path {
48        &self.path
49    }
50
51    /// Get the path to the `~/.ssh/config` configuration file. Does not check if it exists.
52    #[must_use]
53    pub fn config_path(&self) -> PathBuf {
54        self.path.join("config")
55    }
56
57    /// Iterate over the private keys in the `~/.ssh` directory.
58    ///
59    /// # Errors
60    /// Returns [`Error::Io`] in the event of I/O errors.
61    pub fn private_keys(&self) -> Result<impl Iterator<Item = PrivateKey>> {
62        Ok(PrivateKeysIter {
63            read_dir: fs::read_dir(&self.path)?,
64        })
65    }
66
67    /// Find a private key whose public key has the given key fingerprint.
68    #[cfg(feature = "sha2")]
69    #[must_use]
70    pub fn private_key_with_fingerprint(&self, fingerprint: Fingerprint) -> Option<PrivateKey> {
71        self.private_keys()
72            .ok()?
73            .find(|key| key.public_key().fingerprint(fingerprint.algorithm()) == fingerprint)
74    }
75
76    /// Iterate over the public keys in the `~/.ssh` directory.
77    ///
78    /// # Errors
79    /// Returns [`Error::Io`] in the event of I/O errors.
80    pub fn public_keys(&self) -> Result<impl Iterator<Item = PublicKey>> {
81        Ok(PublicKeysIter {
82            read_dir: fs::read_dir(&self.path)?,
83        })
84    }
85
86    /// Find a public key with the given key fingerprint.
87    #[cfg(feature = "sha2")]
88    #[must_use]
89    pub fn public_key_with_fingerprint(&self, fingerprint: Fingerprint) -> Option<PublicKey> {
90        self.public_keys()
91            .ok()?
92            .find(|key| key.fingerprint(fingerprint.algorithm()) == fingerprint)
93    }
94
95    /// Write a private key into `~/.ssh`.
96    ///
97    /// # Errors
98    /// Returns [`Error::Io`] in the event of I/O errors.
99    pub fn write_private_key(&self, filename: impl AsRef<Path>, key: &PrivateKey) -> Result<()> {
100        key.write_openssh_file(self.path.join(filename), Default::default())
101    }
102
103    /// Write a public key into `~/.ssh`.
104    ///
105    /// # Errors
106    /// Returns [`Error::Io`] in the event of I/O errors.
107    pub fn write_public_key(&self, filename: impl AsRef<Path>, key: &PublicKey) -> Result<()> {
108        key.write_openssh_file(self.path.join(filename))
109    }
110}
111
112impl Debug for DotSsh {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_struct("DotSsh").finish_non_exhaustive()
115    }
116}
117
118impl Default for DotSsh {
119    /// Calls [`DotSsh::new`] and panics if the home directory could not be located.
120    fn default() -> Self {
121        Self::new().expect("home directory could not be located")
122    }
123}
124
125/// Iterator over the private keys in the `~/.ssh` directory.
126pub(crate) struct PrivateKeysIter {
127    read_dir: ReadDir,
128}
129
130impl Iterator for PrivateKeysIter {
131    type Item = PrivateKey;
132
133    fn next(&mut self) -> Option<Self::Item> {
134        loop {
135            let entry = self.read_dir.next()?.ok()?;
136
137            if let Ok(key) = PrivateKey::read_openssh_file(entry.path()) {
138                return Some(key);
139            }
140        }
141    }
142}
143
144/// Iterator over the public keys in the `~/.ssh` directory.
145pub(crate) struct PublicKeysIter {
146    read_dir: ReadDir,
147}
148
149impl Iterator for PublicKeysIter {
150    type Item = PublicKey;
151
152    fn next(&mut self) -> Option<Self::Item> {
153        loop {
154            let entry = self.read_dir.next()?.ok()?;
155
156            if let Ok(key) = PublicKey::read_openssh_file(entry.path()) {
157                return Some(key);
158            }
159        }
160    }
161}