Skip to main content

ssh_encoding/
mpint.rs

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