Chapter 2: Privileged Programs: Set-UID and Environment Variables

An operating system is, among other things, a referee. Many users share one machine, and the kernel decides who may read, write, or run what. Most of the time the rules are simple: your files are yours, my files are mine. But some legitimate tasks cut across those rules. You are allowed to change your password, yet the password database is a file that only root may write. How can an ordinary user perform an operation that requires more privilege than they have — without being handed that privilege for everything else?

Unix answers with Set-UID programs: ordinary executables that run with the privilege of their owner rather than of the user who launches them. Set-UID is elegant and old, and it creates exactly the situation an attacker loves: a program running with high privilege whose behavior is partly controlled by a low-privilege user. This chapter studies that boundary. We start with the Linux permission model, introduce Set-UID, and then walk through the ways the less-privileged side can reach across — through leaked capabilities, through shell commands, and through a channel programmers often forget is there at all: environment variables.

Learning objectives. After this chapter you should be able to:

  • Read and set Linux file permissions (rwx bits, octal notation, umask, ACLs).
  • Explain real, effective, and saved user IDs, and how a Set-UID program uses them.
  • Identify capability leaking, and fix it.
  • Explain why system() is dangerous in privileged code and why execve() is safer.
  • Describe how environment variables reach a process and why they form part of a privileged program’s attack surface.
  • Trace a C program from source to running process, and explain how the dynamic linker can be manipulated through LD_PRELOAD and LD_LIBRARY_PATH.
  • Compare the Set-UID approach and the service approach to privileged operations.

2.1 Users and Groups

Linux identifies every user by a numeric user ID (UID). Names are a convenience for humans; the kernel only ever compares numbers. UID 0 is root, the superuser, for whom most permission checks are skipped.

User accounts are listed in /etc/passwd, one per line, with seven colon-separated fields:

seed:x:1000:1000:SEED,,,:/home/seed:/bin/bash
 |   |  |    |      |        |          |
 |   |  |    |      |        |          +-- login shell
 |   |  |    |      |        +------------- home directory
 |   |  |    |      +---------------------- comment (GECOS) field
 |   |  |    +----------------------------- primary group ID (GID)
 |   |  +---------------------------------- user ID (UID)
 |   +------------------------------------- password placeholder ("x": see /etc/shadow)
 +----------------------------------------- user name

The id command shows who you are:

$ id
uid=1000(seed) gid=1000(seed) groups=1000(seed),4(adm),27(sudo),...

To add a user, an administrator can run sudo adduser alice (a friendly front end that creates the home directory and sets a password) or, in principle, edit /etc/passwd directly. To act as another user, use su:

$ su alice          # asks for alice's password, then starts a shell as alice
$ sudo su           # become root (asks for *your* password, if you are a sudoer)

A group is a named set of users, identified by a group ID (GID). Groups let an administrator grant a permission to many users at once — for example, every member of group sudo may run sudo. A user has one primary group (the GID field in /etc/passwd) and may belong to any number of supplementary groups, which are listed in /etc/group. The groups command prints a user’s groups; sudo groupadd and sudo usermod -a -G <group> <user> manage them.

2.2 Linux File Permissions

Every file has an owning user, an owning group, and nine permission bits: read (r), write (w), and execute (x) for each of three classes — the user owner, the group owner, and others.

$ ls -l /etc/passwd
-rw-r--r-- 1 root root 2915 Aug 26 10:12 /etc/passwd
 \_/\_/\_/   \__/ \__/
  u  g  o   owner group

Here root may read and write; members of group root and everyone else may only read. For directories, r means “list the names,” w means “create, delete, or rename entries,” and x means “traverse” (use the directory in a path).

The kernel checks permissions in order: if you are the owner, the user bits apply; otherwise if you are in the owning group, the group bits apply; otherwise the other bits apply. Only the first matching class is used — an owner with --- is denied even if “others” have rwx.

Octal notation

Each class’s three bits form one octal digit (r=4, w=2, x=1), so the full mode is three digits:

SymbolicOctalTypical use
rw-r--r--644ordinary file
rwxr-xr-x755program or directory
rw-------600private file (e.g., an SSH key)
rwx------700private directory

Changing permissions and ownership

chmod changes the mode, either symbolically or in octal; chown changes the owner (and optionally the group). Only root may give a file away to another user.

$ chmod u+x prog            # add execute for the owner
$ chmod 640 notes.txt       # rw-r-----
$ sudo chown root prog      # owner becomes root
$ sudo chown root:root prog # owner and group both become root

Default permissions: umask

When a program creates a file, it requests a mode — conventionally 0666 for files and 0777 for directories — and the kernel removes any bit that is set in the process’s umask. The resulting mode is requested & ~umask.

$ umask
0002
$ touch a; mkdir d; ls -ld a d
-rw-rw-r-- 1 seed seed    0 ... a
drwxrwxr-x 2 seed seed 4096 ... d

Try it. Predict the mode of a new file and a new directory for each umask, then check with umask <value>; touch f; mkdir d; ls -ld f d.

umasknew filenew directory
0022??
0077??
0027??

(Answers: 644/755; 600/700; 640/750. Note that the umask only ever removes bits; it never adds x to a regular file.)

Access control lists

The owner/group/other model is coarse. If you want to let exactly one other user, say bob, read a file — without creating a new group — you need an access control list (ACL). ACLs coexist with the traditional bits: they add entries for specific users and groups.

$ setfacl -m u:bob:r-- report.txt
$ getfacl report.txt
# file: report.txt
# owner: seed
# group: seed
user::rw-
user:bob:r--
group::r--
mask::r--
other::---
$ ls -l report.txt
-rw-r-----+ 1 seed seed 120 ... report.txt

The trailing + in ls -l tells you an ACL is present. setfacl -x u:bob report.txt removes the entry, and setfacl -b removes all extended entries.

2.3 The Need for Privileged Programs

Now the dilemma. Password hashes live in /etc/shadow:

$ ls -l /etc/shadow
-rw-r----- 1 root shadow 1468 ... /etc/shadow

Only root can write it — rightly so, since anyone who can write it can set any user’s password. Yet every user must be able to change their own password. Two broad designs could resolve this:

  1. Make /etc/shadow writable by everyone and trust each user to touch only their own line. Obviously unacceptable.
  2. Give users a carefully written program that performs exactly one privileged action — “update my entry in /etc/shadow” — and give that program the privilege, not the user.

The second design requires a mechanism to attach privilege to a program. On Unix that mechanism is the Set-UID bit. (Section 2.13 discusses the other common answer, a privileged service.)

2.4 Set-UID Programs

Three user IDs per process

Every process carries several user IDs. Two matter most:

  • The real UID (RUID) identifies who actually started the process — the “real owner” of the process.
  • The effective UID (EUID) identifies the privilege the process has. Access control decisions use the EUID.

A third, the saved set-user-ID, remembers the EUID the program started with so that a program can temporarily drop privilege and later regain it (Section 2.6).

For a normal program, RUID = EUID = the ID of the user who ran it. A Set-UID program is a normal executable with one extra bit in its mode. When such a program is executed, the kernel sets the EUID (and the saved UID) to the owner of the file, while the RUID stays the invoking user. If the file is owned by root, the program runs with root privilege.

The canonical example is passwd:

$ ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 68208 ... /usr/bin/passwd

The s where the owner’s x would be marks the Set-UID bit. Any user can run passwd; while it runs, its EUID is 0, so it may open /etc/shadow for writing. The program’s logic — “verify the old password, then update only the caller’s line” — is what keeps this safe. The security of the whole arrangement therefore rests entirely on that program being correct.

Making a Set-UID program

Let us turn a copy of cat into a root-owned Set-UID program and watch the effect:

$ cp /bin/cat ./mycat
$ ./mycat /etc/shadow
./mycat: /etc/shadow: Permission denied
$ sudo chown root mycat
$ sudo chmod 4755 mycat       # the leading 4 is the Set-UID bit
$ ls -l mycat
-rwsr-xr-x 1 root seed 43416 ... mycat
$ ./mycat /etc/shadow
root:!:19100:0:99999:7:::
...

The octal digit in front of the usual three encodes three special bits: 4 is Set-UID, 2 is Set-GID (the same idea for groups), and 1 is the sticky bit.

Note. The order of the two commands matters. Changing a file’s owner clears its Set-UID and Set-GID bits; on Linux this happens even when root performs the chown. The kernel does this deliberately — otherwise a user could make a Set-UID program and then hand it to another account, creating a program that runs with that account’s privileges. So always chown first and chmod 4755 second. If you do it the other way around, ls -l will show -rwxr-xr-x, and the program runs without any privilege.

Try it. Write a program that prints getuid() and geteuid(). Run it normally, then make it a root-owned Set-UID program and run it again. You should see RUID 1000 and EUID 0 the second time.

Why study Set-UID?

Set-UID is a small mechanism, but it is a concentrated lesson in three things that recur throughout this book:

  • Access control and privilege management in Unix-like systems: who is allowed to do what, and how a system grants exceptions to its own rules.
  • Privilege escalation: a Set-UID root program is a bridge from user to root. If the bridge has a hole, the attacker walks across.
  • Exploitation targets: in the next chapters, the vulnerable programs you exploit are Set-UID root programs. A buffer overflow in an ordinary program gives you only your own privilege; the same overflow in a Set-UID root program gives you a root shell.

The rest of this chapter is about the holes. A Set-UID program’s code is fixed by its author, but the user who runs it controls a surprising number of its inputs: command-line arguments, standard input, files it reads, inherited file descriptors, the current directory, resource limits, signals, and environment variables. Each is part of the attack surface.

2.5 Capability Leaking

Well-written privileged programs follow the principle of least privilege (Chapter 1): they do their privileged work early and then give up root. The su program, for example, starts with RUID = the invoking user and EUID = root; once it has verified the target user’s password, it permanently switches all its UIDs to the target user and then starts a shell.

Dropping privilege is not the same as dropping capabilities, however. Consider this root-owned Set-UID program:

// cap_leak.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    int fd;
    char *v[2];

    /* /etc/zzz is owned by root and writable only by root (mode 0644). */
    fd = open("/etc/zzz", O_RDWR | O_APPEND);   /* succeeds: EUID is 0 */
    if (fd == -1) {
        printf("Cannot open /etc/zzz\n");
        exit(0);
    }
    printf("fd is %d\n", fd);

    /* Permanently drop privilege: EUID (and RUID, saved UID) := RUID. */
    setuid(getuid());

    /* Hand control to the user. */
    v[0] = "/bin/sh"; v[1] = 0;
    execve(v[0], v, 0);
    return 0;
}

It looks careful: it calls setuid(getuid()) before starting a shell, so the shell runs as the ordinary user. But the program opened /etc/zzz while it was root and never closed the descriptor. Permission checks happen at open() time, not on each write(). File descriptors survive execve() (unless marked close-on-exec), so the unprivileged shell inherits descriptor 3, already opened for writing:

$ ./cap_leak
fd is 3
$ echo "owned by an unprivileged user" >&3
$ exit
$ cat /etc/zzz
...
owned by an unprivileged user

This is capability leaking: the process lost its privileged identity but kept a privileged capability — an open file descriptor — that it acquired while privileged. The fix is to destroy the capability before downgrading: call close(fd) before setuid() (or open the file with O_CLOEXEC so that execve() closes it).

Going deeper — a real capability leak. In July 2015, Stefan Esser disclosed a privilege escalation in OS X 10.10 Yosemite (CVE-2015-3760). Apple had added a DYLD_PRINT_TO_FILE environment variable that tells the dynamic linker dyld to write its debug log to a named file. dyld runs inside every program — including root-owned Set-UID programs — and so could open any file with root privilege. It did not close that descriptor, and it did not ignore the variable for Set-UID programs. An attacker could set DYLD_PRINT_TO_FILE=/etc/sudoers, run any Set-UID program that later drops privilege or executes user-controlled code, and write to the leaked descriptor. Exploits circulated as one-line shell commands within days. Note that this single bug combines both themes of this chapter: a capability leak, reached through an environment variable that a privileged component trusted.

2.6 Dropping Privilege Correctly: setuid() vs. seteuid()

Linux offers two calls to change UIDs, and confusing them is a classic mistake.

  • seteuid(uid) changes only the EUID. If the process started as Set-UID root, the saved UID is still 0, so the program can later call seteuid(0) to regain root. This is a temporary drop: useful when a program wants to perform most work as the user and switch back for one privileged step.
  • setuid(uid) called while the EUID is 0 sets real, effective, and saved UIDs all to uid. This is a permanent drop: there is no way back to root.
                       RUID   EUID   saved
start (Set-UID root)   1000      0       0
after seteuid(1000)    1000   1000       0   <- can seteuid(0) again
after setuid(1000)     1000   1000    1000   <- root is gone for good

A program that intends to hand control to a user — run a shell, run a user-supplied script, or parse untrusted input — must drop privilege permanently, and must first release every privileged resource it holds.

Note. The exact semantics of setuid() when the EUID is not 0 are subtly different, and differ across Unix systems. Chen, Wagner, and Dean’s paper “Setuid Demystified” (USENIX Security 2002) documents the mess and is worth reading if you ever write privileged code.

2.7 Invoking External Programs

Privileged programs often run other programs. There are two very different ways to do it in C.

The unsafe approach: system()

system(cmd) asks a shell to run a command line: it effectively executes /bin/sh -c "cmd". That is convenient — you get PATH lookup, redirection, pipes — and it is exactly the problem. Consider this program, intended to let an auditor read any file on the system but not modify anything:

// catall.c  (root-owned Set-UID)
int main(int argc, char *argv[])
{
    char *v[3];
    char *command;

    if (argc < 2) { printf("Please type a file name.\n"); return 1; }

    v[0] = "/bin/cat"; v[1] = argv[1]; v[2] = NULL;
    command = malloc(strlen(v[0]) + strlen(v[1]) + 2);
    sprintf(command, "%s %s", v[0], v[1]);

    system(command);          /* runs: /bin/sh -c "/bin/cat <argv[1]>" */
    return 0;
}

The author’s reasoning was “this program only ever runs cat, and cat cannot modify files.” But the user’s argument is pasted into a shell command line, and the shell interprets it. The user can supply shell syntax:

$ ./catall "/etc/shadow; /bin/sh"
root:!:19100:0:99999:7:::
...
# id
uid=1000(seed) gid=1000(seed) euid=0(root) ...

The ; ends the cat command and starts a second one — a root shell. Something meant to be data (a file name) has become code (a command). This is the same root cause as SQL injection and cross-site scripting.

Note — the dash countermeasure. On Ubuntu, /bin/sh is a symbolic link to /bin/dash. When dash (and bash, unless started with -p) detects that its EUID differs from its RUID, it sets its EUID back to the RUID, i.e., it drops the Set-UID privilege before running anything. The attack above then yields only a normal shell. This is a useful safety net, but it is a property of one shell, not a fix in your program. For the labs, the SEED environment re-points /bin/sh to a shell without this check:

$ sudo ln -sf /bin/zsh /bin/sh      # lab setting: remove the countermeasure
$ sudo ln -sf /bin/dash /bin/sh     # restore afterwards

The safe approach: execve()

execve(path, argv, envp) replaces the current process image with the program at path. It does not involve a shell. The program name is supplied by the program itself; the user’s data travels in argv and is delivered verbatim to the new program:

v[0] = "/bin/cat"; v[1] = argv[1]; v[2] = NULL;
execve(v[0], v, NULL);

Now ./catall "/etc/shadow; /bin/sh" makes cat look for a file literally named /etc/shadow; /bin/sh, which does not exist. Code and data travel in separate channels, so there is no way for the data to become code.

system():   "/bin/cat " + user_input  ──►  /bin/sh parses ONE string  ──►  ??? 
execve():   argv[0] = "/bin/cat"      ──►  kernel runs /bin/cat
            argv[1] = user_input      ──►  delivered as a single argument, never parsed

2.8 Two Principles, Concretely

The examples above illustrate two design principles from Chapter 1.

Isolation of code and data. Attacks happen when a channel that should carry only data is also interpreted as code. system() command injection, SQL injection, cross-site scripting, and (in Chapter 4) stack buffer overflows all violate this principle. The robust fixes all restore the separation: execve() with an argument vector, parameterized SQL queries, contextual output escaping, non-executable data pages.

Least privilege. A privileged program should hold only the power needed for its task, and only while it needs it. Use seteuid() to set privilege aside temporarily and setuid() to discard it permanently — after releasing privileged resources. Other systems offer finer tools: Linux capabilities split root’s power into pieces such as CAP_NET_BIND_SERVICE, and sandboxes such as seccomp restrict which system calls a process may make.

2.9 Environment Variables

An environment variable is a named string value, such as HOME=/home/seed, attached to every process. Environment variables were introduced in Unix (in Version 7, 1979) and later adopted by essentially every OS, including Windows. They configure how programs behave without changing their code. The best known is PATH: when you type ls, the shell searches the colon-separated directories in PATH, in order, for an executable named ls.

$ printenv PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$ export GREETING=hello       # set (bash built-in)
$ printenv GREETING
hello
$ unset GREETING              # remove (bash built-in)

Accessing them from C

A C program can read its environment in two ways. The main function may take a third parameter, and the C library exposes a global variable:

#include <stdio.h>
extern char **environ;

int main(int argc, char *argv[], char *envp[])
{
    for (int i = 0; envp[i] != NULL; i++)      /* only valid inside main */
        printf("%s\n", envp[i]);

    for (char **p = environ; *p != NULL; p++)  /* works anywhere */
        printf("%s\n", *p);
    return 0;
}

At program start, envp and environ point to the same array. The global environ is the more reliable choice: it is accessible from any function, and if the program changes its environment with setenv() or putenv(), the library may move the array to the heap and update environ — leaving envp pointing at the stale original. For a single variable, use getenv("NAME").

Where they come from

A process gets its environment from whoever executes it. There are two paths:

  • fork() creates a child that is a copy of the parent, including its environment.
  • execve(path, argv, envp) discards the old program, and the third argument becomes the new program’s entire environment. Pass NULL and the new program starts with an empty environment; pass environ and it inherits the caller’s.
/* passenv.c: run /usr/bin/env with a chosen environment */
#include <unistd.h>
extern char **environ;

int main(void)
{
    char *argv[] = { "/usr/bin/env", NULL };
    char *newenv[] = { "AAA=aaa", "BBB=bbb", NULL };

    execve("/usr/bin/env", argv, newenv);    /* prints AAA=aaa and BBB=bbb  */
    /* execve(argv[0], argv, NULL);             prints nothing              */
    /* execve(argv[0], argv, environ);          prints the parent's variables */
    return 0;
}

The kernel copies the environment strings onto the top of the new process’s stack, just above the argument strings, and passes pointers to them to the program’s startup code:

 high addresses
 +---------------------------+
 | environment strings       |  "PATH=/usr/bin:...", "HOME=/home/seed", ...
 | argument strings          |  "./prog", "arg1", ...
 +---------------------------+
 | envp[] pointers, NULL     |  <- envp, environ (initially)
 | argv[] pointers, NULL     |  <- argv
 | argc                      |
 +---------------------------+
 | main()'s stack frame ...  |
 v  (stack grows down)       v
 low addresses

You will use this layout in later chapters: an environment variable is an easy way to place an attacker-chosen string (say, /bin/sh) at a predictable address in a victim process’s memory.

The attack surface

Here is the key point. When a user runs a Set-UID program, the user’s shell calls execve() with the user’s environment. The privileged program inherits an environment chosen entirely by the unprivileged user. Any code in that program — or in any library it uses, or in any program it runs — that consults an environment variable is taking input from the attacker.

Explicit uses (getenv("HOME") in the program’s own code) are at least visible during code review. The dangerous ones are hidden uses: the dynamic linker reads LD_* variables before main runs; system() starts a shell that reads PATH and others; the C library reads locale variables. The next three sections examine these.

2.10 From Source to Process: Compiling, Linking, and Loading

To understand the dynamic linker attack, we need to know how a program becomes a process. Four tools and a loader are involved:

           cpp            cc1            as               ld               loader
 prog.c ───────► prog.i ───────► prog.s ───────► prog.o ───────► prog ───────► ./prog
 source       preprocessed     assembly      object file     executable      process
             (headers inlined)                (ELF)           (ELF)      (+ shared libraries)

You can stop gcc after each stage to see the intermediate files:

$ gcc -E prog.c -o prog.i     # preprocess only
$ gcc -S prog.i               # compile to assembly: prog.s
$ gcc -c prog.s               # assemble to an object file: prog.o
$ gcc prog.o -o prog          # link (gcc invokes ld with the right libraries)

On Linux, object files and executables use the Executable and Linkable Format (ELF). Inspect them with file, readelf -h -l -S, and objdump -d.

Linking resolves references to code that lives elsewhere. A call to printf in prog.o is a placeholder until the linker connects it to printf’s code in the C library. There are two ways to do that:

  • Static linking copies the library code into the executable at build time. The result is self-contained but large, because it carries its own copy of every library function it uses (and their dependencies):

    $ gcc hello.c -o hello_dyn
    $ gcc -static hello.c -o hello_static
    $ ls -l hello_dyn hello_static
    -rwxrwxr-x 1 seed seed  16696 ... hello_dyn
    -rwxrwxr-x 1 seed seed 871688 ... hello_static
    

    Roughly fifty to a hundred times larger, depending on the platform and libc version. Static linking also means a security fix to libc does not reach the program until it is rebuilt.

  • Dynamic linking defers the work to run time. The executable records which shared libraries it needs (ldd hello_dyn lists them) and the path of the dynamic linker/loader (/lib/ld-linux.so.2 for 32-bit x86, /lib64/ld-linux-x86-64.so.2 for x86-64). When the kernel execves the program, it first maps the dynamic linker, which finds and maps the shared libraries (.so files; DLLs on Windows) and resolves symbols before jumping to the program’s entry point. Chapter 7 looks at the PLT/GOT machinery that makes the calls work.

Dynamic linking saves disk and memory and lets libraries be patched independently. It also means a privileged program’s code is not fully determined until run time — and the dynamic linker decides what to load partly based on environment variables.

2.11 Attacks via the Dynamic Linker

Two environment variables steer the dynamic linker:

  • LD_PRELOAD — a list of shared libraries to load before all others. Symbols they define take precedence over those in later libraries, including libc.
  • LD_LIBRARY_PATH — directories to search for libraries before the default ones.

Both are legitimately useful (debugging, profiling, testing a new library build), and both are fully controlled by whoever sets the environment.

Example 1: a normal program

This program sleeps for one second:

/* myprog.c */
#include <unistd.h>
int main(void) { sleep(1); return 0; }

sleep is resolved at run time from libc. Now write our own sleep:

/* mylib.c */
#include <stdio.h>
void sleep(int s)
{
    printf("I am not sleeping!\n");
}

Build it as a shared library and preload it:

$ gcc -fPIC -g -c mylib.c
$ gcc -shared -o libmylib.so.1.0.1 mylib.o -lc
$ export LD_PRELOAD=./libmylib.so.1.0.1
$ gcc myprog.c -o myprog
$ ./myprog
I am not sleeping!

The dynamic linker found sleep in our library first, so our code ran inside myprog. For a normal program this is harmless — the user could run any code they like as themselves anyway.

Example 2: a Set-UID program

If the same trick worked on a root-owned Set-UID program, any user could inject code into it and run that code as root. Let us check:

$ sudo chown root myprog && sudo chmod 4755 myprog
$ export LD_PRELOAD=./libmylib.so.1.0.1
$ ./myprog
$                        # one-second pause, no message: the real sleep() ran

Our sleep was not used. This is a countermeasure in the dynamic linker: when a program runs in secure-execution mode — which the kernel signals to the loader (via the AT_SECURE auxiliary vector entry) when, among other cases, the process’s EUID differs from its RUID — ld.so ignores LD_LIBRARY_PATH, restricts LD_PRELOAD to libraries in standard system directories that are themselves marked Set-UID, and removes these variables from the environment.

You can watch the variables disappear. Make a Set-UID copy of env and compare:

$ cp /usr/bin/env ./myenv
$ sudo chown root myenv && sudo chmod 4755 myenv
$ export LD_PRELOAD=./libmylib.so.1.0.1
$ export LD_LIBRARY_PATH=.
$ env | grep LD_           # the normal env program sees both
LD_PRELOAD=./libmylib.so.1.0.1
LD_LIBRARY_PATH=.
$ ./myenv | grep LD_       # the Set-UID copy sees neither
$

Note. The countermeasure keys on RUID ≠ EUID. If the owner of a Set-UID program runs it, RUID equals EUID and LD_PRELOAD is honored — which is why, in Lab 1, the result depends on which user runs the program and who owns it. Work through all the combinations in Lab 1 Task 7 and explain each one.

2.12 Attacks via External Programs

A privileged program may not read any environment variable itself, yet still be vulnerable through a program it runs. How it runs that program determines the attack surface:

  • The exec family (execve, execl, …) runs the target directly. The target sees whatever environment the caller passes.
  • system() runs /bin/sh -c cmd. In glibc it ultimately calls execve("/bin/sh", ...) with the caller’s environment, and the shell then runs the command. The shell is a large program whose behavior depends on many environment variables.

The most important of those is PATH. Consider:

/* runls.c  (root-owned Set-UID) */
#include <stdlib.h>
int main(void)
{
    system("ls");         /* no absolute path! */
    return 0;
}

The shell resolves ls by searching PATH, which the attacker controls:

$ ./runls                         # normal behavior
file1  file2  runls
$ cat > ls <<'EOF'
#!/bin/sh
echo "running as: $(id)"
EOF
$ chmod +x ls
$ export PATH=.:$PATH             # put the current directory first
$ ./runls
running as: uid=1000(seed) gid=1000(seed) euid=0(root) ...

Our ls ran instead of /bin/ls — and, if /bin/sh does not drop privilege, it ran with EUID 0. The fixes, in order of preference: do not call system() from privileged code; if you must run a program, use execve() with an absolute path and an explicitly constructed, minimal environment; never rely on a shell to keep you safe.

2.13 Countermeasures: The Set-UID Approach vs. the Service Approach

Step back and compare two architectures for letting ordinary users perform privileged operations:

 (a) Set-UID approach                         (b) Service approach

   user ──execve──► privileged process          user process ──request──► privileged daemon
          env vars, fds, args,                   (only the request         (started by the
          cwd, limits ... all                     message crosses           system with its
          inherited from user                     the boundary)             own environment)

In the Set-UID approach, the user starts the privileged process. Everything the user controls about process creation — environment, open descriptors, working directory, resource limits, signal dispositions — flows into the privileged process. That is a broad and easily overlooked attack surface.

In the service approach, a privileged daemon is started by the system (for example, by init/systemd at boot) with an environment the system chose. Users send it requests over a well-defined channel such as a Unix-domain socket or an IPC mechanism; the daemon checks the requester’s identity and decides. Only the request crosses the trust boundary, so the daemon can trust its own environment variables.

Most operating systems use both. But the trend favors services: Android, for instance, does not support Set-UID and Set-GID programs for its apps at all — the system partition is mounted nosuid, and privileged operations go through system services reached via Binder IPC. Desktop Linux has moved in the same direction with mechanisms such as polkit and systemd services replacing many traditional Set-UID helpers.

Check Your Understanding

1. A file has mode -rw-r-----, owner alice, group staff. User bob is in group staff; user carol is not. Who can read the file? Who can write it?

Answer

alice (owner) can read and write. bob (group) can read but not write. carol (other) can do neither. Root can do both, since it bypasses these checks.

2. With umask 0027, what are the permissions of a newly created regular file and a newly created directory?

Answer

File: 0666 & ~0027 = 0640 (rw-r-----). Directory: 0777 & ~0027 = 0750 (rwxr-x---).

3. An administrator runs sudo chmod 4755 prog and then sudo chown root prog. The program does not run with root privilege. Why?

Answer

Changing ownership clears the Set-UID (and Set-GID) bit, even when root does it. The chown after the chmod removed the bit. The correct order is chown first, then chmod 4755.

4. In cap_leak.c, the program calls setuid(getuid()) before starting the shell. Why can the user still write to /etc/zzz, and what is the minimal fix?

Answer

The file was opened while the process was root, and permission is checked only at open(). The open descriptor (3) survives both setuid() and execve(), so the unprivileged shell inherits a writable handle to /etc/zzz. The minimal fix is to close(fd) before dropping privilege (or open with O_CLOEXEC).

5. Why is execve("/bin/cat", v, NULL) safe where system("/bin/cat " + input) is not, even though both run cat with the user’s input?

Answer

system() hands a single string to a shell, which parses it; shell metacharacters in the input (;, |, $(...), …) are interpreted as code. execve() passes the program path and each argument as separate strings directly to the kernel; the input is never parsed, so it remains data. Code and data are kept in separate channels.

6. A root-owned Set-UID program calls sleep(). A normal user sets LD_PRELOAD to a library defining sleep() and runs the program. Does the user’s sleep() run? What if root runs the same program with the same environment?

Answer

When a normal user runs it, RUID ≠ EUID, so the dynamic linker runs in secure-execution mode and ignores the user’s LD_PRELOAD; the real sleep() runs. When root runs it, RUID = EUID = 0, so LD_PRELOAD is honored and the custom sleep() runs — harmless, since root could run any code anyway.

7. Why can a privileged service trust its environment variables while a Set-UID program cannot?

Answer

A Set-UID program is created by execve() from the user’s process, so its environment is whatever the user supplied. A service is started by the system with an environment the system controls; users only send it request messages. The environment never crosses the trust boundary.

Summary

  • Linux access control is based on numeric user and group IDs, the rwx bits for user/group/other, the umask, and optional ACLs.
  • A process has a real UID (who started it) and an effective UID (whose privilege it has); access checks use the EUID. A Set-UID program runs with its owner’s EUID, making it a deliberate privilege-escalation bridge.
  • Capability leaking happens when a program drops its privileged identity but keeps privileged resources such as open file descriptors. Release them first; drop permanently with setuid(), temporarily with seteuid().
  • system() lets user data become shell code; execve() keeps code and data separate.
  • Environment variables are inherited through fork() and set by execve()’s third argument. In a Set-UID program they are attacker-controlled input, often consumed by hidden code: the dynamic linker (LD_PRELOAD, LD_LIBRARY_PATH) and shells run by system() (PATH).
  • The dynamic linker defends itself by entering secure-execution mode when RUID ≠ EUID. Shells such as dash drop Set-UID privilege. Both are safety nets, not substitutes for correct code.
  • The service approach shrinks the attack surface compared with Set-UID, which is why systems like Android removed Set-UID altogether.

Connection to the Labs

Lab 1: Environment Variables and Set-UID Programs is the hands-on companion to this chapter:

  • Tasks 1–3 explore how environment variables are set and inherited through fork() and execve() (Section 2.9).
  • Tasks 4–6 show how system() and Set-UID programs consume environment variables, including the PATH attack (Sections 2.7 and 2.12).
  • Task 7 is the LD_PRELOAD experiment from Section 2.11; be ready to explain each owner/runner combination.
  • Task 8 is the catall command-injection scenario (Section 2.7).
  • Task 9 is the capability-leaking program from Section 2.5.

In the following chapters, the vulnerable programs you exploit are root-owned Set-UID programs. Everything you learn here about why such programs are dangerous applies directly.

Further Reading

  • Wenliang Du. Computer & Internet Security: A Hands-on Approach, 3rd edition, Chapters 1 and 2 (Set-UID programs and environment variables).
  • Hao Chen, David Wagner, and Drew Dean. “Setuid Demystified.” 11th USENIX Security Symposium, 2002.
  • Linux manual pages: man 7 environ, man 3 system, man 2 execve, man 2 setuid, man 2 seteuid, man 8 ld.so (see “Secure-execution mode”), man 1 setfacl.