sudo
- Acquire root privileges via the setuid bit
- Identify the executor, host, target user, and command
- Sequentially match with sudoers rules
- Authentication (password or timestamp)
- Execute the command via fork → setuid/setgid → execve
Info
- If the
-u option is not specified, root is the default.
- For setgid, it is set to the target user's primary group.
Operation
1
2// sudo internal code (pseudo-code)
3
4struct context {
5 char *real_user; // "john" (from RUID)
6 char *hostname; // "macbook-pro.local"
7 char *target_user; // "postgres" (-u option)
8 char *target_group; // "postgres" (-g option or default)
9 jchar *command; // "/usr/bin/psql"
10 char **args; // command arguments
11};
12
13context ctx = {
14 .real_user = getpwuid(getuid()), // john
15 .hostname = gethostname(), // macbook-pro.local
16 .target_user = parse_u_option() ?: "root", // postgres
17 .command = find_command_path("psql"), // /usr/bin/psql
18};
19
20// Read sudoers file (requires root privileges to read)
21FILE *sudoers = fopen("/etc/sudoers", "r");
22
23// Parsing result (example)
24rules[] = {
25 { user: "root", host: "ALL", runas_user: "ALL", runas_group: "ALL", command: "ALL" },
26 {
27 user: "%admin", // % = group
28 host: "ALL",
29 runas_user: "ALL",
30 runas_group: "ALL",
31 command: "ALL"
32 },
33 // ... other rules
34};
35
36// Rule matching
37// Authentication (+timestamp check)
38// Command execution
sudoers
/etc/sudoers
- The policy engine for
sudo
Syntax
1# User Host = (Runas_User) Command
2%admin ALL = (ALL) ALL