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

Fix overflow in mask to prefix conversion #47

Merged
merged 1 commit into from Jan 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/mask.rs
Expand Up @@ -20,7 +20,7 @@ pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result<u8, PrefixLenError> {
let mask = u32::from(mask);

let prefix = mask.leading_ones();
if (mask << prefix) == 0 {
if mask.checked_shl(prefix).unwrap_or(0) == 0 {
Ok(prefix as u8)
} else {
Err(PrefixLenError)
Expand All @@ -35,7 +35,7 @@ pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result<u8, PrefixLenError> {
let mask = u128::from(mask);

let prefix = mask.leading_ones();
if (mask << prefix) == 0 {
if mask.checked_shl(prefix).unwrap_or(0) == 0 {
Ok(prefix as u8)
} else {
Err(PrefixLenError)
Expand All @@ -54,6 +54,13 @@ mod tests {
assert_eq!(prefix, Ok(25));
}

#[test]
fn v4_mask_to_prefix_max() {
let mask = Ipv4Addr::from(u32::MAX);
let prefix = ipv4_mask_to_prefix(mask);
assert_eq!(prefix, Ok(32));
}

#[test]
fn invalid_v4_mask_to_prefix() {
let mask = Ipv4Addr::new(255, 0, 255, 0);
Expand Down Expand Up @@ -86,6 +93,13 @@ mod tests {
assert_eq!(prefix, Ok(48));
}

#[test]
fn v6_mask_to_prefix_max() {
let mask = Ipv6Addr::from(u128::MAX);
let prefix = ipv6_mask_to_prefix(mask);
assert_eq!(prefix, Ok(128));
}

#[test]
fn invalid_v6_mask_to_prefix() {
let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0);
Expand Down