Skip to content

DRAFT: Rename GeneralizedTime #493

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

Closed
wants to merge 10 commits into from
Closed
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,11 @@ asn1 = { version = "0.18", default-features = false }
[deps-rs-link]: https://deps.rs/repo/github/alex/rust-asn1
[docs-rs-image]: https://docs.rs/asn1/badge.svg
[docs-rs-link]: https://docs.rs/asn1/

## Changelog

### [0.19.0]

#### :rotating_light: Breaking changes

- The behavior of `GeneralizedTime` has changed. It now accepts fractional seconds which were previously rejected as invalid values. To fallback to the previous behavior, use `X509GeneralizedTime`. ( [492](https://github.com/alex/rust-asn1/pull/492) )
2 changes: 1 addition & 1 deletion fuzz/fuzz_targets/fuzz_asn1_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ enum Data<'a> {
ObjectIdentifier(asn1::ObjectIdentifier),

UtcTime(asn1::UtcTime),
GeneralizedTime(asn1::GeneralizedTime),
X509GeneralizedTime(asn1::X509GeneralizedTime),

Enumerated(asn1::Enumerated),

Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
//! #[derive(asn1::Asn1Read, asn1::Asn1Write)]
//! enum Time {
//! UTCTime(asn1::UtcTime),
//! GeneralizedTime(asn1::GeneralizedTime)
//! X509GeneralizedTime(asn1::X509GeneralizedTime)
//! }
//! ```
//!
Expand Down Expand Up @@ -161,7 +161,7 @@ pub use crate::types::{
GeneralizedTime, IA5String, Implicit, Null, OctetStringEncoded, OwnedBigInt, OwnedBigUint,
PrintableString, Sequence, SequenceOf, SequenceOfWriter, SequenceWriter, SetOf, SetOfWriter,
SimpleAsn1Readable, SimpleAsn1Writable, Tlv, UniversalString, UtcTime, Utf8String,
VisibleString,
VisibleString, X509GeneralizedTime,
};
pub use crate::writer::{write, write_single, WriteBuf, WriteError, WriteResult, Writer};

Expand Down
64 changes: 58 additions & 6 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ mod tests {
Explicit, GeneralizedTime, IA5String, Implicit, ObjectIdentifier, OctetStringEncoded,
OwnedBigInt, OwnedBigUint, OwnedBitString, ParseError, ParseErrorKind, ParseLocation,
ParseResult, PrintableString, Sequence, SequenceOf, SetOf, Tag, Tlv, UniversalString,
UtcTime, Utf8String, VisibleString,
UtcTime, Utf8String, VisibleString, X509GeneralizedTime,
};
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
Expand Down Expand Up @@ -1439,10 +1439,10 @@ mod tests {
}

#[test]
fn test_generalizedtime() {
assert_parses::<GeneralizedTime>(&[
fn test_x509_generalizedtime() {
assert_parses::<X509GeneralizedTime>(&[
(
Ok(GeneralizedTime::new(DateTime::new(2010, 1, 2, 3, 4, 5).unwrap()).unwrap()),
Ok(X509GeneralizedTime::new(DateTime::new(2010, 1, 2, 3, 4, 5).unwrap()).unwrap()),
b"\x18\x0f20100102030405Z",
),
(
Expand All @@ -1459,7 +1459,7 @@ mod tests {
),
(
// 29th of February (Leap Year)
Ok(GeneralizedTime::new(DateTime::new(2000, 2, 29, 3, 4, 5).unwrap()).unwrap()),
Ok(X509GeneralizedTime::new(DateTime::new(2000, 2, 29, 3, 4, 5).unwrap()).unwrap()),
b"\x18\x0f20000229030405Z",
),
(
Expand Down Expand Up @@ -1560,7 +1560,7 @@ mod tests {
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1019000228030405Z ",
),
// Tests for fractional seconds, which we currently don't support
// Tests for fractional seconds which are forbidden
(
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1620100102030405.123456Z",
Expand Down Expand Up @@ -1588,6 +1588,58 @@ mod tests {
]);
}

#[test]
fn test_generalized_time() {
assert_parses::<GeneralizedTime>(&[
(
// General case
Ok(GeneralizedTime::new(
DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(),
Some(123_456_000),
)
.unwrap()),
b"\x18\x1620100102030405.123456Z",
),
(
// No fractional time
Ok(
GeneralizedTime::new(DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(), None)
.unwrap(),
),
b"\x18\x0f20100102030405Z",
),
(
// Starting with 0 is ok
Ok(GeneralizedTime::new(
DateTime::new(2010, 1, 2, 3, 4, 5).unwrap(),
Some(12_375_600),
)
.unwrap()),
b"\x18\x1720100102030405.0123756Z",
),
(
// But ending with 0 is not OK
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1220100102030405.10Z",
),
(
// Too many digits
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1a20100102030405.0123456789Z",
),
(
// Missing timezone
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1520100102030405.123456",
),
(
// Invalid fractional second
Err(ParseError::new(ParseErrorKind::InvalidValue)),
b"\x18\x1020100102030405.Z",
),
])
}

#[test]
fn test_enumerated() {
assert_parses::<Enumerated>(&[
Expand Down
174 changes: 166 additions & 8 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
Expand Down Expand Up @@ -914,7 +915,11 @@ fn push_four_digits(dest: &mut WriteBuf, val: u16) -> WriteResult {
}

/// A structure representing a (UTC timezone) date and time.
/// Wrapped by `UtcTime` and `GeneralizedTime`.
/// Wrapped by `UtcTime` and `X509GeneralizedTime` and used in
/// `GeneralizedTime`.
/// The difference between in `X509GeneralizedTime` and
/// `GeneralizedTime` is that the `X509GeneralizedTime` does not
/// accept fractional seconds.
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd)]
pub struct DateTime {
year: u16,
Expand Down Expand Up @@ -1042,18 +1047,118 @@ impl SimpleAsn1Writable for UtcTime {
/// Used for parsing and writing ASN.1 `GENERALIZED TIME` values. Wraps a
/// `DateTime`.
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct GeneralizedTime(DateTime);
pub struct X509GeneralizedTime(DateTime);

impl GeneralizedTime {
pub fn new(dt: DateTime) -> ParseResult<GeneralizedTime> {
Ok(GeneralizedTime(dt))
impl X509GeneralizedTime {
pub fn new(dt: DateTime) -> ParseResult<X509GeneralizedTime> {
Ok(X509GeneralizedTime(dt))
}

pub fn as_datetime(&self) -> &DateTime {
&self.0
}
}

impl SimpleAsn1Readable<'_> for X509GeneralizedTime {
const TAG: Tag = Tag::primitive(0x18);
fn parse_data(mut data: &[u8]) -> ParseResult<X509GeneralizedTime> {
let year = read_4_digits(&mut data)?;
let month = read_2_digits(&mut data)?;
let day = read_2_digits(&mut data)?;
let hour = read_2_digits(&mut data)?;
let minute = read_2_digits(&mut data)?;
let second = read_2_digits(&mut data)?;

read_tz_and_finish(&mut data)?;

X509GeneralizedTime::new(DateTime::new(year, month, day, hour, minute, second)?)
}
}

impl SimpleAsn1Writable for X509GeneralizedTime {
const TAG: Tag = Tag::primitive(0x18);
fn write_data(&self, dest: &mut WriteBuf) -> WriteResult {
let dt = self.as_datetime();
push_four_digits(dest, dt.year())?;
push_two_digits(dest, dt.month())?;
push_two_digits(dest, dt.day())?;

push_two_digits(dest, dt.hour())?;
push_two_digits(dest, dt.minute())?;
push_two_digits(dest, dt.second())?;

dest.push_byte(b'Z')
}
}

/// Used for parsing and writing ASN.1 `GENERALIZED TIME` values accepting
/// fractional seconds value.
/// See https://github.com/alex/rust-asn1/issues/491 for discussion.
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq)]
pub struct GeneralizedTime {
datetime: DateTime,
nanoseconds: Option<u32>, // Up to 1 ns precision (10^9)
}

impl GeneralizedTime {
pub fn new(dt: DateTime, nanoseconds: Option<u32>) -> ParseResult<GeneralizedTime> {
if let Some(val) = nanoseconds {
if val < 1 || val >= 1e9 as u32 {
return Err(ParseError::new(ParseErrorKind::InvalidValue));
}
}

Ok(GeneralizedTime {
datetime: dt,
nanoseconds,
})
}

pub fn as_datetime(&self) -> &DateTime {
&self.datetime
}

pub fn nanoseconds(&self) -> Option<u32> {
self.nanoseconds
}
}

fn read_fractional_time(data: &mut &[u8]) -> ParseResult<Option<u32>> {
// We cannot use read_byte here because it will advance the pointer
// However, we know that the is suffixed by 'Z' so reading into an empty
// data should lead to an error.
if data.first() == Some(&b'.') {
*data = &data[1..];

let mut fraction = 0u32;
let mut digits = 0;
// Read up to 9 digits
for b in data.iter().take(9) {
if !b.is_ascii_digit() {
if digits == 0 {
// We must have at least one digit
return Err(ParseError::new(ParseErrorKind::InvalidValue));
}
break;
}
fraction = fraction * 10 + (b - b'0') as u32;
digits += 1;
}
*data = &data[digits..];

// No trailing zero
if fraction % 10 == 0 {
return Err(ParseError::new(ParseErrorKind::InvalidValue));
}

// Now let scale up in nanoseconds
let nanoseconds: u32 = fraction * 10u32.pow(9 - digits as u32);
Ok(Some(nanoseconds))
} else {
Ok(None)
}
}

impl SimpleAsn1Readable<'_> for GeneralizedTime {
const TAG: Tag = Tag::primitive(0x18);
fn parse_data(mut data: &[u8]) -> ParseResult<GeneralizedTime> {
Expand All @@ -1064,9 +1169,13 @@ impl SimpleAsn1Readable<'_> for GeneralizedTime {
let minute = read_2_digits(&mut data)?;
let second = read_2_digits(&mut data)?;

let fraction = read_fractional_time(&mut data)?;
read_tz_and_finish(&mut data)?;

GeneralizedTime::new(DateTime::new(year, month, day, hour, minute, second)?)
GeneralizedTime::new(
DateTime::new(year, month, day, hour, minute, second)?,
fraction,
)
}
}

Expand All @@ -1082,6 +1191,17 @@ impl SimpleAsn1Writable for GeneralizedTime {
push_two_digits(dest, dt.minute())?;
push_two_digits(dest, dt.second())?;

if let Some(nanoseconds) = self.nanoseconds() {
dest.push_byte(b'.')?;

for digit in format!("{:09}", nanoseconds)
.trim_end_matches('0')
.as_bytes()
{
dest.push_byte(*digit)?;
}
}

dest.push_byte(b'Z')
}
}
Expand Down Expand Up @@ -1726,7 +1846,7 @@ mod tests {
parse_single, BigInt, BigUint, DateTime, DefinedByMarker, Enumerated, GeneralizedTime,
IA5String, ObjectIdentifier, OctetStringEncoded, OwnedBigInt, OwnedBigUint, ParseError,
ParseErrorKind, PrintableString, SequenceOf, SequenceOfWriter, SetOf, SetOfWriter, Tag,
Tlv, UtcTime, Utf8String, VisibleString,
Tlv, UtcTime, Utf8String, VisibleString, X509GeneralizedTime,
};
use crate::{Explicit, Implicit};
#[cfg(not(feature = "std"))]
Expand Down Expand Up @@ -1998,9 +2118,47 @@ mod tests {
assert!(UtcTime::new(DateTime::new(2100, 1, 1, 12, 0, 0).unwrap()).is_err());
}

#[test]
fn test_x509_generalized_time_new() {
assert!(X509GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap()).is_ok());
}

#[test]
fn test_generalized_time_new() {
assert!(GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap()).is_ok());
assert!(
GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1234))
.is_ok()
);
assert!(
GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), None).is_ok()
);
assert!(GeneralizedTime::new(
DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(),
Some(1e9 as u32 + 1)
)
.is_err());
}

#[test]
fn test_generalized_time_partial_ord() {
let point =
GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1234))
.unwrap();
assert!(
point
< GeneralizedTime::new(DateTime::new(2023, 6, 30, 23, 59, 59).unwrap(), Some(1234))
.unwrap()
);
assert!(
point
< GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), Some(1235))
.unwrap()
);
assert!(
point
> GeneralizedTime::new(DateTime::new(2015, 6, 30, 23, 59, 59).unwrap(), None)
.unwrap()
);
}

#[test]
Expand Down
Loading