| 1 | use super::ast_names::UserFriendly; |
| 2 | use super::basic_parser::*; |
| 3 | use super::tokens::*; |
| 4 | use crate::common::SudoString; |
| 5 | use crate::common::{ |
| 6 | HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2, HARDENED_ENUM_VALUE_3, |
| 7 | HARDENED_ENUM_VALUE_4, HARDENED_ENUM_VALUE_5, |
| 8 | }; |
| 9 | use crate::defaults; |
| 10 | |
| 11 | /// The Sudoers file allows negating items with the exclamation mark. |
| 12 | #[cfg_attr(test, derive(Debug, Eq))] |
| 13 | #[derive(Clone, PartialEq)] |
| 14 | #[repr(u32)] |
| 15 | pub enum Qualified<T> { |
| 16 | Allow(T) = HARDENED_ENUM_VALUE_0, |
| 17 | Forbid(T) = HARDENED_ENUM_VALUE_1, |
| 18 | } |
| 19 | |
| 20 | /// Type aliases; many items can be replaced by ALL, aliases, and negated. |
| 21 | pub type Spec<T> = Qualified<Meta<T>>; |
| 22 | pub type SpecList<T> = Vec<Spec<T>>; |
| 23 | |
| 24 | /// A generic mapping function (only used for turning `Spec<SimpleCommand>` into `Spec<Command>`) |
| 25 | impl<T> Spec<T> { |
| 26 | pub fn map<U>(self, f: impl Fn(T) -> U) -> Spec<U> { |
| 27 | let transform = |meta| match meta { |
| 28 | Meta::All => Meta::All, |
| 29 | Meta::Alias(alias) => Meta::Alias(alias), |
| 30 | Meta::Only(x) => Meta::Only(f(x)), |
| 31 | }; |
| 32 | |
| 33 | match self { |
| 34 | Qualified::Allow(x) => Qualified::Allow(transform(x)), |
| 35 | Qualified::Forbid(x) => Qualified::Forbid(transform(x)), |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// An identifier is a name or a #number |
| 41 | #[cfg_attr(test, derive(Clone, Debug, PartialEq, Eq))] |
| 42 | #[repr(u32)] |
| 43 | pub enum Identifier { |
| 44 | Name(SudoString) = HARDENED_ENUM_VALUE_0, |
| 45 | ID(u32) = HARDENED_ENUM_VALUE_1, |
| 46 | } |
| 47 | |
| 48 | /// A userspecifier is either a username, or a (non-unix) group name, or netgroup |
| 49 | #[cfg_attr(test, derive(Clone, Debug, PartialEq, Eq))] |
| 50 | #[repr(u32)] |
| 51 | pub enum UserSpecifier { |
| 52 | User(Identifier) = HARDENED_ENUM_VALUE_0, |
| 53 | Group(Identifier) = HARDENED_ENUM_VALUE_1, |
| 54 | NonunixGroup(Identifier) = HARDENED_ENUM_VALUE_2, |
| 55 | } |
| 56 | |
| 57 | /// The RunAs specification consists of a (possibly empty) list of userspecifiers, followed by a (possibly empty) list of groups. |
| 58 | pub struct RunAs { |
| 59 | pub users: SpecList<UserSpecifier>, |
| 60 | pub groups: SpecList<Identifier>, |
| 61 | } |
| 62 | |
| 63 | // `sudo -l l` calls this the `authenticate` option |
| 64 | #[derive(Copy, Clone, Default, PartialEq)] |
| 65 | #[cfg_attr(test, derive(Debug, Eq))] |
| 66 | #[repr(u32)] |
| 67 | pub enum Authenticate { |
| 68 | #[default] |
| 69 | None = HARDENED_ENUM_VALUE_0, |
| 70 | // PASSWD: |
| 71 | Passwd = HARDENED_ENUM_VALUE_1, |
| 72 | // NOPASSWD: |
| 73 | Nopasswd = HARDENED_ENUM_VALUE_2, |
| 74 | } |
| 75 | |
| 76 | #[derive(Copy, Clone, Default, PartialEq)] |
| 77 | #[cfg_attr(test, derive(Debug, Eq))] |
| 78 | #[repr(u32)] |
| 79 | pub enum EnvironmentControl { |
| 80 | #[default] |
| 81 | Implicit = HARDENED_ENUM_VALUE_0, |
| 82 | // PASSWD: |
| 83 | Setenv = HARDENED_ENUM_VALUE_1, |
| 84 | // NOPASSWD: |
| 85 | Nosetenv = HARDENED_ENUM_VALUE_2, |
| 86 | } |
| 87 | |
| 88 | #[derive(Copy, Clone, Default, PartialEq)] |
| 89 | #[cfg_attr(test, derive(Debug, Eq))] |
| 90 | #[repr(u32)] |
| 91 | pub enum ExecControl { |
| 92 | #[default] |
| 93 | Implicit = HARDENED_ENUM_VALUE_0, |
| 94 | // PASSWD: |
| 95 | Exec = HARDENED_ENUM_VALUE_1, |
| 96 | // NOPASSWD: |
| 97 | Noexec = HARDENED_ENUM_VALUE_2, |
| 98 | } |
| 99 | |
| 100 | /// Commands in /etc/sudoers can have attributes attached to them, such as NOPASSWD, NOEXEC, ... |
| 101 | #[derive(Default, Clone, PartialEq)] |
| 102 | #[cfg_attr(test, derive(Debug, Eq))] |
| 103 | pub struct Tag { |
| 104 | pub(super) authenticate: Authenticate, |
| 105 | pub(super) cwd: Option<ChDir>, |
| 106 | pub(super) env: EnvironmentControl, |
| 107 | pub(super) apparmor_profile: Option<String>, |
| 108 | pub(super) noexec: ExecControl, |
| 109 | pub(super) ignored: Vec<Span>, |
| 110 | } |
| 111 | |
| 112 | impl Tag { |
| 113 | pub fn needs_passwd(&self) -> bool { |
| 114 | matches!(self.authenticate, Authenticate::None | Authenticate::Passwd) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Commands with attached attributes. |
| 119 | pub struct CommandSpec(pub Vec<Modifier>, pub Spec<Command>); |
| 120 | |
| 121 | /// The main AST object for one sudoer-permission line |
| 122 | type PairVec<A, B> = Vec<(A, Vec<B>)>; |
| 123 | |
| 124 | pub struct PermissionSpec { |
| 125 | pub users: SpecList<UserSpecifier>, |
| 126 | pub permissions: PairVec<SpecList<Hostname>, (Option<RunAs>, CommandSpec)>, |
| 127 | } |
| 128 | |
| 129 | pub type Defs<T> = Vec<Def<T>>; |
| 130 | pub struct Def<T>(pub String, pub SpecList<T>); |
| 131 | |
| 132 | /// AST object for directive specifications (aliases, arguments, etc) |
| 133 | #[repr(u32)] |
| 134 | pub enum Directive { |
| 135 | UserAlias(Defs<UserSpecifier>) = HARDENED_ENUM_VALUE_0, |
| 136 | HostAlias(Defs<Hostname>) = HARDENED_ENUM_VALUE_1, |
| 137 | CmndAlias(Defs<Command>) = HARDENED_ENUM_VALUE_2, |
| 138 | RunasAlias(Defs<UserSpecifier>) = HARDENED_ENUM_VALUE_3, |
| 139 | Defaults(Vec<defaults::SettingsModifier>, ConfigScope) = HARDENED_ENUM_VALUE_4, |
| 140 | } |
| 141 | |
| 142 | /// AST object for the 'context' (host, user, cmnd, runas) of a Defaults directive |
| 143 | #[repr(u32)] |
| 144 | pub enum ConfigScope { |
| 145 | // "Defaults entries are parsed in the following order: |
| 146 | // generic, host and user Defaults first, then runas Defaults and finally command defaults." |
| 147 | Generic = HARDENED_ENUM_VALUE_0, |
| 148 | Host(SpecList<Hostname>) = HARDENED_ENUM_VALUE_1, |
| 149 | User(SpecList<UserSpecifier>) = HARDENED_ENUM_VALUE_2, |
| 150 | RunAs(SpecList<UserSpecifier>) = HARDENED_ENUM_VALUE_3, |
| 151 | Command(SpecList<SimpleCommand>) = HARDENED_ENUM_VALUE_4, |
| 152 | } |
| 153 | |
| 154 | /// The Sudoers file can contain permissions and directives |
| 155 | #[repr(u32)] |
| 156 | pub enum Sudo { |
| 157 | Spec(PermissionSpec) = HARDENED_ENUM_VALUE_0, |
| 158 | Decl(Directive) = HARDENED_ENUM_VALUE_1, |
| 159 | Include(String, Span) = HARDENED_ENUM_VALUE_2, |
| 160 | IncludeDir(String, Span) = HARDENED_ENUM_VALUE_3, |
| 161 | #[cfg(feature = "unstable-remote-sudoers")] |
| 162 | Remote(String, Span) = HARDENED_ENUM_VALUE_4, |
| 163 | LineComment = HARDENED_ENUM_VALUE_5, |
| 164 | } |
| 165 | |
| 166 | /// grammar: |
| 167 | /// ```text |
| 168 | /// identifier = name |
| 169 | /// | #<numerical id> |
| 170 | /// ``` |
| 171 | impl Parse for Identifier { |
| 172 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 173 | if stream.eat_char('#') { |
| 174 | let DigitsU32(guid) = expect_nonterminal(stream)?; |
| 175 | make(Identifier::ID(guid)) |
| 176 | } else { |
| 177 | let Username(name) = try_nonterminal(stream)?; |
| 178 | make(Identifier::Name(name)) |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | impl Many for Identifier {} |
| 184 | |
| 185 | /// grammar: |
| 186 | /// ```text |
| 187 | /// qualified<T> = T | "!", qualified<T> |
| 188 | /// ``` |
| 189 | /// |
| 190 | /// This computes the correct negation with multiple exclamation marks in the parsing stage so we |
| 191 | /// are not bothered by it later. |
| 192 | impl<T: Parse + UserFriendly> Parse for Qualified<T> { |
| 193 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 194 | if is_syntax('!', stream)? { |
| 195 | let mut neg = true; |
| 196 | while is_syntax('!', stream)? { |
| 197 | neg = !neg; |
| 198 | } |
| 199 | let ident = expect_nonterminal(stream)?; |
| 200 | if neg { |
| 201 | make(Qualified::Forbid(ident)) |
| 202 | } else { |
| 203 | make(Qualified::Allow(ident)) |
| 204 | } |
| 205 | } else { |
| 206 | let ident = try_nonterminal(stream)?; |
| 207 | make(Qualified::Allow(ident)) |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | impl<T: Many> Many for Qualified<T> { |
| 213 | const SEP: char = T::SEP; |
| 214 | const LIMIT: usize = T::LIMIT; |
| 215 | } |
| 216 | |
| 217 | /// Helper function for parsing `Meta<T>` things where T is not a token |
| 218 | fn parse_meta<T: Parse>( |
| 219 | stream: &mut CharStream, |
| 220 | embed: impl FnOnce(SudoString) -> T, |
| 221 | ) -> Parsed<Meta<T>> { |
| 222 | if let Some(meta) = try_nonterminal(stream)? { |
| 223 | make(match meta { |
| 224 | Meta::All => Meta::All, |
| 225 | Meta::Alias(alias) => Meta::Alias(alias), |
| 226 | Meta::Only(Username(name)) => Meta::Only(embed(name)), |
| 227 | }) |
| 228 | } else { |
| 229 | make(Meta::Only(T::parse(stream)?)) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /// Since Identifier is not a token, add the parser for `Meta<Identifier>` |
| 234 | impl Parse for Meta<Identifier> { |
| 235 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 236 | parse_meta(stream, Identifier::Name) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | /// grammar: |
| 241 | /// ```text |
| 242 | /// userspec = identifier |
| 243 | /// | %identifier |
| 244 | /// | %:identifier |
| 245 | /// | +netgroup |
| 246 | /// ``` |
| 247 | impl Parse for UserSpecifier { |
| 248 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 249 | fn parse_user(stream: &mut CharStream) -> Parsed<UserSpecifier> { |
| 250 | let userspec = if stream.eat_char('%') { |
| 251 | let ctor = if stream.eat_char(':') { |
| 252 | UserSpecifier::NonunixGroup |
| 253 | } else { |
| 254 | UserSpecifier::Group |
| 255 | }; |
| 256 | // in this case we must fail 'hard', since input has been consumed |
| 257 | ctor(expect_nonterminal(stream)?) |
| 258 | } else if stream.eat_char('+') { |
| 259 | // TODO Netgroups |
| 260 | unrecoverable!(stream, "netgroups are not supported yet"); |
| 261 | } else { |
| 262 | // in this case we must fail 'softly', since no input has been consumed yet |
| 263 | UserSpecifier::User(try_nonterminal(stream)?) |
| 264 | }; |
| 265 | |
| 266 | make(userspec) |
| 267 | } |
| 268 | |
| 269 | // if we see a quote, first parse the quoted text as a token and then |
| 270 | // re-parse whatever we found inside; this is a lazy solution but it works |
| 271 | if stream.eat_char('"') { |
| 272 | let begin_pos = stream.get_pos(); |
| 273 | let Unquoted(text, _): Unquoted<Username> = expect_nonterminal(stream)?; |
| 274 | let result = parse_user(&mut CharStream::new_with_pos(&text, begin_pos))?; |
| 275 | expect_syntax('"', stream)?; |
| 276 | |
| 277 | Ok(result) |
| 278 | } else { |
| 279 | parse_user(stream) |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | impl Many for UserSpecifier {} |
| 285 | |
| 286 | /// UserSpecifier is not a token, implement the parser for `Meta<UserSpecifier>` |
| 287 | impl Parse for Meta<UserSpecifier> { |
| 288 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 289 | parse_meta(stream, |name| UserSpecifier::User(Identifier::Name(name))) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// grammar: |
| 294 | /// ```text |
| 295 | /// runas = "(", userlist, (":", grouplist?)?, ")" |
| 296 | /// ``` |
| 297 | impl Parse for RunAs { |
| 298 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 299 | try_syntax('(', stream)?; |
| 300 | let users = try_nonterminal(stream).unwrap_or_default(); |
| 301 | let groups = maybe(try_syntax(':', stream).and_then(|_| try_nonterminal(stream)))? |
| 302 | .unwrap_or_default(); |
| 303 | expect_syntax(')', stream)?; |
| 304 | |
| 305 | make(RunAs { users, groups }) |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// Implementing the trait Parse for `Meta<flag>`. Wrapped in an own object to avoid |
| 310 | /// conflicting with a potential future generic parse definition for [Meta]. |
| 311 | /// |
| 312 | /// The reason for combining a parser for these two unrelated categories is that this is one spot |
| 313 | /// where the sudoer grammar isn't nicely LL(1); so at the same place where "NOPASSWD" can appear, |
| 314 | /// we could also see "ALL". |
| 315 | struct MetaOrTag(Meta<Modifier>); |
| 316 | |
| 317 | /// A `Modifier` is something that updates the `Tag`. |
| 318 | pub type Modifier = Box<dyn Fn(&mut Tag)>; |
| 319 | |
| 320 | // note: at present, "ALL" can be distinguished from a tag using a lookup of 1, since no tag starts with an "A"; but this feels like hanging onto |
| 321 | // the parseability by a thread (although the original sudo also has some ugly parts, like 'sha224' being an illegal user name). |
| 322 | // to be more general, we impl Parse for Meta<Tag> so a future tag like "AFOOBAR" can be added with no problem |
| 323 | |
| 324 | impl Parse for MetaOrTag { |
| 325 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 326 | use Meta::*; |
| 327 | |
| 328 | let start_pos = stream.get_pos(); |
| 329 | let AliasName(keyword) = try_nonterminal(stream)?; |
| 330 | |
| 331 | let mut switch = |modifier: fn(&mut Tag)| { |
| 332 | expect_syntax(':', stream)?; |
| 333 | make(Box::new(modifier)) |
| 334 | }; |
| 335 | |
| 336 | let result: Modifier = match keyword.as_str() { |
| 337 | "EXEC" => switch(|tag| tag.noexec = ExecControl::Exec)?, |
| 338 | "NOEXEC" => switch(|tag| tag.noexec = ExecControl::Noexec)?, |
| 339 | |
| 340 | "SETENV" => switch(|tag| tag.env = EnvironmentControl::Setenv)?, |
| 341 | "NOSETENV" => switch(|tag| tag.env = EnvironmentControl::Nosetenv)?, |
| 342 | "PASSWD" => switch(|tag| tag.authenticate = Authenticate::Passwd)?, |
| 343 | "NOPASSWD" => switch(|tag| tag.authenticate = Authenticate::Nopasswd)?, |
| 344 | |
| 345 | "CWD" => { |
| 346 | expect_syntax('=', stream)?; |
| 347 | let path: ChDir = expect_nonterminal(stream)?; |
| 348 | Box::new(move |tag| tag.cwd = Some(path.clone())) |
| 349 | } |
| 350 | |
| 351 | // we do not support these, and that should make sudo-rs "fail safe" |
| 352 | spec @ ("INTERCEPT" | "CHROOT" | "TIMEOUT" | "NOTBEFORE" | "NOTAFTER") => { |
| 353 | unrecoverable!( |
| 354 | pos = start_pos, |
| 355 | stream, |
| 356 | "{spec} is not supported by sudo-rs" |
| 357 | ) |
| 358 | } |
| 359 | "ROLE" | "TYPE" => unrecoverable!( |
| 360 | pos = start_pos, |
| 361 | stream, |
| 362 | "SELinux role based access control is not yet supported by sudo-rs" |
| 363 | ), |
| 364 | |
| 365 | // this is less fatal |
| 366 | "LOG_INPUT" | "NOLOG_INPUT" | "LOG_OUTPUT" | "NOLOG_OUTPUT" | "MAIL" | "NOMAIL" |
| 367 | | "FOLLOW" => { |
| 368 | let ignored_location = Span { |
| 369 | start: start_pos, |
| 370 | end: stream.get_pos(), |
| 371 | }; |
| 372 | expect_syntax(':', stream)?; |
| 373 | Box::new(move |tag| tag.ignored.push(ignored_location)) |
| 374 | } |
| 375 | |
| 376 | // 'NOFOLLOW' and 'NOINTERCEPT' are the default behaviour. |
| 377 | "NOFOLLOW" | "NOINTERCEPT" => switch(|_| {})?, |
| 378 | |
| 379 | "APPARMOR_PROFILE" => { |
| 380 | expect_syntax('=', stream)?; |
| 381 | let StringParameter(profile) = expect_nonterminal(stream)?; |
| 382 | Box::new(move |tag| tag.apparmor_profile = Some(profile.clone())) |
| 383 | } |
| 384 | |
| 385 | "ALL" => return make(MetaOrTag(All)), |
| 386 | alias => { |
| 387 | if is_syntax('=', stream)? { |
| 388 | unrecoverable!(pos = start_pos, stream, "unsupported modifier '{}'", alias); |
| 389 | } else { |
| 390 | return make(MetaOrTag(Alias(alias.to_string()))); |
| 391 | } |
| 392 | } |
| 393 | }; |
| 394 | |
| 395 | make(MetaOrTag(Only(result))) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | /// grammar: |
| 400 | /// ```text |
| 401 | /// commandspec = [tag modifiers]*, command |
| 402 | /// ``` |
| 403 | impl Parse for CommandSpec { |
| 404 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 405 | use Qualified::Allow; |
| 406 | let mut tags = vec![]; |
| 407 | while let Some(MetaOrTag(keyword)) = try_nonterminal(stream)? { |
| 408 | match keyword { |
| 409 | Meta::Only(modifier) => tags.push(modifier), |
| 410 | Meta::All => return make(CommandSpec(tags, Allow(Meta::All))), |
| 411 | Meta::Alias(name) => return make(CommandSpec(tags, Allow(Meta::Alias(name)))), |
| 412 | } |
| 413 | if tags.len() > Identifier::LIMIT { |
| 414 | unrecoverable!(stream, "too many tags for command specifier") |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | let cmd: Spec<Command> = expect_nonterminal(stream)?; |
| 419 | |
| 420 | make(CommandSpec(tags, cmd)) |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /// Parsing for a tuple of hostname, runas specifier and commandspec. |
| 425 | /// grammar: |
| 426 | /// ```text |
| 427 | /// (host,runas,commandspec) = hostlist, "=", [runas?, commandspec]+ |
| 428 | /// ``` |
| 429 | impl Parse for (SpecList<Hostname>, Vec<(Option<RunAs>, CommandSpec)>) { |
| 430 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 431 | let hosts = try_nonterminal(stream)?; |
| 432 | expect_syntax('=', stream)?; |
| 433 | let runas_cmds = expect_nonterminal(stream)?; |
| 434 | |
| 435 | make((hosts, runas_cmds)) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// A hostname, runas specifier, commandspec combination can occur multiple times in a single |
| 440 | /// sudoer line (separated by ":") |
| 441 | impl Many for (SpecList<Hostname>, Vec<(Option<RunAs>, CommandSpec)>) { |
| 442 | const SEP: char = ':'; |
| 443 | } |
| 444 | |
| 445 | /// Parsing for a tuple of hostname, runas specifier and commandspec. |
| 446 | /// grammar: |
| 447 | /// ```text |
| 448 | /// (runas,commandspec) = runas?, commandspec |
| 449 | /// ``` |
| 450 | impl Parse for (Option<RunAs>, CommandSpec) { |
| 451 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 452 | let runas: Option<RunAs> = try_nonterminal(stream)?; |
| 453 | let cmd = if runas.is_some() { |
| 454 | expect_nonterminal(stream)? |
| 455 | } else { |
| 456 | try_nonterminal(stream)? |
| 457 | }; |
| 458 | |
| 459 | make((runas, cmd)) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | /// A runas specifier, commandspec combination can occur multiple times in a single |
| 464 | /// sudoer line (separated by ","); there is some ambiguity in the original grammar: |
| 465 | /// commands can also occur multiple times; we parse that here as if they have an omitted |
| 466 | /// "runas" specifier (which has to be placed correctly during the AST analysis phase) |
| 467 | impl Many for (Option<RunAs>, CommandSpec) {} |
| 468 | |
| 469 | /// Directives such as "Defaults" and "HostAlias" also could be parsed as part of a |
| 470 | /// UserSpecifier list. We need to detect to give a parse error in cases where the syntax |
| 471 | /// seems to suggest they are used in that manner. |
| 472 | /// Technically, "Defaults@host" is also a valid username, but the logic can disambiguate |
| 473 | /// those cases clearly. E.g. "Defaults@host1,host2 secure_path=/bin/sh" is technically |
| 474 | /// ambiguous but it can be parsed. Time flies like an arrow, fruit flies like a banana. |
| 475 | impl Directive { |
| 476 | fn could_be_username(&self) -> bool { |
| 477 | matches!( |
| 478 | self, |
| 479 | Self::Defaults(_, ConfigScope::Generic) |
| 480 | | Self::UserAlias(_) |
| 481 | | Self::HostAlias(_) |
| 482 | | Self::CmndAlias(_) |
| 483 | | Self::RunasAlias(_) |
| 484 | ) |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | /// grammar: |
| 489 | /// ```text |
| 490 | /// sudo = permissionspec |
| 491 | /// | Keyword_Alias identifier = identifier_list |
| 492 | /// | Defaults (name [+-]?= ...)+ |
| 493 | /// ``` |
| 494 | /// There is a syntactical ambiguity in the sudoer Directive and Permission specifications, so we |
| 495 | /// have to parse them 'together' and do a delayed decision on which category we are in. |
| 496 | impl Parse for Sudo { |
| 497 | // note: original sudo would reject: |
| 498 | // "User_Alias, user machine = command" |
| 499 | // but accept: |
| 500 | // "user, User_Alias machine = command"; this does the same |
| 501 | fn parse(stream: &mut CharStream) -> Parsed<Sudo> { |
| 502 | if stream.eat_char('@') { |
| 503 | return parse_include(stream); |
| 504 | } |
| 505 | |
| 506 | // the existence of "#include" forces us to handle lines that start with #<ID> explicitly |
| 507 | if stream.peek() == Some('#') { |
| 508 | return if let Ok(ident) = try_nonterminal::<Identifier>(stream) { |
| 509 | let first_user = Qualified::Allow(Meta::Only(UserSpecifier::User(ident))); |
| 510 | let users = if is_syntax(',', stream)? { |
| 511 | // parse the rest of the userlist and add the already-parsed user in front |
| 512 | let mut rest = expect_nonterminal::<SpecList<_>>(stream)?; |
| 513 | rest.insert(0, first_user); |
| 514 | rest |
| 515 | } else { |
| 516 | vec![first_user] |
| 517 | }; |
| 518 | // no need to check get_directive as no other directive starts with # |
| 519 | let permissions = expect_nonterminal(stream)?; |
| 520 | make(Sudo::Spec(PermissionSpec { users, permissions })) |
| 521 | } else { |
| 522 | // the failed "try_nonterminal::<Identifier>" will have consumed the '#' |
| 523 | // the most ignominious part of sudoers: having to parse bits of comments |
| 524 | parse_include(stream).or_else(|_| { |
| 525 | stream.skip_to_newline(); |
| 526 | make(Sudo::LineComment) |
| 527 | }) |
| 528 | }; |
| 529 | } |
| 530 | |
| 531 | let start_state = stream.clone(); |
| 532 | if stream.peek() == Some('"') { |
| 533 | // a quoted userlist follows; this forces us to read a userlist |
| 534 | let users = expect_nonterminal(stream)?; |
| 535 | let permissions = expect_nonterminal(stream)?; |
| 536 | make(Sudo::Spec(PermissionSpec { users, permissions })) |
| 537 | } else if let Some(users) = maybe(try_nonterminal::<SpecList<_>>(stream))? { |
| 538 | // this could be the start of a Defaults or Alias definition, so distinguish. |
| 539 | // element 1 always exists (parse_list fails on an empty list) |
| 540 | let key = &users[0]; |
| 541 | let start_pos = start_state.get_pos(); |
| 542 | if let Some(directive) = maybe(get_directive(key, stream, start_state))? { |
| 543 | if users.len() != 1 && directive.could_be_username() { |
| 544 | // this is here to guard against User_Alias,foo ALIAS=def being accepted |
| 545 | unrecoverable!(pos = start_pos, stream, "ambiguous syntax"); |
| 546 | } |
| 547 | make(Sudo::Decl(directive)) |
| 548 | } else { |
| 549 | let permissions = expect_nonterminal(stream)?; |
| 550 | make(Sudo::Spec(PermissionSpec { users, permissions })) |
| 551 | } |
| 552 | } else { |
| 553 | // this will leave whatever could not be parsed on the input stream |
| 554 | make(Sudo::LineComment) |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | /// Parse the include/include dir part that comes after the '#' or '@' prefix symbol |
| 560 | fn parse_include(stream: &mut CharStream) -> Parsed<Sudo> { |
| 561 | fn get_path(stream: &mut CharStream, key_pos: (usize, usize)) -> Parsed<(String, Span)> { |
| 562 | let path = if stream.eat_char('"') { |
| 563 | let QuotedIncludePath(path) = expect_nonterminal(stream)?; |
| 564 | expect_syntax('"', stream)?; |
| 565 | path |
| 566 | } else { |
| 567 | let value_pos = stream.get_pos(); |
| 568 | let IncludePath(path) = expect_nonterminal(stream)?; |
| 569 | if stream.peek() != Some('\n') { |
| 570 | unrecoverable!( |
| 571 | pos = value_pos, |
| 572 | stream, |
| 573 | "use quotes around filenames or escape whitespace" |
| 574 | ) |
| 575 | } |
| 576 | path |
| 577 | }; |
| 578 | make(( |
| 579 | path, |
| 580 | Span { |
| 581 | start: key_pos, |
| 582 | end: stream.get_pos(), |
| 583 | }, |
| 584 | )) |
| 585 | } |
| 586 | |
| 587 | let key_pos = stream.get_pos(); |
| 588 | let result = match try_nonterminal(stream)? { |
| 589 | Some(Username(key)) if key == "include" => { |
| 590 | let (path, span) = get_path(stream, key_pos)?; |
| 591 | Sudo::Include(path, span) |
| 592 | } |
| 593 | Some(Username(key)) if key == "includedir" => { |
| 594 | let (path, span) = get_path(stream, key_pos)?; |
| 595 | Sudo::IncludeDir(path, span) |
| 596 | } |
| 597 | #[cfg(feature = "unstable-remote-sudoers")] |
| 598 | Some(Username(key)) if key == "socket" => { |
| 599 | let (path, span) = get_path(stream, key_pos)?; |
| 600 | Sudo::Remote(path, span) |
| 601 | } |
| 602 | _ => unrecoverable!(pos = key_pos, stream, "unknown directive"), |
| 603 | }; |
| 604 | |
| 605 | make(result) |
| 606 | } |
| 607 | |
| 608 | fn is_reserved_alias(name: &str) -> bool { |
| 609 | matches!( |
| 610 | name, |
| 611 | "ALL" | "CHROOT" | "CWD" | "NOTAFTER" | "NOTBEFORE" | "ROLE" | "TIMEOUT" | "TYPE" |
| 612 | ) |
| 613 | } |
| 614 | |
| 615 | /// grammar: |
| 616 | /// ```text |
| 617 | /// name = definition [ : name = definition [ : ... ] ] |
| 618 | /// ``` |
| 619 | /// |
| 620 | impl<T> Parse for Def<T> |
| 621 | where |
| 622 | T: UserFriendly, |
| 623 | Meta<T>: Parse + Many, |
| 624 | { |
| 625 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 626 | let begin_pos = stream.get_pos(); |
| 627 | let AliasName(name) = try_nonterminal(stream)?; |
| 628 | if is_reserved_alias(&name) { |
| 629 | unrecoverable!( |
| 630 | pos = begin_pos, |
| 631 | stream, |
| 632 | "reserved word {} used as an alias name", |
| 633 | name |
| 634 | ); |
| 635 | } |
| 636 | expect_syntax('=', stream)?; |
| 637 | |
| 638 | make(Def(name, expect_nonterminal(stream)?)) |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | impl<T> Many for Def<T> { |
| 643 | const SEP: char = ':'; |
| 644 | } |
| 645 | |
| 646 | // NOTE: This function is a bit of a hack, since it relies on the fact that all directives |
| 647 | // occur in the spot of a username, and are of a form that would otherwise be a legal user name. |
| 648 | // I.e. after a valid username has been parsed, we check if it isn't actually a valid start of a |
| 649 | // directive. A more robust solution would be to use the approach taken by the `MetaOrTag` above. |
| 650 | |
| 651 | fn get_directive<'a>( |
| 652 | perhaps_keyword: &Spec<UserSpecifier>, |
| 653 | stream: &mut CharStream<'a>, |
| 654 | begin_state: CharStream<'a>, |
| 655 | ) -> Parsed<Directive> { |
| 656 | use super::ast::Directive::*; |
| 657 | use super::ast::Meta::*; |
| 658 | use super::ast::Qualified::*; |
| 659 | use super::ast::UserSpecifier::*; |
| 660 | let Allow(Only(User(Identifier::Name(keyword)))) = perhaps_keyword else { |
| 661 | return reject(); |
| 662 | }; |
| 663 | |
| 664 | let begin_pos = begin_state.get_pos(); |
| 665 | |
| 666 | match keyword.as_str() { |
| 667 | "User_Alias" => make(UserAlias(expect_nonterminal(stream)?)), |
| 668 | "Host_Alias" => make(HostAlias(expect_nonterminal(stream)?)), |
| 669 | "Cmnd_Alias" | "Cmd_Alias" => make(CmndAlias(expect_nonterminal(stream)?)), |
| 670 | "Runas_Alias" => make(RunasAlias(expect_nonterminal(stream)?)), |
| 671 | _ if keyword.starts_with("Defaults") => { |
| 672 | // HACK #1: no space is allowed between "Defaults" and '!>@:'. The below avoids having to |
| 673 | // add "Defaults!" etc as separate tokens; but relying on positional information during |
| 674 | // parsing is of course, cheating. |
| 675 | // HACK #2: '@' can be part of a username, so it will already have been parsed; |
| 676 | // an acceptable hostname is subset of an acceptable username, so that's actually OK. |
| 677 | // This resolves an ambiguity in the grammar similarly to how MetaOrTag does that. |
| 678 | const DEFAULTS_LEN: usize = "Defaults".len(); |
| 679 | let allow_scope_modifier = keyword[DEFAULTS_LEN..].starts_with('@') |
| 680 | || (stream.get_pos().0 == begin_pos.0 |
| 681 | && stream.get_pos().1 - begin_pos.1 == DEFAULTS_LEN); |
| 682 | |
| 683 | let scope = if allow_scope_modifier { |
| 684 | if keyword[DEFAULTS_LEN..].starts_with('@') { |
| 685 | // Backtrack and start parsing following the '@' sign |
| 686 | *stream = begin_state; |
| 687 | stream.advance(DEFAULTS_LEN + 1); |
| 688 | skip_trailing_whitespace(stream)?; |
| 689 | |
| 690 | ConfigScope::Host(expect_nonterminal(stream)?) |
| 691 | } else if is_syntax(':', stream)? { |
| 692 | ConfigScope::User(expect_nonterminal(stream)?) |
| 693 | } else if is_syntax('!', stream)? { |
| 694 | ConfigScope::Command(expect_nonterminal(stream)?) |
| 695 | } else if is_syntax('>', stream)? { |
| 696 | ConfigScope::RunAs(expect_nonterminal(stream)?) |
| 697 | } else { |
| 698 | ConfigScope::Generic |
| 699 | } |
| 700 | } else { |
| 701 | ConfigScope::Generic |
| 702 | }; |
| 703 | |
| 704 | make(Defaults(expect_nonterminal(stream)?, scope)) |
| 705 | } |
| 706 | _ => reject(), |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | /// grammar: |
| 711 | /// ```text |
| 712 | /// parameter = name [+-]?= ... |
| 713 | /// ``` |
| 714 | impl Parse for defaults::SettingsModifier { |
| 715 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 716 | let id_pos = stream.get_pos(); |
| 717 | |
| 718 | // Parse multiple entries enclosed in quotes (for list-like Defaults-settings) |
| 719 | let parse_vars = |stream: &mut CharStream| -> Parsed<Vec<String>> { |
| 720 | if stream.eat_char('"') { |
| 721 | let mut result = Vec::new(); |
| 722 | while let Some(EnvVar(name)) = try_nonterminal(stream)? { |
| 723 | if is_syntax('=', stream)? { |
| 724 | let StringParameter(value) = expect_nonterminal(stream)?; |
| 725 | result.push(name + "=" + &value); |
| 726 | } else { |
| 727 | result.push(name); |
| 728 | } |
| 729 | if result.len() > Identifier::LIMIT { |
| 730 | unrecoverable!(stream, "environment variable list too long") |
| 731 | } |
| 732 | } |
| 733 | expect_syntax('"', stream)?; |
| 734 | if result.is_empty() { |
| 735 | unrecoverable!(stream, "empty string not allowed"); |
| 736 | } |
| 737 | |
| 738 | make(result) |
| 739 | } else { |
| 740 | let EnvVar(name) = expect_nonterminal(stream)?; |
| 741 | if is_syntax('=', stream)? { |
| 742 | unrecoverable!(stream, "double quotes are required for VAR=value pairs") |
| 743 | } else { |
| 744 | make(vec![name]) |
| 745 | } |
| 746 | } |
| 747 | }; |
| 748 | |
| 749 | // Parse the remainder of a list variable |
| 750 | let list_items = |
| 751 | |mode: defaults::ListMode, name: String, cfg: defaults::SettingKind, stream: &mut _| { |
| 752 | expect_syntax('=', stream)?; |
| 753 | let defaults::SettingKind::List(checker) = cfg else { |
| 754 | unrecoverable!(pos = id_pos, stream, "{name} is not a list parameter"); |
| 755 | }; |
| 756 | |
| 757 | make(checker(mode, parse_vars(stream)?)) |
| 758 | }; |
| 759 | |
| 760 | // Parse a text parameter |
| 761 | let text_item = |stream: &mut CharStream| { |
| 762 | if stream.eat_char('"') { |
| 763 | let QuotedStringParameter(text) = expect_nonterminal(stream)?; |
| 764 | expect_syntax('"', stream)?; |
| 765 | make(text) |
| 766 | } else { |
| 767 | let StringParameter(name) = expect_nonterminal(stream)?; |
| 768 | make(name) |
| 769 | } |
| 770 | }; |
| 771 | |
| 772 | if is_syntax('!', stream)? { |
| 773 | let value_pos = stream.get_pos(); |
| 774 | let DefaultName(name) = expect_nonterminal(stream)?; |
| 775 | let Some(modifier) = defaults::negate(&name) else { |
| 776 | if defaults::set(&name).is_some() { |
| 777 | unrecoverable!( |
| 778 | pos = value_pos, |
| 779 | stream, |
| 780 | "'{name}' cannot be used in a boolean context" |
| 781 | ); |
| 782 | } else { |
| 783 | unrecoverable!(pos = value_pos, stream, "unknown setting: '{name}'"); |
| 784 | } |
| 785 | }; |
| 786 | |
| 787 | make(modifier) |
| 788 | } else { |
| 789 | let DefaultName(name) = try_nonterminal(stream)?; |
| 790 | let Some(cfg) = defaults::set(&name) else { |
| 791 | unrecoverable!(pos = id_pos, stream, "unknown setting: '{name}'"); |
| 792 | }; |
| 793 | |
| 794 | if is_syntax('+', stream)? { |
| 795 | list_items(defaults::ListMode::Add, name, cfg, stream) |
| 796 | } else if is_syntax('-', stream)? { |
| 797 | list_items(defaults::ListMode::Del, name, cfg, stream) |
| 798 | } else if is_syntax('=', stream)? { |
| 799 | let value_pos = stream.get_pos(); |
| 800 | match cfg { |
| 801 | defaults::SettingKind::Flag(_) => { |
| 802 | unrecoverable!(stream, "can't assign to boolean setting '{name}'") |
| 803 | } |
| 804 | defaults::SettingKind::Integer(checker) => { |
| 805 | let Numeric(denotation) = expect_nonterminal(stream)?; |
| 806 | if let Some(modifier) = checker(&denotation) { |
| 807 | make(modifier) |
| 808 | } else { |
| 809 | unrecoverable!( |
| 810 | pos = value_pos, |
| 811 | stream, |
| 812 | "'{denotation}' is not a valid value for {name}" |
| 813 | ); |
| 814 | } |
| 815 | } |
| 816 | defaults::SettingKind::List(checker) => { |
| 817 | let items = parse_vars(stream)?; |
| 818 | |
| 819 | make(checker(defaults::ListMode::Set, items)) |
| 820 | } |
| 821 | defaults::SettingKind::Text(checker) => { |
| 822 | let text = text_item(stream)?; |
| 823 | let Some(modifier) = checker(&text) else { |
| 824 | unrecoverable!( |
| 825 | pos = value_pos, |
| 826 | stream, |
| 827 | "'{text}' is not a valid value for {name}" |
| 828 | ); |
| 829 | }; |
| 830 | make(modifier) |
| 831 | } |
| 832 | } |
| 833 | } else { |
| 834 | let defaults::SettingKind::Flag(modifier) = cfg else { |
| 835 | unrecoverable!(pos = id_pos, stream, "'{name}' is not a boolean setting"); |
| 836 | }; |
| 837 | |
| 838 | make(modifier) |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | } |
| 843 | |
| 844 | impl Many for defaults::SettingsModifier {} |