Skip to content
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

Add NTPv5 support to Peer #1168

Merged
merged 3 commits into from
Nov 1, 2023
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
27 changes: 20 additions & 7 deletions ntp-proto/src/packet/extension_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,16 +446,26 @@ impl<'a> ExtensionField<'a> {
#[cfg(feature = "ntpv5")]
fn decode_draft_identification(
message: &'a [u8],
extension_header_version: ExtensionHeaderVersion,
) -> Result<Self, ParsingError<std::convert::Infallible>> {
let di = match core::str::from_utf8(message) {
Ok(di) if di.is_ascii() => di,
_ => return Err(super::v5::V5Error::InvalidDraftIdentification.into()),
};

let di = match extension_header_version {
ExtensionHeaderVersion::V4 => di.trim_end_matches('\0'),
ExtensionHeaderVersion::V5 => di,
};

Ok(ExtensionField::DraftIdentification(Cow::Borrowed(di)))
}

fn decode(raw: RawExtensionField<'a>) -> Result<Self, ParsingError<std::convert::Infallible>> {
fn decode(
raw: RawExtensionField<'a>,
#[cfg_attr(not(feature = "ntpv5"), allow(unused_variables))]
extension_header_version: ExtensionHeaderVersion,
) -> Result<Self, ParsingError<std::convert::Infallible>> {
type EF<'a> = ExtensionField<'a>;
type TypeId = ExtensionFieldTypeId;

Expand All @@ -466,7 +476,9 @@ impl<'a> ExtensionField<'a> {
TypeId::NtsCookie => EF::decode_nts_cookie(message),
TypeId::NtsCookiePlaceholder => EF::decode_nts_cookie_placeholder(message),
#[cfg(feature = "ntpv5")]
TypeId::DraftIdentification => EF::decode_draft_identification(message),
TypeId::DraftIdentification => {
EF::decode_draft_identification(message, extension_header_version)
}
type_id => EF::decode_unknown(type_id.to_type_id(), message),
}
}
Expand Down Expand Up @@ -617,7 +629,8 @@ impl<'a> ExtensionFieldData<'a> {
efdata.authenticated.append(&mut efdata.untrusted);
}
_ => {
let field = ExtensionField::decode(field).map_err(|e| e.generalize())?;
let field =
ExtensionField::decode(field, version).map_err(|e| e.generalize())?;
efdata.untrusted.push(field);
}
}
Expand Down Expand Up @@ -701,7 +714,7 @@ impl<'a> RawEncryptedField<'a> {
// TODO: Discuss whether we want this check
Err(ParsingError::MalformedNtsExtensionFields)
} else {
Ok(ExtensionField::decode(encrypted_field)
Ok(ExtensionField::decode(encrypted_field, version)
.map_err(|e| e.generalize())?
.into_owned())
}
Expand Down Expand Up @@ -931,15 +944,15 @@ mod tests {
type_id: ExtensionFieldTypeId::NtsCookiePlaceholder,
message_bytes: &[1; COOKIE_LENGTH],
};
let output = ExtensionField::decode(raw).unwrap_err();
let output = ExtensionField::decode(raw, ExtensionHeaderVersion::V4).unwrap_err();

assert!(matches!(output, ParsingError::MalformedCookiePlaceholder));

let raw = RawExtensionField {
type_id: ExtensionFieldTypeId::NtsCookiePlaceholder,
message_bytes: &[0; COOKIE_LENGTH],
};
let output = ExtensionField::decode(raw).unwrap();
let output = ExtensionField::decode(raw, ExtensionHeaderVersion::V4).unwrap();

let ExtensionField::NtsCookiePlaceholder { cookie_length } = output else {
panic!("incorrect variant");
Expand Down Expand Up @@ -972,7 +985,7 @@ mod tests {
data.extend(&[0]); // Padding

let raw = RawExtensionField::deserialize(&data, 4, ExtensionHeaderVersion::V5).unwrap();
let ef = ExtensionField::decode(raw).unwrap();
let ef = ExtensionField::decode(raw, ExtensionHeaderVersion::V4).unwrap();

let ExtensionField::DraftIdentification(ref parsed) = ef else {
panic!("Unexpected extensionfield {ef:?}... expected DraftIdentification");
Expand Down
94 changes: 65 additions & 29 deletions ntp-proto/src/packet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ struct NtpHeaderV3V4 {
leap: NtpLeapIndicator,
mode: NtpAssociationMode,
stratum: u8,
poll: i8,
poll: PollInterval,
precision: i8,
root_delay: NtpDuration,
root_dispersion: NtpDuration,
Expand Down Expand Up @@ -159,7 +159,7 @@ impl NtpHeaderV3V4 {
leap: NtpLeapIndicator::NoWarning,
mode: NtpAssociationMode::Client,
stratum: 0,
poll: 0,
poll: PollInterval::from_byte(0),
precision: 0,
root_delay: NtpDuration::default(),
root_dispersion: NtpDuration::default(),
Expand All @@ -181,7 +181,7 @@ impl NtpHeaderV3V4 {
leap: NtpLeapIndicator::from_bits((data[0] & 0xC0) >> 6),
mode: NtpAssociationMode::from_bits(data[0] & 0x07),
stratum: data[1],
poll: data[2] as i8,
poll: PollInterval::from_byte(data[2]),
precision: data[3] as i8,
root_delay: NtpDuration::from_bits_short(data[4..8].try_into().unwrap()),
root_dispersion: NtpDuration::from_bits_short(data[8..12].try_into().unwrap()),
Expand All @@ -197,7 +197,7 @@ impl NtpHeaderV3V4 {

fn serialize<W: std::io::Write>(&self, w: &mut W, version: u8) -> std::io::Result<()> {
w.write_all(&[(self.leap.to_bits() << 6) | (version << 3) | self.mode.to_bits()])?;
w.write_all(&[self.stratum, self.poll as u8, self.precision as u8])?;
w.write_all(&[self.stratum, self.poll.as_byte(), self.precision as u8])?;
w.write_all(&self.root_delay.to_bits_short())?;
w.write_all(&self.root_dispersion.to_bits_short())?;
w.write_all(&self.reference_id.to_bytes())?;
Expand All @@ -210,7 +210,7 @@ impl NtpHeaderV3V4 {

fn poll_message(poll_interval: PollInterval) -> (Self, RequestIdentifier) {
let mut packet = Self::new();
packet.poll = poll_interval.as_log();
packet.poll = poll_interval;
packet.mode = NtpAssociationMode::Client;

// In order to increase the entropy of the transmit timestamp
Expand Down Expand Up @@ -519,6 +519,27 @@ impl<'a> NtpPacket<'a> {
)
}

#[cfg(feature = "ntpv5")]
pub fn poll_message_upgrade_request(poll_interval: PollInterval) -> (Self, RequestIdentifier) {
let (mut header, id) = NtpHeaderV3V4::poll_message(poll_interval);

header.reference_timestamp = v5::UPGRADE_TIMESTAMP;
let draft_id = ExtensionField::DraftIdentification(Cow::Borrowed(v5::DRAFT_VERSION));

(
NtpPacket {
header: NtpHeader::V4(header),
efdata: ExtensionFieldData {
authenticated: vec![],
encrypted: vec![],
untrusted: vec![draft_id],
},
mac: None,
},
id,
)
}

#[cfg(feature = "ntpv5")]
pub fn poll_message_v5(poll_interval: PollInterval) -> (Self, RequestIdentifier) {
let (header, id) = v5::NtpHeaderV5::poll_message(poll_interval);
Expand Down Expand Up @@ -560,6 +581,7 @@ impl<'a> NtpPacket<'a> {
NtpHeader::V4(header) => {
let mut response_header =
NtpHeaderV3V4::timestamp_response(system, header, recv_timestamp, clock);
let mut extra_ef = None;

#[cfg(feature = "ntpv5")]
{
Expand All @@ -569,6 +591,9 @@ impl<'a> NtpPacket<'a> {
(header.reference_timestamp, input.draft_id())
{
response_header.reference_timestamp = v5::UPGRADE_TIMESTAMP;
extra_ef = Some(ExtensionField::DraftIdentification(Cow::Borrowed(
v5::DRAFT_VERSION,
)));
};
}

Expand All @@ -584,6 +609,7 @@ impl<'a> NtpPacket<'a> {
.into_iter()
.chain(input.efdata.authenticated)
.filter(|ef| matches!(ef, ExtensionField::UniqueIdentifier(_)))
.chain(extra_ef)
.collect(),
},
mac: None,
Expand Down Expand Up @@ -849,6 +875,14 @@ impl<'a> NtpPacket<'a> {
}
}

pub fn poll(&self) -> PollInterval {
match self.header {
NtpHeader::V3(h) | NtpHeader::V4(h) => h.poll,
#[cfg(feature = "ntpv5")]
NtpHeader::V5(h) => h.poll,
}
}

pub fn stratum(&self) -> u8 {
match self.header {
NtpHeader::V3(header) => header.stratum,
Expand Down Expand Up @@ -908,7 +942,8 @@ impl<'a> NtpPacket<'a> {
NtpHeader::V3(header) => header.reference_id,
NtpHeader::V4(header) => header.reference_id,
#[cfg(feature = "ntpv5")]
NtpHeader::V5(_header) => todo!("NTPv5 does not have reference IDs"),
// TODO NTPv5 does not have reference IDs so this should always be None for now
NtpHeader::V5(_header) => ReferenceId::NONE,
}
}

Expand All @@ -917,7 +952,8 @@ impl<'a> NtpPacket<'a> {
NtpHeader::V3(header) => header.stratum == 0,
NtpHeader::V4(header) => header.stratum == 0,
#[cfg(feature = "ntpv5")]
NtpHeader::V5(_header) => todo!("NTPv5 does not have kiss codes yet"),
// TODO NTPv5 does not have Kiss codes so we pretend everything is always fine
NtpHeader::V5(_header) => false,
}
}

Expand All @@ -937,6 +973,20 @@ impl<'a> NtpPacket<'a> {
self.is_kiss() && self.reference_id().is_ntsn()
}

#[cfg(feature = "ntpv5")]
pub fn is_upgrade(&self) -> bool {
matches!(
(self.header, self.draft_id()),
(
NtpHeader::V4(NtpHeaderV3V4 {
reference_timestamp: v5::UPGRADE_TIMESTAMP,
..
}),
Some(v5::DRAFT_VERSION),
)
)
}

pub fn valid_server_response(&self, identifier: RequestIdentifier, nts_enabled: bool) -> bool {
if let Some(uid) = identifier.uid {
let auth = check_uid_extensionfield(self.efdata.authenticated.iter(), &uid);
Expand Down Expand Up @@ -1200,7 +1250,7 @@ mod tests {
leap: NtpLeapIndicator::NoWarning,
mode: NtpAssociationMode::Client,
stratum: 2,
poll: 6,
poll: PollInterval::from_byte(6),
precision: -24,
root_delay: NtpDuration::from_fixed_int(1023 << 16),
root_dispersion: NtpDuration::from_fixed_int(893 << 16),
Expand Down Expand Up @@ -1229,7 +1279,7 @@ mod tests {
leap: NtpLeapIndicator::NoWarning,
mode: NtpAssociationMode::Client,
stratum: 2,
poll: 6,
poll: PollInterval::from_byte(6),
precision: -24,
root_delay: NtpDuration::from_fixed_int(1023 << 16),
root_dispersion: NtpDuration::from_fixed_int(893 << 16),
Expand Down Expand Up @@ -1261,7 +1311,7 @@ mod tests {
leap: NtpLeapIndicator::NoWarning,
mode: NtpAssociationMode::Server,
stratum: 2,
poll: 6,
poll: PollInterval::from_byte(6),
precision: -23,
root_delay: NtpDuration::from_fixed_int(566 << 16),
root_dispersion: NtpDuration::from_fixed_int(951 << 16),
Expand Down Expand Up @@ -1508,21 +1558,10 @@ mod tests {
assert!(!response.valid_server_response(id, true));
}

#[cfg(feature = "ntpv5")]
#[test]
fn v5_upgrade_packet() {
let (mut packet, _) = NtpPacket::poll_message(PollInterval::default());
let NtpHeader::V4(header) = &mut packet.header else {
panic!("wrong version");
};
header.reference_timestamp = NtpTimestamp::from_fixed_int(0x4E5450354E545035);

#[cfg(feature = "ntpv5")]
packet
.efdata
.untrusted
.push(ExtensionField::DraftIdentification(Cow::Borrowed(
v5::DRAFT_VERSION,
)));
let (packet, _) = NtpPacket::poll_message_upgrade_request(PollInterval::default());

let response = NtpPacket::timestamp_response(
&SystemSnapshot::default(),
Expand All @@ -1537,13 +1576,10 @@ mod tests {
panic!("wrong version");
};

let expect = if cfg!(feature = "ntpv5") {
assert_eq!(
header.reference_timestamp,
NtpTimestamp::from_fixed_int(0x4E5450354E545035)
} else {
NtpTimestamp::from_fixed_int(0)
};

assert_eq!(header.reference_timestamp, expect);
);
}

#[test]
Expand Down
18 changes: 9 additions & 9 deletions ntp-proto/src/packet/v5/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub use error::V5Error;
use super::RequestIdentifier;

#[allow(dead_code)]
pub(crate) const DRAFT_VERSION: &str = "draft-ietf-ntp-ntpv5-00";
pub(crate) const DRAFT_VERSION: &str = "draft-ietf-ntp-ntpv5-01";
pub(crate) const UPGRADE_TIMESTAMP: NtpTimestamp = NtpTimestamp::from_bits(*b"NTP5NTP5");

#[repr(u8)]
Expand Down Expand Up @@ -140,7 +140,7 @@ pub struct NtpHeaderV5 {
pub leap: NtpLeapIndicator,
pub mode: NtpMode,
pub stratum: u8,
pub poll: i8,
pub poll: PollInterval,
pub precision: i8,
pub timescale: NtpTimescale,
pub era: NtpEra,
Expand All @@ -161,7 +161,7 @@ impl NtpHeaderV5 {
leap: NtpLeapIndicator::NoWarning,
mode: NtpMode::Request,
stratum: 0,
poll: 0,
poll: PollInterval::from_byte(0),
precision: 0,
root_delay: NtpDuration::default(),
root_dispersion: NtpDuration::default(),
Expand Down Expand Up @@ -229,7 +229,7 @@ impl NtpHeaderV5 {
leap: NtpLeapIndicator::from_bits((data[0] & 0xC0) >> 6),
mode: NtpMode::from_bits(data[0] & 0x07)?,
stratum: data[1],
poll: data[2] as i8,
poll: PollInterval::from_byte(data[2]),
precision: data[3] as i8,
timescale: NtpTimescale::from_bits(data[4])?,
era: NtpEra(data[5]),
Expand All @@ -248,7 +248,7 @@ impl NtpHeaderV5 {
#[allow(dead_code)]
pub(crate) fn serialize<W: std::io::Write>(&self, w: &mut W) -> std::io::Result<()> {
w.write_all(&[(self.leap.to_bits() << 6) | (Self::VERSION << 3) | self.mode.to_bits()])?;
w.write_all(&[self.stratum, self.poll as u8, self.precision as u8])?;
w.write_all(&[self.stratum, self.poll.as_byte(), self.precision as u8])?;
w.write_all(&[self.timescale.to_bits()])?;
w.write_all(&[self.era.0])?;
w.write_all(&self.flags.as_bits())?;
Expand All @@ -263,7 +263,7 @@ impl NtpHeaderV5 {

pub fn poll_message(poll_interval: PollInterval) -> (Self, RequestIdentifier) {
let mut packet = Self::new();
packet.poll = poll_interval.as_log();
packet.poll = poll_interval;
packet.mode = NtpMode::Request;

let client_cookie = NtpClientCookie::new_random();
Expand Down Expand Up @@ -358,7 +358,7 @@ mod tests {
assert_eq!(parsed.leap, NtpLeapIndicator::NoWarning);
assert!(parsed.mode.is_request());
assert_eq!(parsed.stratum, 0);
assert_eq!(parsed.poll, 5);
assert_eq!(parsed.poll, PollInterval::from_byte(5));
assert_eq!(parsed.precision, 0);
assert_eq!(parsed.timescale, NtpTimescale::Ut1);
assert_eq!(parsed.era, NtpEra(0));
Expand Down Expand Up @@ -422,7 +422,7 @@ mod tests {
assert_eq!(parsed.leap, NtpLeapIndicator::NoWarning);
assert!(parsed.mode.is_response());
assert_eq!(parsed.stratum, 4);
assert_eq!(parsed.poll, 5);
assert_eq!(parsed.poll, PollInterval::from_byte(5));
assert_eq!(parsed.precision, 6);
assert_eq!(parsed.timescale, NtpTimescale::Tai);
assert_eq!(parsed.era, NtpEra(7));
Expand Down Expand Up @@ -468,7 +468,7 @@ mod tests {
leap: NtpLeapIndicator::from_bits(i % 4),
mode: NtpMode::from_bits(3 + (i % 2)).unwrap(),
stratum: i.wrapping_add(1),
poll: i.wrapping_add(3) as i8,
poll: PollInterval::from_byte(i.wrapping_add(3)),
precision: i.wrapping_add(4) as i8,
timescale: NtpTimescale::from_bits(i % 4).unwrap(),
era: NtpEra(i.wrapping_add(6)),
Expand Down
Loading