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

Reject octal zeros in IPv4 addresses #86984

Merged
merged 6 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 4 additions & 1 deletion library/std/src/net/ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ pub enum IpAddr {
///
/// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
/// notation, divided by `.` (this is called "dot-decimal notation").
/// Notably, octal numbers and hexadecimal numbers are not allowed per [IETF RFC 6943].
/// Notably, octal numbers (which are indicated with a leading `0`) and hexadecimal numbers (which
/// are indicated with a leading `0x`) are not allowed per [IETF RFC 6943].
///
/// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
/// [`FromStr`]: crate::str::FromStr
Expand All @@ -72,6 +73,8 @@ pub enum IpAddr {
/// let localhost = Ipv4Addr::new(127, 0, 0, 1);
/// assert_eq!("127.0.0.1".parse(), Ok(localhost));
/// assert_eq!(localhost.is_loopback(), true);
/// assert!("012.004.002.000".parse::<Ipv4Addr>().is_err()); // all octets are in octal
/// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
/// ```
#[derive(Copy)]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
8 changes: 8 additions & 0 deletions library/std/src/net/ip/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ fn test_from_str_ipv4() {
// no number between dots
let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
assert_eq!(None, none);
// octal
let none: Option<Ipv4Addr> = "255.0.0.01".parse().ok();
assert_eq!(None, none);
// octal zero
let none: Option<Ipv4Addr> = "255.0.0.00".parse().ok();
assert_eq!(None, none);
let none: Option<Ipv4Addr> = "255.0.00.0".parse().ok();
assert_eq!(None, none);
}

#[test]
Expand Down
33 changes: 23 additions & 10 deletions library/std/src/net/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::fmt;
use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use crate::str::FromStr;

trait ReadNumberHelper: crate::marker::Sized {
trait ReadNumberHelper: crate::marker::Sized + crate::cmp::PartialEq {
const ZERO: Self;
fn checked_mul(&self, other: u32) -> Option<Self>;
fn checked_add(&self, other: u32) -> Option<Self>;
Expand Down Expand Up @@ -111,10 +111,12 @@ impl<'a> Parser<'a> {
&mut self,
radix: u32,
max_digits: Option<usize>,
allow_zero_prefix: bool,
) -> Option<T> {
self.read_atomically(move |p| {
let mut result = T::ZERO;
let mut digit_count = 0;
let has_leading_zero = p.peek_char() == Some('0');

while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
result = result.checked_mul(radix)?;
Expand All @@ -127,7 +129,16 @@ impl<'a> Parser<'a> {
}
}

if digit_count == 0 { None } else { Some(result) }
if digit_count == 0 {
None
} else if !allow_zero_prefix
&& has_leading_zero
&& (result != T::ZERO || result == T::ZERO && digit_count > 1)
{
None
} else {
Some(result)
}
})
}

Expand All @@ -140,10 +151,7 @@ impl<'a> Parser<'a> {
*slot = p.read_separator('.', i, |p| {
// Disallow octal number in IP string.
// https://tools.ietf.org/html/rfc6943#section-3.1.1
match (p.peek_char(), p.read_number(10, None)) {
(Some('0'), Some(number)) if number != 0 => None,
(_, number) => number,
}
p.read_number(10, None, false)
})?;
}

Expand Down Expand Up @@ -175,7 +183,7 @@ impl<'a> Parser<'a> {
}
}

let group = p.read_separator(':', i, |p| p.read_number(16, Some(4)));
let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));

match group {
Some(g) => *slot = g,
Expand Down Expand Up @@ -227,15 +235,15 @@ impl<'a> Parser<'a> {
fn read_port(&mut self) -> Option<u16> {
self.read_atomically(|p| {
p.read_given_char(':')?;
p.read_number(10, None)
p.read_number(10, None, true)
})
}

/// Read a `%` followed by a scope ID in base 10.
fn read_scope_id(&mut self) -> Option<u32> {
self.read_atomically(|p| {
p.read_given_char('%')?;
p.read_number(10, None)
p.read_number(10, None, true)
})
}

Expand Down Expand Up @@ -281,7 +289,12 @@ impl FromStr for IpAddr {
impl FromStr for Ipv4Addr {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
Parser::new(s).parse_with(|p| p.read_ipv4_addr())
// don't try to parse if too long
if s.len() > 15 {
Err(AddrParseError(()))
} else {
Parser::new(s).parse_with(|p| p.read_ipv4_addr())
}
}
}

Expand Down