| 1 | use std::{ |
| 2 | collections::HashMap, |
| 3 | env, |
| 4 | ffi::OsString, |
| 5 | fs, |
| 6 | path::{Path, PathBuf}, |
| 7 | }; |
| 8 | |
| 9 | use crate::common::{error::Error, resolve::CurrentUser}; |
| 10 | use crate::exec::{RunOptions, Umask}; |
| 11 | use crate::log::user_warn; |
| 12 | use crate::system::{Group, User}; |
| 13 | use crate::{common::resolve::is_valid_executable, system::interface::UserId}; |
| 14 | |
| 15 | type Environment = HashMap<OsString, OsString>; |
| 16 | |
| 17 | use super::cli::SuRunOptions; |
| 18 | |
| 19 | const VALID_LOGIN_SHELLS_LIST: &str = "/etc/shells"; |
| 20 | const FALLBACK_LOGIN_SHELL: &str = "/bin/sh"; |
| 21 | |
| 22 | // TODO: use _PATH_STDPATH and _PATH_DEFPATH_ROOT from paths.h |
| 23 | const PATH_DEFAULT: &str = "/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"; |
| 24 | const PATH_DEFAULT_ROOT: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; |
| 25 | |
| 26 | #[derive(Debug)] |
| 27 | pub(crate) struct SuContext { |
| 28 | command: PathBuf, |
| 29 | arguments: Vec<OsString>, |
| 30 | pub(crate) options: SuRunOptions, |
| 31 | pub(crate) environment: Environment, |
| 32 | pub(crate) user: User, |
| 33 | pub(crate) requesting_user: CurrentUser, |
| 34 | group: Group, |
| 35 | } |
| 36 | |
| 37 | /// check that a shell is not restricted / exists in /etc/shells |
| 38 | fn is_restricted(shell: &Path) -> bool { |
| 39 | if let Some(pattern) = shell.as_os_str().to_str() { |
| 40 | if let Ok(contents) = fs::read_to_string(VALID_LOGIN_SHELLS_LIST) { |
| 41 | return !contents.lines().any(|l| l == pattern); |
| 42 | } else { |
| 43 | return FALLBACK_LOGIN_SHELL != pattern; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | true |
| 48 | } |
| 49 | |
| 50 | impl SuContext { |
| 51 | pub(crate) fn from_env(options: SuRunOptions) -> Result<SuContext, Error> { |
| 52 | // resolve environment, reset if this is a login |
| 53 | let mut environment = if options.login { |
| 54 | Environment::default() |
| 55 | } else { |
| 56 | env::vars_os().collect::<Environment>() |
| 57 | }; |
| 58 | |
| 59 | // Don't reset the environment variables specified in the |
| 60 | // comma-separated list when clearing the environment for |
| 61 | // --login. The whitelist is ignored for the environment |
| 62 | // variables HOME, SHELL, USER, LOGNAME, and PATH. |
| 63 | if options.login { |
| 64 | if let Some(value) = env::var_os("TERM") { |
| 65 | environment.insert("TERM".into(), value); |
| 66 | } |
| 67 | |
| 68 | for name in options.whitelist_environment.iter() { |
| 69 | if let Some(value) = env::var_os(name) { |
| 70 | environment.insert(name.into(), value); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | let requesting_user = CurrentUser::resolve()?; |
| 76 | |
| 77 | // resolve target user |
| 78 | let mut user = User::from_name(options.user.as_cstr())? |
| 79 | .ok_or_else(|| Error::UserNotFound(options.user.clone().into()))?; |
| 80 | |
| 81 | // check the current user is root |
| 82 | let is_current_root = User::real_uid() == UserId::ROOT; |
| 83 | let is_target_root = options.user == "root"; |
| 84 | |
| 85 | // only root can set a (additional) group |
| 86 | if !is_current_root && (!options.supp_group.is_empty() || !options.group.is_empty()) { |
| 87 | return Err(Error::Options( |
| 88 | "only root can specify alternative groups".to_owned(), |
| 89 | )); |
| 90 | } |
| 91 | |
| 92 | // resolve target group |
| 93 | let mut group = user.primary_group()?; |
| 94 | |
| 95 | if !options.supp_group.is_empty() || !options.group.is_empty() { |
| 96 | user.groups.clear(); |
| 97 | } |
| 98 | |
| 99 | for group_name in options.group.iter() { |
| 100 | let primary_group = Group::from_name(group_name.as_cstr())? |
| 101 | .ok_or_else(|| Error::GroupNotFound(group_name.clone().into()))?; |
| 102 | |
| 103 | // last argument is the primary group |
| 104 | group = primary_group.clone(); |
| 105 | user.groups.insert(0, primary_group.gid); |
| 106 | } |
| 107 | |
| 108 | // add additional group if current user is root |
| 109 | for (index, group_name) in options.supp_group.iter().enumerate() { |
| 110 | let supp_group = Group::from_name(group_name.as_cstr())? |
| 111 | .ok_or_else(|| Error::GroupNotFound(group_name.clone().into()))?; |
| 112 | |
| 113 | // set primary group if none was provided |
| 114 | if index == 0 && options.group.is_empty() { |
| 115 | group = supp_group.clone(); |
| 116 | } |
| 117 | |
| 118 | user.groups.push(supp_group.gid); |
| 119 | } |
| 120 | |
| 121 | // the shell specified with --shell |
| 122 | // the shell specified in the environment variable SHELL, if the --preserve-environment option is used |
| 123 | // the shell listed in the passwd entry of the target user |
| 124 | let user_shell = &user.shell; |
| 125 | |
| 126 | let mut command = options |
| 127 | .shell |
| 128 | .as_ref() |
| 129 | .cloned() |
| 130 | .or_else(|| { |
| 131 | if options.preserve_environment && is_current_root { |
| 132 | environment.get(&OsString::from("SHELL")).map(|v| v.into()) |
| 133 | } else { |
| 134 | None |
| 135 | } |
| 136 | }) |
| 137 | .unwrap_or(user_shell.clone()); |
| 138 | |
| 139 | // If the target user has a restricted shell (i.e. the shell field of |
| 140 | // this user's entry in /etc/passwd is not listed in /etc/shells), |
| 141 | // then the --shell option or the $SHELL environment variable won't be |
| 142 | // taken into account, unless su is called by root. |
| 143 | if is_restricted(user_shell.as_path()) && !is_current_root { |
| 144 | command = user_shell.to_path_buf(); |
| 145 | user_warn!("using restricted shell {path}", path = command.display()); |
| 146 | } |
| 147 | |
| 148 | if !command.exists() { |
| 149 | return Err(Error::CommandNotFound(command)); |
| 150 | } |
| 151 | |
| 152 | if !is_valid_executable(&command) { |
| 153 | return Err(Error::InvalidCommand(command)); |
| 154 | } |
| 155 | |
| 156 | // pass command to shell |
| 157 | let arguments = if let Some(command) = &options.command { |
| 158 | vec!["-c".into(), command.into()] |
| 159 | } else { |
| 160 | options.arguments.clone() |
| 161 | }; |
| 162 | |
| 163 | if options.login { |
| 164 | environment.insert( |
| 165 | "PATH".into(), |
| 166 | if is_target_root { |
| 167 | PATH_DEFAULT_ROOT |
| 168 | } else { |
| 169 | PATH_DEFAULT |
| 170 | } |
| 171 | .into(), |
| 172 | ); |
| 173 | } |
| 174 | |
| 175 | if !options.preserve_environment { |
| 176 | // extend environment with fixed variables |
| 177 | environment.insert("HOME".into(), user.home.clone().into()); |
| 178 | environment.insert("SHELL".into(), command.clone().into()); |
| 179 | |
| 180 | if !is_target_root || options.login { |
| 181 | environment.insert("USER".into(), options.user.clone().into()); |
| 182 | environment.insert("LOGNAME".into(), options.user.clone().into()); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | Ok(SuContext { |
| 187 | command, |
| 188 | arguments, |
| 189 | options, |
| 190 | environment, |
| 191 | user, |
| 192 | requesting_user, |
| 193 | group, |
| 194 | }) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | impl SuContext { |
| 199 | pub(crate) fn as_run_options(&self) -> RunOptions<'_> { |
| 200 | RunOptions { |
| 201 | command: &self.command, |
| 202 | arguments: &self.arguments, |
| 203 | arg0: None, |
| 204 | chdir: None, |
| 205 | is_login: self.options.login, |
| 206 | user: &self.user, |
| 207 | group: &self.group, |
| 208 | umask: Umask::Preserve, |
| 209 | |
| 210 | background: false, |
| 211 | use_pty: true, |
| 212 | noexec: false, |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | #[cfg(test)] |
| 218 | mod tests { |
| 219 | use std::path::PathBuf; |
| 220 | |
| 221 | use crate::{ |
| 222 | common::{Error, resolve::CurrentUser}, |
| 223 | su::cli::{SuAction, SuOptions, SuRunOptions}, |
| 224 | su::context::{User, is_restricted}, |
| 225 | }; |
| 226 | |
| 227 | use super::SuContext; |
| 228 | |
| 229 | fn get_options(args: &[&str]) -> SuRunOptions { |
| 230 | let mut args = args.iter().map(|s| s.to_string()).collect::<Vec<String>>(); |
| 231 | args.insert(0, "/bin/su".to_string()); |
| 232 | let SuAction::Run(options) = SuOptions::parse_arguments(args) |
| 233 | .unwrap() |
| 234 | .validate() |
| 235 | .unwrap() |
| 236 | else { |
| 237 | panic!(); |
| 238 | }; |
| 239 | |
| 240 | options |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn su_to_root() { |
| 245 | let options = get_options(&["root"]); |
| 246 | let context = SuContext::from_env(options).unwrap(); |
| 247 | |
| 248 | assert_eq!(context.user.name, "root"); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn group_as_non_root() { |
| 253 | let options = get_options(&["-g", "root"]); |
| 254 | let result = SuContext::from_env(options); |
| 255 | let expected = Error::Options("only root can specify alternative groups".to_owned()); |
| 256 | |
| 257 | assert!(result.is_err()); |
| 258 | assert_eq!(format!("{}", result.err().unwrap()), format!("{expected}")); |
| 259 | } |
| 260 | |
| 261 | #[test] |
| 262 | fn invalid_shell() { |
| 263 | let cur_user = CurrentUser::resolve().unwrap(); |
| 264 | let daemon = User::from_name(c"daemon").unwrap().unwrap(); |
| 265 | for user in [&cur_user, &daemon] { |
| 266 | let options = get_options(&["-s", "/not/a/shell", &user.name]); |
| 267 | let result = SuContext::from_env(options); |
| 268 | let expected; |
| 269 | |
| 270 | // this test is allowed to fail if run as root -- do not run unit tests as root |
| 271 | if is_restricted(&user.shell) { |
| 272 | if let Ok(ctx) = result { |
| 273 | // some linux distro's actually provide a "/bin/nologin" command; in this |
| 274 | // case we test that the --shell command is properly ignored |
| 275 | assert_eq!(ctx.command, user.shell); |
| 276 | return; |
| 277 | } else { |
| 278 | // others (Fedora) do not |
| 279 | expected = Error::CommandNotFound(PathBuf::from(&user.shell)); |
| 280 | } |
| 281 | } else { |
| 282 | expected = Error::CommandNotFound(PathBuf::from("/not/a/shell")); |
| 283 | } |
| 284 | |
| 285 | assert!(result.is_err()); |
| 286 | assert_eq!(format!("{}", result.err().unwrap()), format!("{expected}")); |
| 287 | } |
| 288 | } |
| 289 | } |