| 1 | use crate::system::interface::UserId; |
| 2 | use crate::system::{Group, User}; |
| 3 | use core::fmt; |
| 4 | use std::{ |
| 5 | env, |
| 6 | ffi::CStr, |
| 7 | fs, io, ops, |
| 8 | os::unix::prelude::MetadataExt, |
| 9 | path::{Path, PathBuf}, |
| 10 | str::FromStr, |
| 11 | }; |
| 12 | |
| 13 | use super::SudoString; |
| 14 | use super::{Error, context::LaunchType}; |
| 15 | |
| 16 | #[derive(PartialEq, Debug)] |
| 17 | enum NameOrId<'a, T: FromStr> { |
| 18 | Name(&'a SudoString), |
| 19 | Id(T), |
| 20 | } |
| 21 | |
| 22 | impl<'a, T: FromStr> NameOrId<'a, T> { |
| 23 | pub fn parse(input: &'a SudoString) -> Option<Self> { |
| 24 | if input.is_empty() { |
| 25 | None |
| 26 | } else if let Some(stripped) = input.strip_prefix('#') { |
| 27 | stripped.parse::<T>().ok().map(|id| Self::Id(id)) |
| 28 | } else { |
| 29 | Some(Self::Name(input)) |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Clone)] |
| 35 | pub struct CurrentUser { |
| 36 | inner: User, |
| 37 | } |
| 38 | |
| 39 | impl From<CurrentUser> for User { |
| 40 | fn from(value: CurrentUser) -> Self { |
| 41 | value.inner |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl fmt::Debug for CurrentUser { |
| 46 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 47 | f.debug_tuple("CurrentUser").field(&self.inner).finish() |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl ops::Deref for CurrentUser { |
| 52 | type Target = User; |
| 53 | |
| 54 | fn deref(&self) -> &Self::Target { |
| 55 | &self.inner |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl CurrentUser { |
| 60 | #[cfg(test)] |
| 61 | pub fn fake(user: User) -> Self { |
| 62 | Self { inner: user } |
| 63 | } |
| 64 | |
| 65 | pub fn resolve() -> Result<Self, Error> { |
| 66 | Ok(Self { |
| 67 | inner: User::real()?.ok_or(Error::UserNotFound("current user".to_string()))?, |
| 68 | }) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | #[derive(Clone, Debug)] |
| 73 | pub struct AuthUser(User); |
| 74 | |
| 75 | impl AuthUser { |
| 76 | pub fn from_current_user(user: CurrentUser) -> Self { |
| 77 | Self(user.inner) |
| 78 | } |
| 79 | |
| 80 | pub fn resolve_root_for_rootpw() -> Result<Self, Error> { |
| 81 | Ok(Self( |
| 82 | User::from_uid(UserId::ROOT)?.ok_or(Error::UserNotFound("root".to_string()))?, |
| 83 | )) |
| 84 | } |
| 85 | |
| 86 | pub fn from_user_for_targetpw(user: User) -> Self { |
| 87 | Self(user) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl ops::Deref for AuthUser { |
| 92 | type Target = User; |
| 93 | |
| 94 | fn deref(&self) -> &Self::Target { |
| 95 | &self.0 |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | type Shell = Option<PathBuf>; |
| 100 | |
| 101 | pub(super) fn resolve_shell( |
| 102 | launch_type: LaunchType, |
| 103 | current_user: &User, |
| 104 | target_user: &User, |
| 105 | ) -> Shell { |
| 106 | match launch_type { |
| 107 | LaunchType::Login => Some(target_user.shell.clone()), |
| 108 | |
| 109 | LaunchType::Shell => Some( |
| 110 | env::var("SHELL") |
| 111 | .map(|s| s.into()) |
| 112 | .unwrap_or_else(|_| current_user.shell.clone()), |
| 113 | ), |
| 114 | |
| 115 | LaunchType::Direct => None, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | pub(crate) fn resolve_target_user_and_group( |
| 120 | target_user_name_or_id: &Option<SudoString>, |
| 121 | target_group_name_or_id: &Option<SudoString>, |
| 122 | current_user: &CurrentUser, |
| 123 | ) -> Result<(User, Group), Error> { |
| 124 | // resolve user name or #<id> to a user |
| 125 | let mut target_user = |
| 126 | resolve_from_name_or_id(target_user_name_or_id, User::from_name, User::from_uid)?; |
| 127 | |
| 128 | // resolve group name or #<id> to a group |
| 129 | let mut target_group = |
| 130 | resolve_from_name_or_id(target_group_name_or_id, Group::from_name, Group::from_gid)?; |
| 131 | |
| 132 | match (&target_user_name_or_id, &target_group_name_or_id) { |
| 133 | // when -g is specified, but -u is not specified default -u to the current user |
| 134 | (None, Some(_)) => { |
| 135 | target_user = Some(current_user.clone().into()); |
| 136 | } |
| 137 | // when -u is specified but -g is not specified, default -g to the primary group of the specified user |
| 138 | (Some(_), None) => { |
| 139 | if let Some(user) = &target_user { |
| 140 | target_group = Some(user.primary_group()?); |
| 141 | } |
| 142 | } |
| 143 | // when no -u or -g is specified, default to root:root |
| 144 | (None, None) => { |
| 145 | target_user = User::from_name(c"root")?; |
| 146 | target_group = Group::from_name(if cfg!(target_os = "linux") { |
| 147 | c"root" |
| 148 | } else { |
| 149 | c"wheel" |
| 150 | })?; |
| 151 | } |
| 152 | _ => {} |
| 153 | } |
| 154 | |
| 155 | match (target_user, target_group) { |
| 156 | (Some(user), Some(group)) => { |
| 157 | // resolve success |
| 158 | Ok((user, group)) |
| 159 | } |
| 160 | // group name or id not found |
| 161 | (Some(_), None) => Err(Error::GroupNotFound( |
| 162 | target_group_name_or_id |
| 163 | .as_deref() |
| 164 | .unwrap_or_default() |
| 165 | .to_string(), |
| 166 | )), |
| 167 | // user (and maybe group) name or id not found |
| 168 | _ => Err(Error::UserNotFound( |
| 169 | target_user_name_or_id |
| 170 | .as_deref() |
| 171 | .unwrap_or_default() |
| 172 | .to_string(), |
| 173 | )), |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn resolve_from_name_or_id<T, I, E>( |
| 178 | input: &Option<SudoString>, |
| 179 | from_name: impl FnOnce(&CStr) -> Result<Option<T>, E>, |
| 180 | from_id: impl FnOnce(I) -> Result<Option<T>, E>, |
| 181 | ) -> Result<Option<T>, E> |
| 182 | where |
| 183 | I: FromStr, |
| 184 | { |
| 185 | match input.as_ref().and_then(NameOrId::parse) { |
| 186 | Some(NameOrId::Name(name)) => from_name(name.as_cstr()), |
| 187 | Some(NameOrId::Id(id)) => from_id(id), |
| 188 | None => Ok(None), |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// Check whether a path points to a regular file and any executable flag is set |
| 193 | pub(crate) fn is_valid_executable(path: &Path) -> bool { |
| 194 | if path.is_file() { |
| 195 | match fs::metadata(path) { |
| 196 | Ok(meta) => meta.mode() & 0o111 != 0, |
| 197 | _ => false, |
| 198 | } |
| 199 | } else { |
| 200 | false |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /// Resolve a executable name based in the PATH environment variable |
| 205 | /// When resolving a path, this code checks whether the target file is |
| 206 | /// a regular file and has any executable bits set. It does not specifically |
| 207 | /// check for user, group, or others' executable bit. |
| 208 | pub(crate) fn resolve_path(command: &Path, path: &str) -> Option<PathBuf> { |
| 209 | // Depending on the security policy, the user's PATH environment variable may be modified, |
| 210 | // replaced, or passed unchanged to the program that sudo executes. |
| 211 | |
| 212 | path.split(':') |
| 213 | .map(Path::new) |
| 214 | // ignore all relative paths ("", "." or "./") |
| 215 | .filter(|path| path.is_absolute()) |
| 216 | // construct a possible executable absolute path candidate |
| 217 | .map(|path| path.join(command)) |
| 218 | // check whether the candidate is a regular file and any executable flag is set |
| 219 | .find(|arg| is_valid_executable(arg)) |
| 220 | } |
| 221 | |
| 222 | #[cfg(test)] |
| 223 | mod tests { |
| 224 | use std::path::Path; |
| 225 | |
| 226 | use crate::common::resolve::CurrentUser; |
| 227 | use crate::system::ROOT_GROUP_NAME; |
| 228 | |
| 229 | use super::{NameOrId, is_valid_executable, resolve_path, resolve_target_user_and_group}; |
| 230 | |
| 231 | #[test] |
| 232 | fn test_resolve_path() { |
| 233 | // Assume any linux distro has utilities in this PATH |
| 234 | let path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; |
| 235 | |
| 236 | assert!(is_valid_executable( |
| 237 | &resolve_path(Path::new("yes"), path).unwrap() |
| 238 | )); |
| 239 | |
| 240 | assert!(is_valid_executable( |
| 241 | &resolve_path(Path::new("whoami"), path).unwrap() |
| 242 | )); |
| 243 | |
| 244 | assert!(is_valid_executable( |
| 245 | &resolve_path(Path::new("env"), path).unwrap() |
| 246 | )); |
| 247 | assert_eq!(resolve_path(Path::new("thisisnotonyourfs"), path), None); |
| 248 | assert_eq!(resolve_path(Path::new("thisisnotonyourfs"), "."), None); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn test_name_or_id() { |
| 253 | assert_eq!(NameOrId::<u32>::parse(&"".into()), None); |
| 254 | assert_eq!( |
| 255 | NameOrId::<u32>::parse(&"mies".into()), |
| 256 | Some(NameOrId::Name(&"mies".into())) |
| 257 | ); |
| 258 | assert_eq!( |
| 259 | NameOrId::<u32>::parse(&"1337".into()), |
| 260 | Some(NameOrId::Name(&"1337".into())) |
| 261 | ); |
| 262 | assert_eq!( |
| 263 | NameOrId::<u32>::parse(&"#1337".into()), |
| 264 | Some(NameOrId::Id(1337)) |
| 265 | ); |
| 266 | assert_eq!(NameOrId::<u32>::parse(&"#-1".into()), None); |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn test_resolve_target_user_and_group() { |
| 271 | let current_user = CurrentUser::resolve().unwrap(); |
| 272 | |
| 273 | // fallback to root |
| 274 | let (user, group) = resolve_target_user_and_group(&None, &None, ¤t_user).unwrap(); |
| 275 | assert_eq!(user.name, "root"); |
| 276 | assert_eq!(group.name.unwrap(), ROOT_GROUP_NAME); |
| 277 | |
| 278 | // unknown user |
| 279 | let result = |
| 280 | resolve_target_user_and_group(&Some("non_existing_ghost".into()), &None, ¤t_user); |
| 281 | assert!(result.is_err()); |
| 282 | |
| 283 | // unknown user |
| 284 | let result = |
| 285 | resolve_target_user_and_group(&None, &Some("non_existing_ghost".into()), ¤t_user); |
| 286 | assert!(result.is_err()); |
| 287 | |
| 288 | // fallback to current user when different group specified |
| 289 | let (user, group) = |
| 290 | resolve_target_user_and_group(&None, &Some(ROOT_GROUP_NAME.into()), ¤t_user) |
| 291 | .unwrap(); |
| 292 | assert_eq!(user.name, current_user.name); |
| 293 | assert_eq!(group.name.unwrap(), ROOT_GROUP_NAME); |
| 294 | |
| 295 | // fallback to current users group when no group specified |
| 296 | let (user, group) = |
| 297 | resolve_target_user_and_group(&Some(current_user.name.clone()), &None, ¤t_user) |
| 298 | .unwrap(); |
| 299 | assert_eq!(user.name, current_user.name); |
| 300 | assert_eq!(group.gid, current_user.gid); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | /// Resolve symlinks in all the directories leading up to a file, but |
| 305 | /// not the file itself; this allows sudo to specify a precise policy with |
| 306 | /// tools like busybox or pgrep (which is a symlink to pgrep on systems) |
| 307 | /// This function will check for existence. |
| 308 | pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> { |
| 309 | let reconstructed_path = canonicalize_newfile(path)?; |
| 310 | |
| 311 | // access the object to generate the regular error if it does not exist |
| 312 | let _ = fs::metadata(&reconstructed_path)?; |
| 313 | |
| 314 | Ok(reconstructed_path) |
| 315 | } |
| 316 | |
| 317 | /// Resolve symlinks in all the directories leading up to a file, but |
| 318 | /// not the file itself; this allows us to keep symlinks as is, and will |
| 319 | /// also work on non-existing files. |
| 320 | pub fn canonicalize_newfile<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> { |
| 321 | let path = path.as_ref(); |
| 322 | let Some(parent) = path.parent() else { |
| 323 | // path is "/" or a prefix |
| 324 | return Ok(path.to_path_buf()); |
| 325 | }; |
| 326 | |
| 327 | let canon_path = fs::canonicalize(parent)?; |
| 328 | |
| 329 | let reconstructed_path = if let Some(file_name) = path.file_name() { |
| 330 | canon_path.join(file_name) |
| 331 | } else { |
| 332 | canon_path |
| 333 | }; |
| 334 | |
| 335 | Ok(reconstructed_path) |
| 336 | } |
| 337 | |
| 338 | #[cfg(test)] |
| 339 | mod test { |
| 340 | use super::canonicalize; |
| 341 | use std::path::Path; |
| 342 | |
| 343 | #[test] |
| 344 | fn canonicalization() { |
| 345 | assert_eq!(canonicalize("/").unwrap(), Path::new("/")); |
| 346 | assert!(canonicalize("").is_err()); |
| 347 | if cfg!(any(target_os = "linux")) { |
| 348 | // this test REQUIRES /usr/bin/unxz to be a symlink for /usr/bin/xz or /usr/bin/busybox |
| 349 | assert!(Path::new("/bin").is_symlink()); |
| 350 | assert!(Path::new("/usr/bin/unxz").is_symlink()); |
| 351 | assert_eq!( |
| 352 | canonicalize("/usr/bin/unxz").unwrap(), |
| 353 | Path::new("/usr/bin/unxz") |
| 354 | ); |
| 355 | // this assumes /bin is a symlink on /usr/bin, like it is on modern Debian/Ubuntu |
| 356 | assert_eq!( |
| 357 | canonicalize("/bin/unxz").unwrap(), |
| 358 | Path::new("/usr/bin/unxz") |
| 359 | ); |
| 360 | } else if cfg!(target_os = "freebsd") { |
| 361 | // this test REQUIRES /usr/bin/pkill to be a symlink |
| 362 | assert!(Path::new("/usr/bin/pkill").is_symlink()); |
| 363 | assert_eq!( |
| 364 | canonicalize("/usr/bin/pkill").unwrap(), |
| 365 | Path::new("/usr/bin/pkill") |
| 366 | ); |
| 367 | assert_eq!(canonicalize("/bin/pkill").unwrap(), Path::new("/bin/pkill")); |
| 368 | } else { |
| 369 | panic!( |
| 370 | "canonicalization test not yet adapted for {}", |
| 371 | std::env::consts::OS |
| 372 | ); |
| 373 | } |
| 374 | } |
| 375 | } |