Skip to content

Commit

Permalink
der: return Tag::Integer.length_error() on empty ints (#1400)
Browse files Browse the repository at this point in the history
From X.690 § 8.3.1:

> 8.3 Encoding of an integer value
> 8.3.1 The encoding of an integer value shall be primitive.
> The contents octets shall consist of one or more octets.
  • Loading branch information
tarcieri committed May 8, 2024
1 parent 59d84bf commit 471c073
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
16 changes: 15 additions & 1 deletion der/src/asn1/integer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ where
#[cfg(test)]
#[allow(clippy::unwrap_used)]
pub(crate) mod tests {
use crate::{Decode, Encode};
use crate::{Decode, Encode, ErrorKind, Tag};

// Vectors from Section 5.7 of:
// https://luca.ntop.org/Teaching/Appunti/asn1.html
Expand Down Expand Up @@ -151,6 +151,20 @@ pub(crate) mod tests {
assert_eq!(I65535_BYTES, 65535u16.encode_to_slice(&mut buffer).unwrap());
}

/// Integers cannot be empty.
///
/// From X.690 § 8.3.1: "The contents octets shall consist of one or more octets"
#[test]
fn reject_empty() {
const EMPTY_INT: &[u8] = &[0x02, 0x00];

let err = u8::from_der(EMPTY_INT).expect_err("empty INTEGER should return error");
assert_eq!(err.kind(), ErrorKind::Length { tag: Tag::Integer });

let err = i8::from_der(EMPTY_INT).expect_err("empty INTEGER should return error");
assert_eq!(err.kind(), ErrorKind::Length { tag: Tag::Integer });
}

/// Integers must be encoded with a minimum number of octets
#[test]
fn reject_non_canonical() {
Expand Down
4 changes: 4 additions & 0 deletions der/src/asn1/integer/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ macro_rules! impl_encoding_traits {
let mut buf = [0u8; Self::BITS as usize / 8];
let max_length = u32::from(header.length) as usize;

if max_length == 0 {
return Err(Tag::Integer.length_error());
}

if max_length > buf.len() {
return Err(Self::TAG.non_canonical_error());
}
Expand Down
5 changes: 4 additions & 1 deletion der/src/asn1/integer/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,15 @@ macro_rules! impl_encoding_traits {
let mut buf = [0u8; (Self::BITS as usize / 8) + UNSIGNED_HEADROOM];
let max_length = u32::from(header.length) as usize;

if max_length == 0 {
return Err(Tag::Integer.length_error());
}

if max_length > buf.len() {
return Err(Self::TAG.non_canonical_error());
}

let bytes = reader.read_into(&mut buf[..max_length])?;

let result = Self::from_be_bytes(decode_to_array(bytes)?);

// Ensure we compute the same encoded length as the original any value
Expand Down

0 comments on commit 471c073

Please sign in to comment.