Skip to content

Commit a733df6

Browse files
committed
Validate environment variable names in std::process
Make sure that they're not empty and do not contain `=` signs beyond the first character. This prevents environment variable injection, because previously, setting the `PATH=/opt:` variable to `foobar` would lead to the `PATH` variable being overridden. Fixes #122335.
1 parent 56e112a commit a733df6

File tree

6 files changed

+96
-35
lines changed

6 files changed

+96
-35
lines changed

library/std/src/process/tests.rs

+29
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,35 @@ fn test_interior_nul_in_env_value_is_error() {
378378
}
379379
}
380380

381+
#[test]
382+
fn test_empty_env_key_is_error() {
383+
match env_cmd().env("", "value").spawn() {
384+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
385+
Ok(_) => panic!(),
386+
}
387+
}
388+
389+
#[test]
390+
fn test_interior_equals_in_env_key_is_error() {
391+
match env_cmd().env("has=equals", "value").spawn() {
392+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
393+
Ok(_) => panic!(),
394+
}
395+
}
396+
397+
#[test]
398+
fn test_env_leading_equals() {
399+
let mut cmd = env_cmd();
400+
cmd.env("=RUN_TEST_LEADING_EQUALS", "789=012");
401+
let result = cmd.output().unwrap();
402+
let output = String::from_utf8_lossy(&result.stdout).to_string();
403+
404+
assert!(
405+
output.contains("=RUN_TEST_LEADING_EQUALS=789=012"),
406+
"didn't find =RUN_TEST_LEADING_EQUALS inside of:\n\n{output}",
407+
);
408+
}
409+
381410
/// Tests that process creation flags work by debugging a process.
382411
/// Other creation flags make it hard or impossible to detect
383412
/// behavioral changes in the process.

library/std/src/sys/pal/unix/process/process_common.rs

+29-4
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ pub struct Command {
100100
uid: Option<uid_t>,
101101
gid: Option<gid_t>,
102102
saw_nul: bool,
103+
saw_invalid_env_key: bool,
103104
closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
104105
groups: Option<Box<[gid_t]>>,
105106
stdin: Option<Stdio>,
@@ -193,6 +194,7 @@ impl Command {
193194
uid: None,
194195
gid: None,
195196
saw_nul,
197+
saw_invalid_env_key: false,
196198
closures: Vec::new(),
197199
groups: None,
198200
stdin: None,
@@ -217,6 +219,7 @@ impl Command {
217219
uid: None,
218220
gid: None,
219221
saw_nul,
222+
saw_invalid_env_key: false,
220223
closures: Vec::new(),
221224
groups: None,
222225
stdin: None,
@@ -279,8 +282,18 @@ impl Command {
279282
self.create_pidfd
280283
}
281284

282-
pub fn saw_nul(&self) -> bool {
283-
self.saw_nul
285+
pub fn validate_input(&self) -> io::Result<()> {
286+
if self.saw_invalid_env_key {
287+
Err(io::const_io_error!(io::ErrorKind::InvalidInput, "env key empty or equals sign found in env key"))
288+
} else if self.saw_nul {
289+
Err(io::const_io_error!(io::ErrorKind::InvalidInput, "nul byte found in provided data"))
290+
} else {
291+
Ok(())
292+
}
293+
}
294+
295+
pub fn saw_invalid_env_key(&self) -> bool {
296+
self.saw_invalid_env_key
284297
}
285298

286299
pub fn get_program(&self) -> &OsStr {
@@ -361,7 +374,7 @@ impl Command {
361374

362375
pub fn capture_env(&mut self) -> Option<CStringArray> {
363376
let maybe_env = self.env.capture_if_changed();
364-
maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
377+
maybe_env.map(|env| construct_envp(env, &mut self.saw_nul, &mut self.saw_invalid_env_key))
365378
}
366379

367380
#[allow(dead_code)]
@@ -426,9 +439,21 @@ impl CStringArray {
426439
}
427440
}
428441

429-
fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
442+
fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool, saw_invalid_env_key: &mut bool) -> CStringArray {
430443
let mut result = CStringArray::with_capacity(env.len());
431444
for (mut k, v) in env {
445+
{
446+
let mut iter = k.as_bytes().iter();
447+
if iter.next().is_none() {
448+
*saw_invalid_env_key = true;
449+
continue;
450+
}
451+
if iter.any(|&b| b == b'=') {
452+
*saw_invalid_env_key = true;
453+
continue;
454+
}
455+
}
456+
432457
// Reserve additional space for '=' and null terminator
433458
k.reserve_exact(v.len() + 2);
434459
k.push("=");

library/std/src/sys/pal/unix/process/process_fuchsia.rs

+3-11
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,7 @@ impl Command {
2121
) -> io::Result<(Process, StdioPipes)> {
2222
let envp = self.capture_env();
2323

24-
if self.saw_nul() {
25-
return Err(io::const_io_error!(
26-
io::ErrorKind::InvalidInput,
27-
"nul byte found in provided data",
28-
));
29-
}
24+
self.validate_input()?;
3025

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

@@ -41,11 +36,8 @@ impl Command {
4136
}
4237

4338
pub fn exec(&mut self, default: Stdio) -> io::Error {
44-
if self.saw_nul() {
45-
return io::const_io_error!(
46-
io::ErrorKind::InvalidInput,
47-
"nul byte found in provided data",
48-
);
39+
if let Err(err) = self.validate_input() {
40+
return err;
4941
}
5042

5143
match self.setup_io(default, true) {

library/std/src/sys/pal/unix/process/process_unix.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,7 @@ impl Command {
6666

6767
let envp = self.capture_env();
6868

69-
if self.saw_nul() {
70-
return Err(io::const_io_error!(
71-
ErrorKind::InvalidInput,
72-
"nul byte found in provided data",
73-
));
74-
}
69+
self.validate_input()?;
7570

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

@@ -238,8 +233,8 @@ impl Command {
238233
pub fn exec(&mut self, default: Stdio) -> io::Error {
239234
let envp = self.capture_env();
240235

241-
if self.saw_nul() {
242-
return io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data",);
236+
if let Err(err) = self.validate_input() {
237+
return err;
243238
}
244239

245240
match self.setup_io(default, true) {

library/std/src/sys/pal/unix/process/process_vxworks.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,8 @@ impl Command {
2121
use crate::sys::cvt_r;
2222
let envp = self.capture_env();
2323

24-
if self.saw_nul() {
25-
return Err(io::const_io_error!(
26-
ErrorKind::InvalidInput,
27-
"nul byte found in provided data",
28-
));
29-
}
24+
self.validate_input()?;
25+
3026
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
3127
let mut p = Process { pid: 0, status: None };
3228

library/std/src/sys/pal/windows/process.rs

+30-6
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,36 @@ impl AsRef<OsStr> for EnvKey {
149149
}
150150
}
151151

152-
pub(crate) fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
153-
if str.as_ref().encode_wide().any(|b| b == 0) {
154-
Err(io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
155-
} else {
156-
Ok(str)
152+
153+
/// Returns an error if the provided string has a NUL byte anywhere or a `=`
154+
/// after the first character.
155+
fn ensure_env_var_name<T: AsRef<OsStr>>(s: T) -> io::Result<T> {
156+
fn inner(s: &OsStr) -> io::Result<()> {
157+
let err = || Err(io::const_io_error!(ErrorKind::InvalidInput, "nul or '=' byte found in provided data"));
158+
let mut iter = s.as_encoded_bytes().iter();
159+
if iter.next() == Some(&0) {
160+
return err();
161+
}
162+
if iter.any(|&b| b == 0 || b == b'=') {
163+
return err();
164+
}
165+
Ok(())
166+
}
167+
inner(s.as_ref())?;
168+
Ok(s)
169+
}
170+
171+
/// Returns an error if the provided string has a NUL byte anywhere.
172+
pub(crate) fn ensure_no_nuls<T: AsRef<OsStr>>(s: T) -> io::Result<T> {
173+
fn inner(s: &OsStr) -> io::Result<()> {
174+
if s.as_encoded_bytes().iter().any(|&b| b == 0) {
175+
Err(io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
176+
} else {
177+
Ok(())
178+
}
157179
}
180+
inner(s.as_ref())?;
181+
Ok(s)
158182
}
159183

160184
pub struct Command {
@@ -857,7 +881,7 @@ fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut
857881
}
858882

859883
for (k, v) in env {
860-
ensure_no_nuls(k.os_string)?;
884+
ensure_env_var_name(k.os_string)?;
861885
blk.extend(k.utf16);
862886
blk.push('=' as u16);
863887
blk.extend(ensure_no_nuls(v)?.encode_wide());

0 commit comments

Comments
 (0)