puressh 0.2.3

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
//! RSA host keys (RFC 8332):
//!
//! - `ssh-rsa`       — RSA + SHA-1 (legacy; disabled by default in modern OpenSSH)
//! - `rsa-sha2-256`  — RSA + SHA-256 (PKCS#1 v1.5)
//! - `rsa-sha2-512`  — RSA + SHA-512 (PKCS#1 v1.5)
//!
//! All three share the same public-key blob layout under the algorithm
//! string `"ssh-rsa"` (RFC 8332 §3); only the signature blob differs.
//!
//! Backed by [`purecrypto::rsa::BoxedRsaPrivateKey`] (signing via
//! `sign_pkcs1v15::<D>`) and [`purecrypto::rsa::BoxedRsaPublicKey`]
//! (`verify_pkcs1v15::<D>`); the SSH public blob is built directly from
//! `BoxedRsaPublicKey::{modulus, exponent}`.

use super::HostKeyAlgorithm;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
use purecrypto::bignum::BoxedUint;
#[cfg(feature = "alloc")]
use purecrypto::hash::{Sha1, Sha256, Sha512};
#[cfg(feature = "alloc")]
use purecrypto::rsa::{BoxedRsaPrivateKey, BoxedRsaPublicKey};

#[cfg(feature = "alloc")]
use super::{HostKey, HostKeyVerify};
#[cfg(feature = "alloc")]
use crate::error::{Error, Result};
#[cfg(feature = "alloc")]
use crate::format::{Reader, Writer, read_mpint, write_mpint};

/// `ssh-rsa` (RSA-SHA1, legacy).
pub struct SshRsa;
impl HostKeyAlgorithm for SshRsa {
    const NAME: &'static str = "ssh-rsa";
}

/// `rsa-sha2-256`.
pub struct RsaSha2_256;
impl HostKeyAlgorithm for RsaSha2_256 {
    const NAME: &'static str = "rsa-sha2-256";
}

/// `rsa-sha2-512`.
pub struct RsaSha2_512;
impl HostKeyAlgorithm for RsaSha2_512 {
    const NAME: &'static str = "rsa-sha2-512";
}

/// The hash variant used in an RSA signature.
#[cfg(feature = "alloc")]
#[derive(Clone, Copy)]
enum RsaHash {
    Sha1,
    Sha256,
    Sha512,
}

#[cfg(feature = "alloc")]
impl RsaHash {
    const fn algorithm(self) -> &'static str {
        match self {
            RsaHash::Sha1 => SshRsa::NAME,
            RsaHash::Sha256 => RsaSha2_256::NAME,
            RsaHash::Sha512 => RsaSha2_512::NAME,
        }
    }
}

/// Convert mpint bytes (two's-complement big-endian) into a non-negative
/// `BoxedUint`, rejecting negative encodings.
#[cfg(feature = "alloc")]
fn mpint_to_uint(bytes: &[u8]) -> Result<BoxedUint> {
    if bytes.is_empty() {
        return Ok(BoxedUint::from_u64(0));
    }
    if (bytes[0] & 0x80) != 0 {
        return Err(Error::Format("rsa: negative mpint"));
    }
    let mut start = 0usize;
    while start + 1 < bytes.len() && bytes[start] == 0 {
        start += 1;
    }
    Ok(BoxedUint::from_be_bytes(&bytes[start..]))
}

/// Minimum accepted RSA modulus size, in bits.
///
/// purecrypto's `BoxedRsaPublicKey` accepts anything down to ~1024 bits, but
/// 1024-bit RSA is considered broken for SSH authentication (NIST SP 800-131A
/// withdrew it and OpenSSH 7.6+ rejects shorter-than-2048 by default). We
/// refuse at parse time rather than at verify time so callers cannot hold a
/// key/cert that will never be safely usable.
#[cfg(feature = "alloc")]
pub(crate) const MIN_RSA_MODULUS_BITS: usize = 2048;

/// Validate a raw RSA modulus `mpint` (as it appears in a public-key or
/// certificate blob): reject negative / zero encodings and enforce the
/// [`MIN_RSA_MODULUS_BITS`] floor. This is the single source of truth shared
/// by the plain-key parser and the certificate parser so the floor cannot be
/// bypassed by wrapping a weak key in a certificate.
#[cfg(feature = "alloc")]
pub(crate) fn check_rsa_modulus_mpint(n_raw: &[u8]) -> Result<()> {
    let n = mpint_to_uint(n_raw)?;
    if n.is_zero() {
        return Err(Error::Format("rsa: zero modulus"));
    }
    if n.bit_len() < MIN_RSA_MODULUS_BITS {
        return Err(Error::Format("rsa: modulus shorter than 2048 bits"));
    }
    Ok(())
}

/// Maximum accepted RSA public exponent size, in bits.
///
/// A signature verification costs one modular exponentiation whose work is
/// linear in `bit_len(e)`. purecrypto only requires `3 <= e < n`, so an
/// unauthenticated peer could otherwise present a 16384-bit modulus with a
/// ~16383-bit exponent and burn seconds of CPU per verify — before any
/// authorization decision is made. Real keys use `e = 65537` (17 bits);
/// OpenSSL refuses `e` wider than 64 bits (`OPENSSL_RSA_MAX_PUBEXP_BITS`),
/// and Go / BoringSSL are stricter still.
#[cfg(feature = "alloc")]
pub(crate) const MAX_RSA_EXPONENT_BITS: usize = 64;

/// Validate a raw RSA public-exponent `mpint` (as it appears in a public-key
/// or certificate blob): reject negative encodings and enforce the
/// [`MAX_RSA_EXPONENT_BITS`] cap. Shared by the plain-key parser and the
/// certificate parser so the cap cannot be bypassed by wrapping the key in
/// a certificate.
#[cfg(feature = "alloc")]
pub(crate) fn check_rsa_exponent_mpint(e_raw: &[u8]) -> Result<()> {
    let e = mpint_to_uint(e_raw)?;
    if e.bit_len() > MAX_RSA_EXPONENT_BITS {
        return Err(Error::Format("rsa: public exponent wider than 64 bits"));
    }
    Ok(())
}

#[cfg(feature = "alloc")]
fn parse_rsa_public_blob(blob: &[u8]) -> Result<(BoxedRsaPublicKey, usize)> {
    let mut r = Reader::new(blob);
    let name = r.read_string()?;
    if name != SshRsa::NAME.as_bytes() {
        return Err(Error::Format("rsa: public key type mismatch"));
    }
    let e_raw = read_mpint(&mut r)?;
    let n_raw = read_mpint(&mut r)?;
    if !r.is_empty() {
        return Err(Error::Format("rsa: public key trailing data"));
    }
    // Cap `e` before building the verifier: a huge exponent is the cheap
    // way for an unauthenticated peer to make each verify cost seconds.
    check_rsa_exponent_mpint(e_raw)?;
    let e = mpint_to_uint(e_raw)?;
    let n = mpint_to_uint(n_raw)?;
    if n.is_zero() {
        return Err(Error::Format("rsa: zero modulus"));
    }
    if n.bit_len() < MIN_RSA_MODULUS_BITS {
        return Err(Error::Format("rsa: modulus shorter than 2048 bits"));
    }
    let k = n.bit_len().div_ceil(8);
    let pk = BoxedRsaPublicKey::try_new(n, e)
        .map_err(|_| Error::Format("rsa: modulus out of accepted range"))?;
    Ok((pk, k))
}

#[cfg(feature = "alloc")]
fn build_rsa_public_blob(pk: &BoxedRsaPublicKey) -> Vec<u8> {
    let n = pk.modulus();
    let e = pk.exponent();
    let mut w = Writer::new();
    w.write_string(SshRsa::NAME.as_bytes());
    let nbytes = n.to_be_bytes(n.bit_len().div_ceil(8).max(1));
    let ebytes = e.to_be_bytes(e.bit_len().div_ceil(8).max(1));
    write_mpint(&mut w, &ebytes);
    write_mpint(&mut w, &nbytes);
    w.into_vec()
}

#[cfg(feature = "alloc")]
fn sign_rsa(hash: RsaHash, sk: &BoxedRsaPrivateKey, msg: &[u8]) -> Result<Vec<u8>> {
    let raw = match hash {
        RsaHash::Sha1 => sk.sign_pkcs1v15::<Sha1>(msg),
        RsaHash::Sha256 => sk.sign_pkcs1v15::<Sha256>(msg),
        RsaHash::Sha512 => sk.sign_pkcs1v15::<Sha512>(msg),
    }
    .map_err(|_| Error::Crypto("rsa: signing failed"))?;

    let mut w = Writer::with_capacity(4 + hash.algorithm().len() + 4 + raw.len());
    w.write_string(hash.algorithm().as_bytes());
    w.write_string(&raw);
    Ok(w.into_vec())
}

#[cfg(feature = "alloc")]
fn verify_rsa(
    hash: RsaHash,
    pk: &BoxedRsaPublicKey,
    k: usize,
    msg: &[u8],
    sig_blob: &[u8],
) -> Result<()> {
    let mut r = Reader::new(sig_blob);
    let name = r.read_string()?;
    if name != hash.algorithm().as_bytes() {
        return Err(Error::Format("rsa: signature algorithm mismatch"));
    }
    let raw = r.read_string()?;
    if !r.is_empty() {
        return Err(Error::Format("rsa: signature trailing data"));
    }
    if raw.len() != k {
        return Err(Error::Format("rsa: signature length mismatch"));
    }
    match hash {
        RsaHash::Sha1 => pk.verify_pkcs1v15::<Sha1>(msg, raw),
        RsaHash::Sha256 => pk.verify_pkcs1v15::<Sha256>(msg, raw),
        RsaHash::Sha512 => pk.verify_pkcs1v15::<Sha512>(msg, raw),
    }
    .map_err(|_| Error::BadSignature)
}

/// Check that `(p, q)` are a plausible factorisation of `n`: both odd, both
/// at least 3 bits wide, distinct, and `p * q == n`. Shared by the RSA host
/// key constructor and the private-key file parsers.
#[cfg(feature = "alloc")]
pub(crate) fn check_rsa_primes(n: &BoxedUint, p: &BoxedUint, q: &BoxedUint) -> Result<()> {
    if p.bit_len() < 3 || q.bit_len() < 3 || !p.is_odd() || !q.is_odd() || p == q {
        return Err(Error::Format("rsa: invalid prime factors"));
    }
    if &p.mul(q) != n {
        return Err(Error::Format("rsa: prime factors do not match modulus"));
    }
    Ok(())
}

macro_rules! rsa_host_key {
    ($name:ident, $hash:expr, $algname:expr, $doc:expr, $upgrade:expr) => {
        #[cfg(feature = "alloc")]
        #[doc = $doc]
        pub struct $name {
            private: Option<BoxedRsaPrivateKey>,
            public: BoxedRsaPublicKey,
            k: usize,
        }

        #[cfg(feature = "alloc")]
        impl $name {
            /// Build a host key from its `(n, e, d)` components.
            ///
            /// Without the prime factors `(p, q)`, base-blinding is disabled
            /// on the private path — see `BoxedRsaPrivateKey::from_components`
            /// — leaving signing exposed to remote timing analysis
            /// (Brumley–Boneh). Prefer [`Self::from_components_with_primes`]
            /// whenever the key file carries `p` and `q` (openssh-key-v1,
            /// PKCS#1 and PKCS#8 all do).
            pub fn from_components(n: BoxedUint, e: BoxedUint, d: BoxedUint) -> Result<Self> {
                let public = BoxedRsaPublicKey::try_new(n.clone(), e.clone())
                    .map_err(|_| Error::Crypto("rsa: modulus out of accepted range"))?;
                let k = n.bit_len().div_ceil(8);
                let private = BoxedRsaPrivateKey::from_components(n, e, d);
                Ok(Self {
                    private: Some(private),
                    public,
                    k,
                })
            }

            /// Build a host key from `(n, e, d)` **and** the prime factors
            /// `(p, q)`, keeping purecrypto's base blinding (and CRT) enabled
            /// on the signing path.
            ///
            /// The primes are checked against the modulus (`p * q == n`, both
            /// odd and non-trivial) before use: purecrypto's constructor
            /// performs no validation, and a corrupt key file with mismatched
            /// primes would otherwise produce garbage CRT signatures.
            pub fn from_components_with_primes(
                n: BoxedUint,
                e: BoxedUint,
                d: BoxedUint,
                p: BoxedUint,
                q: BoxedUint,
            ) -> Result<Self> {
                check_rsa_primes(&n, &p, &q)?;
                let public = BoxedRsaPublicKey::try_new(n.clone(), e.clone())
                    .map_err(|_| Error::Crypto("rsa: modulus out of accepted range"))?;
                let k = n.bit_len().div_ceil(8);
                let private = BoxedRsaPrivateKey::from_components_with_primes(n, e, d, p, q);
                Ok(Self {
                    private: Some(private),
                    public,
                    k,
                })
            }

            /// Build a verifier-only host key from `(n, e)`.
            pub fn from_public_components(n: BoxedUint, e: BoxedUint) -> Result<Self> {
                let k = n.bit_len().div_ceil(8);
                let public = BoxedRsaPublicKey::try_new(n, e)
                    .map_err(|_| Error::Crypto("rsa: modulus out of accepted range"))?;
                Ok(Self {
                    private: None,
                    public,
                    k,
                })
            }

            /// The modulus byte length (`k` per PKCS#1).
            pub fn modulus_bytes(&self) -> usize {
                self.k
            }

            /// Build a same-key variant of a sibling RSA host key type
            /// (used by `upgraded_for` to promote `ssh-rsa` → `rsa-sha2-*`
            /// over the same `(n, e[, d])` material).
            #[doc(hidden)]
            #[allow(dead_code)]
            pub(crate) fn from_rsa_parts(
                private: Option<BoxedRsaPrivateKey>,
                public: BoxedRsaPublicKey,
                k: usize,
            ) -> Self {
                Self { private, public, k }
            }
        }

        #[cfg(feature = "alloc")]
        impl HostKey for $name {
            fn algorithm(&self) -> &'static str {
                $algname
            }

            fn public_blob(&self) -> Vec<u8> {
                build_rsa_public_blob(&self.public)
            }

            fn sign(&self, msg: &[u8]) -> Result<Vec<u8>> {
                let sk = self
                    .private
                    .as_ref()
                    .ok_or(Error::Crypto("rsa: no private key"))?;
                sign_rsa($hash, sk, msg)
            }

            fn upgraded_for(&self, server_sig_algs: &str) -> Option<Box<dyn HostKey>> {
                #[allow(clippy::redundant_closure_call)]
                ($upgrade)(self, server_sig_algs)
            }
        }

        #[cfg(feature = "alloc")]
        impl HostKeyVerify for $name {
            fn algorithm(&self) -> &'static str {
                $algname
            }

            fn verify(&self, msg: &[u8], sig_blob: &[u8]) -> Result<()> {
                verify_rsa($hash, &self.public, self.k, msg, sig_blob)
            }

            fn from_public_blob(blob: &[u8]) -> Result<Self> {
                let (public, k) = parse_rsa_public_blob(blob)?;
                Ok(Self {
                    private: None,
                    public,
                    k,
                })
            }
        }
    };
}

/// Returns the preferred RSA SHA-2 algorithm name (`rsa-sha2-512` first,
/// then `rsa-sha2-256`) that the server advertised in its
/// `server-sig-algs`, or `None` if neither is available. Pure parsing —
/// no side effects.
#[cfg(feature = "alloc")]
fn preferred_rsa_sha2(server_sig_algs: &str) -> Option<&'static str> {
    let mut has_512 = false;
    let mut has_256 = false;
    for algo in server_sig_algs.split(',') {
        match algo.trim() {
            "rsa-sha2-512" => has_512 = true,
            "rsa-sha2-256" => has_256 = true,
            _ => {}
        }
    }
    if has_512 {
        Some(RsaSha2_512::NAME)
    } else if has_256 {
        Some(RsaSha2_256::NAME)
    } else {
        None
    }
}

/// The signature algorithm an RSA identity should use given an algorithm
/// list (`server-sig-algs`, or the local `PubkeyAcceptedAlgorithms`):
/// `rsa-sha2-512`, then `rsa-sha2-256`, then — only with the process-wide
/// SHA-1 opt-in ([`super::allow_rsa_sha1`]) — legacy `ssh-rsa`.
#[cfg(feature = "alloc")]
fn rsa_variant_for(
    private: &Option<BoxedRsaPrivateKey>,
    public: &BoxedRsaPublicKey,
    k: usize,
    current: &str,
    sig_algs: &str,
) -> Option<Box<dyn HostKey>> {
    let name = preferred_rsa_sha2(sig_algs).or_else(|| {
        (super::allow_rsa_sha1() && sig_algs.split(',').any(|a| a.trim() == SshRsa::NAME))
            .then_some(SshRsa::NAME)
    })?;
    if name == current {
        return None;
    }
    let (private, public, k) = clone_rsa_parts(private, public, k);
    Some(match name {
        "rsa-sha2-512" => Box::new(RsaSha2_512HostKey::from_rsa_parts(private, public, k)),
        "rsa-sha2-256" => Box::new(RsaSha2_256HostKey::from_rsa_parts(private, public, k)),
        _ => Box::new(RsaSha1HostKey::from_rsa_parts(private, public, k)),
    })
}

/// Clone an RSA host key's inner `(private, public, k)` triple so a
/// sibling variant (e.g. SHA-1 → SHA-512 over the same key) can be
/// constructed from the same material.
#[cfg(feature = "alloc")]
fn clone_rsa_parts(
    private: &Option<BoxedRsaPrivateKey>,
    public: &BoxedRsaPublicKey,
    k: usize,
) -> (Option<BoxedRsaPrivateKey>, BoxedRsaPublicKey, usize) {
    (private.clone(), public.clone(), k)
}

rsa_host_key!(
    RsaSha1HostKey,
    RsaHash::Sha1,
    SshRsa::NAME,
    "RSA host key signing with `ssh-rsa` (RSA + SHA-1).",
    (|this: &RsaSha1HostKey, sig_algs: &str| -> Option<Box<dyn HostKey>> {
        let name = preferred_rsa_sha2(sig_algs)?;
        let (private, public, k) = clone_rsa_parts(&this.private, &this.public, this.k);
        match name {
            "rsa-sha2-512" => Some(
                Box::new(RsaSha2_512HostKey::from_rsa_parts(private, public, k))
                    as Box<dyn HostKey>,
            ),
            "rsa-sha2-256" => Some(
                Box::new(RsaSha2_256HostKey::from_rsa_parts(private, public, k))
                    as Box<dyn HostKey>,
            ),
            _ => None,
        }
    })
);
rsa_host_key!(
    RsaSha2_256HostKey,
    RsaHash::Sha256,
    RsaSha2_256::NAME,
    "RSA host key signing with `rsa-sha2-256` (RSA + SHA-256).",
    (|this: &RsaSha2_256HostKey, sig_algs: &str| -> Option<Box<dyn HostKey>> {
        rsa_variant_for(
            &this.private,
            &this.public,
            this.k,
            RsaSha2_256::NAME,
            sig_algs,
        )
    })
);
rsa_host_key!(
    RsaSha2_512HostKey,
    RsaHash::Sha512,
    RsaSha2_512::NAME,
    "RSA host key signing with `rsa-sha2-512` (RSA + SHA-512).",
    (|this: &RsaSha2_512HostKey, sig_algs: &str| -> Option<Box<dyn HostKey>> {
        rsa_variant_for(
            &this.private,
            &this.public,
            this.k,
            RsaSha2_512::NAME,
            sig_algs,
        )
    })
);

#[cfg(all(test, feature = "alloc"))]
mod tests {
    use super::*;

    fn known_n_e() -> (BoxedUint, BoxedUint) {
        let mut n_bytes = alloc::vec![0u8; 256];
        n_bytes[0] = 0xc0;
        for (i, b) in n_bytes.iter_mut().enumerate().skip(1) {
            *b = (i as u8).wrapping_mul(31).wrapping_add(7) | 0x01;
        }
        let n = BoxedUint::from_be_bytes(&n_bytes);
        let e = BoxedUint::from_u64(65537);
        (n, e)
    }

    #[test]
    fn rsa_public_blob_roundtrip() {
        let (n, e) = known_n_e();
        let hk = RsaSha2_256HostKey::from_public_components(n.clone(), e.clone()).unwrap();
        let blob = hk.public_blob();

        let parsed = RsaSha2_256HostKey::from_public_blob(&blob).unwrap();
        let mut r = Reader::new(&blob);
        let name = r.read_string().unwrap();
        assert_eq!(name, SshRsa::NAME.as_bytes());
        let e_raw = read_mpint(&mut r).unwrap();
        let n_raw = read_mpint(&mut r).unwrap();
        assert_eq!(
            mpint_to_uint(e_raw).unwrap().to_be_bytes(3),
            e.to_be_bytes(3)
        );
        assert_eq!(
            mpint_to_uint(n_raw).unwrap().to_be_bytes(256),
            n.to_be_bytes(256)
        );
        assert_eq!(parsed.modulus_bytes(), hk.modulus_bytes());
    }

    #[test]
    fn rsa_signature_blob_format_smoke() {
        let (n, e) = known_n_e();
        let pk = RsaSha2_256HostKey::from_public_components(n, e).unwrap();
        let mut bogus = Writer::new();
        bogus.write_string(b"rsa-sha2-256");
        bogus.write_string(&alloc::vec![0u8; pk.modulus_bytes()]);
        assert!(matches!(
            pk.verify(b"x", &bogus.into_vec()),
            Err(Error::BadSignature)
        ));
    }

    #[test]
    fn rsa_signature_rejects_wrong_algorithm_name() {
        let (n, e) = known_n_e();
        let pk = RsaSha2_256HostKey::from_public_components(n, e).unwrap();
        let mut bad = Writer::new();
        bad.write_string(b"ssh-rsa");
        bad.write_string(&alloc::vec![0u8; pk.modulus_bytes()]);
        assert!(matches!(
            pk.verify(b"x", &bad.into_vec()),
            Err(Error::Format(_))
        ));
    }

    #[test]
    fn rsa_signature_rejects_wrong_length() {
        let (n, e) = known_n_e();
        let pk = RsaSha2_256HostKey::from_public_components(n, e).unwrap();
        let mut bad = Writer::new();
        bad.write_string(b"rsa-sha2-256");
        bad.write_string(&alloc::vec![0u8; 1]);
        assert!(matches!(
            pk.verify(b"x", &bad.into_vec()),
            Err(Error::Format(_))
        ));
    }

    #[test]
    fn rsa_parse_rejects_short_modulus() {
        // 1024-bit modulus encoded as a public blob: must be refused by the
        // 2048-bit floor in parse_rsa_public_blob.
        let mut n_bytes = alloc::vec![0u8; 128];
        n_bytes[0] = 0xc0;
        for (i, b) in n_bytes.iter_mut().enumerate().skip(1) {
            *b = (i as u8).wrapping_mul(31).wrapping_add(7) | 0x01;
        }
        let n = BoxedUint::from_be_bytes(&n_bytes);
        let e = BoxedUint::from_u64(65537);
        let hk = RsaSha2_256HostKey::from_public_components(n, e).unwrap();
        let blob = hk.public_blob();
        match RsaSha2_256HostKey::from_public_blob(&blob) {
            Err(Error::Format(msg)) => assert!(
                msg.contains("2048"),
                "expected 2048-bit floor error, got {msg:?}"
            ),
            Err(other) => panic!("expected Format(2048), got {other:?}"),
            Ok(_) => panic!("expected 1024-bit modulus to be rejected"),
        }
    }

    /// Encode a public blob by hand so the exponent can be any width
    /// (`from_public_components` would go through purecrypto, which does
    /// not cap `e`).
    fn raw_rsa_blob(e_mag: &[u8], n_mag: &[u8]) -> Vec<u8> {
        let mut w = Writer::new();
        w.write_string(SshRsa::NAME.as_bytes());
        write_mpint(&mut w, e_mag);
        write_mpint(&mut w, n_mag);
        w.into_vec()
    }

    #[test]
    fn rsa_parse_rejects_oversized_exponent() {
        // A 2048-bit modulus with a 2047-bit exponent: legal for purecrypto
        // (3 <= e < n) but a verify-cost DoS. Must be refused at parse time.
        let (n, _) = known_n_e();
        let n_mag = n.to_be_bytes(256);
        let mut e_mag = alloc::vec![0xffu8; 256];
        e_mag[0] = 0x7f;
        let blob = raw_rsa_blob(&e_mag, &n_mag);
        match RsaSha2_256HostKey::from_public_blob(&blob) {
            Err(Error::Format(msg)) => assert!(msg.contains("exponent"), "got {msg:?}"),
            Err(other) => panic!("expected Format(exponent), got {other:?}"),
            Ok(_) => panic!("expected oversized exponent to be rejected"),
        }
        // 65-bit exponent: one over the cap.
        let mut e65 = alloc::vec![0xffu8; 9];
        e65[0] = 0x01;
        assert!(matches!(
            RsaSha2_256HostKey::from_public_blob(&raw_rsa_blob(&e65, &n_mag)),
            Err(Error::Format(_))
        ));
        // Exactly 64 bits (odd) still parses.
        let e64 = alloc::vec![0xffu8; 8];
        RsaSha2_256HostKey::from_public_blob(&raw_rsa_blob(&e64, &n_mag))
            .expect("64-bit exponent must be accepted");
        // And the common case, of course.
        RsaSha2_256HostKey::from_public_blob(&raw_rsa_blob(&[0x01, 0x00, 0x01], &n_mag))
            .expect("e = 65537 must be accepted");
    }

    #[test]
    fn rsa_public_blob_uses_ssh_rsa_for_all_hashes() {
        let (n, e) = known_n_e();
        let s256 = RsaSha2_256HostKey::from_public_components(n.clone(), e.clone()).unwrap();
        let s512 = RsaSha2_512HostKey::from_public_components(n.clone(), e.clone()).unwrap();
        let s1 = RsaSha1HostKey::from_public_components(n, e).unwrap();
        assert_eq!(s256.public_blob(), s512.public_blob());
        assert_eq!(s256.public_blob(), s1.public_blob());
    }

    #[test]
    fn rsa_sha1_upgrades_to_sha512_when_server_advertises_it() {
        let (n, e) = known_n_e();
        let s1 = RsaSha1HostKey::from_public_components(n.clone(), e.clone()).unwrap();
        let expected_blob = s1.public_blob();
        let upgraded = s1
            .upgraded_for("rsa-sha2-512,rsa-sha2-256,ssh-ed25519")
            .expect("server advertises rsa-sha2-512, must upgrade");
        assert_eq!(upgraded.algorithm(), "rsa-sha2-512");
        // The public blob is identical for ssh-rsa / rsa-sha2-{256,512}
        // (RFC 8332 §3) — proves we're reusing the same RSA key.
        assert_eq!(upgraded.public_blob(), expected_blob);
    }

    #[test]
    fn rsa_sha1_upgrades_to_sha256_when_only_256_advertised() {
        let (n, e) = known_n_e();
        let s1 = RsaSha1HostKey::from_public_components(n, e).unwrap();
        let upgraded = s1
            .upgraded_for("rsa-sha2-256,ssh-ed25519")
            .expect("server advertises rsa-sha2-256, must upgrade");
        assert_eq!(upgraded.algorithm(), "rsa-sha2-256");
    }

    #[test]
    fn rsa_sha1_no_upgrade_when_server_only_offers_ssh_rsa() {
        let (n, e) = known_n_e();
        let s1 = RsaSha1HostKey::from_public_components(n, e).unwrap();
        assert!(
            s1.upgraded_for("ssh-rsa,ssh-ed25519").is_none(),
            "no rsa-sha2-{{256,512}} on the server: must not upgrade",
        );
    }

    #[test]
    fn rsa_sha1_no_upgrade_when_server_sig_algs_empty() {
        let (n, e) = known_n_e();
        let s1 = RsaSha1HostKey::from_public_components(n, e).unwrap();
        assert!(s1.upgraded_for("").is_none());
    }

    #[test]
    fn rsa_sha1_prefers_sha512_over_sha256_when_both_advertised() {
        // Order-independent: server can list them in any order, we still
        // pick the strongest available.
        let (n, e) = known_n_e();
        let s1 = RsaSha1HostKey::from_public_components(n, e).unwrap();
        let upgraded = s1
            .upgraded_for("rsa-sha2-256,rsa-sha2-512")
            .expect("must upgrade");
        assert_eq!(upgraded.algorithm(), "rsa-sha2-512");
    }

    #[test]
    fn rsa_sha2_signers_switch_to_what_the_list_allows() {
        // The auth layer only asks when the current algorithm is not on
        // the list; the variant is then the best one that is.
        let (n, e) = known_n_e();
        let s256 = RsaSha2_256HostKey::from_public_components(n.clone(), e.clone()).unwrap();
        assert_eq!(
            s256.upgraded_for("rsa-sha2-512").unwrap().algorithm(),
            "rsa-sha2-512"
        );
        let s512 = RsaSha2_512HostKey::from_public_components(n, e).unwrap();
        assert_eq!(
            s512.upgraded_for("ssh-ed25519,rsa-sha2-256")
                .unwrap()
                .algorithm(),
            "rsa-sha2-256"
        );
    }

    #[test]
    fn rsa_sha2_512_signer_does_not_upgrade() {
        let (n, e) = known_n_e();
        let s512 = RsaSha2_512HostKey::from_public_components(n, e).unwrap();
        assert!(s512.upgraded_for("rsa-sha2-512,rsa-sha2-256").is_none());
    }
}