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

Check for correct env keys in Command #39338

Closed
wants to merge 3 commits into from
Closed
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
21 changes: 21 additions & 0 deletions src/libstd/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,27 @@ mod tests {
}
}

#[test]
fn test_empty_env_key_is_error() {
match env_cmd().env("", "value").spawn() {
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
Ok(_) => panic!(),
}
}

#[test]
fn test_interior_eq_in_env_key_is_error() {
match env_cmd().env("has-some-==s-inside", "value").spawn() {
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
Ok(_) => panic!(),
}
}

#[test]
fn test_leading_eq_key_is_no_error() {
env_cmd().env("=NAME", "value").output().unwrap();
}

/// Test that process creation flags work by debugging a process.
/// Other creation flags make it hard or impossible to detect
/// behavioral changes in the process.
Expand Down
49 changes: 42 additions & 7 deletions src/libstd/sys/unix/process/process_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ pub struct Command {
uid: Option<uid_t>,
gid: Option<gid_t>,
saw_nul: bool,
saw_malformed_env_key: bool,
closures: Vec<Box<FnMut() -> io::Result<()> + Send + Sync>>,
stdin: Option<Stdio>,
stdout: Option<Stdio>,
Expand Down Expand Up @@ -102,6 +103,7 @@ impl Command {
uid: None,
gid: None,
saw_nul: saw_nul,
saw_malformed_env_key: false,
closures: Vec::new(),
stdin: None,
stdout: None,
Expand All @@ -127,7 +129,11 @@ impl Command {
let mut map = HashMap::new();
let mut envp = Vec::new();
for (k, v) in env::vars_os() {
let s = pair_to_key(&k, &v, &mut self.saw_nul);
let mut saw_nul = false;
let mut saw_malformed_env_key = false;
let s = pair_to_key(&k, &v, &mut saw_nul, &mut saw_malformed_env_key);
assert!(!saw_nul);
assert!(!saw_malformed_env_key);
envp.push(s.as_ptr());
map.insert(k, (envp.len() - 1, s));
}
Expand All @@ -139,7 +145,11 @@ impl Command {
}

pub fn env(&mut self, key: &OsStr, val: &OsStr) {
let new_key = pair_to_key(key, val, &mut self.saw_nul);
let new_key = pair_to_key(key, val, &mut self.saw_nul, &mut self.saw_malformed_env_key);
if self.saw_malformed_env_key {
println!("{:?} {:?}", key, val);
}

let (map, envp) = self.init_env_map();

// If `key` is already present then we just update `envp` in place
Expand All @@ -162,6 +172,11 @@ impl Command {
}

pub fn env_remove(&mut self, key: &OsStr) {
pair_to_key(key, OsStr::new(""), &mut self.saw_nul, &mut self.saw_malformed_env_key);
if self.saw_malformed_env_key {
println!("{:?}", key);
}

let (map, envp) = self.init_env_map();

// If we actually ended up removing a key, then we need to update the
Expand Down Expand Up @@ -193,9 +208,6 @@ impl Command {
self.gid = Some(id);
}

pub fn saw_nul(&self) -> bool {
self.saw_nul
}
pub fn get_envp(&self) -> &Option<Vec<*const c_char>> {
&self.envp
}
Expand Down Expand Up @@ -237,6 +249,18 @@ impl Command {
self.stderr = Some(stderr);
}

pub fn check_malformed(&self) -> io::Result<()> {
if self.saw_nul {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"nul byte found in provided data"));
}
if self.saw_malformed_env_key {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"malformed env key in provided data"));
}
Ok(())
}

pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
-> io::Result<(StdioPipes, ChildPipes)> {
let null = Stdio::Null;
Expand All @@ -261,6 +285,13 @@ impl Command {
}
}

fn check_env_key(s: &OsStr, saw_malformed: &mut bool) {
let bytes = s.as_bytes();
if bytes.is_empty() || bytes[1..].contains(&b'=') {
*saw_malformed = true;
}
}

fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| {
*saw_nul = true;
Expand Down Expand Up @@ -325,15 +356,19 @@ impl ChildStdio {
}
}

fn pair_to_key(key: &OsStr, value: &OsStr, saw_nul: &mut bool) -> CString {
fn pair_to_key(key: &OsStr, value: &OsStr, saw_nul: &mut bool, saw_malformed: &mut bool)
-> CString
{
check_env_key(key, saw_malformed);

let (key, value) = (key.as_bytes(), value.as_bytes());
let mut v = Vec::with_capacity(key.len() + value.len() + 1);
v.extend(key);
v.push(b'=');
v.extend(value);
CString::new(v).unwrap_or_else(|_e| {
*saw_nul = true;
CString::new("foo=bar").unwrap()
CString::new("<ENV_WITH_NUL>").unwrap()
})
}

Expand Down
11 changes: 4 additions & 7 deletions src/libstd/sys/unix/process/process_fuchsia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ use sys::process::process_common::*;
impl Command {
pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
-> io::Result<(Process, StdioPipes)> {
if self.saw_nul() {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"nul byte found in provided data"));
}
self.check_malformed()?;

let (ours, theirs) = self.setup_io(default, needs_stdin)?;

Expand All @@ -36,9 +33,9 @@ impl Command {
}

pub fn exec(&mut self, default: Stdio) -> io::Error {
if self.saw_nul() {
return io::Error::new(io::ErrorKind::InvalidInput,
"nul byte found in provided data")
match self.check_malformed() {
Ok(()) => {},
Err(e) => return e,
}

match self.setup_io(default, true) {
Expand Down
11 changes: 4 additions & 7 deletions src/libstd/sys/unix/process/process_unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ impl Command {

const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";

if self.saw_nul() {
return Err(io::Error::new(ErrorKind::InvalidInput,
"nul byte found in provided data"));
}
self.check_malformed()?;

let (ours, theirs) = self.setup_io(default, needs_stdin)?;
let (input, output) = sys::pipe::anon_pipe()?;
Expand Down Expand Up @@ -100,9 +97,9 @@ impl Command {
}

pub fn exec(&mut self, default: Stdio) -> io::Error {
if self.saw_nul() {
return io::Error::new(ErrorKind::InvalidInput,
"nul byte found in provided data")
match self.check_malformed() {
Ok(()) => {},
Err(e) => return e,
}

match self.setup_io(default, true) {
Expand Down
11 changes: 10 additions & 1 deletion src/libstd/sys/windows/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
}
}

fn ensure_valid_env_key<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
if str.as_ref().is_empty() || str.as_ref().encode_wide().skip(1).any(|b| b == b'=' as u16) {
Err(io::Error::new(io::ErrorKind::InvalidInput,
"malformed env key in provided data"))
} else {
ensure_no_nuls(str)
}
}

pub struct Command {
program: OsString,
args: Vec<OsString>,
Expand Down Expand Up @@ -479,7 +488,7 @@ fn make_envp(env: Option<&collections::HashMap<OsString, OsString>>)
let mut blk = Vec::new();

for pair in env {
blk.extend(ensure_no_nuls(pair.0)?.encode_wide());
blk.extend(ensure_valid_env_key(pair.0)?.encode_wide());
blk.push('=' as u16);
blk.extend(ensure_no_nuls(pair.1)?.encode_wide());
blk.push(0);
Expand Down