Debian Codegraph @

src/sudo/env/environment.rs

raw symbols SCIP
1 use std::{
2 collections::{HashMap, HashSet},
3 ffi::{OsStr, OsString},
4 os::unix::prelude::OsStrExt,
5 };
6
7 use crate::common::{CommandAndArguments, Context, Error, context::LaunchType};
8 use crate::sudoers::Restrictions;
9 use crate::system::{PATH_MAX, audit::zoneinfo_path};
10
11 use super::wildcard_match::wildcard_match;
12
13 // TODO: use _PATH_STDPATH from paths.h
14 pub(crate) const PATH_DEFAULT: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
15
16 pub type Environment = HashMap<OsString, OsString>;
17
18 /// obtain the system environment
19 pub fn system_environment() -> Environment {
20 std::env::vars_os().collect()
21 }
22
23 /// check byte slice contains with given byte slice
24 fn contains_subsequence(haystack: &[u8], needle: &[u8]) -> bool {
25 haystack
26 .windows(needle.len())
27 .any(|window| window == needle)
28 }
29
30 /// Formats the command and arguments passed for the SUDO_COMMAND
31 /// environment variable. Limit the length to 4096 bytes to prevent
32 /// execve failure for very long argument vectors
33 fn format_command(command_and_arguments: &CommandAndArguments) -> OsString {
34 let mut formatted: OsString = command_and_arguments.command.clone().into();
35
36 for arg in &command_and_arguments.arguments {
37 if formatted.len() + arg.len() < 4096 {
38 formatted.push(" ");
39 formatted.push(arg);
40 }
41 }
42
43 formatted
44 }
45
46 /// Construct sudo-specific environment variables
47 fn add_extra_env(
48 context: &Context,
49 cfg: &Restrictions,
50 sudo_ps1: Option<OsString>,
51 environment: &mut Environment,
52 ) {
53 // current user
54 environment.insert("SUDO_COMMAND".into(), format_command(&context.command));
55 environment.insert(
56 "SUDO_UID".into(),
57 context.current_user.uid.to_string().into(),
58 );
59 environment.insert(
60 "SUDO_GID".into(),
61 context.current_user.gid.to_string().into(),
62 );
63 environment.insert("SUDO_USER".into(), context.current_user.name.clone().into());
64 environment.insert("SUDO_HOME".into(), context.current_user.home.clone().into());
65 // The current SHELL variable should determine the shell to run when -s is passed, if none set use passwd entry
66 environment
67 .entry("SHELL".into())
68 .or_insert_with(|| context.target_user.shell.clone().into());
69 // HOME: Set to the home directory of the target user if -i or -H are specified, env_reset or always_set_home are
70 // set in sudoers, or when the -s option is specified and set_home is set in sudoers.
71 // In sudo-rs env_reset is mandatory, so we always set HOME unless it's in the env_keep list.
72 environment
73 .entry("HOME".into())
74 .or_insert_with(|| context.target_user.home.clone().into());
75
76 match (
77 environment.get(OsStr::new("LOGNAME")),
78 environment.get(OsStr::new("USER")),
79 ) {
80 // Set to the login name of the target user when the -i option is specified,
81 // when the set_logname option is enabled in sudoers, or when the env_reset option
82 // is enabled in sudoers (unless LOGNAME is present in the env_keep list).
83 // Since we always want to do env_reset -> always set these except when present in env
84 (None, None) => {
85 environment.insert("LOGNAME".into(), context.target_user.name.clone().into());
86 environment.insert("USER".into(), context.target_user.name.clone().into());
87 }
88 // LOGNAME should be set to the same value as USER if the latter is preserved.
89 (None, Some(user)) => {
90 environment.insert("LOGNAME".into(), user.clone());
91 }
92 // USER should be set to the same value as LOGNAME if the latter is preserved.
93 (Some(logname), None) => {
94 environment.insert("USER".into(), logname.clone());
95 }
96 (Some(_), Some(_)) => {}
97 }
98
99 // Overwrite PATH when secure_path is set
100 if let Some(secure_path) = &cfg.path {
101 // assign path by env path or secure_path configuration
102 environment.insert("PATH".into(), secure_path.into());
103 }
104 // If the PATH and TERM variables are not preserved from the user's environment, they will be set to default value
105 environment
106 .entry("PATH".into())
107 .or_insert_with(|| PATH_DEFAULT.into());
108 // If the TERM variable is not preserved from the user's environment, it will be set to default value
109 environment
110 .entry("TERM".into())
111 .or_insert_with(|| "unknown".into());
112 // The SUDO_PS1 variable requires special treatment as the PS1 variable must be set in the
113 // target environment to the same value of SUDO_PS1 if the latter is set.
114 if let Some(sudo_ps1_value) = sudo_ps1 {
115 // set PS1 to the SUDO_PS1 value in the target environment
116 environment.insert("PS1".into(), sudo_ps1_value);
117 }
118 }
119
120 /// Check a string only contains printable (non-space) characters
121 fn is_printable(input: &[u8]) -> bool {
122 input
123 .iter()
124 .all(|c| c.is_ascii_alphanumeric() || c.is_ascii_punctuation())
125 }
126
127 /// The TZ variable is considered unsafe if any of the following are true:
128 /// It consists of a fully-qualified path name, optionally prefixed with a colon (‘:’), that does not match the location of the zoneinfo directory.
129 /// It contains a .. path element.
130 /// It contains white space or non-printable characters.
131 /// It is longer than the value of PATH_MAX.
132 fn is_safe_tz(value: &[u8]) -> bool {
133 let check_value = if value.starts_with(b":") {
134 &value[1..]
135 } else {
136 value
137 };
138
139 if check_value.starts_with(b"/") {
140 if let Some(path_zoneinfo) = zoneinfo_path() {
141 if !check_value.starts_with(path_zoneinfo.as_bytes())
142 || check_value.get(path_zoneinfo.len()) != Some(&b'/')
143 {
144 return false;
145 }
146 } else {
147 return false;
148 }
149 }
150
151 !contains_subsequence(check_value, "..".as_bytes())
152 && is_printable(check_value)
153 && check_value.len() < PATH_MAX as usize
154 }
155
156 /// Check whether the needle exists in a haystack, in which the haystack is a list of patterns, possibly containing wildcards
157 fn in_table(needle: (&OsStr, &OsStr), haystack: &HashSet<String>) -> bool {
158 haystack.iter().any(|pattern| {
159 if let Some((key, value)) = pattern.split_once('=') {
160 wildcard_match(needle.0.as_bytes(), key.as_bytes())
161 && wildcard_match(needle.1.as_bytes(), value.as_bytes())
162 } else {
163 wildcard_match(needle.0.as_bytes(), pattern.as_bytes())
164 }
165 })
166 }
167
168 /// Determine whether a specific environment variable should be kept
169 fn should_keep(key: &OsStr, value: &OsStr, cfg: &Restrictions) -> bool {
170 if value.as_bytes().starts_with("()".as_bytes()) {
171 return false;
172 }
173
174 if cfg.path.is_some() && key == "PATH" {
175 return false;
176 }
177
178 if key == "TZ" {
179 return in_table((key, value), cfg.env_keep)
180 || (in_table((key, value), cfg.env_check) && is_safe_tz(value.as_bytes()));
181 }
182
183 if in_table((key, value), cfg.env_check) {
184 return !value.as_bytes().iter().any(|c| *c == b'%' || *c == b'/');
185 }
186
187 in_table((key, value), cfg.env_keep)
188 }
189
190 /// Construct the final environment from the current one and a sudo context
191 /// see <https://github.com/sudo-project/sudo/blob/main/plugins/sudoers/env.c> for the original implementation
192 /// see <https://www.sudo.ws/docs/man/sudoers.man/#Command_environment> for the original documentation
193 ///
194 /// The HOME, SHELL, LOGNAME and USER environment variables are initialized based on the target user
195 /// and the SUDO_* variables are set based on the invoking user.
196 ///
197 /// Additional variables, such as DISPLAY, PATH and TERM, are preserved from the invoking user's
198 /// environment if permitted by the env_check, or env_keep options
199 ///
200 /// If the PATH and TERM variables are not preserved from the user's environment, they will be set to default value
201 ///
202 /// Environment variables with a value beginning with ‘()’ are removed
203 pub fn get_target_environment(
204 current_env: Environment,
205 additional_env: impl IntoIterator<Item = (OsString, OsString)>,
206 user_override: Vec<(String, String)>,
207 context: &Context,
208 settings: &Restrictions,
209 ) -> Result<Environment, Error> {
210 // retrieve SUDO_PS1 value to set a PS1 value as additional environment
211 let sudo_ps1 = current_env.get(OsStr::new("SUDO_PS1")).cloned();
212
213 // variables preserved from the invoking user's environment by the
214 // env_keep list take precedence over those in the PAM environment
215 let mut environment: HashMap<_, _> = additional_env.into_iter().collect();
216
217 let login_vars: &[_] = if context.launch == LaunchType::Login {
218 &["HOME", "SHELL", "USER", "LOGNAME"].map(OsStr::new)
219 } else {
220 &[]
221 };
222
223 environment.extend(current_env.into_iter().filter(|(key, value)| {
224 !login_vars.contains(&key.as_os_str()) && should_keep(key, value, settings)
225 }));
226
227 add_extra_env(context, settings, sudo_ps1, &mut environment);
228
229 let mut rejected_vars = Vec::new();
230 for (key, value) in user_override {
231 if should_keep(OsStr::new(&key), OsStr::new(&value), settings) {
232 environment.insert(key.into(), value.into());
233 } else {
234 rejected_vars.push(key);
235 }
236 }
237 if !rejected_vars.is_empty() {
238 return Err(Error::EnvironmentVar(rejected_vars));
239 }
240
241 Ok(environment)
242 }
243
244 /// Extend the environment with user-supplied info
245 pub fn dangerous_extend<S>(env: &mut Environment, user_override: impl IntoIterator<Item = (S, S)>)
246 where
247 S: Into<OsString>,
248 {
249 env.extend(
250 user_override
251 .into_iter()
252 .map(|(key, value)| (key.into(), value.into())),
253 )
254 }
255
256 #[cfg(test)]
257 mod tests {
258 use super::{is_safe_tz, should_keep, zoneinfo_path};
259 use std::{collections::HashSet, ffi::OsStr};
260
261 struct TestConfiguration {
262 keep: HashSet<String>,
263 check: HashSet<String>,
264 path: Option<String>,
265 }
266
267 impl TestConfiguration {
268 pub fn check_should_keep(&self, key: &str, value: &str, expected: bool) {
269 assert_eq!(
270 should_keep(
271 OsStr::new(key),
272 OsStr::new(value),
273 &crate::sudoers::Restrictions {
274 env_keep: &self.keep,
275 env_check: &self.check,
276 path: self.path.as_deref(),
277 chdir: crate::sudoers::DirChange::Strict(None),
278 trust_environment: false,
279 use_pty: true,
280 umask: crate::exec::Umask::Preserve,
281 #[cfg(feature = "apparmor")]
282 apparmor_profile: None,
283 noexec: false,
284 }
285 ),
286 expected,
287 "{} should {}",
288 key,
289 if expected { "be kept" } else { "not be kept" }
290 );
291 }
292 }
293
294 #[test]
295 fn test_filtering() {
296 let mut config = TestConfiguration {
297 keep: HashSet::from(["AAP".to_string(), "NOOT".to_string()]),
298 check: HashSet::from(["MIES".to_string(), "TZ".to_string()]),
299 path: Some("/bin".to_string()),
300 };
301
302 config.check_should_keep("AAP", "FOO", true);
303 config.check_should_keep("MIES", "BAR", true);
304 config.check_should_keep("AAP", "()=foo", false);
305 config.check_should_keep("TZ", "Europe/Amsterdam", true);
306 config.check_should_keep("TZ", "../Europe/Berlin", false);
307 config.check_should_keep("MIES", "FOO/BAR", false);
308 config.check_should_keep("MIES", "FOO/BAR", false);
309
310 config.keep.insert("PATH".to_string());
311 config.check_should_keep("PATH", "FOO", false);
312 config.path = None;
313 config.check_should_keep("PATH", "FOO", true);
314 }
315
316 #[allow(clippy::bool_assert_comparison)]
317 #[test]
318 fn test_tzinfo() {
319 let path_zoneinfo = zoneinfo_path().unwrap();
320 assert_eq!(is_safe_tz(b"Europe/Amsterdam"), true);
321 assert_eq!(
322 is_safe_tz(format!("{path_zoneinfo}/Europe/London").as_bytes()),
323 true
324 );
325 assert_eq!(
326 is_safe_tz(format!(":{path_zoneinfo}/Europe/Amsterdam").as_bytes()),
327 true
328 );
329 assert_eq!(is_safe_tz(b"/Europe/Amsterdam"), false);
330 assert_eq!(is_safe_tz(b"/schaap/Europe/Amsterdam"), false);
331 assert_eq!(
332 is_safe_tz(format!("{path_zoneinfo}/../Europe/London").as_bytes()),
333 false
334 );
335 assert_eq!(
336 is_safe_tz(format!("{path_zoneinfo}/../Europe/London").as_bytes()),
337 false
338 );
339 }
340 }