Skip to content

Commit c6c358b

Browse files
authored
ssh-key: preserve signed certificate bytes verbatim (#659)
SSH certificate decoding can normalize fields such as RSA `mpints`, however the CA signs their wire encoding. Re-encoding the parsed fields can reject a valid signature or accept an encoding the CA never signed. Make `ssh_encoding::Reader`s independently `Clone`able. Save the decoder position before parsing the certificate and use the cloned to copy the signed bytes through the CA public key. Reuse those bytes for signature verification and serialization. Have the builder retain the exact buffer it passes to the signer. Unfortunately this requires another breaking change to `ssh-encoding` even after I *just* cut another `rc`, but hopefully that's the last one before a final release. See also: #651
1 parent 95c8df7 commit c6c358b

10 files changed

Lines changed: 229 additions & 50 deletions

File tree

‎ssh-encoding/src/base64/reader.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use core::fmt::{self, Debug};
77
type Inner<'i> = base64ct::Decoder<'i, base64ct::Base64>;
88

99
/// Constant-time Base64 reader implementation.
10+
#[derive(Clone)]
1011
pub struct Base64Reader<'i> {
1112
/// Inner Base64 reader.
1213
inner: Inner<'i>,

‎ssh-encoding/src/decoder.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ const MAX_NESTING_DEPTH: u8 = 64;
1717
/// A failed read or nested decoding operation invalidates the decoder. Subsequent reads and
1818
/// completion checks return [`Error::Failed`]. The underlying reader is not rewound on errors.
1919
///
20+
/// A clone has an independent read position and retains the current scope, nesting depth,
21+
/// and failure state.
22+
///
2023
/// # Example
2124
/// ```
2225
/// use ssh_encoding::{Decode, Reader};
@@ -26,6 +29,7 @@ const MAX_NESTING_DEPTH: u8 = 64;
2629
/// assert_eq!(decoder.finish(value)?, 42);
2730
/// # Ok::<(), ssh_encoding::Error>(())
2831
/// ```
32+
#[derive(Clone)]
2933
pub struct Decoder<R> {
3034
/// Underlying byte reader.
3135
reader: R,
@@ -369,6 +373,7 @@ mod tests {
369373
#[test]
370374
fn input_size_limit_before_reading() {
371375
// Exercise the actual limit without allocating a large input buffer.
376+
#[derive(Clone)]
372377
struct Unreadable(usize);
373378

374379
impl Reader for Unreadable {

‎ssh-encoding/src/mpint.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,7 @@ mod allocating {
516516

517517
#[test]
518518
fn reject_oversized_before_reading_body() {
519+
#[derive(Clone)]
519520
struct Unreadable {
520521
prefix: Option<[u8; 4]>,
521522
}

‎ssh-encoding/src/pem/reader.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::{Reader, Result};
44
type Inner<'i> = pem_rfc7468::Decoder<'i>;
55

66
/// Constant-time PEM reader.
7+
#[derive(Clone)]
78
pub(crate) struct PemReader<'i> {
89
/// Inner PEM reader.
910
inner: Inner<'i>,

‎ssh-encoding/src/reader.rs‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ use crate::{Decoder, Error, Result};
66
///
77
/// Use [`Reader::into_decoder`] to decode SSH protocol data types. Readers only supply bytes;
88
/// the decoder enforces nested length boundaries and complete consumption.
9-
pub trait Reader: Sized {
9+
///
10+
/// A clone starts at the same position and yields the same remaining bytes. Reading from
11+
/// either copy must leave the other copy's position unchanged.
12+
pub trait Reader: Clone {
1013
/// Read as much data as is needed to exactly fill `out`.
1114
///
1215
/// Returns `out` reborrowed as an immutable byte slice. On success, [`Reader::remaining_len`]
@@ -45,13 +48,3 @@ impl Reader for &[u8] {
4548
self.len()
4649
}
4750
}
48-
49-
impl<R: Reader> Reader for &mut R {
50-
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
51-
(**self).read(out)
52-
}
53-
54-
fn remaining_len(&self) -> usize {
55-
(**self).remaining_len()
56-
}
57-
}

‎ssh-encoding/tests/decoder.rs‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,32 @@ fn nested_scopes_and_siblings() {
8484
check_backends(&hex!("00000009 00000001 aa 00000000 bb"), Ok(Value));
8585
}
8686

87+
#[test]
88+
fn cloned_decoder_retains_position_and_scope() {
89+
#[derive(Debug, Eq, PartialEq)]
90+
struct Value;
91+
92+
impl Decode for Value {
93+
type Error = Error;
94+
95+
fn decode(decoder: &mut Decoder<impl Reader>) -> Result<Self, Error> {
96+
let mut clone = decoder.read_prefixed(|decoder| {
97+
assert_eq!(u8::decode(decoder)?, 0xaa);
98+
let clone = decoder.clone();
99+
assert_eq!(u8::decode(decoder)?, 0xbb);
100+
Ok::<_, Error>(clone)
101+
})?;
102+
103+
assert_eq!(u8::decode(&mut clone)?, 0xbb);
104+
assert_eq!(u8::decode(&mut clone), Err(Error::Length));
105+
assert_eq!(u8::decode(decoder)?, 0xcc);
106+
Ok(Self)
107+
}
108+
}
109+
110+
check_backends(&hex!("00000002 aabb cc"), Ok(Value));
111+
}
112+
87113
#[test]
88114
fn unread_body_is_rejected() {
89115
#[derive(Debug, Eq, PartialEq)]
@@ -257,6 +283,7 @@ fn unwinding_restores_scope_and_invalidates_decoder() {
257283

258284
#[test]
259285
fn partially_advanced_reader_cannot_be_reused_after_error() {
286+
#[derive(Clone)]
260287
struct PartialReader<'a>(&'a [u8]);
261288

262289
impl Reader for PartialReader<'_> {
@@ -270,10 +297,9 @@ fn partially_advanced_reader_cannot_be_reused_after_error() {
270297
}
271298
}
272299

273-
let mut reader = PartialReader(&[0xaa, 0xbb]);
274-
let mut decoder = Decoder::new(&mut reader).unwrap();
300+
let mut decoder = PartialReader(&[0xaa, 0xbb]).into_decoder().unwrap();
275301
assert_eq!(u8::decode(&mut decoder), Err(Error::CharacterEncoding));
302+
assert_eq!(decoder.clone().finish(()), Err(Error::Failed));
276303
assert_eq!(u8::decode(&mut decoder), Err(Error::Failed));
277304
assert_eq!(decoder.finish(()), Err(Error::Failed));
278-
assert_eq!(reader.remaining_len(), 1);
279305
}

‎ssh-key/src/certificate.rs‎

Lines changed: 51 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ const MAX_PRINCIPALS: usize = 256;
4040
///
4141
/// OpenSSH supports X.509-like certificate authorities, but using a custom encoding format.
4242
///
43+
/// The signed portion is retained verbatim when decoding and reused for signature verification
44+
/// and encoding. Certificates created with [`Builder`] retain the exact bytes passed to the signer.
45+
///
4346
/// <div class="warning">
4447
/// <b>Security Warning</b>
4548
///
@@ -165,6 +168,12 @@ pub struct Certificate {
165168

166169
/// Comment on the certificate.
167170
comment: Comment,
171+
172+
/// Certificate algorithm, including any RSA hash selection in the wire identifier.
173+
algorithm: Algorithm,
174+
175+
/// Exact signed bytes, from the initial algorithm string through the signature key.
176+
tbs_certificate: Vec<u8>,
168177
}
169178

170179
impl Certificate {
@@ -187,7 +196,7 @@ impl Certificate {
187196
let mut cert = Certificate::decode(&mut reader)?;
188197

189198
// Verify that the algorithm in the Base64-encoded data matches the text
190-
if encapsulation.algorithm_id != cert.algorithm().to_certificate_type() {
199+
if encapsulation.algorithm_id != cert.algorithm.to_certificate_type() {
191200
return Err(Error::AlgorithmUnknown);
192201
}
193202

@@ -211,11 +220,7 @@ impl Certificate {
211220
/// # Errors
212221
/// Returns [`Error::Encoding`] in the event of an encoding error.
213222
pub fn to_openssh(&self) -> Result<String> {
214-
SshFormat::encode_string(
215-
&self.algorithm().to_certificate_type(),
216-
self,
217-
self.comment(),
218-
)
223+
SshFormat::encode_string(&self.algorithm.to_certificate_type(), self, self.comment())
219224
}
220225

221226
/// Serialize OpenSSH certificate as raw bytes.
@@ -249,10 +254,10 @@ impl Certificate {
249254
Ok(())
250255
}
251256

252-
/// Get the public key algorithm for this certificate.
257+
/// Get the algorithm identified by this certificate.
253258
#[must_use]
254259
pub fn algorithm(&self) -> Algorithm {
255-
self.public_key.algorithm()
260+
self.algorithm.clone()
256261
}
257262

258263
/// Get the comment on this certificate.
@@ -480,17 +485,14 @@ impl Certificate {
480485
/// </div>
481486
#[doc(hidden)]
482487
pub fn verify_signature(&self) -> Result<()> {
483-
let mut tbs_certificate = Vec::new();
484-
self.encode_tbs(&mut tbs_certificate)?;
485488
self.signature_key
486-
.verify(&tbs_certificate, &self.signature)
489+
.verify(&self.tbs_certificate, &self.signature)
487490
.map_err(|_| Error::CertificateValidation)
488491
}
489492

490-
/// Encode the portion of the certificate "to be signed" by the CA
491-
/// (or to be verified against an existing CA signature)
493+
/// Encode the fields of a newly built certificate before signing it.
492494
fn encode_tbs(&self, writer: &mut impl Writer) -> encoding::Result<()> {
493-
self.algorithm().to_certificate_type().encode(writer)?;
495+
self.algorithm.to_certificate_type().encode(writer)?;
494496
self.nonce.encode(writer)?;
495497
self.public_key.encode_key_data(writer)?;
496498
self.serial.encode(writer)?;
@@ -507,13 +509,34 @@ impl Certificate {
507509

508510
/// Decode [`Certificate`] for the specified algorithm.
509511
///
512+
/// The initial algorithm string has already been consumed. Its encoding is supplied by
513+
/// `algorithm.to_certificate_type()`; the remaining signed bytes are retained verbatim.
514+
///
510515
/// # Errors
511516
/// - Returns [`Error::Encoding`] in the event of an encoding error.
512517
/// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
513518
pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
519+
Self::decode_inner(reader, Some(algorithm))
520+
}
521+
522+
fn decode_inner(
523+
reader: &mut Decoder<impl Reader>,
524+
algorithm: Option<Algorithm>,
525+
) -> Result<Self> {
526+
let mut source = reader.clone();
527+
let mut tbs = Vec::new();
528+
let algorithm = match algorithm {
529+
Some(algorithm) => {
530+
// The caller already consumed the algorithm string.
531+
algorithm.to_certificate_type().encode(&mut tbs)?;
532+
algorithm
533+
}
534+
None => Algorithm::new_certificate(&String::decode(reader)?)?,
535+
};
536+
514537
Ok(Self {
515538
nonce: Vec::decode(reader)?,
516-
public_key: KeyData::decode_as(reader, algorithm)?,
539+
public_key: KeyData::decode_as(reader, algorithm.clone())?,
517540
serial: u64::decode(reader)?,
518541
cert_type: CertType::decode(reader)?,
519542
key_id: String::decode(reader)?,
@@ -524,8 +547,18 @@ impl Certificate {
524547
extensions: OptionsMap::decode(reader)?,
525548
reserved: Vec::decode(reader)?,
526549
signature_key: decode_signature_key(reader)?,
550+
tbs_certificate: {
551+
// The signature covers everything consumed through the signature key.
552+
let len = source.remaining_len() - reader.remaining_len();
553+
let start = tbs.len();
554+
tbs.try_reserve_exact(len).map_err(encoding::Error::from)?;
555+
tbs.resize(start + len, 0);
556+
source.read(&mut tbs[start..])?;
557+
tbs
558+
},
527559
signature: reader.read_prefixed(Signature::decode)?,
528560
comment: Comment::default(),
561+
algorithm,
529562
})
530563
}
531564
}
@@ -568,34 +601,21 @@ impl Decode for Certificate {
568601
type Error = Error;
569602

570603
fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
571-
let algorithm = Algorithm::new_certificate(&String::decode(reader)?)?;
572-
Self::decode_as(reader, algorithm)
604+
Self::decode_inner(reader, None)
573605
}
574606
}
575607

576608
impl Encode for Certificate {
577609
fn encoded_len(&self) -> encoding::Result<usize> {
578610
[
579-
self.algorithm().to_certificate_type().encoded_len()?,
580-
self.nonce.encoded_len()?,
581-
self.public_key.encoded_key_data_len()?,
582-
self.serial.encoded_len()?,
583-
self.cert_type.encoded_len()?,
584-
self.key_id.encoded_len()?,
585-
self.valid_principals.encoded_len()?,
586-
self.valid_after.encoded_len()?,
587-
self.valid_before.encoded_len()?,
588-
self.critical_options.encoded_len()?,
589-
self.extensions.encoded_len()?,
590-
self.reserved.encoded_len()?,
591-
self.signature_key.encoded_len_prefixed()?,
611+
self.tbs_certificate.len(),
592612
self.signature.encoded_len_prefixed()?,
593613
]
594614
.checked_sum()
595615
}
596616

597617
fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
598-
self.encode_tbs(writer)?;
618+
writer.write(&self.tbs_certificate)?;
599619
self.signature.encode_prefixed(writer)
600620
}
601621
}

‎ssh-key/src/certificate/builder.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,8 @@ impl Builder {
326326
}
327327

328328
let mut cert = Certificate {
329+
algorithm: self.public_key.algorithm(),
330+
tbs_certificate: Vec::new(),
329331
nonce: self.nonce,
330332
public_key: self.public_key,
331333
serial: self.serial.unwrap_or_default(),
@@ -338,13 +340,14 @@ impl Builder {
338340
extensions: self.extensions,
339341
reserved: Vec::new(),
340342
comment: self.comment.unwrap_or_default(),
341-
signature_key: signing_key.public_key(),
343+
signature_key,
342344
signature: Signature::placeholder(),
343345
};
344346

345347
let mut tbs_cert = Vec::new();
346348
cert.encode_tbs(&mut tbs_cert)?;
347349
cert.signature = signing_key.try_sign(&tbs_cert)?;
350+
cert.tbs_certificate = tbs_cert;
348351

349352
#[cfg(all(debug_assertions, feature = "sha2"))]
350353
cert.validate_at(

0 commit comments

Comments
 (0)