1use 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
17const COMMENT_DELIMITER: char = '#';
19const MAGIC_HASH_PREFIX: &str = "|1|";
21
22pub struct KnownHosts<'a> {
49 lines: str::Lines<'a>,
51}
52
53impl<'a> KnownHosts<'a> {
54 #[must_use]
56 pub fn new(input: &'a str) -> Self {
57 Self {
58 lines: input.lines(),
59 }
60 }
61
62 #[cfg(feature = "std")]
68 pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<Entry>> {
69 let input = fs::read_to_string(path)?;
71 KnownHosts::new(&input).collect()
72 }
73
74 fn next_line_trimmed(&mut self) -> Option<&'a str> {
76 loop {
77 let mut line = self.lines.next()?;
78
79 if let Some((l, _)) = line.split_once(COMMENT_DELIMITER) {
81 line = l;
82 }
83
84 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#[derive(Clone, Debug, Eq, PartialEq)]
110pub struct Entry {
111 marker: Option<Marker>,
113
114 host_patterns: HostPatterns,
116
117 public_key: PublicKey,
119}
120
121impl Entry {
122 #[must_use]
124 pub fn marker(&self) -> Option<&Marker> {
125 self.marker.as_ref()
126 }
127
128 #[must_use]
130 pub fn host_patterns(&self) -> &HostPatterns {
131 &self.host_patterns
132 }
133
134 #[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 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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223pub enum Marker {
224 CertAuthority,
226
227 Revoked,
230}
231
232impl Marker {
233 #[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#[derive(Clone, Debug, Eq, PartialEq)]
274pub enum HostPatterns {
275 Patterns(Vec<String>),
277 HashedName {
279 salt: Vec<u8>,
281 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 #[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 }
448}