| 1 | //! Various tokens |
| 2 | |
| 3 | use crate::common::{SudoPath, SudoString}; |
| 4 | use std::ffi::OsString; |
| 5 | |
| 6 | use super::basic_parser::{Many, Token}; |
| 7 | use crate::common::{HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2}; |
| 8 | |
| 9 | #[cfg_attr(test, derive(Clone, PartialEq, Eq))] |
| 10 | pub struct Username(pub SudoString); |
| 11 | |
| 12 | /// A username consists of alphanumeric characters as well as ".", "-", "_". |
| 13 | /// Furthermore, it may contain embedded "@" characters (but not start with them) and end in a "$". |
| 14 | // See: https://systemd.io/USER_NAMES/ |
| 15 | impl Token for Username { |
| 16 | fn construct(text: String) -> Result<Self, String> { |
| 17 | // if a '$' occurs in a username, it has to be the final character |
| 18 | if text.strip_suffix('$').unwrap_or(&text).contains('$') { |
| 19 | return Err("embedded $ in username".to_string()); |
| 20 | } |
| 21 | |
| 22 | SudoString::new(text) |
| 23 | .map_err(|e| e.to_string()) |
| 24 | .map(Username) |
| 25 | } |
| 26 | |
| 27 | fn accept(c: char) -> bool { |
| 28 | c.is_alphanumeric() || ".-_@$".contains(c) |
| 29 | } |
| 30 | |
| 31 | fn accept_1st(c: char) -> bool { |
| 32 | c != '@' && Self::accept(c) |
| 33 | } |
| 34 | |
| 35 | const ALLOW_ESCAPE: bool = true; |
| 36 | fn escaped(c: char) -> bool { |
| 37 | matches!(c, '\\' | '"' | ',' | ':' | '=' | '!' | '(' | ')' | ' ') |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl Many for Username {} |
| 42 | |
| 43 | pub struct DigitsU32(pub u32); |
| 44 | |
| 45 | impl Token for DigitsU32 { |
| 46 | const MAX_LEN: usize = 10; |
| 47 | |
| 48 | fn construct(s: String) -> Result<Self, String> { |
| 49 | s.parse() |
| 50 | .map(Self) |
| 51 | .map_err(|_| "value too large".to_string()) |
| 52 | } |
| 53 | |
| 54 | fn accept(c: char) -> bool { |
| 55 | c.is_ascii_digit() |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub struct Numeric(pub String); |
| 60 | |
| 61 | impl Token for Numeric { |
| 62 | const MAX_LEN: usize = 18; |
| 63 | |
| 64 | fn construct(s: String) -> Result<Self, String> { |
| 65 | Ok(Numeric(s)) |
| 66 | } |
| 67 | |
| 68 | fn accept(c: char) -> bool { |
| 69 | c.is_ascii_hexdigit() || c == '.' |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// A hostname consists of alphanumeric characters and ".", "-", "_" |
| 74 | pub struct Hostname(pub String); |
| 75 | |
| 76 | impl std::ops::Deref for Hostname { |
| 77 | type Target = String; |
| 78 | |
| 79 | fn deref(&self) -> &Self::Target { |
| 80 | &self.0 |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | impl Token for Hostname { |
| 85 | fn construct(text: String) -> Result<Self, String> { |
| 86 | // reject hostnames that resemble IPv4 addresses too closely |
| 87 | // (IPv6 addresses will already be reject since ':' is not in the accept-set) |
| 88 | let mut chunks = text.rsplitn(5, '.'); |
| 89 | if (&mut chunks) |
| 90 | .take(4) |
| 91 | .all(|part| !part.is_empty() && part.len() <= 3 && part.chars().all(char::is_numeric)) |
| 92 | && chunks.next().is_none() |
| 93 | { |
| 94 | return Err("hosts cannot be specified using an IPv4 address".to_string()); |
| 95 | } |
| 96 | |
| 97 | Ok(Hostname(text)) |
| 98 | } |
| 99 | |
| 100 | fn accept(c: char) -> bool { |
| 101 | c.is_ascii_alphanumeric() || ".-_".contains(c) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl Many for Hostname {} |
| 106 | |
| 107 | /// This enum allows items to use the ALL wildcard or be specified with aliases, or directly. |
| 108 | /// (Maybe this is better defined not as a Token but simply directly as an implementation of [crate::sudoers::basic_parser::Parse]) |
| 109 | #[cfg_attr(test, derive(Debug, PartialEq, Eq))] |
| 110 | #[repr(u32)] |
| 111 | pub enum Meta<T> { |
| 112 | All = HARDENED_ENUM_VALUE_0, |
| 113 | Only(T) = HARDENED_ENUM_VALUE_1, |
| 114 | Alias(String) = HARDENED_ENUM_VALUE_2, |
| 115 | } |
| 116 | |
| 117 | impl<T: Token> Token for Meta<T> { |
| 118 | fn construct(raw: String) -> Result<Self, String> { |
| 119 | // `T` may accept whitespace resulting in `raw` having trailing whitespace which would make |
| 120 | // the first two checks below fail. this `cooked` version has no trailing whitespace |
| 121 | let cooked = raw.trim_end().to_string(); |
| 122 | |
| 123 | Ok(if cooked == "ALL" { |
| 124 | Meta::All |
| 125 | } else if cooked.starts_with(AliasName::accept_1st) |
| 126 | && cooked.chars().skip(1).all(AliasName::accept) |
| 127 | { |
| 128 | Meta::Alias(cooked) |
| 129 | } else { |
| 130 | Meta::Only(T::construct(raw)?) |
| 131 | }) |
| 132 | } |
| 133 | |
| 134 | const MAX_LEN: usize = T::MAX_LEN; |
| 135 | |
| 136 | fn accept(c: char) -> bool { |
| 137 | T::accept(c) || c.is_uppercase() |
| 138 | } |
| 139 | fn accept_1st(c: char) -> bool { |
| 140 | T::accept_1st(c) || c.is_uppercase() |
| 141 | } |
| 142 | |
| 143 | const ALLOW_ESCAPE: bool = T::ALLOW_ESCAPE; |
| 144 | |
| 145 | fn escaped(c: char) -> bool { |
| 146 | T::escaped(c) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | impl<T: Many> Many for Meta<T> { |
| 151 | const SEP: char = T::SEP; |
| 152 | const LIMIT: usize = T::LIMIT; |
| 153 | } |
| 154 | |
| 155 | /// An identifier that consists of only uppercase characters. |
| 156 | pub struct AliasName(pub String); |
| 157 | |
| 158 | impl Token for AliasName { |
| 159 | fn construct(s: String) -> Result<Self, String> { |
| 160 | Ok(AliasName(s)) |
| 161 | } |
| 162 | |
| 163 | fn accept_1st(c: char) -> bool { |
| 164 | c.is_ascii_uppercase() |
| 165 | } |
| 166 | |
| 167 | fn accept(c: char) -> bool { |
| 168 | Self::accept_1st(c) || c.is_ascii_digit() || c == '_' |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// A struct that represents valid command strings; this can contain escape sequences and are |
| 173 | /// limited to 1024 characters. |
| 174 | #[derive(PartialEq)] |
| 175 | #[repr(u32)] |
| 176 | pub enum Args { |
| 177 | Prefix(Box<[OsString]>) = HARDENED_ENUM_VALUE_0, |
| 178 | Exact(Box<[OsString]>) = HARDENED_ENUM_VALUE_1, |
| 179 | } |
| 180 | |
| 181 | pub type Command = (SimpleCommand, Args); |
| 182 | |
| 183 | /// A type that is specific to 'only commands', that can only happen in "Defaults!command" contexts; |
| 184 | /// which is essentially a subset of "Command" |
| 185 | pub type SimpleCommand = glob::Pattern; |
| 186 | |
| 187 | impl Token for Command { |
| 188 | const MAX_LEN: usize = 1024; |
| 189 | |
| 190 | fn construct(s: String) -> Result<Self, String> { |
| 191 | // the tokenizer should not give us a token that consists of only whitespace |
| 192 | let mut cmd_iter = s.split_whitespace(); |
| 193 | let cmd = cmd_iter.next().unwrap().to_string(); |
| 194 | let mut args = cmd_iter.map(OsString::from).collect::<Vec<OsString>>(); |
| 195 | |
| 196 | let command = SimpleCommand::construct(cmd)?; |
| 197 | |
| 198 | let argpat = if args.is_empty() { |
| 199 | // if no arguments are mentioned, anything is allowed |
| 200 | Args::Prefix(Box::default()) |
| 201 | } else { |
| 202 | if args |
| 203 | .first() |
| 204 | .is_some_and(|x| x.as_encoded_bytes().starts_with(b"^")) |
| 205 | { |
| 206 | // regular expressions are not supported, give an error message. If there is only a |
| 207 | // terminating '$', this is not treated as a malformed regex by millersudo, so we don't |
| 208 | // need to seperately check for that |
| 209 | return Err("regular expressions are not supported".to_string()); |
| 210 | } |
| 211 | let match_type = match args.last().map(|x| x.as_encoded_bytes()) { |
| 212 | // if the magic * appears, any further arguments are allowed |
| 213 | Some(b"*") => { |
| 214 | args.pop(); |
| 215 | Args::Prefix |
| 216 | } |
| 217 | // if the magic "" appears, no (further) arguments are allowed |
| 218 | Some(b"\"\"") => { |
| 219 | args.pop(); |
| 220 | Args::Exact |
| 221 | } |
| 222 | _ => Args::Exact, |
| 223 | }; |
| 224 | |
| 225 | if args |
| 226 | .iter() |
| 227 | .any(|arg| arg.as_encoded_bytes().iter().any(|c| b"?*".contains(c))) |
| 228 | { |
| 229 | return Err("wildcards are not allowed in command arguments".to_string()); |
| 230 | } |
| 231 | |
| 232 | match_type(args.into_boxed_slice()) |
| 233 | }; |
| 234 | |
| 235 | if command.as_str() == "list" && argpat != Args::Prefix(Box::default()) { |
| 236 | return Err("list does not take arguments".to_string()); |
| 237 | } |
| 238 | |
| 239 | Ok((command, argpat)) |
| 240 | } |
| 241 | |
| 242 | // all commands start with "/" except "sudoedit" or "list" |
| 243 | fn accept_1st(c: char) -> bool { |
| 244 | SimpleCommand::accept_1st(c) |
| 245 | } |
| 246 | |
| 247 | fn accept(c: char) -> bool { |
| 248 | SimpleCommand::accept(c) || c == ' ' |
| 249 | } |
| 250 | |
| 251 | const ALLOW_ESCAPE: bool = SimpleCommand::ALLOW_ESCAPE; |
| 252 | fn escaped(c: char) -> bool { |
| 253 | SimpleCommand::escaped(c) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | impl Token for SimpleCommand { |
| 258 | const MAX_LEN: usize = 1024; |
| 259 | |
| 260 | fn construct(mut cmd: String) -> Result<Self, String> { |
| 261 | let cvt_err = |pat: Result<_, glob::PatternError>| { |
| 262 | pat.map_err(|err| format!("wildcard pattern error {err}")) |
| 263 | }; |
| 264 | |
| 265 | // detect the two edges cases |
| 266 | if cmd == "list" || cmd == "sudoedit" { |
| 267 | return cvt_err(glob::Pattern::new(&cmd)); |
| 268 | } else if cmd.starts_with("sha") { |
| 269 | return Err("digest specifications are not supported".to_string()); |
| 270 | } else if cmd.starts_with('^') { |
| 271 | return Err("regular expressions are not supported".to_string()); |
| 272 | } else if !cmd.starts_with('/') { |
| 273 | return Err("fully qualified path needed".to_string()); |
| 274 | } |
| 275 | |
| 276 | // record if the cmd ends in a slash and remove it if it does |
| 277 | let is_dir = cmd.ends_with('/') && { |
| 278 | cmd.pop(); |
| 279 | true |
| 280 | }; |
| 281 | |
| 282 | // canonicalize path (if possible) |
| 283 | if let Ok(real_cmd) = crate::common::resolve::canonicalize(&cmd) { |
| 284 | cmd = real_cmd |
| 285 | .to_str() |
| 286 | .ok_or("non-UTF8 characters in filesystem")? |
| 287 | .to_string(); |
| 288 | } |
| 289 | |
| 290 | // if the cmd ends with a slash, any command in that directory is allowed |
| 291 | if is_dir { |
| 292 | cmd.push_str("/*"); |
| 293 | } |
| 294 | |
| 295 | cvt_err(glob::Pattern::new(&cmd)) |
| 296 | } |
| 297 | |
| 298 | // all commands start with "/" except "sudoedit" or "list" |
| 299 | fn accept_1st(c: char) -> bool { |
| 300 | c == '/' || c == 's' || c == 'l' |
| 301 | } |
| 302 | |
| 303 | fn accept(c: char) -> bool { |
| 304 | // '=' is allowed both escaped and un-escaped |
| 305 | (!Self::escaped(c) && !c.is_control()) || c == '=' |
| 306 | } |
| 307 | |
| 308 | const ALLOW_ESCAPE: bool = true; |
| 309 | fn escaped(c: char) -> bool { |
| 310 | matches!(c, '\\' | ',' | ':' | '=' | '#' | ' ') |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | impl Many for Command {} |
| 315 | impl Many for SimpleCommand {} |
| 316 | |
| 317 | pub struct DefaultName(pub String); |
| 318 | |
| 319 | impl Token for DefaultName { |
| 320 | fn construct(text: String) -> Result<Self, String> { |
| 321 | Ok(DefaultName(text)) |
| 322 | } |
| 323 | |
| 324 | fn accept(c: char) -> bool { |
| 325 | c.is_ascii_alphanumeric() || c == '_' |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | pub struct EnvVar(pub String); |
| 330 | |
| 331 | impl Token for EnvVar { |
| 332 | fn construct(text: String) -> Result<Self, String> { |
| 333 | Ok(EnvVar(text)) |
| 334 | } |
| 335 | |
| 336 | fn accept(c: char) -> bool { |
| 337 | !c.is_control() && !c.is_whitespace() && !Self::escaped(c) |
| 338 | } |
| 339 | |
| 340 | const ALLOW_ESCAPE: bool = true; |
| 341 | fn escaped(c: char) -> bool { |
| 342 | matches!(c, '\\' | '=' | '#' | '"' | ',') |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// A token with a very liberal inner tokenizer; compare StringParameter below |
| 347 | pub struct QuotedStringParameter(pub String); |
| 348 | |
| 349 | impl Token for QuotedStringParameter { |
| 350 | const MAX_LEN: usize = 1024; |
| 351 | |
| 352 | fn construct(s: String) -> Result<Self, String> { |
| 353 | Ok(Self(s)) |
| 354 | } |
| 355 | |
| 356 | fn accept(c: char) -> bool { |
| 357 | !Self::escaped(c) |
| 358 | } |
| 359 | |
| 360 | const ALLOW_ESCAPE: bool = true; |
| 361 | fn escaped(c: char) -> bool { |
| 362 | matches!(c, '\\' | '"') || c.is_control() |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// Similar to QuotedStringParameter but treats backslashes differently |
| 367 | /// Compare IncludePath below. |
| 368 | // `@include "some/path"` |
| 369 | // ^^^^^^^^^^^ |
| 370 | pub struct QuotedIncludePath(pub String); |
| 371 | |
| 372 | impl Token for QuotedIncludePath { |
| 373 | const MAX_LEN: usize = 1024; |
| 374 | |
| 375 | fn construct(s: String) -> Result<Self, String> { |
| 376 | Ok(Self(s)) |
| 377 | } |
| 378 | |
| 379 | fn accept(c: char) -> bool { |
| 380 | !Self::escaped(c) |
| 381 | } |
| 382 | |
| 383 | const ALLOW_ESCAPE: bool = true; |
| 384 | fn escaped(c: char) -> bool { |
| 385 | matches!(c, '"') || c.is_control() |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | pub struct IncludePath(pub String); |
| 390 | |
| 391 | impl Token for IncludePath { |
| 392 | const MAX_LEN: usize = 1024; |
| 393 | |
| 394 | fn construct(s: String) -> Result<Self, String> { |
| 395 | Ok(IncludePath(s)) |
| 396 | } |
| 397 | |
| 398 | fn accept(c: char) -> bool { |
| 399 | !c.is_control() && !Self::escaped(c) |
| 400 | } |
| 401 | |
| 402 | const ALLOW_ESCAPE: bool = true; |
| 403 | fn escaped(c: char) -> bool { |
| 404 | matches!(c, '\\' | '"' | ' ') |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | // used for Defaults where quotes around some items are optional |
| 409 | pub struct StringParameter(pub String); |
| 410 | |
| 411 | impl Token for StringParameter { |
| 412 | const MAX_LEN: usize = QuotedStringParameter::MAX_LEN; |
| 413 | |
| 414 | fn construct(s: String) -> Result<Self, String> { |
| 415 | Ok(StringParameter(s)) |
| 416 | } |
| 417 | |
| 418 | fn accept(c: char) -> bool { |
| 419 | !c.is_control() && !Self::escaped(c) |
| 420 | } |
| 421 | |
| 422 | const ALLOW_ESCAPE: bool = true; |
| 423 | fn escaped(c: char) -> bool { |
| 424 | matches!(c, '\\' | '"' | ' ' | '#' | ',') |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | // a path used for in CWD and CHROOT specs |
| 429 | #[derive(Clone, PartialEq)] |
| 430 | #[cfg_attr(test, derive(Debug, Eq))] |
| 431 | #[repr(u32)] |
| 432 | pub enum ChDir { |
| 433 | Path(SudoPath) = HARDENED_ENUM_VALUE_0, |
| 434 | Any = HARDENED_ENUM_VALUE_1, |
| 435 | } |
| 436 | |
| 437 | impl Token for ChDir { |
| 438 | const MAX_LEN: usize = 1024; |
| 439 | |
| 440 | fn construct(s: String) -> Result<Self, String> { |
| 441 | if s == "*" { |
| 442 | Ok(ChDir::Any) |
| 443 | } else if s.contains('*') { |
| 444 | Err("path cannot contain '*'".to_string()) |
| 445 | } else { |
| 446 | Ok(ChDir::Path( |
| 447 | SudoPath::try_from(s).map_err(|e| e.to_string())?, |
| 448 | )) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | fn accept(c: char) -> bool { |
| 453 | !c.is_control() && !Self::escaped(c) |
| 454 | } |
| 455 | |
| 456 | fn accept_1st(c: char) -> bool { |
| 457 | "~/*".contains(c) |
| 458 | } |
| 459 | |
| 460 | const ALLOW_ESCAPE: bool = true; |
| 461 | fn escaped(c: char) -> bool { |
| 462 | matches!(c, '\\' | '"' | ' ') |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | /// Some tokens that support escape characters also support being surrounded by quotes to avoid escaping directly. |
| 467 | pub struct Unquoted<T>(pub String, pub std::marker::PhantomData<T>); |
| 468 | |
| 469 | impl<T: Token> Token for Unquoted<T> { |
| 470 | const MAX_LEN: usize = 1024; |
| 471 | |
| 472 | fn construct(text: String) -> Result<Self, String> { |
| 473 | let mut quoted = String::new(); |
| 474 | for ch in text.chars() { |
| 475 | if T::escaped(ch) { |
| 476 | quoted.push('\\'); |
| 477 | } |
| 478 | quoted.push(ch); |
| 479 | } |
| 480 | |
| 481 | Ok(Self(quoted, std::marker::PhantomData)) |
| 482 | } |
| 483 | |
| 484 | fn accept(c: char) -> bool { |
| 485 | c != '"' && !c.is_control() |
| 486 | } |
| 487 | } |