Skip to main content

ssh_key/
known_hosts.rs

1//! Parser for `KnownHostsFile`-formatted data.
2
3use crate::{Error, PublicKey, Result};
4use alloc::{
5    string::{String, ToString},
6    vec::Vec,
7};
8use core::{
9    fmt::{self, Debug},
10    str,
11};
12use encoding::base64::{Base64, Encoding};
13
14#[cfg(feature = "std")]
15use std::{fs, path::Path};
16
17/// Character that begins a comment
18const COMMENT_DELIMITER: char = '#';
19/// The magic string prefix of a hashed hostname
20const MAGIC_HASH_PREFIX: &str = "|1|";
21
22/// Parser for `KnownHostsFile`-formatted data, typically found in
23/// `~/.ssh/known_hosts`.
24///
25/// For a full description of the format, see:
26/// <https://man7.org/linux/man-pages/man8/sshd.8.html#SSH_KNOWN_HOSTS_FILE_FORMAT>
27///
28/// Each line of the file consists of a single public key tied to one or more hosts.
29/// Blank lines are ignored.
30///
31/// Public keys consist of the following space-separated fields:
32///
33/// ```text
34/// marker, hostnames, keytype, base64-encoded key, comment
35/// ```
36///
37/// - The marker field is optional, but if present begins with an `@`. Known markers are `@cert-authority`
38///   and `@revoked`.
39/// - The hostnames is a comma-separated list of patterns (with `*` and '?' as glob-style wildcards)
40///   against which hosts are matched. If it begins with a `!` it is a negation of the pattern. If the
41///   pattern starts with `[` and ends with `]`, it contains a hostname pattern and a port number separated
42///   by a `:`. If it begins with `|1|`, the hostname is hashed. In that case, there can only be one exact
43///   hostname and it can't also be negated (ie. `!|1|x|y` is not legal and you can't hash `*.example.org`).
44/// - The keytype is `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521`,
45///   `ssh-ed25519`, `ssh-dss` or `ssh-rsa`
46/// - The comment field is not used for anything (but may be convenient for the user to identify
47///   the key).
48pub struct KnownHosts<'a> {
49    /// Lines of the file being iterated over
50    lines: str::Lines<'a>,
51}
52
53impl<'a> KnownHosts<'a> {
54    /// Create a new parser for the given input buffer.
55    #[must_use]
56    pub fn new(input: &'a str) -> Self {
57        Self {
58            lines: input.lines(),
59        }
60    }
61
62    /// Read a [`KnownHosts`] file from the filesystem, returning an [`Entry`] vector on success.
63    ///
64    /// # Errors
65    /// - Returns [`Error::Io`] in event of I/O errors reading the file.
66    /// - Propagates [`Entry`] parsing errors as [`Error::FormatEncoding`].
67    #[cfg(feature = "std")]
68    pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<Entry>> {
69        // TODO(tarcieri): permissions checks
70        let input = fs::read_to_string(path)?;
71        KnownHosts::new(&input).collect()
72    }
73
74    /// Get the next line, trimming any comments and trailing whitespace. Ignores empty lines.
75    fn next_line_trimmed(&mut self) -> Option<&'a str> {
76        loop {
77            let mut line = self.lines.next()?;
78
79            // Strip comment if present
80            if let Some((l, _)) = line.split_once(COMMENT_DELIMITER) {
81                line = l;
82            }
83
84            // Trim trailing whitespace
85            line = line.trim_end();
86
87            if !line.is_empty() {
88                return Some(line);
89            }
90        }
91    }
92}
93
94impl Debug for KnownHosts<'_> {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.debug_struct("KnownHosts").finish_non_exhaustive()
97    }
98}
99
100impl Iterator for KnownHosts<'_> {
101    type Item = Result<Entry>;
102
103    fn next(&mut self) -> Option<Result<Entry>> {
104        self.next_line_trimmed().map(str::parse)
105    }
106}
107
108/// Individual entry in an `known_hosts` file containing a single public key.
109#[derive(Clone, Debug, Eq, PartialEq)]
110pub struct Entry {
111    /// Marker field, if present.
112    marker: Option<Marker>,
113
114    /// Host patterns
115    host_patterns: HostPatterns,
116
117    /// Public key
118    public_key: PublicKey,
119}
120
121impl Entry {
122    /// Get the marker for this entry, if present.
123    #[must_use]
124    pub fn marker(&self) -> Option<&Marker> {
125        self.marker.as_ref()
126    }
127
128    /// Get the host pattern enumerator for this entry
129    #[must_use]
130    pub fn host_patterns(&self) -> &HostPatterns {
131        &self.host_patterns
132    }
133
134    /// Get public key for this entry.
135    #[must_use]
136    pub fn public_key(&self) -> &PublicKey {
137        &self.public_key
138    }
139}
140impl From<Entry> for Option<Marker> {
141    fn from(entry: Entry) -> Option<Marker> {
142        entry.marker
143    }
144}
145impl From<Entry> for HostPatterns {
146    fn from(entry: Entry) -> HostPatterns {
147        entry.host_patterns
148    }
149}
150impl From<Entry> for PublicKey {
151    fn from(entry: Entry) -> PublicKey {
152        entry.public_key
153    }
154}
155
156impl str::FromStr for Entry {
157    type Err = Error;
158
159    fn from_str(line: &str) -> Result<Self> {
160        // Unlike authorized_keys, in known_hosts it's pretty common
161        // to not include a key comment, so the number of spaces is
162        // not a reliable indicator of the fields in the line. Instead,
163        // the optional marker field starts with an @, so look for that
164        // and act accordingly.
165        //
166        // Fields are separated by any run of whitespace rather than by exactly
167        // one space: OpenSSH writes `keytype key` with a single space, but real
168        // files are hand-edited and commonly use tabs, several spaces, or an
169        // indented first field. Splitting on whitespace also removes the leading
170        // whitespace that an indented line would otherwise leave in front of the
171        // host field, and tolerates a marker followed by a tab.
172        let mut fields = line.split_whitespace();
173
174        let first = fields.next().ok_or(Error::FormatEncoding)?;
175        let (marker, hosts_str) = match first.strip_prefix('@') {
176            Some(marker_str) => {
177                let marker = format!("@{marker_str}").parse()?;
178                (Some(marker), fields.next().ok_or(Error::FormatEncoding)?)
179            }
180            None => (None, first),
181        };
182
183        // The key parser expects `keytype key` separated by a single space, so
184        // the remainder is re-joined with single spaces.
185        let public_key_str = fields.collect::<Vec<_>>().join(" ");
186        if public_key_str.is_empty() {
187            return Err(Error::FormatEncoding);
188        }
189
190        let host_patterns = hosts_str.parse()?;
191        let public_key = public_key_str.parse()?;
192
193        Ok(Self {
194            marker,
195            host_patterns,
196            public_key,
197        })
198    }
199}
200
201#[allow(clippy::to_string_trait_impl)]
202impl ToString for Entry {
203    fn to_string(&self) -> String {
204        let mut s = String::new();
205
206        if let Some(marker) = &self.marker {
207            s.push_str(marker.as_str());
208            s.push(' ');
209        }
210
211        s.push_str(&self.host_patterns.to_string());
212        s.push(' ');
213
214        s.push_str(&self.public_key.to_string());
215        s
216    }
217}
218
219/// Markers associated with this host key entry.
220///
221/// There can only be one of these per host key entry.
222#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223pub enum Marker {
224    /// This host entry's public key is for a certificate authority's private key.
225    CertAuthority,
226
227    /// This host entry's public key has been revoked, and should not be allowed to connect
228    /// regardless of any other entry.
229    Revoked,
230}
231
232impl Marker {
233    /// Get the string form of the marker
234    #[must_use]
235    pub fn as_str(&self) -> &str {
236        match self {
237            Self::CertAuthority => "@cert-authority",
238            Self::Revoked => "@revoked",
239        }
240    }
241}
242
243impl AsRef<str> for Marker {
244    fn as_ref(&self) -> &str {
245        self.as_str()
246    }
247}
248
249impl str::FromStr for Marker {
250    type Err = Error;
251
252    fn from_str(s: &str) -> Result<Self> {
253        Ok(match s {
254            "@cert-authority" => Marker::CertAuthority,
255            "@revoked" => Marker::Revoked,
256            _ => return Err(Error::FormatEncoding),
257        })
258    }
259}
260
261impl fmt::Display for Marker {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.write_str(self.as_str())
264    }
265}
266
267/// The host pattern(s) for this host entry.
268///
269/// The host patterns can either be a comma separated list of host patterns
270/// (which may include glob patterns (`*` and `?`), negations (a `!` prefix),
271/// or `pattern:port` pairs inside square brackets), or a single hashed
272/// hostname prefixed with `|1|`.
273#[derive(Clone, Debug, Eq, PartialEq)]
274pub enum HostPatterns {
275    /// A comma separated list of hostname patterns.
276    Patterns(Vec<String>),
277    /// A single hashed hostname
278    HashedName {
279        /// The salt used for the hash
280        salt: Vec<u8>,
281        /// An SHA-1 hash of the hostname along with the salt
282        hash: [u8; 20],
283    },
284}
285
286impl str::FromStr for HostPatterns {
287    type Err = Error;
288
289    fn from_str(s: &str) -> Result<Self> {
290        if let Some(s) = s.strip_prefix(MAGIC_HASH_PREFIX) {
291            let mut hash = [0; 20];
292            let (salt, hash_str) = s.split_once('|').ok_or(Error::FormatEncoding)?;
293
294            let salt = Base64::decode_vec(salt)?;
295            Base64::decode(hash_str, &mut hash)?;
296
297            Ok(HostPatterns::HashedName { salt, hash })
298        } else if !s.is_empty() {
299            Ok(HostPatterns::Patterns(
300                s.split_terminator(',').map(str::to_string).collect(),
301            ))
302        } else {
303            Err(Error::FormatEncoding)
304        }
305    }
306}
307
308#[allow(clippy::to_string_trait_impl)]
309impl ToString for HostPatterns {
310    fn to_string(&self) -> String {
311        match &self {
312            HostPatterns::Patterns(patterns) => patterns.join(","),
313            HostPatterns::HashedName { salt, hash } => {
314                let salt = Base64::encode_string(salt);
315                let hash = Base64::encode_string(hash);
316                format!("|1|{salt}|{hash}")
317            }
318        }
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use alloc::string::ToString;
325    use core::str::FromStr;
326
327    use super::Entry;
328    use super::HostPatterns;
329    use super::Marker;
330
331    #[test]
332    fn simple_markers() {
333        assert_eq!(Ok(Marker::CertAuthority), "@cert-authority".parse());
334        assert_eq!(Ok(Marker::Revoked), "@revoked".parse());
335        assert!(Marker::from_str("@gibberish").is_err());
336    }
337
338    #[test]
339    fn empty_host_patterns() {
340        assert!(HostPatterns::from_str("").is_err());
341    }
342
343    // Note: The sshd man page has this completely incomprehensible 'example known_hosts entry':
344    // closenet,...,192.0.2.53 1024 37 159...93 closenet.example.net
345    // I'm not sure how this one is supposed to work or what it means.
346
347    #[test]
348    fn tab_separated_fields() {
349        let entry: Entry = "cvs.example.net\tssh-ed25519\tAAAAC3NzaC1lZDI1NTE5AAAAIB9dG4kjRhQTtWTVzd2t27+t0DEHBPW7iOD23TUiYLio"
350            .parse()
351            .expect("tab-separated entry");
352        assert_eq!(entry.marker(), None);
353        assert_eq!(
354            entry.host_patterns(),
355            &HostPatterns::Patterns(vec!["cvs.example.net".to_string()])
356        );
357    }
358
359    #[test]
360    fn leading_whitespace_is_ignored() {
361        let entry: Entry = "   cvs.example.net ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB9dG4kjRhQTtWTVzd2t27+t0DEHBPW7iOD23TUiYLio"
362            .parse()
363            .expect("indented entry");
364        assert_eq!(
365            entry.host_patterns(),
366            &HostPatterns::Patterns(vec!["cvs.example.net".to_string()])
367        );
368    }
369
370    #[test]
371    fn several_spaces_between_fields() {
372        let entry: Entry = "cvs.example.net   ssh-ed25519   AAAAC3NzaC1lZDI1NTE5AAAAIB9dG4kjRhQTtWTVzd2t27+t0DEHBPW7iOD23TUiYLio"
373            .parse()
374            .expect("entry with runs of spaces");
375        assert_eq!(
376            entry.host_patterns(),
377            &HostPatterns::Patterns(vec!["cvs.example.net".to_string()])
378        );
379    }
380
381    #[test]
382    fn a_marker_may_be_followed_by_a_tab() {
383        let entry: Entry = "@revoked\tcvs.example.net\tssh-ed25519\tAAAAC3NzaC1lZDI1NTE5AAAAIB9dG4kjRhQTtWTVzd2t27+t0DEHBPW7iOD23TUiYLio"
384            .parse()
385            .expect("tab-separated entry with a marker");
386        assert_eq!(entry.marker(), Some(&Marker::Revoked));
387        assert_eq!(
388            entry.host_patterns(),
389            &HostPatterns::Patterns(vec!["cvs.example.net".to_string()])
390        );
391    }
392
393    #[test]
394    fn single_host_pattern() {
395        assert_eq!(
396            Ok(HostPatterns::Patterns(vec!["cvs.example.net".to_string()])),
397            "cvs.example.net".parse()
398        );
399    }
400    #[test]
401    fn multiple_host_patterns() {
402        assert_eq!(
403            Ok(HostPatterns::Patterns(vec![
404                "cvs.example.net".to_string(),
405                "!test.example.???".to_string(),
406                "[*.example.net]:999".to_string(),
407            ])),
408            "cvs.example.net,!test.example.???,[*.example.net]:999".parse()
409        );
410    }
411    #[test]
412    fn single_hashed_host() {
413        assert_eq!(
414            Ok(HostPatterns::HashedName {
415                salt: vec![
416                    37, 242, 147, 116, 24, 123, 172, 214, 215, 145, 80, 16, 9, 26, 120, 57, 10, 15,
417                    126, 98
418                ],
419                hash: [
420                    81, 33, 2, 175, 116, 150, 127, 82, 84, 62, 201, 172, 228, 10, 159, 15, 148, 31,
421                    198, 67
422                ],
423            }),
424            "|1|JfKTdBh7rNbXkVAQCRp4OQoPfmI=|USECr3SWf1JUPsms5AqfD5QfxkM=".parse()
425        );
426    }
427
428    #[test]
429    fn full_line_hashed() {
430        let line = "@revoked |1|lcY/In3lsGnkJikLENb0DM70B/I=|Qs4e9Nr7mM6avuEv02fw2uFnwQo= ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB9dG4kjRhQTtWTVzd2t27+t0DEHBPW7iOD23TUiYLio comment";
431        let entry = Entry::from_str(line).expect("Valid entry");
432        assert_eq!(entry.marker(), Some(&Marker::Revoked));
433        assert_eq!(
434            entry.host_patterns(),
435            &HostPatterns::HashedName {
436                salt: vec![
437                    149, 198, 63, 34, 125, 229, 176, 105, 228, 38, 41, 11, 16, 214, 244, 12, 206,
438                    244, 7, 242
439                ],
440                hash: [
441                    66, 206, 30, 244, 218, 251, 152, 206, 154, 190, 225, 47, 211, 103, 240, 218,
442                    225, 103, 193, 10
443                ],
444            }
445        );
446        // key parsing is tested elsewhere
447    }
448}