Skip to content

Extra ASN.1 validity checks #192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 20, 2020
Merged
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
50 changes: 50 additions & 0 deletions ecdsa/src/asn1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ where
// encoding) so the resulting raw signature will have length
// at most 254 bytes.
//
// A SEQUENCE + INTEGER + INTEGER imply a length >= 2 + 3 + 3.
if bytes.len() < 8 {
return Err(Error::new());
}

// First byte is SEQUENCE tag.
if bytes[0] != SEQUENCE_TAG as u8 {
return Err(Error::new());
Expand All @@ -209,6 +214,10 @@ where
}

zlen = bytes[2] as usize;
if zlen <= 127 {
// SEQUENCE length should have been the 1-byte encoding to be DER.
return Err(Error::new());
}
3
} else {
2
Expand Down Expand Up @@ -343,6 +352,7 @@ fn trim_zeroes(mut bytes: &[u8], scalar_size: usize) -> Result<usize, Error> {

#[cfg(all(feature = "dev", test))]
mod tests {
use super::{INTEGER_TAG, SEQUENCE_TAG};
use crate::dev::curve::Signature;
use signature::Signature as _;

Expand All @@ -364,4 +374,44 @@ mod tests {

assert_eq!(signature1, signature2);
}

#[test]
fn test_asn1_too_short_signature() {
assert!(Signature::from_asn1(&[]).is_err());
assert!(Signature::from_asn1(&[SEQUENCE_TAG]).is_err());
assert!(Signature::from_asn1(&[SEQUENCE_TAG, 0x00]).is_err());
assert!(Signature::from_asn1(&[SEQUENCE_TAG, 0x03, INTEGER_TAG, 0x01, 0x01]).is_err());
}

#[test]
fn test_asn1_non_der_signature() {
// A minimal 8-byte ASN.1 signature parses OK.
assert!(Signature::from_asn1(&[
SEQUENCE_TAG,
0x06, // length of below
INTEGER_TAG,
0x01, // length of value
0x01, // value=1
INTEGER_TAG,
0x01, // length of value
0x01, // value=1
])
.is_ok());

// But length fields that are not minimally encoded should be rejected, as they are not
// valid DER, cf.
// https://github.com/google/wycheproof/blob/2196000605e4/testvectors/ecdsa_secp256k1_sha256_test.json#L57-L66
assert!(Signature::from_asn1(&[
SEQUENCE_TAG,
0x81, // extended length: 1 length byte to come
0x06, // length of below
INTEGER_TAG,
0x01, // length of value
0x01, // value=1
INTEGER_TAG,
0x01, // length of value
0x01, // value=1
])
.is_err());
}
}