puressh 0.2.4

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! In-memory `KnownHosts` model: load, save, lookup, mutate.

use std::fs;
use std::io;
use std::path::Path;

use purecrypto::rng::{OsRng, RngCore};

use super::format::{
    Entry, HostSpec, Marker, ParsedLine, format_entry, format_host_pattern, parse_line,
    patterns_match,
};
use super::hash::{check_hashed, hash_new, parse_hashed};

/// Outcome of looking up a host in a [`KnownHosts`] store.
#[derive(Debug)]
#[non_exhaustive]
pub enum LookupResult {
    /// At least one entry's host and key match the candidate exactly.
    /// Connection is safe to proceed.
    Match,
    /// At least one entry's host matched, but no entry's key did. The
    /// expected keys (`(key_type, key_blob)`) are returned so the caller
    /// can render a helpful diagnostic.
    Mismatch {
        /// `(key_type, key_blob)` pairs the store has on file for the
        /// host — the keys we would have accepted, in load order.
        expected: Vec<(String, Vec<u8>)>,
    },
    /// No entry's host matched. The caller decides whether to TOFU-add.
    Unknown,
    /// An `@revoked` line matched both the host and the presented key.
    /// This is a hard failure: no policy (`StrictHostKeyChecking=no`,
    /// prompt, silent accept) may override it, and the store must not be
    /// rotated. Matches OpenSSH, which aborts the connection outright on
    /// a revoked host key.
    Revoked,
}

/// In-memory model of a `known_hosts` file. Preserves comments,
/// formatting, and unknown lines verbatim across load → save.
pub struct KnownHosts {
    /// Original file lines, kept in order so `save` produces a stable
    /// diff. Entries are mutable in-place; verbatim lines are passed
    /// through unchanged.
    lines: Vec<Slot>,
}

enum Slot {
    Verbatim(String),
    /// A line that is not valid UTF-8, kept as raw bytes so a save writes
    /// it back unchanged instead of dropping it. When the line (decoded
    /// lossily) is an `@revoked` entry, that entry is kept alongside and
    /// still revokes its key: an undecodable comment must not silently
    /// un-revoke a key.
    Raw(Vec<u8>, Option<Entry>),
    Entry(Entry),
    /// Tombstoned slot — skipped on save. Lets `remove` keep indices
    /// stable for callers that hold references during a mutation pass.
    Removed,
}

impl Default for KnownHosts {
    fn default() -> Self {
        Self::new()
    }
}

impl KnownHosts {
    /// Empty store.
    pub fn new() -> Self {
        Self { lines: Vec::new() }
    }

    /// Parse the bytes of a `known_hosts` file.
    ///
    /// Parsing is done line-by-line over the raw bytes (split on `\n`,
    /// with a trailing `\r` stripped) so a single non-UTF-8 byte anywhere
    /// in the file cannot empty the whole store. Applying `from_utf8` to
    /// the entire buffer and falling back to `""` on error would turn one
    /// bad byte into zero loaded entries → every lookup returns `Unknown`
    /// → host-key verification is silently disabled and a MITM key is
    /// accepted/pinned via TOFU. Instead, each line that is valid UTF-8 is
    /// parsed as usual; a line that is not valid UTF-8 is skipped (just
    /// that line), matching OpenSSH's tolerance of individual bad lines.
    pub fn from_bytes(data: &[u8]) -> Self {
        let mut out = Self::new();
        // `split(b'\n')` yields a trailing empty element for a buffer that
        // ends in `\n` (and for an empty buffer); `str::lines()` does not.
        // Drop that single trailing empty element so a normally-terminated
        // file doesn't gain a spurious blank line on save.
        let mut parts = data.split(|&b| b == b'\n').peekable();
        while let Some(line) = parts.next() {
            if parts.peek().is_none() && line.is_empty() {
                break;
            }
            // Strip a trailing `\r` so CRLF files parse the same as LF.
            let line = match line.split_last() {
                Some((b'\r', rest)) => rest,
                _ => line,
            };
            // A line that isn't valid UTF-8 is not parsed as an entry (do
            // not abort parsing and do not empty the store), but it is kept
            // verbatim for save — and an `@revoked` one still revokes.
            let raw = match std::str::from_utf8(line) {
                Ok(s) => s,
                Err(_) => {
                    let revoked = match parse_line(&String::from_utf8_lossy(line)) {
                        ParsedLine::Entry(e) if e.marker == Some(Marker::Revoked) => Some(e),
                        _ => None,
                    };
                    out.lines.push(Slot::Raw(line.to_vec(), revoked));
                    continue;
                }
            };
            match parse_line(raw) {
                ParsedLine::Entry(e) => out.lines.push(Slot::Entry(e)),
                ParsedLine::Verbatim(s) => out.lines.push(Slot::Verbatim(s)),
            }
        }
        out
    }

    /// Load from a path. If the file doesn't exist, returns an empty
    /// store (the OpenSSH client behaves the same).
    pub fn load(path: impl AsRef<Path>) -> io::Result<Self> {
        match fs::read(path) {
            Ok(bytes) => Ok(Self::from_bytes(&bytes)),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Self::new()),
            Err(e) => Err(e),
        }
    }

    /// Serialise back to bytes. Each line is `\n`-terminated.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for slot in &self.lines {
            match slot {
                Slot::Verbatim(s) => {
                    out.extend_from_slice(s.as_bytes());
                    out.push(b'\n');
                }
                Slot::Entry(e) => {
                    out.extend_from_slice(format_entry(e).as_bytes());
                    out.push(b'\n');
                }
                Slot::Raw(b, _) => {
                    out.extend_from_slice(b);
                    out.push(b'\n');
                }
                Slot::Removed => {}
            }
        }
        out
    }

    /// Atomically save to `path`. Writes to a per-call unique temporary
    /// file then renames into place.
    ///
    /// Hardening notes:
    /// - The tmp filename embeds `pid` plus a fresh `u64` from `OsRng`,
    ///   so two concurrent saves cannot collide on the same temp name.
    /// - On Unix the tmp file is opened with `O_EXCL` (`create_new`) and
    ///   mode `0o600`, so a pre-existing symlink in the directory cannot
    ///   be used to trick us into overwriting an attacker-chosen target.
    /// - After writing, the tmp file is `fsync`ed, then renamed into
    ///   place. On Unix the parent directory is `fsync`ed after the
    ///   rename so the new entry survives a crash. The host-key list is
    ///   thus never world- or group-readable, even during the brief
    ///   window before the rename — matching OpenSSH and avoiding
    ///   information leak via `umask 0` shells or shared filesystems.
    /// - On error the leftover tmp file is best-effort cleaned up; the
    ///   cleanup error is intentionally swallowed so we surface the
    ///   original failure.
    pub fn save(&self, path: impl AsRef<Path>) -> io::Result<()> {
        let path = path.as_ref();
        let tmp = unique_tmp_path(path);
        match write_private_file(&tmp, &self.to_bytes()) {
            Ok(()) => {}
            Err(e) => {
                let _ = fs::remove_file(&tmp);
                return Err(e);
            }
        }
        if let Err(e) = fs::rename(&tmp, path) {
            let _ = fs::remove_file(&tmp);
            return Err(e);
        }
        #[cfg(unix)]
        {
            // Best-effort directory fsync so the rename is durable.
            // Failing here is not fatal: the data has already been
            // written and renamed, and many filesystems (notably
            // virtualised ones) reject O_RDONLY+fsync on directories.
            if let Some(parent) = path.parent() {
                let parent = if parent.as_os_str().is_empty() {
                    Path::new(".")
                } else {
                    parent
                };
                if let Ok(dir) = fs::File::open(parent) {
                    let _ = dir.sync_all();
                }
            }
        }
        Ok(())
    }

    /// Look up a host+key. See [`LookupResult`].
    ///
    /// Per OpenSSH semantics, `@revoked` is evaluated **first** across
    /// every entry in the file — a revoke line elsewhere in the file
    /// outranks any non-revoked match and yields [`LookupResult::Revoked`].
    /// After that, the first matching (host, key) pair wins; if any
    /// entry's host matches but no matching key is found, the result is
    /// `Mismatch` with the list of expected keys.
    ///
    /// `@cert-authority` lines are **not** consulted for a plain (non
    /// certificate) host key: a CA line says "trust certificates signed by
    /// this key", not "this key is the host's key", so it neither counts as
    /// a host match nor as an expected key here. Certificates go through
    /// [`Self::verify_host_cert`] instead.
    pub fn lookup(&self, host: &str, port: u16, key_type: &str, key_blob: &[u8]) -> LookupResult {
        // Pass 1: any `@revoked` line whose host AND key matches refuses
        // the candidate unconditionally.
        for e in self.revoked_entries() {
            if host_field_matches(&e.host_spec, host, port)
                && e.key_type == key_type
                && e.key_blob == key_blob
            {
                return LookupResult::Revoked;
            }
        }

        // Pass 2: normal Match / Mismatch / Unknown evaluation over the
        // plain (marker-less) entries only.
        let mut host_matched = false;
        let mut expected: Vec<(String, Vec<u8>)> = Vec::new();
        for slot in &self.lines {
            let e = match slot {
                Slot::Entry(e) => e,
                _ => continue,
            };
            // Marker lines carry no evidence about the host's plain key:
            // a `@revoked` line that didn't fire in pass 1 is irrelevant,
            // and a `@cert-authority` line only vouches for certificates.
            // Treating a CA line as a plain key would report a spurious
            // "HOST KEY CHANGED" for a plain-key host under a CA wildcard,
            // and would accept a host presenting the CA's own public key.
            if e.marker.is_some() {
                continue;
            }
            if !host_field_matches(&e.host_spec, host, port) {
                continue;
            }
            host_matched = true;
            if e.key_type == key_type && e.key_blob == key_blob {
                return LookupResult::Match;
            }
            expected.push((e.key_type.clone(), e.key_blob.clone()));
        }

        if host_matched {
            LookupResult::Mismatch { expected }
        } else if port != 22 && self.plain_host_has_key(host, key_type, key_blob) {
            LookupResult::Match
        } else {
            LookupResult::Unknown
        }
    }

    /// OpenSSH's fallback for a non-default port with no `[host]:port`
    /// entry: a key recorded under the bare host name is accepted, though a
    /// *different* key there is not a mismatch (verified against OpenSSH
    /// 10.4).
    fn plain_host_has_key(&self, host: &str, key_type: &str, key_blob: &[u8]) -> bool {
        self.lines.iter().any(|slot| {
            matches!(slot, Slot::Entry(e)
                if e.marker.is_none()
                    && e.key_type == key_type
                    && e.key_blob == key_blob
                    && host_field_matches(&e.host_spec, host, 22))
        })
    }

    /// Decide whether a host *certificate* is trusted for `host[:port]`.
    ///
    /// Trust flows from `@cert-authority` lines: a host cert is accepted iff
    /// some `@cert-authority` entry whose host field matches `host` names a CA
    /// key equal to the certificate's `signature_key_blob`, the certificate's
    /// CA signature verifies under `allowed_ca_algos`, and the cert is a valid,
    /// in-window host cert authorizing `host` as a principal.
    ///
    /// `@revoked` is evaluated first: a revoke line matching either the CA key
    /// or the cert's embedded key refuses the connection outright. (Full KRL
    /// binary format is out of scope; `@revoked` covers key/serial-by-key
    /// revocation at the granularity of a key blob.)
    ///
    /// Returns `Ok(())` when trusted; an `Err` (one of the `Cert*` variants or
    /// `HostKeyRejected`) when not.
    pub fn verify_host_cert(
        &self,
        host: &str,
        port: u16,
        cert: &crate::cert::Certificate,
        allowed_ca_algos: &[&str],
        now: u64,
    ) -> crate::Result<()> {
        use crate::error::Error;

        if self.revokes_cert(host, port, cert) {
            return Err(Error::HostKeyRejected);
        }

        // Validate the certificate itself before consulting the CA list, so a
        // structurally-bad cert is rejected with a precise error.
        cert.check_type(crate::cert::CertType::Host)?;
        cert.check_validity(now)?;
        cert.require_known_critical_options()?;

        // As OpenSSH's check_host_cert: a host certificate carries no
        // critical options.
        if !cert.critical_options.is_empty() {
            return Err(Error::CertUnknownCriticalOption);
        }

        // Pass 2: a matching @cert-authority entry for this host.
        if self.has_ca_for(host, port, cert) {
            // This CA is trusted for this host. Verify the CA signature and
            // the principal binding.
            cert.verify_ca_signature(allowed_ca_algos)?;
            cert.check_principal(host)?;
            return Ok(());
        }
        Err(Error::HostKeyRejected)
    }

    /// Whether an `@cert-authority` line names the certificate's CA for
    /// `[host]:port` (or, like OpenSSH, for a non-default port, the bare
    /// host).
    pub fn has_ca_for(&self, host: &str, port: u16, cert: &crate::cert::Certificate) -> bool {
        let ca_trusted = |port: u16| {
            self.lines.iter().any(|slot| {
                matches!(slot, Slot::Entry(e)
                    if e.marker == Some(Marker::CertAuthority)
                        && e.key_blob == cert.signature_key_blob
                        && host_field_matches(&e.host_spec, host, port))
            })
        };
        ca_trusted(port) || (port != 22 && ca_trusted(22))
    }

    /// Whether an `@revoked` line for `host[:port]` names the certificate's
    /// CA key or its embedded key (revoking either kills the cert).
    pub fn revokes_cert(&self, host: &str, port: u16, cert: &crate::cert::Certificate) -> bool {
        self.revoked_entries().any(|e| {
            host_field_matches(&e.host_spec, host, port)
                && (e.key_blob == cert.signature_key_blob
                    || e.key_blob == cert.embedded_pubkey_blob)
        })
    }

    /// Every `@revoked` entry, including those on lines kept raw because
    /// they are not valid UTF-8.
    fn revoked_entries(&self) -> impl Iterator<Item = &Entry> {
        self.lines.iter().filter_map(|slot| match slot {
            Slot::Entry(e) | Slot::Raw(_, Some(e)) if e.marker == Some(Marker::Revoked) => Some(e),
            _ => None,
        })
    }

    /// Append a new entry. The host is formatted as `host` for the
    /// default port and `[host]:port` otherwise.
    ///
    /// If `hashed` is true, the host field is HMAC-SHA1-hashed (with a
    /// freshly generated salt) before storage — matching OpenSSH's
    /// `HashKnownHosts yes` behaviour.
    ///
    /// A `host` or `key_type` that could not be written as a single,
    /// well-formed line (see [`Self::try_add`]) is refused: nothing is
    /// added.
    pub fn add(&mut self, host: &str, port: u16, key_type: &str, key_blob: &[u8], hashed: bool) {
        let _ = self.try_add(host, port, key_type, key_blob, hashed);
    }

    /// [`Self::add`], reporting a refused entry as an error.
    ///
    /// Both strings land verbatim in a whitespace-separated line, so a
    /// `key_type` or `host` holding whitespace or control characters (a
    /// `\n` would inject whole extra lines, e.g. a wildcard key or an
    /// `@cert-authority` marker), a `key_type` holding `,`, a `host`
    /// holding `,` (which would widen the pattern list), or either one
    /// starting with `@`, `|` or `#` (a marker, hashed host or comment) is
    /// rejected with [`crate::Error::Format`] and nothing is added.
    pub fn try_add(
        &mut self,
        host: &str,
        port: u16,
        key_type: &str,
        key_blob: &[u8],
        hashed: bool,
    ) -> crate::Result<()> {
        if !safe_field(key_type) {
            return Err(crate::Error::Format("known_hosts: invalid key type"));
        }
        if !safe_field(host) {
            return Err(crate::Error::Format("known_hosts: invalid host name"));
        }
        let host_spec = if hashed {
            let mut rng = OsRng;
            let (_salt, token) = hash_new(&mut rng, host, port);
            HostSpec::Hashed(token)
        } else {
            HostSpec::Patterns(vec![format_host_pattern(host, port)])
        };
        self.lines.push(Slot::Entry(Entry {
            marker: None,
            host_spec,
            key_type: key_type.to_string(),
            key_blob: key_blob.to_vec(),
            comment: String::new(),
        }));
        Ok(())
    }

    /// Remove only the plain entries that name **exactly** `host[:port]`:
    /// marker-less lines whose host field is the single literal pattern
    /// `format_host_pattern(host, port)` (compared ASCII
    /// case-insensitively, as host patterns are), or a hashed token for
    /// exactly that host and port. Returns the count removed.
    ///
    /// Unlike [`Self::remove`], this never touches wildcard / negated /
    /// multi-host pattern lines, nor `@cert-authority` or `@revoked`
    /// markers — entries that are typically shared with other hosts and
    /// must survive a key rotation for *this* host. This is the method
    /// the client uses when a user accepts a changed host key; `remove`
    /// keeps its broad `ssh-keygen -R` semantics for explicit CLI use.
    pub fn remove_exact(&mut self, host: &str, port: u16) -> usize {
        let literal = format_host_pattern(host, port);
        let mut removed = 0usize;
        for slot in self.lines.iter_mut() {
            let Slot::Entry(e) = slot else { continue };
            if e.marker.is_some() {
                continue;
            }
            let exact = match &e.host_spec {
                HostSpec::Patterns(pats) => {
                    pats.len() == 1 && pats[0].eq_ignore_ascii_case(&literal)
                }
                HostSpec::Hashed(_) => host_field_matches(&e.host_spec, host, port),
            };
            if exact {
                removed += 1;
                *slot = Slot::Removed;
            }
        }
        removed
    }

    /// Remove every entry whose host field matches `host[:port]`,
    /// including wildcard patterns and `@cert-authority` / `@revoked`
    /// markers — the semantics of `ssh-keygen -R`. Returns the count
    /// removed. For the narrower "replace this one host's key" case use
    /// [`Self::remove_exact`].
    pub fn remove(&mut self, host: &str, port: u16) -> usize {
        let mut removed = 0usize;
        for slot in self.lines.iter_mut() {
            if let Slot::Entry(e) = slot
                && host_field_matches(&e.host_spec, host, port)
            {
                removed += 1;
                *slot = Slot::Removed;
            }
        }
        removed
    }

    /// Return all entries whose host field matches `host[:port]`.
    pub fn find(&self, host: &str, port: u16) -> Vec<&Entry> {
        self.lines
            .iter()
            .filter_map(|s| match s {
                Slot::Entry(e) if host_field_matches(&e.host_spec, host, port) => Some(e),
                _ => None,
            })
            .collect()
    }

    /// The host fields of the plain entries holding `key_blob`, as written
    /// (`[hashed name]` for hashed ones), for OpenSSH's "This host key is
    /// known by the following other names/addresses".
    pub fn find_key(&self, key_blob: &[u8]) -> Vec<String> {
        self.lines
            .iter()
            .filter_map(|s| match s {
                Slot::Entry(e) if e.marker.is_none() && e.key_blob == key_blob => {
                    Some(match &e.host_spec {
                        HostSpec::Hashed(_) => "[hashed name]".to_string(),
                        spec => spec.to_field(),
                    })
                }
                _ => None,
            })
            .collect()
    }

    /// Hash every unhashed entry in place using fresh salts. Equivalent
    /// to `ssh-keygen -H`.
    ///
    /// Entries with multiple host patterns expand to one hashed entry
    /// per pattern, matching OpenSSH's behaviour.
    pub fn hash_in_place(&mut self) {
        let mut rng = OsRng;
        let mut new_lines: Vec<Slot> = Vec::with_capacity(self.lines.len());
        for slot in self.lines.drain(..) {
            match slot {
                Slot::Entry(e) => match e.host_spec {
                    HostSpec::Hashed(_) => new_lines.push(Slot::Entry(e)),
                    HostSpec::Patterns(pats) => {
                        // Buffer one entry per pattern. If any pattern
                        // is malformed (e.g. `[host]:NOT-A-PORT`), we
                        // refuse to silently downgrade — the whole
                        // entry is preserved verbatim instead, so a
                        // typo can't mask a hostkey-change.
                        let mut hashed: Vec<Entry> = Vec::with_capacity(pats.len());
                        let mut all_ok = true;
                        for pat in &pats {
                            let Some((host, port)) = split_host_port(pat) else {
                                all_ok = false;
                                break;
                            };
                            let mut salt = [0u8; super::hash::SALT_LEN];
                            rng.fill_bytes(&mut salt);
                            let token = super::hash::encode_hashed(
                                &salt,
                                &super::hash::format_host(&host, port),
                            );
                            hashed.push(Entry {
                                marker: e.marker,
                                host_spec: HostSpec::Hashed(token),
                                key_type: e.key_type.clone(),
                                key_blob: e.key_blob.clone(),
                                comment: e.comment.clone(),
                            });
                        }
                        if all_ok {
                            for entry in hashed {
                                new_lines.push(Slot::Entry(entry));
                            }
                        } else {
                            new_lines.push(Slot::Entry(Entry {
                                marker: e.marker,
                                host_spec: HostSpec::Patterns(pats),
                                key_type: e.key_type,
                                key_blob: e.key_blob,
                                comment: e.comment,
                            }));
                        }
                    }
                },
                other => new_lines.push(other),
            }
        }
        self.lines = new_lines;
    }
}

/// What OpenSSH's `UpdateHostKeys` would change in a known_hosts file for
/// one host, given the host keys the server offered (see
/// [`KnownHosts::host_keys_update`]).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct HostKeysUpdate {
    /// Indexes (into the offered keys) of the keys not yet recorded: they
    /// must be proven by the server before being added.
    pub new: Vec<usize>,
    /// Recorded keys for the host the server no longer offers.
    pub old: Vec<Vec<u8>>,
    /// Why the file must be left alone (a marker line or a multi-name /
    /// wildcard entry for the host, or an offered key recorded under
    /// another name), if it must.
    pub blocked: Option<&'static str>,
}

impl KnownHosts {
    /// Plan an `UpdateHostKeys` change for `host:port` from the plain host
    /// keys the server offered, as OpenSSH's client_input_hostkeys.
    pub fn host_keys_update(&self, host: &str, port: u16, offered: &[Vec<u8>]) -> HostKeysUpdate {
        let mut plan = HostKeysUpdate::default();
        let mut known = alloc::vec![false; offered.len()];
        for slot in &self.lines {
            let Slot::Entry(e) = slot else {
                continue;
            };
            let ours = host_field_matches(&e.host_spec, host, port);
            if !ours {
                if offered.contains(&e.key_blob) && e.marker.is_none() {
                    plan.blocked = Some("host key found under another name");
                }
                continue;
            }
            let simple = e.marker.is_none()
                && match &e.host_spec {
                    HostSpec::Hashed(_) => true,
                    HostSpec::Patterns(p) => p.len() == 1 && !p[0].contains(['*', '?', '!']),
                };
            if !simple {
                plan.blocked = Some("marker, host list or wildcard entry for the host");
                continue;
            }
            match offered.iter().position(|k| *k == e.key_blob) {
                Some(i) => known[i] = true,
                None => plan.old.push(e.key_blob.clone()),
            }
        }
        plan.new = (0..offered.len()).filter(|i| !known[*i]).collect();
        plan
    }

    /// Apply an `UpdateHostKeys` change for `host:port`: drop its entries
    /// for the keys in `remove`, then record `add` (`(key_type, blob)`),
    /// hashed when `hashed`.
    pub fn update_host_keys(
        &mut self,
        host: &str,
        port: u16,
        remove: &[Vec<u8>],
        add: &[(String, Vec<u8>)],
        hashed: bool,
    ) {
        self.lines.retain(|slot| match slot {
            Slot::Entry(e) => {
                !(e.marker.is_none()
                    && remove.contains(&e.key_blob)
                    && host_field_matches(&e.host_spec, host, port))
            }
            _ => true,
        });
        for (key_type, blob) in add {
            self.add(host, port, key_type, blob, hashed);
        }
    }
}

/// Whether `s` can be written as one field of a `known_hosts` line by
/// [`KnownHosts::try_add`]: non-empty, no whitespace, control characters or
/// `,`, and not starting with `@` (marker), `|` (hashed host) or `#`
/// (comment).
fn safe_field(s: &str) -> bool {
    !s.is_empty()
        && !s.starts_with(['@', '|', '#'])
        && !s
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || c == ',')
}

/// Write `data` to `path` with permissions `0o600` on Unix. The file is
/// opened with `O_EXCL` (`create_new`) so a pre-existing symlink in the
/// target directory cannot be used to redirect the write — the open
/// fails outright if the path already exists. On non-Unix targets the
/// `create_new(true)` open is still used (so we never follow a
/// pre-existing entry); the explicit mode bits are dropped because
/// Windows ACLs already grant owner-only access for files created under
/// the user's profile.
fn write_private_file(path: &Path, data: &[u8]) -> io::Result<()> {
    use std::io::Write as _;
    let mut opts = fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        opts.mode(0o600);
    }
    let mut f = opts.open(path)?;
    f.write_all(data)?;
    f.sync_all()?;
    Ok(())
}

/// Build a per-call unique temporary path next to `path`. The suffix
/// combines the process id and a fresh `u64` from `OsRng`, so two
/// concurrent saves in the same process cannot collide and an attacker
/// cannot predict the name to pre-create as a symlink.
fn unique_tmp_path(path: &Path) -> std::path::PathBuf {
    let mut rng = OsRng;
    let mut nonce = [0u8; 8];
    rng.fill_bytes(&mut nonce);
    let nonce = u64::from_le_bytes(nonce);
    let pid = std::process::id();
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("known_hosts");
    let tmp_name = format!(".{file_name}.tmp.{pid}.{nonce:016x}");
    match path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent.join(tmp_name),
        _ => std::path::PathBuf::from(tmp_name),
    }
}

/// Does the entry's host field match `host[:port]`?
///
/// For plain entries this runs the OpenSSH pattern-list match. For
/// hashed entries this re-computes HMAC-SHA1 under the stored salt.
fn host_field_matches(spec: &HostSpec, host: &str, port: u16) -> bool {
    match spec {
        HostSpec::Patterns(pats) => patterns_match(pats, host, port),
        HostSpec::Hashed(token) => match parse_hashed(token) {
            Some((salt, hash)) => check_hashed(&salt, &hash, host, port),
            None => false,
        },
    }
}

/// Split a plain host pattern (`host` or `[host]:port`) into
/// `(host, port)`. Default port is 22.
///
/// Returns `None` for malformed bracketed forms — specifically
/// `[host]:NOT-A-PORT`, `[host]:` (empty port) and `[host`-without-`]`.
/// Silently downgrading those to port 22 would mask a host-key change
/// (subsequent lookups would target a different host record than the
/// one the user wrote down).
///
/// Delegates to [`crate::config::parse_host_port_pattern`] (the
/// known_hosts grammar variant: brackets allowed around any host, no
/// colon-splitting of bare patterns). The `Err` cases (malformed
/// bracket forms) are mapped to `None` to preserve the original
/// `Option`-based contract.
fn split_host_port(pat: &str) -> Option<(String, u16)> {
    crate::config::parse_host_port_pattern(pat, 22).ok()
}

#[cfg(test)]
mod store_tests {
    use super::*;

    /// A file containing one valid line, one line with an invalid UTF-8
    /// byte, and another valid line must load BOTH valid entries — the bad
    /// line is skipped, not the whole file. Previously a single non-UTF-8
    /// byte emptied the entire store (every lookup → Unknown → silent TOFU
    /// fail-open, accepting a MITM key).
    #[test]
    fn invalid_utf8_line_is_skipped_not_whole_file() {
        // "AAAA" base64-decodes cleanly to a 3-byte blob, so these parse.
        let mut data: Vec<u8> = Vec::new();
        data.extend_from_slice(b"good1.example.com ssh-ed25519 AAAA\n");
        // A line carrying a lone 0xFF byte — invalid UTF-8 anywhere.
        data.extend_from_slice(b"bad.example.com ssh-ed25519 ");
        data.push(0xFF);
        data.push(b'\n');
        data.extend_from_slice(b"good2.example.com ssh-ed25519 AAAA\n");

        let kh = KnownHosts::from_bytes(&data);

        // Both valid hosts must be known.
        assert!(
            matches!(
                kh.lookup("good1.example.com", 22, "ssh-ed25519", &[0, 0, 0]),
                LookupResult::Match
            ),
            "first valid entry should have loaded"
        );
        assert!(
            matches!(
                kh.lookup("good2.example.com", 22, "ssh-ed25519", &[0, 0, 0]),
                LookupResult::Match
            ),
            "third valid entry should have loaded despite the bad middle line"
        );
        // The bad line contributed nothing.
        assert!(
            matches!(
                kh.lookup("bad.example.com", 22, "ssh-ed25519", &[0, 0, 0]),
                LookupResult::Unknown
            ),
            "the invalid-utf8 line must be skipped, not parsed"
        );
        // Exactly the two good entries were loaded.
        let entries = kh
            .lines
            .iter()
            .filter(|s| matches!(s, Slot::Entry(_)))
            .count();
        assert_eq!(entries, 2, "only the two valid lines should load");
    }

    /// A normally-terminated file (trailing `\n`) must not gain a spurious
    /// blank line when round-tripped, matching the old `str::lines()`
    /// behaviour.
    #[test]
    fn trailing_newline_does_not_add_blank_line() {
        let src = b"example.com ssh-ed25519 AAAA\n";
        let kh = KnownHosts::from_bytes(src);
        let out = kh.to_bytes();
        assert_eq!(out, src, "round-trip must not add a trailing blank line");
    }
}