openmoat-core 0.23.1

Policy model and decision engine for OpenMoat. Pure: no I/O, no OS calls.
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
//! Program and extension tables that drive classification.
//!
//! Data only; the modules next to this one hold the behaviour. Tables used by
//! a single module (`decoders`, `make`, `options`) live in that module.

pub const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "fish"];

/// Programs whose first non-option argument is itself a command to run.
pub const WRAPPERS: &[&str] = &[
    "sudo",
    "doas",
    "pkexec",
    // `runuser -u USER cmd…` only; `runuser [-] USER -c cmd` is `shell/embedded.rs`'s
    "runuser",
    "env",
    "nohup",
    "time",
    "nice",
    "ionice",
    "xargs",
    "command",
    "exec",
    "builtin",
    "timeout",
    "watch",
    "caffeinate",
    "stdbuf",
    "chroot",
    "unbuffer",
    // a new session, detached from the terminal (`setsid -f cmd…`)
    "setsid",
    // `flock FILE cmd…`: runs the command holding a lock on FILE
    "flock",
    "npx",
    "bunx",
];

/// Wrappers that take one positional value before the wrapped command.
pub const WRAPPERS_WITH_VALUE: &[&str] = &["timeout", "chroot", "flock"];

/// Package runners whose listed subcommand executes an arbitrary program
/// (`pnpm exec sh -c …`, `yarn dlx pkg`, `npm exec -- cmd`, `bun x pkg`,
/// `uv run cmd`).
pub const WRAPPER_SUBCOMMANDS: &[(&str, &[&str])] = &[
    ("pnpm", &["exec", "dlx"]),
    ("yarn", &["exec", "dlx"]),
    ("npm", &["exec", "x"]),
    ("bun", &["x"]),
    ("uv", &["run"]),
];

/// Package runners that accept a shell string via `-c`/`--call`.
pub const PACKAGE_RUNNERS: &[&str] = &["npx", "bunx", "npm", "pnpm", "yarn", "bun"];

/// Wrapper options that consume the following argument (`sudo -u root …`).
pub const WRAPPER_OPTIONS_WITH_VALUE: &[(&str, &[&str])] = &[
    (
        "sudo",
        &["-u", "-g", "-C", "-h", "-p", "-U", "-r", "-t", "-D"],
    ),
    ("doas", &["-u", "-C"]),
    ("pkexec", &["--user"]),
    (
        "runuser",
        &["-u", "--user", "-g", "--group", "-G", "--supp-group", "-w"],
    ),
    ("env", &["-u", "-C", "-S", "--unset", "--chdir"]),
    ("nice", &["-n"]),
    ("npx", &["-p", "--package"]),
    ("bunx", &["-p", "--package"]),
    ("ionice", &["-c", "-n", "-p"]),
    ("xargs", &["-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a"]),
    ("timeout", &["-s", "-k", "--signal", "--kill-after"]),
    ("watch", &["-n", "-d"]),
    ("stdbuf", &["-i", "-o", "-e"]),
    ("exec", &["-a"]),
    // `-c`/`--command` hold a command line (`shell/embedded.rs`), not the lock file
    (
        "flock",
        &[
            "-w",
            "--timeout",
            "-E",
            "--conflict-exit-code",
            "-c",
            "--command",
        ],
    ),
];

pub const ENV_BUILTINS: &[&str] = &["export", "declare", "typeset", "local", "readonly", "set"];

/// Build tools whose command line can carry shell code (`shell/make.rs`).
pub const MAKES: &[&str] = &["make", "gmake"];

pub const SOURCE_BUILTINS: &[&str] = &["source", "."];

/// Interpreters with an inline-code flag whose payload is scanned, not parsed as shell.
pub const INLINE_INTERPRETERS: &[(&str, &[&str])] = &[
    ("python", &["-c"]),
    ("python3", &["-c"]),
    ("node", &["-e", "--eval", "-p", "--print"]),
    ("deno", &["eval"]),
    ("bun", &["-e"]),
    ("perl", &["-e", "-E"]),
    ("ruby", &["-e"]),
    ("php", &["-r"]),
    ("osascript", &["-e"]),
    ("pwsh", &["-c", "-Command"]),
    ("powershell", &["-c", "-Command"]),
    ("lua", &["-e"]),
    ("luajit", &["-e"]),
    ("Rscript", &["-e"]),
];

/// The inline-code options of `program`, also when it is spelled with a version
/// (`python3.12`, `python2.7`, `ruby3.3`, `lua5.4`).
#[must_use]
pub fn inline_flags(program: &str) -> Option<&'static [&'static str]> {
    let exact = |p: &str| {
        INLINE_INTERPRETERS
            .iter()
            .find(|(n, _)| *n == p)
            .map(|(_, f)| *f)
    };
    exact(program).or_else(|| {
        let base = program.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.');
        let versioned = base.len() < program.len()
            && program[base.len()..].starts_with(|c: char| c.is_ascii_digit());
        // `python3.12` → `python3`, `python2.7` → `python`
        let base = if base == "python" { "python3" } else { base };
        versioned.then(|| exact(base)).flatten()
    })
}

/// Programs for which every path argument is a write. The `rename` tools
/// (util-linux `rename FROM TO FILE…`, Perl `rename EXPR FILE…`) move every file
/// they name; their expressions become writes of paths that rarely exist.
pub const WRITE_ALL_PATHS: &[&str] = &[
    "rm",
    "rmdir",
    "touch",
    "mkdir",
    "chmod",
    "chown",
    "chgrp",
    "truncate",
    "unlink",
    "shred",
    "tee",
    "install",
    "mkfifo",
    "mknod",
    "mv",
    "rename",
    "prename",
    "perl-rename",
    "file-rename",
    // `cpio -p DIR` copies the files named on stdin into DIR; in its other modes
    // the operands are patterns, whose writes only cost a project-local atom
    "cpio",
];

/// The programs of [`WRITE_ALL_PATHS`] that put no chosen content in a file they
/// name: they remove it (`mv` moves it away; its destination is written apart,
/// `copy.rs`), empty it, or change its metadata. `replaced.rs` leaves these out.
pub const NO_CONTENT_WRITES: &[&str] = &[
    "rm", "rmdir", "unlink", "touch", "mkdir", "chmod", "chown", "chgrp", "truncate", "mv",
];

/// Programs for which the last operand is a write and the others are reads.
/// `link FILE NEW` makes the hard link `NEW`; macOS `ditto SRC… DST` and
/// `pax -rw SRC… DIR` copy (`shell/copy.rs`).
pub const WRITE_LAST_PATH: &[&str] = &["cp", "ln", "link", "rsync", "scp", "ditto", "pax"];

/// The tools of the two tables above that GNU coreutils also installs with a
/// `g` in front (Homebrew's `gcp`, `gln`, `grm`): `gcp` is read as `cp`.
pub const GNU_PREFIXED: &[&str] = &[
    "cp", "mv", "ln", "link", "rm", "rmdir", "touch", "mkdir", "chmod", "chown", "chgrp",
    "truncate", "unlink", "shred", "tee", "install", "mkfifo", "mknod",
];

/// Programs whose operands are files they read, so a plain name (`cat s`) is a
/// file read (`operands.rs`). Pattern operands (`grep foo .`) become reads of
/// a path that usually does not exist, which only costs a project-local atom.
pub const FILE_OPERANDS: &[&str] = &[
    "cat",
    "tac",
    "head",
    "tail",
    "less",
    "more",
    "bat",
    "nl",
    "od",
    "xxd",
    "hexdump",
    "strings",
    "grep",
    "egrep",
    "fgrep",
    "rg",
    "ag",
    "ack",
    "wc",
    "diff",
    "cmp",
    "sort",
    "uniq",
    "cut",
    "paste",
    "column",
    "base64",
    "base32",
    "md5",
    "md5sum",
    "shasum",
    "sha1sum",
    "sha256sum",
    "sha512sum",
    "cksum",
    "file",
    "stat",
    "ls",
    "tree",
    "find",
    "du",
    "tar",
    "zip",
    "unzip",
    "gzip",
    "gunzip",
    "zcat",
    "bzip2",
    "xz",
    "jq",
    "yq",
    "gofmt",
    // interpreters read the script they run; later words are treated as files too
    "python",
    "python3",
    "node",
    "openssl",
    "ssh-keygen",
    "split",
    "fold",
    "fmt",
    "iconv",
    "awk",
    "sed",
    "vi",
    "vim",
    "nvim",
    "nano",
    "emacs",
    "code",
    "open",
];

/// Editors among [`FILE_OPERANDS`]: they read the file they open and save it
/// back, so each file operand is a write as well (`vim ~/.zshrc` meets the
/// rule a write of it does, `nano ~/.moat/policy.yaml` `kernel-self`).
pub const EDITORS: &[&str] = &["vi", "vim", "nvim", "nano", "emacs", "code"];

/// Programs whose arguments are never files: `echo` and `printf` print them,
/// `tr` takes character sets. A `/` in them is text.
pub const NO_FILE_OPERANDS: &[&str] = &["echo", "printf", "tr"];

/// Programs that run the command line they are given inside a container or a
/// pod, not on this machine: a `sh -c STR` among their arguments is not
/// classified as a local command (docs/LIMITS.md); `container-host` holds
/// handing the host over to the container.
pub const CONTAINER_RUNNERS: &[&str] = &["docker", "podman", "nerdctl", "kubectl", "oc"];

/// Programs whose path operands name the file system holding them, which they
/// query without opening anything under it: `df -h ~` reports free space and
/// reads no file of the home folder. (`du` walks the tree and is a reader.)
pub const FILESYSTEM_QUERIES: &[&str] = &["df"];

/// Words before a command that leave it running in the current shell, so a
/// `cd` after them still moves it (`builtin cd`, `if cd x; then`, `{ cd x; }`).
pub const CWD_PREFIXES: &[&str] = &[
    "builtin", "command", "time", "{", "!", "if", "then", "else", "elif", "while", "until", "do",
];

/// Shell reserved words that start a command inside a compound one: the command
/// after them is classified on its own (`do git log`, `if cat .env; then`).
pub const RESERVED_PREFIXES: &[&str] = &[
    "do", "then", "else", "elif", "if", "while", "until", "!", "{",
];

/// Reserved words that close a compound command and run nothing themselves.
pub const RESERVED_CLOSERS: &[&str] = &["done", "fi", "}", "esac"];

/// Builtins that may move the shell somewhere the classifier cannot see
/// (`cwd.rs`): `eval` and `source` may run a `cd`; `popd` returns to a
/// directory pushed before this command line.
pub const MAY_CHANGE_CWD: &[&str] = &["eval", "source", ".", "popd"];

/// Special parameters that are not environment variables.
pub const SPECIAL_PARAMS: &[char] = &['?', '$', '!', '#', '@', '*', '-', '0'];

/// Variables that are expanded by the classifier itself or carry no secret.
pub const IGNORED_VARS: &[&str] = &["HOME", "PWD", "OLDPWD", "USER", "SHELL", "TERM", "project"];

/// Variables naming the editor git and other tools run.
pub const EDITOR_VARS: &[&str] = &["GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "EDITOR", "VISUAL"];

/// Editor values that run nothing of their own: a no-op, or a reader that
/// prints the file and leaves it as it is.
pub const INERT_EDITOR_VALUES: &[&str] = &["true", ":", "cat"];

/// The directories a `PATH` may be set to without changing what any command
/// resolves to: the system's own, which no agent writes.
pub const SYSTEM_PATH_DIRS: &[&str] = &["/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"];

/// Programs whose arguments name hosts: a host-shaped word there is network
/// evidence (`Net`), elsewhere only a word that looks like one (`NetWord`, ADR-025).
pub const HOST_PROGRAMS: &[&str] = &[
    "curl",
    "wget",
    "ssh",
    "scp",
    "sftp",
    "rsync",
    "nc",
    "ncat",
    "netcat",
    "telnet",
    "ftp",
    "ping",
    "dig",
    "nslookup",
    "host",
    // more resolvers: a name they look up carries what it is built from to
    // the domain's name server
    "drill",
    "kdig",
    "delv",
    "resolvectl",
    "getent",
    // more clients that connect where their arguments say
    "openssl",
    "socat",
    "mosh",
    "lftp",
    "aria2c",
    "nmap",
    "psql",
    "mysql",
    "redis-cli",
    "mongo",
    "mongosh",
    "http",
    "https",
    "xh",
    "curlie",
    "wget2",
    "whois",
    "traceroute",
    "mtr",
];

/// `git` subcommands whose arguments name a remote host ([`HOST_PROGRAMS`]).
pub const GIT_HOST_SUBCOMMANDS: &[&str] = &["clone", "fetch", "pull", "push", "ls-remote"];

/// Top-level domains accepted for a bare dotted token (no scheme). Dotted
/// identifiers in code (`sys.version`, `os.system`, `console.log`) and names
/// like `fix.bug` are not hosts; a token with a scheme is always one.
pub const KNOWN_TLDS: &[&str] = &[
    "com", "org", "net", "io", "dev", "ai", "co", "app", "sh", "me", "us", "uk", "de", "fr", "jp",
    "cn", "in", "ru", "br", "edu", "gov", "mil", "int", "info", "biz", "xyz", "cloud", "tech",
    "so", "to", "ly", "gg", "tv", "fm", "am", "is", "it", "nl", "se", "no", "fi", "dk", "ch", "at",
    "be", "es", "pt", "pl", "cz", "au", "nz", "ca", "mx", "ar", "cl", "kr", "tw", "hk", "sg", "id",
    "ph", "vn", "th", "il", "za", "ng", "ke", "eg", "ie", "eu", "asia", "online", "site", "store",
    "space", "live", "run", "page", "zone", "link", "click", "top", "pro", "name", "mobi",
    "network", "systems", "services", "digital", "email", "host", "cc", "ws", "nu", "la", "im",
    "pw", "tk", "ml", "ga", "cf", "gq", "onion", "local", "internal", "lan", "arpa", "ee", "lv",
    "lt", "ua", "by", "kz", "tr", "gr", "hu", "ro", "bg", "rs", "hr", "si", "sk", "pk", "bd", "lk",
    "np", "ir", "iq", "sa", "ae", "qa", "my", "pe", "ve", "uy", "ec",
];

/// Suffixes that make a dotted token a file name rather than a host.
pub const FILE_EXTENSIONS: &[&str] = &[
    "rs", "js", "ts", "tsx", "jsx", "mjs", "cjs", "py", "rb", "php", "go", "java", "kt", "swift",
    "c", "h", "cpp", "hpp", "cs", "md", "txt", "json", "yaml", "yml", "toml", "lock", "sh", "bash",
    "zsh", "html", "css", "scss", "vue", "svelte", "png", "jpg", "jpeg", "gif", "svg", "pdf",
    "zip", "tar", "gz", "tgz", "bz2", "xz", "log", "env", "cfg", "ini", "xml", "csv", "sql", "db",
    "sqlite", "wasm", "so", "dylib", "dll", "exe", "bin", "o", "a", "class", "jar", "war", "plist",
    "conf", "pem", "key", "crt",
];

/// Output redirection targets that are no file: the data sink and the
/// command's own standard output and error (`2>/dev/null`, `>&2` spelt as a
/// path). Compared with the resolved path; `/dev/tty`, `/dev/fd/3` and every
/// other device stay writes.
pub const STREAM_SINKS: &[&str] = &[
    "/dev/null",
    "/dev/stdout",
    "/dev/stderr",
    "/dev/fd/1",
    "/dev/fd/2",
];

/// Input redirection sources that are no file: the empty source and the
/// command's own standard input (`</dev/null`).
pub const STREAM_SOURCES: &[&str] = &["/dev/null", "/dev/stdin", "/dev/fd/0"];