Careers Post-AI
Security: all chapters

SecurityPart 1: Foundations

Chapter 3Operating systems and privilege

35 min read, 2 labs, Beginner

In January 2022 Qualys disclosed PwnKit (CVE-2021-4034), a memory bug in pkexec, a setuid-root helper that had shipped by default on most Linux distributions for about twelve years. The bug was small. The damage came from the privilege the program carried, and administrators who had removed the setuid bit from helpers they never used were not exposed. This chapter explains how an operating system decides who may do what, so you can configure that decision deliberately and audit it on Linux and Windows.

After this chapter you can

  • Explain why the CPU separates kernel mode from user mode and how system calls cross the boundary
  • Describe processes, threads, signals and a process's virtual memory layout
  • Read users, groups, permission bits, setuid and capabilities, and predict whether an access succeeds
  • Locate Linux identity data and authentication logs, and name the Windows equivalent of each
  • Audit a Linux host for setuid files, file capabilities, loose permissions and broad sudo rules
  • Apply least privilege to an operating system with a concrete hardening checklist

Kernel mode, user mode and system calls

The CPU runs code at different privilege levels. In kernel mode code can touch any memory, program hardware and change the page tables that define what every process can see. In user mode it can do none of that. Every ordinary program, including one running as root, runs in user mode and must ask the kernel to act for it.

That request is a system call (syscall): the program puts a call number and arguments in registers and executes a special instruction that jumps into the kernel at a fixed entry point. The kernel checks the request, does the work and returns a result or an error code. Opening a file, sending a packet, starting a process and allocating memory all go through this one narrow path, which makes it the only doorway into the kernel.

The boundary exists because programs are buggy and some are hostile. If any program could write to any memory, one crash or one malicious download would own the whole machine. With the boundary, the kernel is the single place that enforces policy, and a bug in a user program is contained to what that program's identity is allowed to do.

Processes, threads and signals

A process is a running program plus the resources the kernel tracks for it: an address space, open file descriptors, a current directory and an identity (user and group IDs). A thread is a path of execution inside a process; threads share the address space and files, but each has its own stack and registers. Every process has a numeric process ID (PID) and a parent.

New processes are created by fork (copy the current process) followed by execve (replace the copy's program with a new one). The result is a tree rooted at PID 1, the init system, which on most distributions is systemd.

The tree is a security tool. A web server worker that suddenly has a child shell, or a shell whose parent is a database, is a classic detection signal you will meet again in the detection engineering chapter. Notice also the privilege drop: nginx starts as root to bind port 80, then runs its workers as the unprivileged www-data user.

Signals are small asynchronous notifications the kernel delivers to a process. You can only signal processes you own unless you are root.

SignalNumberDefault effectTypical use
SIGTERM15TerminatePolite request to shut down; the process can clean up
SIGKILL9TerminateCannot be caught or ignored; last resort
SIGHUP1TerminateMany daemons treat it as "reload your config"
SIGINT2TerminateWhat Ctrl+C sends
SIGSTOP19StopPause a process; cannot be caught

The virtual memory layout of a process

Each process sees its own virtual address space: a private range of addresses that the kernel and the CPU's memory management unit map to physical memory page by page. Two processes can both use address 0x400000 and never see each other's data. This isolation is enforced by hardware, which is why it holds even when a program is buggy.

Each region carries permissions. Code pages are readable and executable but not writable; stack and heap are writable but, on any modern system, not executable. That rule is often called W^X (write xor execute). Address space layout randomization (ASLR) places these regions at different addresses each run.

RegionHoldsTypical permissions
TextMachine code of the programr-x
Data, BSSInitialized and zeroed globalsrw-
HeapDynamic allocationsrw-
Mapped librariesCode and data of libc and othersr-x for code, rw- for data
StackFunction frames, local variablesrw-

On Linux you can read this map for any process you own in /proc/PID/maps, which you will do in the first lab. How memory bugs break these protections is the subject of the memory safety chapter; here the point is that the layout and its permissions are kernel-enforced policy.

Users, groups and file permissions

Linux identity is numeric. A user ID (UID) and one or more group IDs (GIDs) are attached to every process; names like alice are just labels looked up in /etc/passwd. UID 0 is root, and the kernel skips most permission checks for it. System services get their own low-numbered UIDs so a compromise of one does not hand over the others.

Every file has an owner UID, an owner GID and nine permission bits: read, write and execute for the owner, the group and everyone else. Run ls -l and you see them as a string such as -rw-r-----, or in octal as 640.

BitsOctalOn a fileOn a directory
r4Read contentsList names
w2Modify contentsCreate, delete and rename entries
x1ExecuteEnter and reach files inside

The kernel picks exactly one class and stops. If you own the file, only the owner bits count, even if the group bits are more generous. Otherwise, if you are in the file's group, the group bits apply; otherwise the "other" bits do.

Setuid, capabilities and sudo

Some programs need more privilege than the user running them. passwd must write /etc/shadow, which only root can modify. The setuid bit (shown as s in the owner execute slot, -rwsr-xr-x) tells the kernel to run the program with the file owner's UID as its effective UID, while the real UID still records who launched it. A setuid-root program is therefore code that any user can run as root.

That is why administrators audit setuid files. Every one is trusted to handle hostile input from unprivileged users perfectly, and PwnKit showed what happens when one does not. The audit question for each file is simple: does this host need it, and does it need it to be setuid?

Linux capabilities split root's power into about forty named privileges so a program can get only the one it needs. A web server can hold CAP_NET_BIND_SERVICE to bind port 443 without being root; ping can hold CAP_NET_RAW to send raw packets. Capabilities can be attached to a file (visible with getcap) or granted to a service by systemd. A capability is a slice of root, and some slices, such as CAP_SYS_ADMIN or CAP_DAC_OVERRIDE, are nearly the whole thing.

MechanismGrantsAudit commandRed flag
Setuid rootFull root while runningfind / -xdev -perm -4000 -type fAnything you cannot explain, any interpreter or editor
SetgidThe file's groupfind / -xdev -perm -2000 -type fGroup with access to secrets
File capabilityNamed privilegesgetcap -r / 2>/dev/nullcap_sys_admin, cap_dac_override, cap_setuid
sudo ruleCommands as another usersudo -l -U userALL, wildcards, shells, editors

sudo lets named users run named commands as another user, with a password prompt and a log entry. Rules live in /etc/sudoers and files under /etc/sudoers.d/, always edited with visudo, which refuses to save a file with syntax errors.

Over-broad rule

  • deploy ALL=(ALL) NOPASSWD: ALL
  • Any command, as any user, no password
  • Equivalent to giving the account root
  • Logs show only that deploy ran something

Least-privilege rule

  • deploy ALL=(root) /usr/local/bin/rotate-logs
  • One full path, no arguments wildcard
  • The script is owned by root and not writable by deploy
  • Every use is attributable and reviewable

Namespaces and cgroups, briefly

Two more kernel features shape privilege, and containers are built from them. Namespaces give a process its own view of a resource: its own PID tree, mount table, network stack, hostname or even UID mapping, so root inside a user namespace can be an ordinary user outside. Control groups (cgroups) limit and account for what a group of processes may consume: CPU, memory, I/O and number of processes.

FeatureAnswers the questionExample
PID namespaceWhich processes can I see?Container sees its app as PID 1
Mount namespaceWhich file system do I see?Container has its own root directory
Network namespaceWhich interfaces and ports?Container gets its own IP
User namespaceWho am I outside?Container root maps to UID 100000 on the host
cgroupsHow much may I use?Memory capped at 512 MB

A container is a process tree with these applied, not a virtual machine; it shares the host kernel. The containers and Kubernetes chapter builds on this.

Where Linux keeps identity and logs

Identity data is split so that the widely readable part contains no secrets. /etc/passwd is world-readable and lists each account's name, UID, primary GID, home directory and login shell. Password hashes moved to /etc/shadow, readable only by root and the shadow group, along with password aging rules.

File or toolContainsWho can read
/etc/passwdAccounts, UIDs, home, shellEveryone
/etc/shadowPassword hashes, expiryroot, shadow group
/etc/groupGroups and membersEveryone
/etc/sudoers, /etc/sudoers.d/sudo rulesroot
/var/log/auth.log (Debian, Ubuntu) or /var/log/secure (RHEL family)Logins, sudo, su, SSHroot, adm group
journalctlsystemd journal of all servicesroot, members of systemd-journal or adm

On systemd hosts, journald collects logs from every service in a structured binary journal. Useful queries are journalctl -u ssh for one unit, journalctl _COMM=sudo for every sudo use and journalctl --since "1 hour ago". Many distributions also forward to rsyslog, which writes the classic text files above.

The Windows equivalents

Windows uses different names for the same ideas. Each logged-on session gets an access token listing the user's security identifier (SID), group SIDs and privileges. Every securable object has a security descriptor holding an access control list (ACL) of allow and deny entries, which the kernel's security reference monitor checks against the token.

ConceptLinuxWindows
IdentityUID, GIDsSID in an access token
Superuserroot (UID 0)SYSTEM account, local Administrators group
Object permissionsOwner, group, other bits; optional ACLsDiscretionary ACL with allow and deny entries
Fine-grained privilegeCapabilitiesPrivileges such as SeDebugPrivilege, SeBackupPrivilege
Elevationsudo, setuidUAC prompt, Run as administrator
Background programssystemd unitsServices, managed by the Service Control Manager
Configuration storeFiles under /etcRegistry hives such as HKLM
Auth logsauth.log, journaldSecurity event log (4624 logon, 4625 failed logon, 4672 special privileges)

User Account Control (UAC) gives administrators two tokens at logon: a filtered standard-user token used by default and a full token used only after an elevation prompt. Services are the Windows counterpart of daemons, and each runs as an account; running one as LocalSystem when LocalService or a dedicated account would do is the Windows version of running a daemon as root.

Least privilege on an operating system

Least privilege means every account, process and file gets only the access its job needs. On an OS that turns into a checklist you can run and re-run.

  • Accounts: remove unused accounts; give services their own system users with nologin shells; disable direct root SSH login.
  • sudo: grant specific commands by full path to groups, not ALL; avoid NOPASSWD except for narrowly scoped automation; review /etc/sudoers.d/ regularly.
  • Setuid and capabilities: inventory both, remove the bit from helpers you do not use, and alert when the inventory changes.
  • File permissions: no world-writable files outside /tmp-style directories; secrets at 600 or 640; a restrictive default umask such as 027.
  • Services: run each as a dedicated user and use systemd sandboxing options such as NoNewPrivileges=yes, ProtectSystem=strict and CapabilityBoundingSet=.
  • Patching and logging: patch the kernel and setuid packages promptly, and forward auth logs off the host.
  • Windows: daily work on standard accounts, UAC on, services on least-privileged accounts, and no shared local administrator passwords (use Windows LAPS).

Key terms

Kernel mode
The CPU privilege level in which code can access all memory and hardware; only the kernel runs here.
System call
The controlled entry point a user-mode program uses to ask the kernel to perform a privileged operation.
Process
A running program with its own virtual address space, file descriptors and user identity.
Virtual address space
The private range of memory addresses a process sees, mapped to physical memory by the kernel and the CPU.
Effective UID
The user ID the kernel uses for permission checks, which differs from the real UID when a setuid program runs.
Setuid bit
A file mode bit that makes a program run with its owner's user ID rather than the caller's.
Capability
One named slice of root's privileges, such as binding low ports, that can be granted on its own.
Access token
The Windows object attached to a process that lists its user SID, group SIDs and privileges.
Namespace
A kernel feature that gives a process its own isolated view of a resource such as PIDs or the network.
Least privilege
Granting each account and process only the access its job needs, and no more.
Lab

Watch a program talk to the kernel

Beginner, 40 min

Goal: observe system calls, the process tree and a process's memory map on a Linux system you own.

You need: Docker (Docker Desktop on macOS or Windows, docker.io on Linux). Everything runs inside a throwaway Ubuntu container on your own machine.

  1. Start a container and install the tools:

    docker run -it --rm --name osl ubuntu:24.04 bash
    apt-get update && apt-get install -y strace procps

    If strace later reports Operation not permitted, exit and restart the container with --cap-add=SYS_PTRACE.

  2. Trace a tiny program and count its system calls:

    strace -e trace=openat,read,write,close cat /etc/hostname
    strace -c ls / > /dev/null

    In the first output, find the openat(AT_FDCWD, "/etc/hostname", O_RDONLY) line and the number it returns: that is the file descriptor. Before it you will see openat calls loading libc.so.6. The second command prints a table of every syscall ls made, typically a few dozen distinct ones.

  3. Watch the kernel refuse a request. Create a user and trace a read of a root-only file:

    useradd -m alice
    su alice -c 'strace -e trace=openat cat /etc/shadow'

    Expect openat(AT_FDCWD, "/etc/shadow", O_RDONLY) = -1 EACCES (Permission denied). The decision happened in the kernel, not in cat.

  4. List processes, their owners and the tree:

    su alice -c 'sleep 600' &
    ps -eo user,pid,ppid,comm --forest

    You should see bash (root) as the parent of su, and sleep running as alice.

  5. Read the sleeping process's identity and memory map:

    PID=$(pgrep -u alice sleep)
    grep -E 'Uid|Gid|Threads' /proc/$PID/status
    cat /proc/$PID/maps

    The Uid line shows four numbers: real, effective, saved and file-system UID. In maps, label each region: the sleep binary (r-xp for code), [heap], libc.so.6, ld-linux, and [stack] near the top.

  6. Start a new process three times and compare where its stack lands:

    for i in 1 2 3; do grep stack /proc/self/maps; done

    Each grep is a fresh process reading its own map, and the three stack addresses differ: that is ASLR.

Check your work: you can point to a syscall that returned a file descriptor, one that returned EACCES, the four UIDs of a process, and the text, heap, library and stack regions in a real memory map.

Stretch: run strace -f -e trace=execve,clone,clone3 bash -c 'ls | wc -l' and draw the process tree it creates. Explain why there are two execve calls after the clones.

Lab

Audit and tighten permissions in a container

Beginner, 60 min

Goal: predict and verify file access, inventory setuid files and capabilities, then find and fix two deliberately loose settings.

You need: Docker. You will only inspect and change a throwaway container you start yourself.

  1. Start a fresh container and install the tools:

    docker run -it --rm --name audit ubuntu:24.04 bash
    apt-get update && apt-get install -y sudo libcap2-bin acl
  2. Build a small permission scenario:

    groupadd finance
    useradd -m alice && useradd -m bob && useradd -m deploy
    usermod -aG finance bob
    mkdir /srv/reports && echo "q3 numbers" > /srv/reports/q3.txt
    chown alice:finance /srv/reports/q3.txt && chmod 640 /srv/reports/q3.txt

    Before running anything else, write down your prediction: can alice read it, can bob read it, can bob write it, can deploy read it?

  3. Verify each prediction:

    su alice -c 'cat /srv/reports/q3.txt'
    su bob -c 'cat /srv/reports/q3.txt'
    su bob -c 'echo x >> /srv/reports/q3.txt'
    su deploy -c 'cat /srv/reports/q3.txt'

    Expected: alice reads (owner bits), bob reads but cannot write (group bits r--), deploy is denied (other bits ---).

  4. Inventory setuid and setgid files:

    find / -xdev -perm -4000 -type f -exec ls -l {} \; 2>/dev/null
    find / -xdev -perm -2000 -type f -exec ls -l {} \; 2>/dev/null

    Expect a short list along the lines of passwd, chsh, chfn, gpasswd, newgrp, su, mount, umount and sudo, plus setgid shadow helpers such as chage and unix_chkpwd. The exact list varies with the image version. In a notes file, write one line per binary on why it needs privilege: for example, passwd must write /etc/shadow, su and sudo must switch UID.

  5. Inventory file capabilities, then see what one looks like:

    getcap -r / 2>/dev/null
    cp /usr/bin/python3 /usr/local/bin/webpy
    setcap cap_net_bind_service=+ep /usr/local/bin/webpy
    getcap -r / 2>/dev/null

    The base image usually has no file capabilities, so the first command may print nothing. After setcap you should see /usr/local/bin/webpy cap_net_bind_service=ep. Note why this is risky: an interpreter with a capability lets anyone who can run it use that capability for any code. Remove it with setcap -r /usr/local/bin/webpy && rm /usr/local/bin/webpy.

  6. Plant two loose settings, as a careless administrator might:

    mkdir -p /etc/app && echo "db_password=changeme" > /etc/app/config.ini
    chmod 666 /etc/app/config.ini
    echo 'deploy ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/deploy
    chmod 440 /etc/sudoers.d/deploy
  7. Find them the way an auditor would:

    find / -xdev -type f -perm -0002 2>/dev/null
    sudo -l -U deploy

    The first lists /etc/app/config.ini. The second reports that deploy may run (ALL) NOPASSWD: ALL, which is full root.

  8. Fix them:

    groupadd appsvc
    chown root:appsvc /etc/app/config.ini && chmod 640 /etc/app/config.ini
    printf '#!/bin/sh\necho rotating logs\n' > /usr/local/bin/rotate-logs
    chown root:root /usr/local/bin/rotate-logs && chmod 755 /usr/local/bin/rotate-logs
    echo 'deploy ALL=(root) /usr/local/bin/rotate-logs' > /etc/sudoers.d/deploy
    chmod 440 /etc/sudoers.d/deploy
    visudo -cf /etc/sudoers.d/deploy

    visudo -cf should print parsed OK.

Check your work: rerun step 7. The world-writable search no longer lists the config file, ls -l /etc/app/config.ini shows -rw-r----- root appsvc, and sudo -l -U deploy lists only (root) /usr/local/bin/rotate-logs. You also have a notes file explaining each setuid binary.

Stretch: turn steps 4, 5 and 7 into a script audit.sh that prints setuid files, capabilities, world-writable files and every sudo rule, and exits non-zero if anything is not on an allowlist you keep in the repo. Commit it with your notes as a portfolio piece.

Check yourself

A file is owned by alice, its group is finance, and its mode is 604 (rw- for owner, nothing for group, r-- for others). Bob is in finance. Can bob read it?

Why is a bug in a setuid-root program more serious than the same bug in an ordinary program?

A web server needs to listen on port 443 but should not run as root. Which approach best applies least privilege?

An audit finds the sudo rule 'deploy ALL=(root) /usr/local/bin/rotate-logs', and the script is owned by deploy with mode 755. What is the problem?

On Windows, an administrator logs on with UAC enabled and opens a normal command prompt. Which token does it use?

Recap

  • The CPU separates kernel mode from user mode, and system calls are the only way a program asks the kernel for anything privileged.
  • Processes form a tree with an identity on every node, and each has a private, permission-tagged virtual address space.
  • File access is decided by one class of permission bits: owner, group or other, never a combination.
  • Setuid binaries, file capabilities and sudo rules are where privilege is granted, so they are where you audit first.
  • Linux keeps public identity in passwd, secrets in shadow and authentication records in auth logs and the journal; Windows maps these to tokens, ACLs, the registry and the Security event log.
  • Least privilege on an OS is a checklist you run repeatedly, not a one-time setting.

Go deeper