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

Ntpv5 packet parsing #1125

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
dfb6de9
Start implementation of NTPv5 header parsing
tdittr Oct 9, 2023
52e1eff
Implemented v5 header parsing
marlonbaeten Oct 9, 2023
0cb97ae
Implement parsing and serialization for draft identification extension
tdittr Oct 9, 2023
ae6dd9c
Add NTPv5 header to general NtpHeader to prepare for usage in server
tdittr Oct 9, 2023
5feaff3
fixup! Add NTPv5 header to general NtpHeader to prepare for usage in …
tdittr Oct 10, 2023
aa93a45
Add NTPv5 feature to CI and fuzzing
tdittr Oct 10, 2023
96e0aca
Address clippy warnings
tdittr Oct 10, 2023
518f4f1
fixup! Address clippy warnings
tdittr Oct 10, 2023
60e05eb
fixup! Add NTPv5 feature to CI and fuzzing
tdittr Oct 10, 2023
1358a94
Implement v5 header serialization
marlonbaeten Oct 10, 2023
8ed0bf4
Remove panic from v5 header parsing
marlonbaeten Oct 10, 2023
5bf4d73
Fix clippy warnings in v5.rs
marlonbaeten Oct 10, 2023
c2522d6
Add extension field ids for all draft extensions
tdittr Oct 17, 2023
4ee909e
Address PR comment and simplify draft id deserialization
tdittr Oct 17, 2023
e72d95f
Address PR comment, fix typo, add comments
tdittr Oct 17, 2023
f344a11
Move v5 module to subdirectory
marlonbaeten Oct 17, 2023
86d8b76
Handle V5 extension fields
tdittr Oct 17, 2023
dc12be4
Undo change that violated MSRV
tdittr Oct 17, 2023
6f90c79
Move NTPv5 errors in seperate enum
tdittr Oct 17, 2023
d9ecc48
Switch flags from using hex to binary for better readability
tdittr Oct 17, 2023
0c64b44
Encode correct length in v5 extension fields
marlonbaeten Oct 17, 2023
88088db
Include ExtensionHeaderVersion in fuzzer call
marlonbaeten Oct 17, 2023
d867e25
Implement missing setters and getters for v5 header
tdittr Oct 17, 2023
6eef269
Fix fuzzer for versioned extension headers
marlonbaeten Oct 17, 2023
160ee32
Merge branch 'main' into ntpv5-packet-parsing
marlonbaeten Oct 17, 2023
0d5b78a
Fix lock file
marlonbaeten Oct 17, 2023
68fdd68
Update versions in fuzz/Cargo.lock
marlonbaeten Oct 17, 2023
6a8f81f
Format fuzzer code
marlonbaeten Oct 17, 2023
c4bfb3f
Also run fuzzer smoke tests for ntpv5
tdittr Oct 17, 2023
0580671
We have derive_arbitrary at home
marlonbaeten Oct 17, 2023
993db2b
Address review comments
tdittr Oct 18, 2023
e58ca4c
fixup! Address review comments
tdittr Oct 18, 2023
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
11 changes: 7 additions & 4 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ jobs:
- ""
features:
- ""
- "--features ntpv5"
steps:
- name: Checkout sources
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
Expand Down Expand Up @@ -67,6 +68,7 @@ jobs:
os: [ubuntu-latest]
features:
- ""
- "--features ntpv5"
steps:
- name: Checkout sources
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
Expand Down Expand Up @@ -96,6 +98,7 @@ jobs:
- ""
features:
- ""
- "--features ntpv5"
steps:
- name: Checkout sources
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
Expand Down Expand Up @@ -243,7 +246,7 @@ jobs:
uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505
with:
command: clippy
args: --workspace --all-targets -- -D warnings
args: --workspace --all-targets --all-features -- -D warnings
- name: Run clippy (fuzzers)
uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505
with:
Expand Down Expand Up @@ -287,7 +290,7 @@ jobs:
TARGET_CC: "/home/runner/.cargo/bin/cargo-zigbuild zig cc -- -target arm-linux-gnueabihf -mcpu=generic+v7a+vfp3-d32+thumb2-neon -g"
with:
command: clippy
args: --target armv7-unknown-linux-gnueabihf --workspace --all-targets -- -D warnings
args: --target armv7-unknown-linux-gnueabihf --workspace --all-targets --all-features -- -D warnings

clippy-macos:
name: ClippyMacOS
Expand Down Expand Up @@ -321,7 +324,7 @@ jobs:
TARGET_CC: "/home/runner/.cargo/bin/cargo-zigbuild zig cc -- -target x86_64-macos-gnu -g"
with:
command: clippy
args: --target x86_64-apple-darwin --workspace --all-targets -- -D warnings
args: --target x86_64-apple-darwin --workspace --all-targets --all-features -- -D warnings

clippy-musl:
name: ClippyMusl
Expand Down Expand Up @@ -355,7 +358,7 @@ jobs:
TARGET_CC: "/home/runner/.cargo/bin/cargo-zigbuild zig cc -- -target x86_64-linux-musl"
with:
command: clippy
args: --target x86_64-unknown-linux-musl --workspace --all-targets -- -D warnings
args: --target x86_64-unknown-linux-musl --workspace --all-targets --all-features -- -D warnings

fuzz:
name: Smoke-test fuzzing targets
Expand Down
3 changes: 3 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ publish = false
[package.metadata]
cargo-fuzz = true

[features]
ntpv5 = ["ntp-proto/ntpv5"]

[dependencies]
rand = "0.8.5"

Expand Down
1 change: 1 addition & 0 deletions ntp-proto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ rust-version.workspace = true
__internal-fuzz = ["arbitrary", "__internal-api"]
__internal-test = ["__internal-api"]
__internal-api = []
ntpv5 = []

[dependencies]
# Note: md5 is needed to calculate ReferenceIDs for IPv6 addresses per RFC5905
Expand Down
32 changes: 32 additions & 0 deletions ntp-proto/src/packet/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ pub enum ParsingError<T> {
MalformedNonce,
MalformedCookiePlaceholder,
DecryptError(T),
#[cfg(feature = "ntpv5")]
InvalidDraftIdentification,
#[cfg(feature = "ntpv5")]
MalformedTimescale,
#[cfg(feature = "ntpv5")]
MalformedMode,
#[cfg(feature = "ntpv5")]
InvalidFlags,
}

impl<T> ParsingError<T> {
Expand All @@ -23,6 +31,14 @@ impl<T> ParsingError<T> {
MalformedNonce => Err(MalformedNonce),
MalformedCookiePlaceholder => Err(MalformedCookiePlaceholder),
DecryptError(decrypt_error) => Ok(decrypt_error),
#[cfg(feature = "ntpv5")]
InvalidDraftIdentification => Err(InvalidDraftIdentification),
#[cfg(feature = "ntpv5")]
MalformedTimescale => Err(MalformedTimescale),
#[cfg(feature = "ntpv5")]
MalformedMode => Err(MalformedMode),
#[cfg(feature = "ntpv5")]
InvalidFlags => Err(InvalidFlags),
}
}
}
Expand All @@ -38,6 +54,14 @@ impl ParsingError<std::convert::Infallible> {
MalformedNonce => MalformedNonce,
MalformedCookiePlaceholder => MalformedCookiePlaceholder,
DecryptError(decrypt_error) => match decrypt_error {},
#[cfg(feature = "ntpv5")]
InvalidDraftIdentification => InvalidDraftIdentification,
#[cfg(feature = "ntpv5")]
MalformedTimescale => MalformedTimescale,
#[cfg(feature = "ntpv5")]
MalformedMode => MalformedMode,
#[cfg(feature = "ntpv5")]
InvalidFlags => InvalidFlags,
}
}
}
Expand All @@ -53,6 +77,14 @@ impl<T> Display for ParsingError<T> {
Self::MalformedNonce => f.write_str("Malformed nonce (likely invalid length)"),
Self::MalformedCookiePlaceholder => f.write_str("Malformed cookie placeholder"),
Self::DecryptError(_) => f.write_str("Failed to decrypt NTS extension fields"),
#[cfg(feature = "ntpv5")]
Self::InvalidDraftIdentification => f.write_str("Draft Identification invalid"),
#[cfg(feature = "ntpv5")]
Self::MalformedTimescale => f.write_str("Malformed timescale"),
#[cfg(feature = "ntpv5")]
Self::MalformedMode => f.write_str("Malformed mode"),
#[cfg(feature = "ntpv5")]
Self::InvalidFlags => f.write_str("Invalid flags specified"),
}
}
}
Expand Down
99 changes: 96 additions & 3 deletions ntp-proto/src/packet/extensionfields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ enum ExtensionFieldTypeId {
NtsCookie,
NtsCookiePlaceholder,
NtsEncryptedField,
Unknown { type_id: u16 },
Unknown {
type_id: u16,
},
#[cfg(feature = "ntpv5")]
DraftIdentification,
}

impl ExtensionFieldTypeId {
Expand All @@ -23,6 +27,8 @@ impl ExtensionFieldTypeId {
0x204 => Self::NtsCookie,
0x304 => Self::NtsCookiePlaceholder,
0x404 => Self::NtsEncryptedField,
#[cfg(feature = "ntpv5")]
0xF5FF => Self::DraftIdentification,
_ => Self::Unknown { type_id },
}
}
Expand All @@ -33,6 +39,8 @@ impl ExtensionFieldTypeId {
ExtensionFieldTypeId::NtsCookie => 0x204,
ExtensionFieldTypeId::NtsCookiePlaceholder => 0x304,
ExtensionFieldTypeId::NtsEncryptedField => 0x404,
#[cfg(feature = "ntpv5")]
ExtensionFieldTypeId::DraftIdentification => 0xF5FF,
ExtensionFieldTypeId::Unknown { type_id } => type_id,
}
}
Expand All @@ -42,9 +50,16 @@ impl ExtensionFieldTypeId {
pub enum ExtensionField<'a> {
UniqueIdentifier(Cow<'a, [u8]>),
NtsCookie(Cow<'a, [u8]>),
NtsCookiePlaceholder { cookie_length: u16 },
NtsCookiePlaceholder {
cookie_length: u16,
},
InvalidNtsEncryptedField,
Unknown { type_id: u16, data: Cow<'a, [u8]> },
#[cfg(feature = "ntpv5")]
DraftIdentification(Cow<'a, str>),
Unknown {
type_id: u16,
data: Cow<'a, [u8]>,
},
}

impl<'a> std::fmt::Debug for ExtensionField<'a> {
Expand All @@ -59,6 +74,10 @@ impl<'a> std::fmt::Debug for ExtensionField<'a> {
.field("body_length", body_length)
.finish(),
Self::InvalidNtsEncryptedField => f.debug_struct("InvalidNtsEncryptedField").finish(),
#[cfg(feature = "ntpv5")]
Self::DraftIdentification(arg0) => {
f.debug_tuple("DraftIdentification").field(arg0).finish()
}
Self::Unknown {
type_id: typeid,
data,
Expand Down Expand Up @@ -92,6 +111,8 @@ impl<'a> ExtensionField<'a> {
cookie_length: body_length,
},
InvalidNtsEncryptedField => InvalidNtsEncryptedField,
#[cfg(feature = "ntpv5")]
DraftIdentification(data) => DraftIdentification(Cow::Owned(data.into_owned())),
}
}

Expand All @@ -108,6 +129,8 @@ impl<'a> ExtensionField<'a> {
cookie_length: body_length,
} => Self::encode_nts_cookie_placeholder(w, *body_length, minimum_size),
InvalidNtsEncryptedField => Err(std::io::ErrorKind::Other.into()),
#[cfg(feature = "ntpv5")]
DraftIdentification(data) => Self::encode_draft_identification(w, data, minimum_size),
}
}

Expand Down Expand Up @@ -335,6 +358,26 @@ impl<'a> ExtensionField<'a> {
Ok(())
}

#[cfg(feature = "ntpv5")]
fn encode_draft_identification(
w: &mut impl Write,
data: &str,
minimum_size: u16,
) -> std::io::Result<()> {
Self::encode_framing(
w,
ExtensionFieldTypeId::DraftIdentification,
data.len(),
minimum_size,
)?;

w.write_all(data.as_bytes())?;

Self::encode_padding(w, data.len(), minimum_size)?;

Ok(())
}

fn decode_unique_identifier(
message: &'a [u8],
) -> Result<Self, ParsingError<std::convert::Infallible>> {
Expand Down Expand Up @@ -375,6 +418,28 @@ impl<'a> ExtensionField<'a> {
})
}

#[cfg(feature = "ntpv5")]
fn decode_draft_identification(
message: &'a [u8],
) -> Result<Self, ParsingError<std::convert::Infallible>> {
let msg = message[..].into();

let new_msg = match msg {
Cow::Borrowed(slice) => std::str::from_utf8(slice).ok().map(Cow::Borrowed),
Cow::Owned(vec) => String::from_utf8(vec).ok().map(Cow::Owned),
};
tdittr marked this conversation as resolved.
Show resolved Hide resolved

let Some(new_msg) = new_msg else {
return Err(ParsingError::InvalidDraftIdentification);
};

if !new_msg.is_ascii() {
return Err(ParsingError::InvalidDraftIdentification);
}

Ok(ExtensionField::DraftIdentification(new_msg))
}

fn decode(raw: RawExtensionField<'a>) -> Result<Self, ParsingError<std::convert::Infallible>> {
type EF<'a> = ExtensionField<'a>;
type TypeId = ExtensionFieldTypeId;
Expand All @@ -385,6 +450,8 @@ impl<'a> ExtensionField<'a> {
TypeId::UniqueIdentifier => EF::decode_unique_identifier(message),
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),
type_id => EF::decode_unknown(type_id.to_type_id(), message),
}
}
Expand Down Expand Up @@ -806,6 +873,32 @@ mod tests {
);
}

#[cfg(feature = "ntpv5")]
#[test]
fn draft_identification() {
let test_id = "draft-ietf-ntp-ntpv5-00\0";
let len = u16::try_from(4 + test_id.len()).unwrap();
let mut data = vec![];
data.extend_from_slice(&[0xF5, 0xFF]);
data.extend_from_slice(&len.to_be_bytes());
data.extend_from_slice(test_id.as_bytes());
tdittr marked this conversation as resolved.
Show resolved Hide resolved

let raw = RawExtensionField::deserialize(&data, 0).unwrap();
let ef = ExtensionField::decode(raw).unwrap();

match ef {
ExtensionField::DraftIdentification(ref data) => {
assert_eq!(data, test_id);
}
_ => panic!("Unexpected extensionfield {ef:?}"),
}

let mut out = vec![];
ef.serialize(&mut out, len).unwrap();

assert_eq!(&out, &data);
}

#[test]
fn extension_field_minimum_size() {
let minimum_size = 32;
Expand Down
Loading