Skip to content

Commit

Permalink
Fix overflow in mask to prefix conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
stormshield-guillaumed committed Jan 3, 2023
1 parent 5765690 commit f37e135
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/mask.rs
Original file line number Diff line number Diff line change
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

0 comments on commit f37e135

Please sign in to comment.