|
| 1 | +//! Parser for `AuthorizedKeysFile`-formatted data. |
| 2 | +
|
| 3 | +use crate::{Error, PublicKey, Result}; |
| 4 | + |
| 5 | +#[cfg(feature = "std")] |
| 6 | +use std::{fs, path::Path}; |
| 7 | + |
| 8 | +/// Character that begins a comment |
| 9 | +const COMMENT_DELIMITER: char = '#'; |
| 10 | + |
| 11 | +/// Parser for `AuthorizedKeysFile`-formatted data, typically found in |
| 12 | +/// `~/.ssh/authorized_keys`. |
| 13 | +/// |
| 14 | +/// For a full description of the format, see: |
| 15 | +/// <https://man7.org/linux/man-pages/man8/sshd.8.html#AUTHORIZED_KEYS_FILE_FORMAT> |
| 16 | +/// |
| 17 | +/// Each line of the file consists of a single public key. Blank lines are ignored. |
| 18 | +/// |
| 19 | +/// Public keys consist of the following space-separated fields: |
| 20 | +/// |
| 21 | +/// ```text |
| 22 | +/// options, keytype, base64-encoded key, comment |
| 23 | +/// ``` |
| 24 | +/// |
| 25 | +/// - The options field is optional. |
| 26 | +/// - The keytype is `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521`, |
| 27 | +/// `ssh-ed25519`, `ssh-dss` or `ssh-rsa` |
| 28 | +/// - The comment field is not used for anything (but may be convenient for the user to identify |
| 29 | +/// the key). |
| 30 | +pub struct AuthorizedKeys<'a> { |
| 31 | + /// Lines of the file being iterated over |
| 32 | + lines: core::str::Lines<'a>, |
| 33 | +} |
| 34 | + |
| 35 | +impl<'a> AuthorizedKeys<'a> { |
| 36 | + /// Create a new parser for the given input buffer. |
| 37 | + pub fn new(input: &'a str) -> Self { |
| 38 | + Self { |
| 39 | + lines: input.lines(), |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /// Read a file from the filesystem, calling the given closure with an |
| 44 | + /// [`AuthorizedKeys`] parser which operates over a temporary buffer. |
| 45 | + #[cfg(feature = "std")] |
| 46 | + #[cfg_attr(docsrs, doc(cfg(feature = "std")))] |
| 47 | + pub fn read_file<T, F>(path: impl AsRef<Path>, f: F) -> Result<T> |
| 48 | + where |
| 49 | + F: FnOnce(AuthorizedKeys<'_>) -> Result<T>, |
| 50 | + { |
| 51 | + // TODO(tarcieri): permissions checks |
| 52 | + let input = fs::read_to_string(path)?; |
| 53 | + f(AuthorizedKeys::new(&input)) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl<'a> Iterator for AuthorizedKeys<'a> { |
| 58 | + type Item = Result<Entry<'a>>; |
| 59 | + |
| 60 | + fn next(&mut self) -> Option<Result<Entry<'a>>> { |
| 61 | + loop { |
| 62 | + let result = LineParser::new(self.lines.next()?); |
| 63 | + |
| 64 | + match result { |
| 65 | + Ok(LineParser { |
| 66 | + options_str: None, |
| 67 | + public_key_str: None, |
| 68 | + }) => (), |
| 69 | + Ok(line) => return Some(line.try_into()), |
| 70 | + Err(err) => return Some(Err(err)), |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +/// Individual entry in an `authorized_keys` file containing a single public key. |
| 77 | +#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 78 | +pub struct Entry<'a> { |
| 79 | + /// Options field, if present. |
| 80 | + pub options: Option<&'a str>, |
| 81 | + |
| 82 | + /// Public key |
| 83 | + pub public_key: PublicKey, |
| 84 | +} |
| 85 | + |
| 86 | +impl<'a> TryFrom<LineParser<'a>> for Entry<'a> { |
| 87 | + type Error = Error; |
| 88 | + |
| 89 | + fn try_from(line: LineParser<'a>) -> Result<Entry<'a>> { |
| 90 | + let public_key = line |
| 91 | + .public_key_str |
| 92 | + .ok_or(Error::FormatEncoding)? |
| 93 | + .parse::<PublicKey>()?; |
| 94 | + |
| 95 | + Ok(Self { |
| 96 | + options: line.options_str, |
| 97 | + public_key, |
| 98 | + }) |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +/// Parser for an individual line in an `authorized_keys` file. |
| 103 | +#[derive(Debug)] |
| 104 | +struct LineParser<'a> { |
| 105 | + /// Options field, if present. |
| 106 | + options_str: Option<&'a str>, |
| 107 | + |
| 108 | + /// Public key data, if present. |
| 109 | + public_key_str: Option<&'a str>, |
| 110 | +} |
| 111 | + |
| 112 | +impl<'a> LineParser<'a> { |
| 113 | + /// Parse the given line. |
| 114 | + pub fn new(mut line: &'a str) -> Result<Self> { |
| 115 | + // Strip comment, if present |
| 116 | + if let Some((l, _)) = line.split_once(COMMENT_DELIMITER) { |
| 117 | + line = l; |
| 118 | + } |
| 119 | + |
| 120 | + // Trim trailing whitespace |
| 121 | + line = line.trim_end(); |
| 122 | + |
| 123 | + if line.is_empty() { |
| 124 | + return Ok(Self { |
| 125 | + options_str: None, |
| 126 | + public_key_str: None, |
| 127 | + }); |
| 128 | + } |
| 129 | + |
| 130 | + match line.matches(' ').count() { |
| 131 | + 1..=2 => Ok(Self { |
| 132 | + options_str: None, |
| 133 | + public_key_str: Some(line), |
| 134 | + }), |
| 135 | + 3 => match line.split_once(' ') { |
| 136 | + Some((options_str, public_key_str)) => Ok(Self { |
| 137 | + options_str: Some(options_str), |
| 138 | + public_key_str: Some(public_key_str), |
| 139 | + }), |
| 140 | + _ => Err(Error::FormatEncoding), |
| 141 | + }, |
| 142 | + _ => Err(Error::FormatEncoding), |
| 143 | + } |
| 144 | + } |
| 145 | +} |
0 commit comments