sudo-rs 0.2.9

A memory safe implementation of sudo and su.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Various tokens

use crate::common::{SudoPath, SudoString};

use super::basic_parser::{Many, Token};
use crate::common::{HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2};

#[cfg_attr(test, derive(Clone, PartialEq, Eq))]
pub struct Username(pub SudoString);

/// A username consists of alphanumeric characters as well as ".", "-", "_".
/// Furthermore, it may contain embedded "@" characters (but not start with them) and end in a "$".
// See: https://systemd.io/USER_NAMES/
impl Token for Username {
    fn construct(text: String) -> Result<Self, String> {
        // if a '$' occurs in a username, it has to be the final character
        if text.strip_suffix('$').unwrap_or(&text).contains('$') {
            return Err("embedded $ in username".to_string());
        }

        SudoString::new(text)
            .map_err(|e| e.to_string())
            .map(Username)
    }

    fn accept(c: char) -> bool {
        c.is_alphanumeric() || ".-_@$".contains(c)
    }

    fn accept_1st(c: char) -> bool {
        c != '@' && Self::accept(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '"' | ',' | ':' | '=' | '!' | '(' | ')' | ' ')
    }
}

impl Many for Username {}

pub struct Digits(pub u32);

impl Token for Digits {
    const MAX_LEN: usize = 9;

    fn construct(s: String) -> Result<Self, String> {
        Ok(Digits(s.parse().unwrap()))
    }

    fn accept(c: char) -> bool {
        c.is_ascii_digit()
    }
}

pub struct Numeric(pub String);

impl Token for Numeric {
    const MAX_LEN: usize = 18;

    fn construct(s: String) -> Result<Self, String> {
        Ok(Numeric(s))
    }

    fn accept(c: char) -> bool {
        c.is_ascii_hexdigit() || c == '.'
    }
}

/// A hostname consists of alphanumeric characters and ".", "-",  "_"
pub struct Hostname(pub String);

impl std::ops::Deref for Hostname {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Token for Hostname {
    fn construct(text: String) -> Result<Self, String> {
        Ok(Hostname(text))
    }

    fn accept(c: char) -> bool {
        c.is_ascii_alphanumeric() || ".-_".contains(c)
    }
}

impl Many for Hostname {}

/// This enum allows items to use the ALL wildcard or be specified with aliases, or directly.
/// (Maybe this is better defined not as a Token but simply directly as an implementation of [crate::sudoers::basic_parser::Parse])
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[repr(u32)]
pub enum Meta<T> {
    All = HARDENED_ENUM_VALUE_0,
    Only(T) = HARDENED_ENUM_VALUE_1,
    Alias(String) = HARDENED_ENUM_VALUE_2,
}

impl<T> Meta<T> {
    #[cfg(test)]
    pub fn is_alias(&self) -> bool {
        matches!(self, Self::Alias(..))
    }
}

impl<T: Token> Token for Meta<T> {
    fn construct(raw: String) -> Result<Self, String> {
        // `T` may accept whitespace resulting in `raw` having trailing whitespace which would make
        // the first two checks below fail. this `cooked` version has no trailing whitespace
        let cooked = raw.trim_end().to_string();

        Ok(if cooked == "ALL" {
            Meta::All
        } else if cooked.starts_with(AliasName::accept_1st)
            && cooked.chars().skip(1).all(AliasName::accept)
        {
            Meta::Alias(cooked)
        } else {
            Meta::Only(T::construct(raw)?)
        })
    }

    const MAX_LEN: usize = T::MAX_LEN;

    fn accept(c: char) -> bool {
        T::accept(c) || c.is_uppercase()
    }
    fn accept_1st(c: char) -> bool {
        T::accept_1st(c) || c.is_uppercase()
    }

    const ALLOW_ESCAPE: bool = T::ALLOW_ESCAPE;

    fn escaped(c: char) -> bool {
        T::escaped(c)
    }
}

impl<T: Many> Many for Meta<T> {
    const SEP: char = T::SEP;
    const LIMIT: usize = T::LIMIT;
}

/// An identifier that consists of only uppercase characters.
pub struct AliasName(pub String);

impl Token for AliasName {
    fn construct(s: String) -> Result<Self, String> {
        Ok(AliasName(s))
    }

    fn accept_1st(c: char) -> bool {
        c.is_ascii_uppercase()
    }

    fn accept(c: char) -> bool {
        Self::accept_1st(c) || c.is_ascii_digit() || c == '_'
    }
}

/// A struct that represents valid command strings; this can contain escape sequences and are
/// limited to 1024 characters.
pub type Command = (SimpleCommand, Option<Box<[String]>>);

/// A type that is specific to 'only commands', that can only happen in "Defaults!command" contexts;
/// which is essentially a subset of "Command"
pub type SimpleCommand = glob::Pattern;

impl Token for Command {
    const MAX_LEN: usize = 1024;

    fn construct(s: String) -> Result<Self, String> {
        // the tokenizer should not give us a token that consists of only whitespace
        let mut cmd_iter = s.split_whitespace();
        let cmd = cmd_iter.next().unwrap().to_string();
        let mut args = cmd_iter.map(String::from).collect::<Vec<String>>();

        let command = SimpleCommand::construct(cmd)?;

        let argpat = if args.is_empty() {
            // if no arguments are mentioned, anything is allowed
            None
        } else {
            if args.last().map(|x| -> &str { x }) == Some("\"\"") {
                // if the magic "" appears, no (further) arguments are allowed
                args.pop();
            }
            Some(args.into_boxed_slice())
        };

        if command.as_str() == "list" && argpat.is_some() {
            return Err("list does not take arguments".to_string());
        }

        Ok((command, argpat))
    }

    // all commands start with "/" except "sudoedit" or "list"
    fn accept_1st(c: char) -> bool {
        SimpleCommand::accept_1st(c)
    }

    fn accept(c: char) -> bool {
        SimpleCommand::accept(c) || c == ' '
    }

    const ALLOW_ESCAPE: bool = SimpleCommand::ALLOW_ESCAPE;
    fn escaped(c: char) -> bool {
        SimpleCommand::escaped(c)
    }
}

impl Token for SimpleCommand {
    const MAX_LEN: usize = 1024;

    fn construct(mut cmd: String) -> Result<Self, String> {
        let cvt_err = |pat: Result<_, glob::PatternError>| {
            pat.map_err(|err| format!("wildcard pattern error {err}"))
        };

        // detect the two edges cases
        if cmd == "list" || cmd == "sudoedit" {
            return cvt_err(glob::Pattern::new(&cmd));
        } else if cmd.starts_with("sha") {
            return Err("digest specifications are not supported".to_string());
        } else if !cmd.starts_with('/') {
            return Err("fully qualified path needed".to_string());
        }

        // record if the cmd ends in a slash and remove it if it does
        let is_dir = cmd.ends_with('/') && {
            cmd.pop();
            true
        };

        // canonicalize path (if possible)
        if let Ok(real_cmd) = crate::common::resolve::canonicalize(&cmd) {
            cmd = real_cmd
                .to_str()
                .ok_or("non-UTF8 characters in filesystem")?
                .to_string();
        }

        // if the cmd ends with a slash, any command in that directory is allowed
        if is_dir {
            cmd.push_str("/*");
        }

        cvt_err(glob::Pattern::new(&cmd))
    }

    // all commands start with "/" except "sudoedit" or "list"
    fn accept_1st(c: char) -> bool {
        c == '/' || c == 's' || c == 'l'
    }

    fn accept(c: char) -> bool {
        !Self::escaped(c) && !c.is_control()
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | ',' | ':' | '#' | ' ')
    }
}

impl Many for Command {}
impl Many for SimpleCommand {}

pub struct DefaultName(pub String);

impl Token for DefaultName {
    fn construct(text: String) -> Result<Self, String> {
        Ok(DefaultName(text))
    }

    fn accept(c: char) -> bool {
        c.is_ascii_alphanumeric() || c == '_'
    }
}

pub struct EnvVar(pub String);

impl Token for EnvVar {
    fn construct(text: String) -> Result<Self, String> {
        Ok(EnvVar(text))
    }

    fn accept(c: char) -> bool {
        !c.is_control() && !c.is_whitespace() && !Self::escaped(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '=' | '#' | '"' | ',')
    }
}

/// A token with a very liberal inner tokenizer; compare StringParameter below
pub struct QuotedStringParameter(pub String);

impl Token for QuotedStringParameter {
    const MAX_LEN: usize = 1024;

    fn construct(s: String) -> Result<Self, String> {
        Ok(Self(s))
    }

    fn accept(c: char) -> bool {
        !Self::escaped(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '"') || c.is_control()
    }
}

/// Similar to QuotedStringParameter but treats backslashes differently
/// Compare IncludePath below.
// `@include "some/path"`
//           ^^^^^^^^^^^
pub struct QuotedIncludePath(pub String);

impl Token for QuotedIncludePath {
    const MAX_LEN: usize = 1024;

    fn construct(s: String) -> Result<Self, String> {
        Ok(Self(s))
    }

    fn accept(c: char) -> bool {
        !Self::escaped(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '"') || c.is_control()
    }
}

pub struct IncludePath(pub String);

impl Token for IncludePath {
    const MAX_LEN: usize = 1024;

    fn construct(s: String) -> Result<Self, String> {
        Ok(IncludePath(s))
    }

    fn accept(c: char) -> bool {
        !c.is_control() && !Self::escaped(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '"' | ' ')
    }
}

// used for Defaults where quotes around some items are optional
pub struct StringParameter(pub String);

impl Token for StringParameter {
    const MAX_LEN: usize = QuotedStringParameter::MAX_LEN;

    fn construct(s: String) -> Result<Self, String> {
        Ok(StringParameter(s))
    }

    fn accept(c: char) -> bool {
        !c.is_control() && !Self::escaped(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '"' | ' ' | '#' | ',')
    }
}

// a path used for in CWD and CHROOT specs
#[derive(Clone, PartialEq)]
#[cfg_attr(test, derive(Debug, Eq))]
#[repr(u32)]
pub enum ChDir {
    Path(SudoPath) = HARDENED_ENUM_VALUE_0,
    Any = HARDENED_ENUM_VALUE_1,
}

impl Token for ChDir {
    const MAX_LEN: usize = 1024;

    fn construct(s: String) -> Result<Self, String> {
        if s == "*" {
            Ok(ChDir::Any)
        } else if s.contains('*') {
            Err("path cannot contain '*'".to_string())
        } else {
            Ok(ChDir::Path(
                SudoPath::try_from(s).map_err(|e| e.to_string())?,
            ))
        }
    }

    fn accept(c: char) -> bool {
        !c.is_control() && !Self::escaped(c)
    }

    fn accept_1st(c: char) -> bool {
        "~/*".contains(c)
    }

    const ALLOW_ESCAPE: bool = true;
    fn escaped(c: char) -> bool {
        matches!(c, '\\' | '"' | ' ')
    }
}

/// Some tokens that support escape characters also support being surrounded by quotes to avoid escaping directly.
pub struct Unquoted<T>(pub String, pub std::marker::PhantomData<T>);

impl<T: Token> Token for Unquoted<T> {
    const MAX_LEN: usize = 1024;

    fn construct(text: String) -> Result<Self, String> {
        let mut quoted = String::new();
        for ch in text.chars() {
            if T::escaped(ch) {
                quoted.push('\\');
            }
            quoted.push(ch);
        }

        Ok(Self(quoted, std::marker::PhantomData))
    }

    fn accept(c: char) -> bool {
        c != '"' && !c.is_control()
    }
}