| 1 | #![forbid(unsafe_code)] |
| 2 | #![cfg_attr(not(feature = "unstable-remote-sudoers"), allow(unused_imports))] |
| 3 | |
| 4 | //! Code that checks (and in the future: lists) permissions in the sudoers file |
| 5 | |
| 6 | mod ast; |
| 7 | mod ast_names; |
| 8 | mod basic_parser; |
| 9 | mod char_stream; |
| 10 | mod entry; |
| 11 | mod tokens; |
| 12 | |
| 13 | use std::collections::{HashMap, HashSet}; |
| 14 | use std::ffi::OsString; |
| 15 | use std::fmt; |
| 16 | use std::io; |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | |
| 19 | use crate::common::resolve::{is_valid_executable, resolve_path}; |
| 20 | use crate::defaults; |
| 21 | use crate::log::auth_warn; |
| 22 | use crate::system::interface::{GroupId, UnixGroup, UnixUser, UserId}; |
| 23 | use crate::system::{self, audit}; |
| 24 | use ast::*; |
| 25 | use tokens::*; |
| 26 | |
| 27 | pub type Settings = defaults::Settings; |
| 28 | pub use basic_parser::Span; |
| 29 | |
| 30 | /// How many nested include files do we allow? |
| 31 | const INCLUDE_LIMIT: u8 = 128; |
| 32 | |
| 33 | /// Export some necessary symbols from modules |
| 34 | pub struct Error { |
| 35 | pub source: Option<PathBuf>, |
| 36 | pub location: Option<basic_parser::Span>, |
| 37 | pub message: String, |
| 38 | } |
| 39 | |
| 40 | /// A "Customiser" represents a "Defaults" setting that has 'late binding'; i.e. |
| 41 | /// cannot be determined simply by reading a sudoers configuration. This is used |
| 42 | /// for Defaults@host, Defaults:user, Defaults>runas and Defaults!cmd. |
| 43 | /// |
| 44 | /// I.e. the Setting modifications in the second part of the tuple only apply for |
| 45 | /// items explicitly matched by the first part of the tuple. |
| 46 | type Customiser<Scope> = (Scope, Vec<defaults::SettingsModifier>); |
| 47 | |
| 48 | #[derive(Default)] |
| 49 | pub struct Sudoers { |
| 50 | rules: Vec<PermissionSpec>, |
| 51 | aliases: AliasTable, |
| 52 | settings: Settings, |
| 53 | customisers: CustomiserTable, |
| 54 | } |
| 55 | |
| 56 | /// A structure that represents what the user wants to do |
| 57 | pub struct Request<'a, User: UnixUser, Group: UnixGroup> { |
| 58 | pub user: &'a User, |
| 59 | pub group: &'a Group, |
| 60 | pub command: &'a Path, |
| 61 | pub arguments: &'a [OsString], |
| 62 | } |
| 63 | |
| 64 | pub struct ListRequest<'a, User: UnixUser, Group: UnixGroup> { |
| 65 | pub inspected_user: &'a User, |
| 66 | pub target_user: &'a User, |
| 67 | pub target_group: &'a Group, |
| 68 | } |
| 69 | |
| 70 | #[derive(Default)] |
| 71 | #[cfg_attr(test, derive(Clone))] |
| 72 | pub struct Judgement { |
| 73 | flags: Option<Tag>, |
| 74 | settings: Settings, |
| 75 | } |
| 76 | |
| 77 | mod policy; |
| 78 | |
| 79 | pub use policy::{AuthenticatingUser, Authentication, Authorization, DirChange, Restrictions}; |
| 80 | |
| 81 | pub use self::entry::Entry; |
| 82 | |
| 83 | type MatchedCommand<'a> = (Option<&'a RunAs>, (Tag, &'a Spec<Command>)); |
| 84 | |
| 85 | /// This function takes a file argument for a sudoers file and processes it. |
| 86 | impl Sudoers { |
| 87 | pub fn open(path: impl AsRef<Path>) -> Result<(Sudoers, Vec<Error>), io::Error> { |
| 88 | let sudoers = open_sudoers(path.as_ref())?; |
| 89 | Ok(analyze(path.as_ref(), sudoers)) |
| 90 | } |
| 91 | |
| 92 | pub fn read<R: io::Read, P: AsRef<Path>>( |
| 93 | reader: R, |
| 94 | path: P, |
| 95 | ) -> Result<(Sudoers, Vec<Error>), io::Error> { |
| 96 | let sudoers = read_sudoers(reader)?; |
| 97 | Ok(analyze(path.as_ref(), sudoers)) |
| 98 | } |
| 99 | |
| 100 | fn specify_host_user_runas<User: UnixUser + PartialEq<User>>( |
| 101 | &mut self, |
| 102 | hostname: &system::Hostname, |
| 103 | requesting_user: &User, |
| 104 | target_user: Option<&User>, |
| 105 | ) { |
| 106 | let customisers = std::mem::take(&mut self.customisers.non_cmnd); |
| 107 | |
| 108 | let host_matcher = &match_token(hostname); |
| 109 | let host_aliases = get_aliases(&self.aliases.host, host_matcher); |
| 110 | |
| 111 | let user_matcher = &match_user(requesting_user); |
| 112 | let user_aliases = get_aliases(&self.aliases.user, user_matcher); |
| 113 | |
| 114 | let runas_matcher_aliases = target_user.map(|target_user| { |
| 115 | let runas_matcher = match_user(target_user); |
| 116 | let runas_aliases = get_aliases(&self.aliases.runas, &runas_matcher); |
| 117 | |
| 118 | (runas_matcher, runas_aliases) |
| 119 | }); |
| 120 | |
| 121 | let match_scope = |scope| match scope { |
| 122 | ConfigScope::Generic => true, |
| 123 | ConfigScope::Host(list) => find_item(&list, host_matcher, &host_aliases).is_some(), |
| 124 | ConfigScope::User(list) => find_item(&list, user_matcher, &user_aliases).is_some(), |
| 125 | ConfigScope::RunAs(list) => { |
| 126 | runas_matcher_aliases |
| 127 | .as_ref() |
| 128 | .is_some_and(|(runas_matcher, runas_aliases)| { |
| 129 | find_item(&list, runas_matcher, runas_aliases).is_some() |
| 130 | }) |
| 131 | } |
| 132 | ConfigScope::Command(_list) => { |
| 133 | unreachable!("command-specific defaults are filtered out") |
| 134 | } |
| 135 | }; |
| 136 | |
| 137 | for (scope, modifiers) in customisers { |
| 138 | if match_scope(scope) { |
| 139 | for modifier in modifiers { |
| 140 | modifier(&mut self.settings); |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn specify_command(&mut self, command: &Path, arguments: &[OsString]) { |
| 147 | let customisers = std::mem::take(&mut self.customisers.cmnd); |
| 148 | |
| 149 | let cmnd_matcher = &match_command((command, arguments)); |
| 150 | let cmnd_aliases = get_aliases(&self.aliases.cmnd, cmnd_matcher); |
| 151 | |
| 152 | for (scope, modifiers) in customisers { |
| 153 | if find_item(&scope, cmnd_matcher, &cmnd_aliases).is_some() { |
| 154 | for modifier in modifiers { |
| 155 | modifier(&mut self.settings); |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | pub fn check<User: UnixUser + PartialEq<User>, Group: UnixGroup>( |
| 162 | &mut self, |
| 163 | am_user: &User, |
| 164 | on_host: &system::Hostname, |
| 165 | request: Request<User, Group>, |
| 166 | ) -> Judgement { |
| 167 | self.specify_host_user_runas(on_host, am_user, Some(request.user)); |
| 168 | self.specify_command(request.command, request.arguments); |
| 169 | |
| 170 | // exception: if user is root or does not switch users, NOPASSWD is implied |
| 171 | let skip_passwd = |
| 172 | am_user.is_root() || (request.user == am_user && in_group(am_user, request.group)); |
| 173 | |
| 174 | let mut flags = check_permission(self, am_user, on_host, request); |
| 175 | if let Some(Tag { authenticate, .. }) = flags.as_mut() { |
| 176 | if skip_passwd { |
| 177 | *authenticate = Authenticate::Nopasswd; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | Judgement { |
| 182 | flags, |
| 183 | settings: self.settings.clone(), |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | pub fn check_list_permission<User: UnixUser + PartialEq<User>, Group: UnixGroup>( |
| 188 | &mut self, |
| 189 | invoking_user: &User, |
| 190 | hostname: &system::Hostname, |
| 191 | request: ListRequest<User, Group>, |
| 192 | ) -> Authorization { |
| 193 | let skip_passwd; |
| 194 | let mut flags = if request.inspected_user != invoking_user { |
| 195 | skip_passwd = invoking_user.is_root(); |
| 196 | |
| 197 | self.check( |
| 198 | invoking_user, |
| 199 | hostname, |
| 200 | Request { |
| 201 | user: request.inspected_user, |
| 202 | group: &request.inspected_user.group(), |
| 203 | command: Path::new("list"), |
| 204 | arguments: &[], |
| 205 | }, |
| 206 | ) |
| 207 | .flags |
| 208 | .or(invoking_user.is_root().then(Tag::default)) |
| 209 | } else { |
| 210 | skip_passwd = invoking_user.is_root() |
| 211 | || (request.target_user == invoking_user |
| 212 | && in_group(invoking_user, request.target_group)); |
| 213 | |
| 214 | self.matching_user_specs(invoking_user, hostname) |
| 215 | .flatten() |
| 216 | .map(|(_, (tag, _))| tag) |
| 217 | .max_by_key(|tag| !tag.needs_passwd()) |
| 218 | }; |
| 219 | |
| 220 | if let Some(tag) = flags.as_mut() { |
| 221 | if skip_passwd { |
| 222 | tag.authenticate = Authenticate::Nopasswd; |
| 223 | } |
| 224 | |
| 225 | Authorization::Allowed(self.settings.to_auth(tag), ()) |
| 226 | } else { |
| 227 | Authorization::Forbidden |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | pub fn check_validate_permission<User: UnixUser + PartialEq<User>>( |
| 232 | &mut self, |
| 233 | invoking_user: &User, |
| 234 | hostname: &system::Hostname, |
| 235 | ) -> Authorization { |
| 236 | self.specify_host_user_runas(hostname, invoking_user, None); |
| 237 | |
| 238 | // exception: if user is root, NOPASSWD is implied |
| 239 | let skip_passwd = invoking_user.is_root(); |
| 240 | |
| 241 | let mut flags = self |
| 242 | .matching_user_specs(invoking_user, hostname) |
| 243 | .flatten() |
| 244 | .map(|(_, (tag, _))| tag) |
| 245 | .max_by_key(|tag| tag.needs_passwd()); |
| 246 | |
| 247 | if let Some(tag) = flags.as_mut() { |
| 248 | if skip_passwd { |
| 249 | tag.authenticate = Authenticate::Nopasswd; |
| 250 | } |
| 251 | |
| 252 | Authorization::Allowed(self.settings.to_auth(tag), ()) |
| 253 | } else { |
| 254 | Authorization::Forbidden |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// returns `User_Spec`s that match `invoking_user` and `hostname` |
| 259 | /// |
| 260 | /// it also distributes `Tag_Spec`s across the `Cmnd_Spec` list of each `User_Spec` |
| 261 | /// |
| 262 | /// the outer iterator are the `User_Spec`s; the inner iterator are the `Cmnd_Spec`s of |
| 263 | /// said `User_Spec`s |
| 264 | fn matching_user_specs<'a, User: UnixUser + PartialEq<User>>( |
| 265 | &'a self, |
| 266 | invoking_user: &'a User, |
| 267 | hostname: &'a system::Hostname, |
| 268 | ) -> impl Iterator<Item = impl Iterator<Item = MatchedCommand<'a>>> { |
| 269 | let Self { rules, aliases, .. } = self; |
| 270 | let user_aliases = get_aliases(&aliases.user, &match_user(invoking_user)); |
| 271 | let host_aliases = get_aliases(&aliases.host, &match_token(hostname)); |
| 272 | |
| 273 | rules |
| 274 | .iter() |
| 275 | .filter_map(move |sudo| { |
| 276 | find_item(&sudo.users, &match_user(invoking_user), &user_aliases)?; |
| 277 | Some(&sudo.permissions) |
| 278 | }) |
| 279 | .flatten() |
| 280 | .filter_map(move |(hosts, runas_cmds)| { |
| 281 | find_item(hosts, &match_token(hostname), &host_aliases)?; |
| 282 | Some(distribute_tags(runas_cmds)) |
| 283 | }) |
| 284 | } |
| 285 | |
| 286 | pub fn matching_entries<'a, User: UnixUser + PartialEq<User>>( |
| 287 | &'a self, |
| 288 | invoking_user: &'a User, |
| 289 | hostname: &'a system::Hostname, |
| 290 | ) -> impl Iterator<Item = Entry<'a>> { |
| 291 | let user_specs = self.matching_user_specs(invoking_user, hostname); |
| 292 | |
| 293 | user_specs.flat_map(|cmd_specs| group_cmd_specs_per_runas(cmd_specs, &self.aliases.cmnd)) |
| 294 | } |
| 295 | |
| 296 | pub(crate) fn visudo_editor_path<User: UnixUser + PartialEq<User>>( |
| 297 | mut self, |
| 298 | on_host: &system::Hostname, |
| 299 | am_user: &User, |
| 300 | target_user: &User, |
| 301 | ) -> Option<(PathBuf, Vec<OsString>)> { |
| 302 | self.specify_host_user_runas(on_host, am_user, Some(target_user)); |
| 303 | |
| 304 | select_editor(&self.settings, self.settings.env_editor()) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | /// Retrieve the chosen editor from a settings object, filtering based on whether the |
| 309 | /// environment is trusted (sudoedit) or maybe less so (visudo) |
| 310 | fn select_editor(settings: &Settings, trusted_env: bool) -> Option<(PathBuf, Vec<OsString>)> { |
| 311 | let blessed_editors = settings.editor(); |
| 312 | |
| 313 | let is_whitelisted = |path: &Path| -> bool { |
| 314 | trusted_env || blessed_editors.split(':').any(|x| Path::new(x) == path) |
| 315 | }; |
| 316 | |
| 317 | // find editor in environment, if possible |
| 318 | |
| 319 | for key in ["SUDO_EDITOR", "VISUAL", "EDITOR"] { |
| 320 | if let Ok(editor_env) = std::env::var(key) { |
| 321 | let mut arguments = editor_env.split(' '); |
| 322 | |
| 323 | let Some(editor) = arguments.next().map(PathBuf::from) else { |
| 324 | continue; |
| 325 | }; |
| 326 | let arguments = arguments.map(OsString::from).collect(); |
| 327 | |
| 328 | let editor = if is_valid_executable(&editor) { |
| 329 | editor |
| 330 | } else if let Some(editor) = resolve_path( |
| 331 | &editor, |
| 332 | &std::env::var("PATH").unwrap_or(crate::sudo::PATH_DEFAULT.to_string()), |
| 333 | ) { |
| 334 | editor |
| 335 | } else { |
| 336 | continue; |
| 337 | }; |
| 338 | |
| 339 | if is_whitelisted(&editor) { |
| 340 | return Some((editor, arguments)); |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // no acceptable editor found in environment, fallback on config |
| 346 | |
| 347 | for editor in blessed_editors.split(':') { |
| 348 | let editor = PathBuf::from(editor); |
| 349 | if is_valid_executable(&editor) { |
| 350 | return Some((editor, vec![])); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | None |
| 355 | } |
| 356 | |
| 357 | // a `take_while` variant that does not consume the first non-matching item |
| 358 | fn peeking_take_while<'a, T>( |
| 359 | iter: &'a mut std::iter::Peekable<impl Iterator<Item = T>>, |
| 360 | pred: impl Fn(&T) -> bool + 'a, |
| 361 | ) -> impl Iterator<Item = T> + 'a { |
| 362 | std::iter::from_fn(move || iter.next_if(&pred)) |
| 363 | } |
| 364 | |
| 365 | fn group_cmd_specs_per_runas<'a>( |
| 366 | cmnd_specs: impl Iterator<Item = (Option<&'a RunAs>, (Tag, &'a Spec<Command>))>, |
| 367 | cmnd_aliases: &'a VecOrd<Def<Command>>, |
| 368 | ) -> impl Iterator<Item = Entry<'a>> { |
| 369 | // `distribute_tags` will have given every spec a reference to the "runas specification" |
| 370 | // that applies to it. The output of sudo --list splits the CmndSpec list based on that: |
| 371 | // every line only has a single "runas" specifier. So we need to combine them for that. |
| 372 | // |
| 373 | // But sudo --list also outputs lines that are from different lines in the sudoers file on |
| 374 | // different lines in the output of sudo --list, so we cannot compare "by value". Luckily, |
| 375 | // once a RunAs is parsed, it will have a unique identifier in the form of its address. |
| 376 | let origin = |runas: Option<&RunAs>| runas.map(|r| r as *const _); |
| 377 | |
| 378 | let mut cmnd_specs = cmnd_specs.peekable(); |
| 379 | |
| 380 | std::iter::from_fn(move || { |
| 381 | if let Some(&(cur_runas, _)) = cmnd_specs.peek() { |
| 382 | let specs = peeking_take_while(&mut cmnd_specs, |&(runas, _)| { |
| 383 | origin(runas) == origin(cur_runas) |
| 384 | }); |
| 385 | |
| 386 | Some(Entry::new( |
| 387 | cur_runas, |
| 388 | specs.map(|x| x.1).collect(), |
| 389 | cmnd_aliases, |
| 390 | )) |
| 391 | } else { |
| 392 | None |
| 393 | } |
| 394 | }) |
| 395 | } |
| 396 | |
| 397 | fn read_sudoers<R: io::Read>(mut reader: R) -> io::Result<Vec<basic_parser::Parsed<Sudo>>> { |
| 398 | // it's a bit frustrating that BufReader.chars() does not exist |
| 399 | let mut buffer = String::new(); |
| 400 | reader.read_to_string(&mut buffer)?; |
| 401 | |
| 402 | use basic_parser::parse_lines; |
| 403 | use char_stream::*; |
| 404 | Ok(parse_lines(&mut CharStream::new(&buffer))) |
| 405 | } |
| 406 | |
| 407 | fn open_sudoers(path: &Path) -> io::Result<Vec<basic_parser::Parsed<Sudo>>> { |
| 408 | let source = audit::secure_open_sudoers(path)?; |
| 409 | read_sudoers(source) |
| 410 | } |
| 411 | |
| 412 | #[cfg(feature = "unstable-remote-sudoers")] |
| 413 | fn open_remote_sudoers(path: &Path) -> io::Result<Vec<basic_parser::Parsed<Sudo>>> { |
| 414 | let source = audit::secure_open_remote_sudoers(path)?; |
| 415 | read_sudoers(source) |
| 416 | } |
| 417 | |
| 418 | // note: trying to DRY using GAT's is tempting but doesn't make the code any shorter |
| 419 | |
| 420 | #[derive(Default)] |
| 421 | struct AliasTable { |
| 422 | user: VecOrd<Def<UserSpecifier>>, |
| 423 | host: VecOrd<Def<Hostname>>, |
| 424 | cmnd: VecOrd<Def<Command>>, |
| 425 | runas: VecOrd<Def<UserSpecifier>>, |
| 426 | } |
| 427 | |
| 428 | #[derive(Default)] |
| 429 | struct CustomiserTable { |
| 430 | non_cmnd: Vec<Customiser<ConfigScope>>, |
| 431 | cmnd: Vec<Customiser<SpecList<Command>>>, |
| 432 | } |
| 433 | |
| 434 | /// A vector with a list defining the order in which it needs to be processed |
| 435 | struct VecOrd<T>(Vec<usize>, Vec<T>); |
| 436 | |
| 437 | impl<T> Default for VecOrd<T> { |
| 438 | fn default() -> Self { |
| 439 | VecOrd(Vec::default(), Vec::default()) |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | impl<T> VecOrd<T> { |
| 444 | fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + Clone { |
| 445 | self.0.iter().map(|&i| &self.1[i]) |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | /// Check if the user `am_user` is allowed to run `cmdline` on machine `on_host` as the requested |
| 450 | /// user/group. Not that in the sudoers file, later permissions override earlier restrictions. |
| 451 | /// The `cmdline` argument should already be ready to essentially feed to an exec() call; or be |
| 452 | /// a special command like 'sudoedit'. |
| 453 | // This code is structure to allow easily reading the 'happy path'; i.e. as soon as something |
| 454 | // doesn't match, we escape using the '?' mechanism. |
| 455 | fn check_permission<User: UnixUser + PartialEq<User>, Group: UnixGroup>( |
| 456 | sudoers: &Sudoers, |
| 457 | am_user: &User, |
| 458 | on_host: &system::Hostname, |
| 459 | request: Request<User, Group>, |
| 460 | ) -> Option<Tag> { |
| 461 | let cmdline = (request.command, request.arguments); |
| 462 | |
| 463 | let aliases = &sudoers.aliases; |
| 464 | let cmnd_aliases = get_aliases(&aliases.cmnd, &match_command(cmdline)); |
| 465 | let runas_user_aliases = get_aliases(&aliases.runas, &match_user(request.user)); |
| 466 | let runas_group_aliases = get_aliases(&aliases.runas, &match_group_alias(request.group)); |
| 467 | |
| 468 | let matching_user_specs = sudoers.matching_user_specs(am_user, on_host).flatten(); |
| 469 | |
| 470 | let allowed_commands = matching_user_specs.filter_map(|(runas, cmdspec)| { |
| 471 | if let Some(RunAs { users, groups }) = runas { |
| 472 | let stays_in_group = in_group(request.user, request.group); |
| 473 | if request.user != am_user || (stays_in_group && !users.is_empty()) { |
| 474 | find_item(users, &match_user(request.user), &runas_user_aliases)? |
| 475 | } |
| 476 | if !stays_in_group { |
| 477 | find_item(groups, &match_group(request.group), &runas_group_aliases)? |
| 478 | } |
| 479 | } else if !(request.user.is_root() && in_group(request.user, request.group)) { |
| 480 | None?; |
| 481 | } |
| 482 | |
| 483 | Some(cmdspec) |
| 484 | }); |
| 485 | |
| 486 | find_item(allowed_commands, &match_command(cmdline), &cmnd_aliases) |
| 487 | } |
| 488 | |
| 489 | /// Process a raw parsed AST bit of RunAs + Command specifications: |
| 490 | /// - RunAs specifications distribute over the commands that follow (until overridden) |
| 491 | /// - Tags accumulate over the entire line |
| 492 | fn distribute_tags( |
| 493 | runas_cmds: &[(Option<RunAs>, CommandSpec)], |
| 494 | ) -> impl Iterator<Item = (Option<&RunAs>, (Tag, &Spec<Command>))> { |
| 495 | runas_cmds.iter().scan( |
| 496 | (None, Default::default()), |
| 497 | |(last_runas, tag), (runas, CommandSpec(mods, cmd))| { |
| 498 | *last_runas = runas.as_ref().or(*last_runas); |
| 499 | for f in mods { |
| 500 | f(tag); |
| 501 | } |
| 502 | |
| 503 | let this_tag = match cmd { |
| 504 | Qualified::Allow(Meta::All) if tag.env != EnvironmentControl::Nosetenv => Tag { |
| 505 | // "ALL" has an implicit "SETENV" that doesn't distribute |
| 506 | env: EnvironmentControl::Setenv, |
| 507 | ..tag.clone() |
| 508 | }, |
| 509 | _ => tag.clone(), |
| 510 | }; |
| 511 | |
| 512 | Some((*last_runas, (this_tag, cmd))) |
| 513 | }, |
| 514 | ) |
| 515 | } |
| 516 | |
| 517 | /// A type to represent positive or negative association with an alias; i.e. if a key maps to true, |
| 518 | /// the alias affirms membership, if a key maps to false, the alias denies membership; if a key |
| 519 | /// isn't present membership is affirmed nor denied |
| 520 | type FoundAliases = HashMap<String, bool>; |
| 521 | |
| 522 | /// Find an item matching a certain predicate in an collection (optionally attributed) list of |
| 523 | /// identifiers; identifiers can be directly identifying, wildcards, and can either be positive or |
| 524 | /// negative (i.e. preceeded by an even number of exclamation marks in the sudoers file) |
| 525 | fn find_item<'a, Predicate, Iter, T: 'a>( |
| 526 | items: Iter, |
| 527 | matches: &Predicate, |
| 528 | aliases: &FoundAliases, |
| 529 | ) -> Option<<Iter::Item as WithInfo>::Info> |
| 530 | where |
| 531 | Predicate: Fn(&T) -> bool, |
| 532 | Iter: IntoIterator, |
| 533 | Iter::Item: WithInfo<Item = &'a Spec<T>>, |
| 534 | { |
| 535 | let mut result = None; |
| 536 | for item in items { |
| 537 | let (judgement, who) = match item.as_inner() { |
| 538 | Qualified::Forbid(x) => (false, x), |
| 539 | Qualified::Allow(x) => (true, x), |
| 540 | }; |
| 541 | let info = || item.into_info(); |
| 542 | match who { |
| 543 | Meta::All => result = judgement.then(info), |
| 544 | Meta::Only(ident) if matches(ident) => result = judgement.then(info), |
| 545 | Meta::Alias(id) if aliases.contains_key(id) => { |
| 546 | result = if aliases[id] { |
| 547 | judgement.then(info) |
| 548 | } else { |
| 549 | // in this case, an explicit negation in the alias applies |
| 550 | (!judgement).then(info) |
| 551 | } |
| 552 | } |
| 553 | _ => {} |
| 554 | }; |
| 555 | } |
| 556 | |
| 557 | result |
| 558 | } |
| 559 | |
| 560 | /// A interface to access optional "satellite data" |
| 561 | trait WithInfo { |
| 562 | type Item; |
| 563 | type Info; |
| 564 | fn as_inner(&self) -> Self::Item; |
| 565 | fn into_info(self) -> Self::Info; |
| 566 | } |
| 567 | |
| 568 | /// A specific interface for `Spec<T>` --- we can't make a generic one; |
| 569 | /// A `Spec<T>` does not contain any additional information. |
| 570 | impl<'a, T> WithInfo for &'a Spec<T> { |
| 571 | type Item = &'a Spec<T>; |
| 572 | type Info = (); |
| 573 | fn as_inner(&self) -> &'a Spec<T> { |
| 574 | self |
| 575 | } |
| 576 | fn into_info(self) {} |
| 577 | } |
| 578 | |
| 579 | /// A commandspec can be "tagged" |
| 580 | impl<'a> WithInfo for (Tag, &'a Spec<Command>) { |
| 581 | type Item = &'a Spec<Command>; |
| 582 | type Info = Tag; |
| 583 | fn as_inner(&self) -> &'a Spec<Command> { |
| 584 | self.1 |
| 585 | } |
| 586 | fn into_info(self) -> Tag { |
| 587 | self.0 |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | /// Now follow a collection of functions used as closures for `find_item` |
| 592 | fn match_user(user: &impl UnixUser) -> impl Fn(&UserSpecifier) -> bool + '_ { |
| 593 | move |spec| match spec { |
| 594 | UserSpecifier::User(id) => match_identifier(user, id), |
| 595 | UserSpecifier::Group(Identifier::Name(name)) => user.in_group_by_name(name.as_cstr()), |
| 596 | UserSpecifier::Group(Identifier::ID(num)) => user.in_group_by_gid(GroupId::new(*num)), |
| 597 | // nonunix-groups, netgroups, etc. are not implemented |
| 598 | UserSpecifier::NonunixGroup(group) => { |
| 599 | match group { |
| 600 | Identifier::Name(name) => auth_warn!("warning: non-unix group {name} was ignored"), |
| 601 | Identifier::ID(num) => auth_warn!("warning: non-unix group #{num} was ignored"), |
| 602 | } |
| 603 | |
| 604 | false |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | fn in_group(user: &impl UnixUser, group: &impl UnixGroup) -> bool { |
| 610 | user.in_group_by_gid(group.as_gid()) |
| 611 | } |
| 612 | |
| 613 | fn match_group(group: &impl UnixGroup) -> impl Fn(&Identifier) -> bool + '_ { |
| 614 | move |id| match id { |
| 615 | Identifier::ID(num) => group.as_gid() == GroupId::new(*num), |
| 616 | Identifier::Name(name) => group.try_as_name().is_some_and(|s| name == s), |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | fn match_group_alias(group: &impl UnixGroup) -> impl Fn(&UserSpecifier) -> bool + '_ { |
| 621 | move |spec| match spec { |
| 622 | UserSpecifier::User(ident) => match_group(group)(ident), |
| 623 | /* the parser does not allow this, but can happen due to Runas_Alias, |
| 624 | * see https://github.com/trifectatechfoundation/sudo-rs/issues/13 */ |
| 625 | _ => { |
| 626 | auth_warn!("warning: ignoring %group syntax in runas_alias for checking sudo -g"); |
| 627 | false |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | fn match_token<T: basic_parser::Token + std::ops::Deref<Target = String>>( |
| 633 | text: &str, |
| 634 | ) -> impl Fn(&T) -> bool + '_ { |
| 635 | move |token| token.as_str() == text |
| 636 | } |
| 637 | |
| 638 | fn match_command<'a>((cmd, args): (&'a Path, &'a [OsString])) -> impl Fn(&Command) -> bool + 'a { |
| 639 | let opts = glob::MatchOptions { |
| 640 | require_literal_separator: true, |
| 641 | ..glob::MatchOptions::new() |
| 642 | }; |
| 643 | move |(cmdpat, argpat)| { |
| 644 | cmdpat.matches_path_with(cmd, opts) |
| 645 | && match argpat { |
| 646 | Args::Prefix(vec) => args.starts_with(vec), |
| 647 | Args::Exact(vec) => args == vec.as_ref(), |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | /// Find all the aliases that a object is a member of; this requires [sanitize_alias_table] to have run first; |
| 653 | /// I.e. this function should not be "pub". |
| 654 | fn get_aliases<Predicate, T>(table: &VecOrd<Def<T>>, pred: &Predicate) -> FoundAliases |
| 655 | where |
| 656 | Predicate: Fn(&T) -> bool, |
| 657 | { |
| 658 | use std::iter::once; |
| 659 | let all = Qualified::Allow(Meta::All); |
| 660 | |
| 661 | let mut set = HashMap::new(); |
| 662 | for Def(id, list) in table.iter() { |
| 663 | if find_item(list, &pred, &set).is_some() { |
| 664 | set.insert(id.clone(), true); |
| 665 | } else if find_item(once(&all).chain(list), &pred, &set).is_none() { |
| 666 | // the item wasn't found even if we prepend ALL to the list of definitions; that means |
| 667 | // it is explicitly excluded by the alias definition. |
| 668 | set.insert(id.clone(), false); |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | set |
| 673 | } |
| 674 | |
| 675 | /// Code to map an ast::Identifier to the UnixUser trait |
| 676 | fn match_identifier(user: &impl UnixUser, ident: &ast::Identifier) -> bool { |
| 677 | match ident { |
| 678 | Identifier::Name(name) => user.has_name(name), |
| 679 | Identifier::ID(num) => user.has_uid(UserId::new(*num)), |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /// Process a sudoers-parsing file into a workable AST |
| 684 | fn analyze( |
| 685 | path: &Path, |
| 686 | sudoers: impl IntoIterator<Item = basic_parser::Parsed<Sudo>>, |
| 687 | ) -> (Sudoers, Vec<Error>) { |
| 688 | use crate::common::{HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2}; |
| 689 | use Directive::*; |
| 690 | |
| 691 | let mut result: Sudoers = Default::default(); |
| 692 | |
| 693 | /// The IncludeState allows to tell whether including new files is allowed. |
| 694 | /// There are two situations: |
| 695 | /// - inclusion is forbidden (as when the @socket directive is used) |
| 696 | /// - inclusion is allowed but we need to ensure we didn't go beyond the limit |
| 697 | #[derive(Clone, Copy)] |
| 698 | #[repr(u32)] |
| 699 | enum IncludeState { |
| 700 | #[cfg(feature = "unstable-remote-sudoers")] |
| 701 | Forbidden = HARDENED_ENUM_VALUE_0, |
| 702 | Allowed(u8) = HARDENED_ENUM_VALUE_1, |
| 703 | } |
| 704 | |
| 705 | impl IncludeState { |
| 706 | #[inline] |
| 707 | fn inc(&mut self) -> &mut Self { |
| 708 | #[cfg_attr( |
| 709 | not(feature = "unstable-remote-sudoers"), |
| 710 | allow(irrefutable_let_patterns) |
| 711 | )] |
| 712 | if let IncludeState::Allowed(x) = self { |
| 713 | *x += 1; |
| 714 | } |
| 715 | self |
| 716 | } |
| 717 | |
| 718 | #[inline] |
| 719 | fn limit_reached(&self) -> bool { |
| 720 | match self { |
| 721 | #[cfg(feature = "unstable-remote-sudoers")] |
| 722 | IncludeState::Forbidden => true, |
| 723 | IncludeState::Allowed(x) => *x >= INCLUDE_LIMIT, |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | /// The directive that produced the inclusion. |
| 729 | #[repr(u32)] |
| 730 | enum IncludeDirective { |
| 731 | Include = HARDENED_ENUM_VALUE_0, |
| 732 | IncludeDir = HARDENED_ENUM_VALUE_1, |
| 733 | #[cfg(feature = "unstable-remote-sudoers")] |
| 734 | Remote = HARDENED_ENUM_VALUE_2, |
| 735 | } |
| 736 | |
| 737 | impl fmt::Display for IncludeDirective { |
| 738 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 739 | let s = match self { |
| 740 | IncludeDirective::Include => "@include", |
| 741 | IncludeDirective::IncludeDir => "@includedir", |
| 742 | #[cfg(feature = "unstable-remote-sudoers")] |
| 743 | IncludeDirective::Remote => "@socket", |
| 744 | }; |
| 745 | write!(f, "{s}") |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | fn resolve_relative(base: &Path, path: impl AsRef<Path>) -> PathBuf { |
| 750 | if path.as_ref().is_relative() { |
| 751 | // there should always be a parent since we start with /etc/sudoers, and make every other path |
| 752 | // absolute based on previous inputs; not having a parent is therefore a serious bug |
| 753 | base.parent() |
| 754 | .expect("invalid hardcoded path in sudo-rs") |
| 755 | .join(path) |
| 756 | } else { |
| 757 | path.as_ref().into() |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | fn include( |
| 762 | cfg: &mut Sudoers, |
| 763 | parent: &Path, |
| 764 | span: Span, |
| 765 | path: &Path, |
| 766 | diagnostics: &mut Vec<Error>, |
| 767 | include_state: &mut IncludeState, |
| 768 | include_source: IncludeDirective, |
| 769 | ) { |
| 770 | // IncludeState::limit_reached() will also detect forbidden includes |
| 771 | if include_state.limit_reached() { |
| 772 | let message = match include_state { |
| 773 | IncludeState::Allowed(_) => { |
| 774 | format!("include file limit reached opening '{}'", path.display()) |
| 775 | } |
| 776 | #[cfg(feature = "unstable-remote-sudoers")] |
| 777 | IncludeState::Forbidden => { |
| 778 | format!("{} forbidden at this stage", include_source) |
| 779 | } |
| 780 | }; |
| 781 | diagnostics.push(Error { |
| 782 | source: Some(parent.to_owned()), |
| 783 | location: Some(span), |
| 784 | message, |
| 785 | }); |
| 786 | } else { |
| 787 | let (res, next_state, kind) = match include_source { |
| 788 | #[cfg(feature = "unstable-remote-sudoers")] |
| 789 | IncludeDirective::Remote => ( |
| 790 | open_remote_sudoers(path), |
| 791 | &mut IncludeState::Forbidden, |
| 792 | "socket", |
| 793 | ), |
| 794 | _ => (open_sudoers(path), include_state.inc(), "file"), |
| 795 | }; |
| 796 | |
| 797 | match res { |
| 798 | Ok(subsudoer) => process(cfg, path, subsudoer, diagnostics, next_state), |
| 799 | Err(e) => { |
| 800 | let message = if e.kind() == io::ErrorKind::NotFound { |
| 801 | // improve the error message in this case |
| 802 | format!("cannot open sudoers {} '{}'", kind, path.display()) |
| 803 | } else { |
| 804 | e.to_string() |
| 805 | }; |
| 806 | |
| 807 | diagnostics.push(Error { |
| 808 | source: Some(parent.to_owned()), |
| 809 | location: Some(span), |
| 810 | message, |
| 811 | }) |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | fn process( |
| 818 | cfg: &mut Sudoers, |
| 819 | cur_path: &Path, |
| 820 | sudoers: impl IntoIterator<Item = basic_parser::Parsed<Sudo>>, |
| 821 | diagnostics: &mut Vec<Error>, |
| 822 | include_state: &mut IncludeState, |
| 823 | ) { |
| 824 | for item in sudoers { |
| 825 | match item { |
| 826 | Ok(line) => match line { |
| 827 | Sudo::LineComment => {} |
| 828 | |
| 829 | Sudo::Spec(permission) => { |
| 830 | diagnostics.extend(get_ignored_tags(&permission).map(|span| Error { |
| 831 | source: Some(cur_path.to_owned()), |
| 832 | location: Some(span), |
| 833 | message: "this tag is ignored by sudo-rs".to_string(), |
| 834 | })); |
| 835 | cfg.rules.push(permission); |
| 836 | } |
| 837 | |
| 838 | Sudo::Decl(HostAlias(mut def)) => cfg.aliases.host.1.append(&mut def), |
| 839 | Sudo::Decl(UserAlias(mut def)) => cfg.aliases.user.1.append(&mut def), |
| 840 | Sudo::Decl(RunasAlias(mut def)) => cfg.aliases.runas.1.append(&mut def), |
| 841 | Sudo::Decl(CmndAlias(mut def)) => cfg.aliases.cmnd.1.append(&mut def), |
| 842 | |
| 843 | Sudo::Decl(Defaults(params, scope)) => { |
| 844 | if let ConfigScope::Command(specs) = scope { |
| 845 | cfg.customisers.cmnd.push(( |
| 846 | specs |
| 847 | .into_iter() |
| 848 | .map(|spec| { |
| 849 | spec.map(|simple_command| { |
| 850 | (simple_command, Args::Prefix(Box::default())) |
| 851 | }) |
| 852 | }) |
| 853 | .collect(), |
| 854 | params, |
| 855 | )); |
| 856 | } else { |
| 857 | cfg.customisers.non_cmnd.push((scope, params)); |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | Sudo::Include(path, span) => include( |
| 862 | cfg, |
| 863 | cur_path, |
| 864 | span, |
| 865 | &resolve_relative(cur_path, path), |
| 866 | diagnostics, |
| 867 | include_state, |
| 868 | IncludeDirective::Include, |
| 869 | ), |
| 870 | |
| 871 | #[cfg(feature = "unstable-remote-sudoers")] |
| 872 | Sudo::Remote(path, span) => { |
| 873 | let socket_path = Path::new(&path); |
| 874 | if socket_path.is_relative() { |
| 875 | diagnostics.push(Error { |
| 876 | source: Some(cur_path.to_owned()), |
| 877 | location: Some(span), |
| 878 | message: format!( |
| 879 | "cannot open socket {path}: path must be absolute" |
| 880 | ), |
| 881 | }); |
| 882 | } else { |
| 883 | include( |
| 884 | cfg, |
| 885 | cur_path, |
| 886 | span, |
| 887 | socket_path, |
| 888 | diagnostics, |
| 889 | include_state, |
| 890 | IncludeDirective::Remote, |
| 891 | ); |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | Sudo::IncludeDir(path, span) => { |
| 896 | if path.contains("%h") { |
| 897 | diagnostics.push(Error { |
| 898 | source: Some(cur_path.to_owned()), |
| 899 | location: Some(span), |
| 900 | message: format!( |
| 901 | "cannot open sudoers file {path}: \ |
| 902 | percent escape %h in includedir is unsupported" |
| 903 | ), |
| 904 | }); |
| 905 | continue; |
| 906 | } |
| 907 | |
| 908 | let path = resolve_relative(cur_path, path); |
| 909 | let Ok(files) = std::fs::read_dir(&path) else { |
| 910 | diagnostics.push(Error { |
| 911 | source: Some(cur_path.to_owned()), |
| 912 | location: Some(span), |
| 913 | message: format!("cannot open sudoers file {}", path.display()), |
| 914 | }); |
| 915 | continue; |
| 916 | }; |
| 917 | let mut safe_files = files |
| 918 | .filter_map(|direntry| { |
| 919 | let path = direntry.ok()?.path(); |
| 920 | let text = path.file_name()?.to_str()?; |
| 921 | if text.ends_with('~') || text.contains('.') { |
| 922 | None |
| 923 | } else { |
| 924 | Some(path) |
| 925 | } |
| 926 | }) |
| 927 | .collect::<Vec<_>>(); |
| 928 | safe_files.sort(); |
| 929 | for file in safe_files { |
| 930 | include( |
| 931 | cfg, |
| 932 | cur_path, |
| 933 | span, |
| 934 | file.as_ref(), |
| 935 | diagnostics, |
| 936 | include_state, |
| 937 | IncludeDirective::IncludeDir, |
| 938 | ) |
| 939 | } |
| 940 | } |
| 941 | }, |
| 942 | |
| 943 | Err(basic_parser::Status::Fatal(pos, message)) => diagnostics.push(Error { |
| 944 | source: Some(cur_path.to_owned()), |
| 945 | location: Some(pos), |
| 946 | message, |
| 947 | }), |
| 948 | Err(_) => panic!("internal parser error"), |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn get_ignored_tags( |
| 954 | PermissionSpec { permissions, .. }: &PermissionSpec, |
| 955 | ) -> impl Iterator<Item = Span> + '_ { |
| 956 | permissions |
| 957 | .iter() |
| 958 | .flat_map(|(_host, runas_cmds)| runas_cmds) |
| 959 | .flat_map(|(_runas, CommandSpec(tags, _cmd))| tags) |
| 960 | .flat_map(|modifier| { |
| 961 | let mut tag = Tag::default(); |
| 962 | modifier(&mut tag); |
| 963 | tag.ignored |
| 964 | }) |
| 965 | } |
| 966 | |
| 967 | let mut diagnostics = vec![]; |
| 968 | process( |
| 969 | &mut result, |
| 970 | path, |
| 971 | sudoers, |
| 972 | &mut diagnostics, |
| 973 | &mut IncludeState::Allowed(0), |
| 974 | ); |
| 975 | |
| 976 | let alias = &mut result.aliases; |
| 977 | alias.user.0 = sanitize_alias_table(&alias.user.1, &mut diagnostics); |
| 978 | alias.host.0 = sanitize_alias_table(&alias.host.1, &mut diagnostics); |
| 979 | alias.cmnd.0 = sanitize_alias_table(&alias.cmnd.1, &mut diagnostics); |
| 980 | alias.runas.0 = sanitize_alias_table(&alias.runas.1, &mut diagnostics); |
| 981 | |
| 982 | (result, diagnostics) |
| 983 | } |
| 984 | |
| 985 | /// Alias definition inin a Sudoers file can come in any order; and aliases can refer to other aliases, etc. |
| 986 | /// It is much easier if they are presented in a "definitional order" (i.e. aliases that use other aliases occur later) |
| 987 | /// At the same time, this is a good place to detect problems in the aliases, such as unknown aliases and cycles. |
| 988 | fn sanitize_alias_table<T>(table: &Vec<Def<T>>, diagnostics: &mut Vec<Error>) -> Vec<usize> { |
| 989 | fn remqualify<U>(item: &Qualified<U>) -> &U { |
| 990 | match item { |
| 991 | Qualified::Allow(x) => x, |
| 992 | Qualified::Forbid(x) => x, |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | // perform a topological sort (hattip [email protected]) to produce a derangement |
| 997 | struct Visitor<'a, T> { |
| 998 | seen: HashSet<usize>, |
| 999 | table: &'a Vec<Def<T>>, |
| 1000 | order: Vec<usize>, |
| 1001 | diagnostics: &'a mut Vec<Error>, |
| 1002 | } |
| 1003 | |
| 1004 | impl<T> Visitor<'_, T> { |
| 1005 | fn complain(&mut self, text: String) { |
| 1006 | self.diagnostics.push(Error { |
| 1007 | source: None, |
| 1008 | location: None, |
| 1009 | message: text, |
| 1010 | }) |
| 1011 | } |
| 1012 | |
| 1013 | fn visit(&mut self, pos: usize) { |
| 1014 | if self.seen.insert(pos) { |
| 1015 | let Def(_, members) = &self.table[pos]; |
| 1016 | for elem in members { |
| 1017 | let Meta::Alias(name) = remqualify(elem) else { |
| 1018 | continue; |
| 1019 | }; |
| 1020 | let Some(dependency) = self.table.iter().position(|Def(id, _)| id == name) |
| 1021 | else { |
| 1022 | self.complain(format!("undefined alias: '{name}'")); |
| 1023 | continue; |
| 1024 | }; |
| 1025 | self.visit(dependency); |
| 1026 | } |
| 1027 | self.order.push(pos); |
| 1028 | } else if !self.order.contains(&pos) { |
| 1029 | let Def(id, _) = &self.table[pos]; |
| 1030 | self.complain(format!("recursive alias: '{id}'")); |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | let mut visitor = Visitor { |
| 1036 | seen: HashSet::new(), |
| 1037 | table, |
| 1038 | order: Vec::with_capacity(table.len()), |
| 1039 | diagnostics, |
| 1040 | }; |
| 1041 | |
| 1042 | let mut dupe = HashSet::new(); |
| 1043 | for (i, Def(name, _)) in table.iter().enumerate() { |
| 1044 | if !dupe.insert(name) { |
| 1045 | visitor.complain(format!("multiple occurrences of '{name}'")); |
| 1046 | } else { |
| 1047 | visitor.visit(i); |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | visitor.order |
| 1052 | } |
| 1053 | |
| 1054 | #[cfg(test)] |
| 1055 | mod test; |