Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ssh-encoding/src/base64/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use core::fmt::{self, Debug};
type Inner<'i> = base64ct::Decoder<'i, base64ct::Base64>;

/// Constant-time Base64 reader implementation.
#[derive(Clone)]
pub struct Base64Reader<'i> {
/// Inner Base64 reader.
inner: Inner<'i>,
Expand Down
5 changes: 5 additions & 0 deletions ssh-encoding/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const MAX_NESTING_DEPTH: u8 = 64;
/// A failed read or nested decoding operation invalidates the decoder. Subsequent reads and
/// completion checks return [`Error::Failed`]. The underlying reader is not rewound on errors.
///
/// A clone has an independent read position and retains the current scope, nesting depth,
/// and failure state.
///
/// # Example
/// ```
/// use ssh_encoding::{Decode, Reader};
Expand All @@ -26,6 +29,7 @@ const MAX_NESTING_DEPTH: u8 = 64;
/// assert_eq!(decoder.finish(value)?, 42);
/// # Ok::<(), ssh_encoding::Error>(())
/// ```
#[derive(Clone)]
pub struct Decoder<R> {
/// Underlying byte reader.
reader: R,
Expand Down Expand Up @@ -369,6 +373,7 @@ mod tests {
#[test]
fn input_size_limit_before_reading() {
// Exercise the actual limit without allocating a large input buffer.
#[derive(Clone)]
struct Unreadable(usize);

impl Reader for Unreadable {
Expand Down
1 change: 1 addition & 0 deletions ssh-encoding/src/mpint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ mod allocating {

#[test]
fn reject_oversized_before_reading_body() {
#[derive(Clone)]
struct Unreadable {
prefix: Option<[u8; 4]>,
}
Expand Down
1 change: 1 addition & 0 deletions ssh-encoding/src/pem/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{Reader, Result};
type Inner<'i> = pem_rfc7468::Decoder<'i>;

/// Constant-time PEM reader.
#[derive(Clone)]
pub(crate) struct PemReader<'i> {
/// Inner PEM reader.
inner: Inner<'i>,
Expand Down
15 changes: 4 additions & 11 deletions ssh-encoding/src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use crate::{Decoder, Error, Result};
///
/// Use [`Reader::into_decoder`] to decode SSH protocol data types. Readers only supply bytes;
/// the decoder enforces nested length boundaries and complete consumption.
pub trait Reader: Sized {
///
/// A clone starts at the same position and yields the same remaining bytes. Reading from
/// either copy must leave the other copy's position unchanged.
pub trait Reader: Clone {
/// Read as much data as is needed to exactly fill `out`.
///
/// Returns `out` reborrowed as an immutable byte slice. On success, [`Reader::remaining_len`]
Expand Down Expand Up @@ -45,13 +48,3 @@ impl Reader for &[u8] {
self.len()
}
}

impl<R: Reader> Reader for &mut R {
fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
(**self).read(out)
}

fn remaining_len(&self) -> usize {
(**self).remaining_len()
}
}
32 changes: 29 additions & 3 deletions ssh-encoding/tests/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ fn nested_scopes_and_siblings() {
check_backends(&hex!("00000009 00000001 aa 00000000 bb"), Ok(Value));
}

#[test]
fn cloned_decoder_retains_position_and_scope() {
#[derive(Debug, Eq, PartialEq)]
struct Value;

impl Decode for Value {
type Error = Error;

fn decode(decoder: &mut Decoder<impl Reader>) -> Result<Self, Error> {
let mut clone = decoder.read_prefixed(|decoder| {
assert_eq!(u8::decode(decoder)?, 0xaa);
let clone = decoder.clone();
assert_eq!(u8::decode(decoder)?, 0xbb);
Ok::<_, Error>(clone)
})?;

assert_eq!(u8::decode(&mut clone)?, 0xbb);
assert_eq!(u8::decode(&mut clone), Err(Error::Length));
assert_eq!(u8::decode(decoder)?, 0xcc);
Ok(Self)
}
}

check_backends(&hex!("00000002 aabb cc"), Ok(Value));
}

#[test]
fn unread_body_is_rejected() {
#[derive(Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -257,6 +283,7 @@ fn unwinding_restores_scope_and_invalidates_decoder() {

#[test]
fn partially_advanced_reader_cannot_be_reused_after_error() {
#[derive(Clone)]
struct PartialReader<'a>(&'a [u8]);

impl Reader for PartialReader<'_> {
Expand All @@ -270,10 +297,9 @@ fn partially_advanced_reader_cannot_be_reused_after_error() {
}
}

let mut reader = PartialReader(&[0xaa, 0xbb]);
let mut decoder = Decoder::new(&mut reader).unwrap();
let mut decoder = PartialReader(&[0xaa, 0xbb]).into_decoder().unwrap();
assert_eq!(u8::decode(&mut decoder), Err(Error::CharacterEncoding));
assert_eq!(decoder.clone().finish(()), Err(Error::Failed));
assert_eq!(u8::decode(&mut decoder), Err(Error::Failed));
assert_eq!(decoder.finish(()), Err(Error::Failed));
assert_eq!(reader.remaining_len(), 1);
}
82 changes: 51 additions & 31 deletions ssh-key/src/certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ const MAX_PRINCIPALS: usize = 256;
///
/// OpenSSH supports X.509-like certificate authorities, but using a custom encoding format.
///
/// The signed portion is retained verbatim when decoding and reused for signature verification
/// and encoding. Certificates created with [`Builder`] retain the exact bytes passed to the signer.
///
/// <div class="warning">
/// <b>Security Warning</b>
///
Expand Down Expand Up @@ -165,6 +168,12 @@ pub struct Certificate {

/// Comment on the certificate.
comment: Comment,

/// Certificate algorithm, including any RSA hash selection in the wire identifier.
algorithm: Algorithm,

/// Exact signed bytes, from the initial algorithm string through the signature key.
tbs_certificate: Vec<u8>,
}

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

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

Expand All @@ -211,11 +220,7 @@ impl Certificate {
/// # Errors
/// Returns [`Error::Encoding`] in the event of an encoding error.
pub fn to_openssh(&self) -> Result<String> {
SshFormat::encode_string(
&self.algorithm().to_certificate_type(),
self,
self.comment(),
)
SshFormat::encode_string(&self.algorithm.to_certificate_type(), self, self.comment())
}

/// Serialize OpenSSH certificate as raw bytes.
Expand Down Expand Up @@ -249,10 +254,10 @@ impl Certificate {
Ok(())
}

/// Get the public key algorithm for this certificate.
/// Get the algorithm identified by this certificate.
#[must_use]
pub fn algorithm(&self) -> Algorithm {
self.public_key.algorithm()
self.algorithm.clone()
}

/// Get the comment on this certificate.
Expand Down Expand Up @@ -480,17 +485,14 @@ impl Certificate {
/// </div>
#[doc(hidden)]
pub fn verify_signature(&self) -> Result<()> {
let mut tbs_certificate = Vec::new();
self.encode_tbs(&mut tbs_certificate)?;
self.signature_key
.verify(&tbs_certificate, &self.signature)
.verify(&self.tbs_certificate, &self.signature)
.map_err(|_| Error::CertificateValidation)
}

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

/// Decode [`Certificate`] for the specified algorithm.
///
/// The initial algorithm string has already been consumed. Its encoding is supplied by
/// `algorithm.to_certificate_type()`; the remaining signed bytes are retained verbatim.
///
/// # Errors
/// - Returns [`Error::Encoding`] in the event of an encoding error.
/// - Returns [`Error::CertificateFieldInvalid`] if a certificate field is invalid.
pub fn decode_as(reader: &mut Decoder<impl Reader>, algorithm: Algorithm) -> Result<Self> {
Self::decode_inner(reader, Some(algorithm))
}

fn decode_inner(
reader: &mut Decoder<impl Reader>,
algorithm: Option<Algorithm>,
) -> Result<Self> {
let mut source = reader.clone();
let mut tbs = Vec::new();
let algorithm = match algorithm {
Some(algorithm) => {
// The caller already consumed the algorithm string.
algorithm.to_certificate_type().encode(&mut tbs)?;
algorithm
}
None => Algorithm::new_certificate(&String::decode(reader)?)?,
};

Ok(Self {
nonce: Vec::decode(reader)?,
public_key: KeyData::decode_as(reader, algorithm)?,
public_key: KeyData::decode_as(reader, algorithm.clone())?,
serial: u64::decode(reader)?,
cert_type: CertType::decode(reader)?,
key_id: String::decode(reader)?,
Expand All @@ -524,8 +547,18 @@ impl Certificate {
extensions: OptionsMap::decode(reader)?,
reserved: Vec::decode(reader)?,
signature_key: decode_signature_key(reader)?,
tbs_certificate: {
// The signature covers everything consumed through the signature key.
let len = source.remaining_len() - reader.remaining_len();
let start = tbs.len();
tbs.try_reserve_exact(len).map_err(encoding::Error::from)?;
tbs.resize(start + len, 0);
source.read(&mut tbs[start..])?;
tbs
},
signature: reader.read_prefixed(Signature::decode)?,
comment: Comment::default(),
algorithm,
})
}
}
Expand Down Expand Up @@ -568,34 +601,21 @@ impl Decode for Certificate {
type Error = Error;

fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
let algorithm = Algorithm::new_certificate(&String::decode(reader)?)?;
Self::decode_as(reader, algorithm)
Self::decode_inner(reader, None)
}
}

impl Encode for Certificate {
fn encoded_len(&self) -> encoding::Result<usize> {
[
self.algorithm().to_certificate_type().encoded_len()?,
self.nonce.encoded_len()?,
self.public_key.encoded_key_data_len()?,
self.serial.encoded_len()?,
self.cert_type.encoded_len()?,
self.key_id.encoded_len()?,
self.valid_principals.encoded_len()?,
self.valid_after.encoded_len()?,
self.valid_before.encoded_len()?,
self.critical_options.encoded_len()?,
self.extensions.encoded_len()?,
self.reserved.encoded_len()?,
self.signature_key.encoded_len_prefixed()?,
self.tbs_certificate.len(),
self.signature.encoded_len_prefixed()?,
]
.checked_sum()
}

fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
self.encode_tbs(writer)?;
writer.write(&self.tbs_certificate)?;
self.signature.encode_prefixed(writer)
}
}
Expand Down
5 changes: 4 additions & 1 deletion ssh-key/src/certificate/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,8 @@ impl Builder {
}

let mut cert = Certificate {
algorithm: self.public_key.algorithm(),
tbs_certificate: Vec::new(),
nonce: self.nonce,
public_key: self.public_key,
serial: self.serial.unwrap_or_default(),
Expand All @@ -338,13 +340,14 @@ impl Builder {
extensions: self.extensions,
reserved: Vec::new(),
comment: self.comment.unwrap_or_default(),
signature_key: signing_key.public_key(),
signature_key,
signature: Signature::placeholder(),
};

let mut tbs_cert = Vec::new();
cert.encode_tbs(&mut tbs_cert)?;
cert.signature = signing_key.try_sign(&tbs_cert)?;
cert.tbs_certificate = tbs_cert;

#[cfg(all(debug_assertions, feature = "sha2"))]
cert.validate_at(
Expand Down
Loading