Skip to main content

ssh_encoding/
mpint.rs

1//! Multiple precision integers.
2
3use crate::{Encode, Error, Result, Writer};
4
5#[cfg(feature = "alloc")]
6pub use allocating::Mpint;
7
8/// A non-negative SSH `mpint` borrowing its unsigned big-endian magnitude.
9///
10/// Use [`Self::from_bytes`] to encode an existing magnitude. [`crate::Decoder::read_mpint_bytes`]
11/// decodes a wire value into caller-provided storage. Both operations are variable-time.
12#[derive(Clone, Copy, Debug)]
13pub struct MpintRef<'a>(&'a [u8]);
14
15impl<'a> MpintRef<'a> {
16    /// Maximum magnitude size in bytes, excluding SSH sign padding.
17    pub const MAX_SIZE: usize = 2048;
18
19    /// Borrow an unsigned big-endian magnitude, stripping any leading zeros.
20    ///
21    /// # Errors
22    /// Returns [`Error::Length`] if the magnitude exceeds [`Self::MAX_SIZE`].
23    pub fn from_bytes(mut bytes: &'a [u8]) -> Result<Self> {
24        while let Some((0, rest)) = bytes.split_first() {
25            bytes = rest;
26        }
27        if bytes.len() > Self::MAX_SIZE {
28            return Err(Error::Length);
29        }
30        Ok(Self(bytes))
31    }
32
33    /// Borrow the unsigned big-endian magnitude without padding. Zero is an empty slice.
34    #[must_use]
35    pub fn as_bytes(&self) -> &'a [u8] {
36        self.0
37    }
38
39    fn needs_padding(&self) -> bool {
40        self.0.first().is_some_and(|byte| *byte >= 0x80)
41    }
42}
43
44impl Encode for MpintRef<'_> {
45    fn encoded_len(&self) -> Result<usize> {
46        Ok(4 + self.0.len() + usize::from(self.needs_padding()))
47    }
48
49    fn encode(&self, writer: &mut impl Writer) -> Result<()> {
50        let padding = self.needs_padding();
51        (self.0.len() + usize::from(padding)).encode(writer)?;
52        if padding {
53            0u8.encode(writer)?;
54        }
55        writer.write(self.0)
56    }
57}
58
59#[cfg(feature = "alloc")]
60mod allocating {
61    use super::MpintRef;
62    use crate::{Decode, Decoder, Encode, Error, Reader, Result, Writer};
63    use alloc::boxed::Box;
64    use core::fmt;
65
66    #[cfg(feature = "bigint")]
67    use crate::Uint;
68    #[cfg(feature = "zeroize")]
69    use zeroize::Zeroize;
70    #[cfg(feature = "ctutils")]
71    use {
72        core::cmp::Ordering,
73        ctutils::{Choice, CtEq, CtLt, CtSelect},
74    };
75
76    /// Multiple precision integer, a.k.a. `mpint`.
77    ///
78    /// This type supports the non-negative subset of [RFC4251 § 5], matching [OpenSSH].
79    /// Values are limited to 16384-bits. Negative SSH encodings are rejected.
80    ///
81    /// [`Self::from_bytes`] and [`Self::as_bytes`] use an unsigned big endian magnitude,
82    /// without a length prefix or sign padding. Leading zeros are stripped and zero
83    /// is represented by an empty slice.
84    ///
85    /// [`Decode`] accepts redundant leading zeros like OpenSSH, but limits the input
86    /// to [`Self::MAX_SIZE`] bytes plus one leading zero byte *before* stripping zeros.
87    /// [`Encode`] always emits the canonical SSH encoding, including a leading zero
88    /// when the most significant bit is set and an empty string for zero.
89    ///
90    /// With the `ctutils` feature, constant-time order and equality operations on equal-length
91    /// magnitudes are supported. Lengths are not treated as secret. Byte conversion, decoding, and
92    /// encoding are variable-time.
93    ///
94    /// ## Examples
95    ///
96    /// | value (hex)     | SSH encoding (hex) |
97    /// |-----------------|--------------------|
98    /// | 0               | `00 00 00 00` |
99    /// | 9a378f9b2e332a7  | `00 00 00 08 09 a3 78 f9 b2 e3 32 a7` |
100    /// | 80              | `00 00 00 02 00 80` |
101    ///
102    /// [RFC4251 § 5]: https://datatracker.ietf.org/doc/html/rfc4251#section-5
103    /// [OpenSSH]: https://github.com/openssh/openssh-portable/blob/1d28115e040b792075a391de01b0f0c033a4850a/sshbuf-getput-basic.c#L598
104    #[derive(Clone)]
105    #[cfg_attr(not(feature = "ctutils"), derive(Eq, PartialEq))]
106    pub struct Mpint {
107        /// Unsigned big endian magnitude without leading zeros. Empty for zero.
108        inner: Box<[u8]>,
109    }
110
111    impl Mpint {
112        /// Maximum magnitude size in bytes, excluding SSH sign padding.
113        ///
114        /// This 16384-bit limit is enforced by every constructor and decoder.
115        pub const MAX_SIZE: usize = MpintRef::MAX_SIZE;
116
117        /// Create an integer from its unsigned big endian magnitude.
118        ///
119        /// Leading zeros are stripped. The most significant bit is part of the magnitude,
120        /// not a sign bit. This method does not expect an SSH length prefix or sign padding.
121        ///
122        /// # Errors
123        /// Returns [`Error::Length`] if the magnitude exceeds [`Self::MAX_SIZE`].
124        /// Returns [`Error::Alloc`] if reserving capacity fails.
125        pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
126            let bytes = MpintRef::from_bytes(bytes)?.as_bytes();
127
128            let mut inner = crate::vec_with_reserve(bytes.len())?;
129            inner.extend_from_slice(bytes);
130
131            Ok(Self {
132                inner: inner.into_boxed_slice(),
133            })
134        }
135
136        /// Get the unsigned big endian magnitude, without leading zeros or SSH sign padding.
137        ///
138        /// Returns an empty slice for zero.
139        #[must_use]
140        pub fn as_bytes(&self) -> &[u8] {
141            &self.inner
142        }
143
144        /// Is this integer zero?
145        #[must_use]
146        pub fn is_zero(&self) -> bool {
147            self.inner.is_empty()
148        }
149    }
150
151    impl AsRef<[u8]> for Mpint {
152        fn as_ref(&self) -> &[u8] {
153            self.as_bytes()
154        }
155    }
156
157    #[cfg(feature = "ctutils")]
158    impl CtEq for Mpint {
159        fn ct_eq(&self, other: &Self) -> Choice {
160            self.as_bytes().ct_eq(other.as_bytes())
161        }
162    }
163
164    #[cfg(feature = "ctutils")]
165    impl Eq for Mpint {}
166
167    #[cfg(feature = "ctutils")]
168    impl PartialEq for Mpint {
169        fn eq(&self, other: &Self) -> bool {
170            self.ct_eq(other).into()
171        }
172    }
173
174    #[cfg(feature = "ctutils")]
175    impl Ord for Mpint {
176        fn cmp(&self, other: &Self) -> Ordering {
177            // Canonical magnitudes with different byte lengths can be ordered by length.
178            match self.inner.len().cmp(&other.inner.len()) {
179                Ordering::Equal => {}
180                ordering => return ordering,
181            }
182
183            // Visit every byte, with more significant differences taking precedence.
184            let mut ordering = Ordering::Equal;
185            for (a, b) in self.inner.iter().zip(other.inner.iter()).rev() {
186                ordering = ordering.ct_select(&Ordering::Less, a.ct_lt(b));
187                ordering = ordering.ct_select(&Ordering::Greater, b.ct_lt(a));
188            }
189            ordering
190        }
191    }
192
193    #[cfg(feature = "ctutils")]
194    impl PartialOrd for Mpint {
195        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
196            Some(self.cmp(other))
197        }
198    }
199
200    impl Decode for Mpint {
201        type Error = Error;
202
203        fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
204            reader.read_prefixed(|reader| {
205                let Some(first) = reader.read_mpint_prefix()? else {
206                    return Self::from_bytes(&[]);
207                };
208
209                let mut bytes = crate::vec_zeroed(reader.remaining_len() + 1)?;
210                bytes[0] = first;
211                reader.read(&mut bytes[1..])?;
212
213                Ok(Self {
214                    inner: bytes.into_boxed_slice(),
215                })
216            })
217        }
218    }
219
220    impl Encode for Mpint {
221        fn encoded_len(&self) -> Result<usize> {
222            MpintRef::from(self).encoded_len()
223        }
224
225        fn encode(&self, writer: &mut impl Writer) -> Result<()> {
226            MpintRef::from(self).encode(writer)
227        }
228    }
229
230    impl<'a> From<&'a Mpint> for MpintRef<'a> {
231        fn from(mpint: &'a Mpint) -> Self {
232            Self(mpint.as_bytes())
233        }
234    }
235
236    impl TryFrom<&[u8]> for Mpint {
237        type Error = Error;
238
239        fn try_from(bytes: &[u8]) -> Result<Self> {
240            Self::from_bytes(bytes)
241        }
242    }
243
244    impl TryFrom<Box<[u8]>> for Mpint {
245        type Error = Error;
246
247        fn try_from(bytes: Box<[u8]>) -> Result<Self> {
248            if bytes.first() == Some(&0) {
249                let result = Self::from_bytes(&bytes);
250                #[cfg(feature = "zeroize")]
251                {
252                    let mut bytes = bytes;
253                    bytes.zeroize();
254                }
255                result
256            } else if bytes.len() > Self::MAX_SIZE {
257                Err(Error::Length)
258            } else {
259                Ok(Self { inner: bytes })
260            }
261        }
262    }
263
264    #[cfg(feature = "zeroize")]
265    impl Zeroize for Mpint {
266        fn zeroize(&mut self) {
267            self.inner.zeroize();
268            // Preserve the canonical representation of zero after clearing the buffer.
269            self.inner = Box::default();
270        }
271    }
272
273    impl fmt::Debug for Mpint {
274        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275            write!(f, "Mpint({self:X})")
276        }
277    }
278
279    impl fmt::Display for Mpint {
280        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281            write!(f, "{self:X}")
282        }
283    }
284
285    impl fmt::LowerHex for Mpint {
286        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287            if self.is_zero() {
288                return f.write_str("0");
289            }
290
291            for byte in self.as_bytes() {
292                write!(f, "{byte:02x}")?;
293            }
294
295            Ok(())
296        }
297    }
298
299    impl fmt::UpperHex for Mpint {
300        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301            if self.is_zero() {
302                return f.write_str("0");
303            }
304
305            for byte in self.as_bytes() {
306                write!(f, "{byte:02X}")?;
307            }
308
309            Ok(())
310        }
311    }
312
313    #[cfg(feature = "bigint")]
314    impl TryFrom<&Uint> for Mpint {
315        type Error = Error;
316
317        fn try_from(uint: &Uint) -> Result<Self> {
318            // Reject oversized values before allocating their byte representation.
319            // TODO(tarcieri): use `bit_width_vartime` when we bump `crypto-bigint` version
320            #[allow(deprecated, reason = "crypto-bigint v0.7.0 compatibility")]
321            let bits = uint.bits_vartime();
322
323            if bits > u32::try_from(Self::MAX_SIZE * 8)? {
324                return Err(Error::Length);
325            }
326
327            // Serialize directly into the fallibly allocated magnitude buffer.
328            let mut inner = crate::vec_with_reserve(usize::try_from(bits.div_ceil(8))?)?;
329
330            for limb in uint.as_limbs().iter().rev() {
331                let bytes = limb.0.to_be_bytes();
332
333                let bytes = if inner.is_empty() {
334                    MpintRef::from_bytes(&bytes)?.as_bytes()
335                } else {
336                    &bytes
337                };
338
339                inner.extend_from_slice(bytes);
340            }
341
342            Ok(Self {
343                inner: inner.into_boxed_slice(),
344            })
345        }
346    }
347
348    #[cfg(feature = "bigint")]
349    impl TryFrom<Uint> for Mpint {
350        type Error = Error;
351
352        fn try_from(uint: Uint) -> Result<Self> {
353            Self::try_from(&uint)
354        }
355    }
356
357    #[cfg(feature = "bigint")]
358    impl From<Mpint> for Uint {
359        fn from(mpint: Mpint) -> Uint {
360            Uint::from(&mpint)
361        }
362    }
363
364    #[cfg(feature = "bigint")]
365    impl From<&Mpint> for Uint {
366        fn from(mpint: &Mpint) -> Uint {
367            Uint::from_be_slice_vartime(mpint.as_bytes())
368        }
369    }
370
371    #[cfg(test)]
372    mod tests {
373        use super::Mpint;
374        use crate::{Decode, Encode, Error, Reader};
375        use alloc::{format, vec, vec::Vec};
376        use hex_literal::hex;
377
378        #[test]
379        fn unsigned_bytes() {
380            for (bytes, expected) in [
381                (&b""[..], &b""[..]),
382                (&hex!("00")[..], &b""[..]),
383                (&hex!("00 00")[..], &b""[..]),
384                (&hex!("00 01")[..], &hex!("01")[..]),
385                (&hex!("00 00 80")[..], &hex!("80")[..]),
386                (&hex!("80")[..], &hex!("80")[..]),
387                (&hex!("ff")[..], &hex!("ff")[..]),
388            ] {
389                for n in [
390                    Mpint::from_bytes(bytes).unwrap(),
391                    Mpint::try_from(bytes).unwrap(),
392                    Mpint::try_from(Vec::from(bytes).into_boxed_slice()).unwrap(),
393                ] {
394                    assert_eq!(n.as_bytes(), expected);
395                    assert_eq!(n.is_zero(), expected.is_empty());
396                }
397            }
398        }
399
400        #[test]
401        fn ssh_encodings() {
402            for (bytes, encoded) in [
403                (&b""[..], &hex!("00000000")[..]),
404                (&hex!("01")[..], &hex!("00000001 01")[..]),
405                (&hex!("7f")[..], &hex!("00000001 7f")[..]),
406                (&hex!("80")[..], &hex!("00000002 0080")[..]),
407                (&hex!("ff")[..], &hex!("00000002 00ff")[..]),
408                (
409                    &hex!("09 a3 78 f9 b2 e3 32 a7")[..],
410                    &hex!("00000008 09 a3 78 f9 b2 e3 32 a7")[..],
411                ),
412            ] {
413                let n = Mpint::from_bytes(bytes).unwrap();
414                let mut output = Vec::new();
415                n.encode(&mut output).unwrap();
416                assert_eq!(output, encoded);
417                assert_eq!(n.encoded_len().unwrap(), output.len());
418                assert_eq!(
419                    Mpint::decode(&mut encoded.into_decoder().unwrap()).unwrap(),
420                    n
421                );
422            }
423        }
424
425        #[test]
426        fn normalize_ssh_padding() {
427            for bytes in [
428                &hex!("00")[..],
429                &hex!("00 00")[..],
430                &hex!("00 01")[..],
431                &hex!("00 00 80")[..],
432            ] {
433                let mut encoded = Vec::new();
434                bytes.encode(&mut encoded).unwrap();
435                let n = Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap()).unwrap();
436                assert_eq!(n, Mpint::from_bytes(bytes).unwrap());
437                let mut canonical = Vec::new();
438                n.encode(&mut canonical).unwrap();
439                assert!(canonical.len() < encoded.len());
440            }
441        }
442
443        #[test]
444        fn reject_negative() {
445            for bytes in [
446                &hex!("80")[..],
447                &hex!("ff")[..],
448                &hex!("ed cc")[..],
449                &hex!("ff 21 52 41 11")[..],
450            ] {
451                let mut encoded = Vec::new();
452                bytes.encode(&mut encoded).unwrap();
453                let mut reader = encoded.as_slice().into_decoder().unwrap();
454                assert_eq!(Mpint::decode(&mut reader), Err(Error::MpintEncoding));
455                assert_eq!(reader.finish(()), Err(Error::Failed));
456            }
457        }
458
459        #[test]
460        fn size_limits() {
461            for size in [Mpint::MAX_SIZE, Mpint::MAX_SIZE + 1] {
462                for first in [0x01, 0x7f, 0x80, 0xff] {
463                    let mut bytes = vec![0xff; size];
464                    bytes[0] = first;
465                    // Leading zeros in an unsigned input do not change the magnitude.
466                    for padding in [0, 1, 2] {
467                        let mut padded = vec![0; padding];
468                        padded.extend_from_slice(&bytes);
469                        for result in [
470                            Mpint::from_bytes(&padded),
471                            Mpint::try_from(padded.clone().into_boxed_slice()),
472                        ] {
473                            if size == Mpint::MAX_SIZE {
474                                let n = result.unwrap();
475                                assert_eq!(n.as_bytes(), bytes);
476                                let mut encoded = Vec::new();
477                                n.encode(&mut encoded).unwrap();
478                                assert_eq!(n.encoded_len().unwrap(), encoded.len());
479                                assert_eq!(
480                                    Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap())
481                                        .unwrap(),
482                                    n
483                                );
484                            } else {
485                                assert_eq!(result, Err(Error::Length));
486                            }
487                        }
488                    }
489                }
490            }
491        }
492
493        #[test]
494        fn ssh_size_limits_before_normalization() {
495            for (first, size, valid) in [
496                (0x7f, Mpint::MAX_SIZE, true),
497                (0x00, Mpint::MAX_SIZE + 1, true),
498                (0x01, Mpint::MAX_SIZE + 1, false),
499                (0x00, Mpint::MAX_SIZE + 2, false),
500            ] {
501                // Even all-zero encodings must obey the wire size limit.
502                for rest in [0, 0xff] {
503                    let mut bytes = vec![rest; size];
504                    bytes[0] = first;
505                    let mut encoded = Vec::new();
506                    bytes.encode(&mut encoded).unwrap();
507                    let result = Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap());
508                    if valid {
509                        assert_eq!(result.unwrap(), Mpint::from_bytes(&bytes).unwrap());
510                    } else {
511                        assert_eq!(result, Err(Error::Length));
512                    }
513                }
514            }
515        }
516
517        #[test]
518        fn reject_oversized_before_reading_body() {
519            #[derive(Clone)]
520            struct Unreadable {
521                prefix: Option<[u8; 4]>,
522            }
523
524            impl Reader for Unreadable {
525                fn read<'o>(&mut self, out: &'o mut [u8]) -> crate::Result<&'o [u8]> {
526                    let prefix = self
527                        .prefix
528                        .take()
529                        .expect("oversized mpint body must not be read");
530                    out.copy_from_slice(&prefix);
531                    Ok(out)
532                }
533
534                fn remaining_len(&self) -> usize {
535                    Mpint::MAX_SIZE + 2 + if self.prefix.is_some() { 4 } else { 0 }
536                }
537            }
538
539            let reader = Unreadable {
540                prefix: Some(u32::try_from(Mpint::MAX_SIZE + 2).unwrap().to_be_bytes()),
541            };
542            assert_eq!(
543                Mpint::decode(&mut reader.into_decoder().unwrap()),
544                Err(Error::Length)
545            );
546        }
547
548        #[test]
549        #[cfg(feature = "ctutils")]
550        fn numeric_ordering() {
551            let values = [
552                0u32, 1, 0x7f, 0x80, 0xff, 0x100, 0x101, 0x1ff, 0x200, 0xffff, 0x10000,
553            ];
554            for a in values {
555                for b in values {
556                    let x = Mpint::from_bytes(&a.to_be_bytes()).unwrap();
557                    let y = Mpint::from_bytes(&b.to_be_bytes()).unwrap();
558                    assert_eq!(x == y, a == b);
559                    assert_eq!(x.cmp(&y), a.cmp(&b));
560                    assert_eq!(x.partial_cmp(&y), a.partial_cmp(&b));
561                }
562            }
563        }
564
565        #[test]
566        fn formatting() {
567            let zero = Mpint::from_bytes(&[]).unwrap();
568            assert_eq!(
569                format!("{zero} {zero:x} {zero:X} {zero:?}"),
570                "0 0 0 Mpint(0)"
571            );
572            let n = Mpint::from_bytes(&hex!("00 ab cd")).unwrap();
573            assert_eq!(
574                format!("{n} {n:x} {n:X} {n:?}"),
575                "ABCD abcd ABCD Mpint(ABCD)"
576            );
577        }
578
579        #[cfg(feature = "zeroize")]
580        #[test]
581        fn zeroize_preserves_invariants() {
582            use zeroize::Zeroize;
583            let mut n = Mpint::from_bytes(&hex!("80 ff")).unwrap();
584            n.zeroize();
585            assert!(n.is_zero());
586            assert_eq!(n, Mpint::from_bytes(&[]).unwrap());
587            let mut encoded = Vec::new();
588            n.encode(&mut encoded).unwrap();
589            assert_eq!(encoded, hex!("00000000"));
590        }
591
592        #[cfg(feature = "bigint")]
593        #[test]
594        fn bigint_conversions() {
595            use crate::Uint;
596            for bytes in [
597                vec![],
598                vec![0],
599                vec![0x80],
600                hex!("12 34 56 78 9a bc de f0 00 01").to_vec(),
601                vec![0xff; Mpint::MAX_SIZE],
602                vec![0xff; Mpint::MAX_SIZE + 1],
603            ] {
604                let uint = Uint::from_be_slice_vartime(&bytes);
605                for result in [Mpint::try_from(&uint), Mpint::try_from(uint.clone())] {
606                    if bytes.len() <= Mpint::MAX_SIZE {
607                        let n = result.unwrap();
608                        assert_eq!(n, Mpint::from_bytes(&bytes).unwrap());
609                        assert_eq!(Uint::from(&n), uint);
610                        assert_eq!(Uint::from(n), uint);
611                    } else {
612                        assert_eq!(result, Err(Error::Length));
613                    }
614                }
615            }
616            // Precision larger than the cap is allowed when the magnitude fits.
617            let mut padded = vec![0; Mpint::MAX_SIZE + 1];
618            padded[Mpint::MAX_SIZE] = 1;
619            let uint = Uint::from_be_slice_vartime(&padded);
620            assert_eq!(Mpint::try_from(&uint).unwrap().as_bytes(), &[1]);
621        }
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::MpintRef;
628    use crate::{Decoder, Encode, Error};
629
630    #[test]
631    fn decode_left_pads_and_encode_is_canonical() {
632        let mut out = [0xff; 2];
633        for (input, expected, canonical) in [
634            (&[0, 0, 0, 2, 0, 0][..], &[0, 0], &[0, 0, 0, 0][..]),
635            (&[0, 0, 0, 3, 0, 0, 1], &[0, 1], &[0, 0, 0, 1, 1]),
636            (
637                &[0, 0, 0, 3, 0, 0x80, 0],
638                &[0x80, 0],
639                &[0, 0, 0, 3, 0, 0x80, 0],
640            ),
641        ] {
642            let mut reader = Decoder::new(input).unwrap();
643            let magnitude = reader.read_mpint_bytes(&mut out).unwrap();
644            assert_eq!(
645                reader.finish(magnitude).unwrap(),
646                MpintRef::from_bytes(expected).unwrap().as_bytes()
647            );
648            assert_eq!(&out, expected);
649            let value = MpintRef::from_bytes(&out).unwrap();
650            let mut buf = [0; 7];
651            assert_eq!(value.encoded_len().unwrap(), canonical.len());
652            let mut writer = &mut buf[..canonical.len()];
653            value.encode(&mut writer).unwrap();
654            assert!(writer.is_empty());
655            assert_eq!(&buf[..canonical.len()], canonical);
656        }
657    }
658
659    #[test]
660    fn reject_negative_and_oversize_values() {
661        for (input, error) in [
662            (&[0, 0, 0, 1, 0x80][..], Error::MpintEncoding),
663            (&[0, 0, 0, 2, 1, 0], Error::Length),
664        ] {
665            let mut reader = Decoder::new(input).unwrap();
666            assert_eq!(reader.read_mpint_bytes(&mut [0]), Err(error));
667            assert_eq!(reader.finish(()), Err(Error::Failed));
668        }
669    }
670}