Learn / Stage 1: Foundations / Lesson 1.2

$ lesson 1.2 --stage foundations

Operating System Fundamentals

Windows, Linux, Android and macOS look different, but underneath they solve the same problems in similar ways. Learn the kernel, processes, memory, file systems and permissions once, and every OS starts to make sense, including how attackers move through it.

  • Stage 1 Foundations
  • Level Beginner
  • 50 min
  • 6 sections, quiz, lab

Start the lesson Jump to the lab

By the end of this lesson you can

  • Explain kernel mode, user mode and why system calls exist
  • Trace how a process is created and read a process tree like an analyst
  • Describe virtual memory and the protections ASLR, DEP and stack canaries
  • Compare file systems and explain inodes, the MFT and timestamps
  • Explain users, permissions, least privilege and privilege escalation
1.2.01

What an operating system actually does

An operating system has two jobs. It is a referee that shares the CPU, memory, disk and network fairly between dozens of programs, and it is a translator that gives programs simple commands like "open this file" instead of making each one talk to disk controllers directly.

The core of the OS is the kernel. It runs in a privileged CPU mode (kernel mode, often called ring 0 on x86) where it can touch any memory and any device. Everything else, including your browser, terminal and antivirus user interface, runs in user mode (ring 3) with restricted rights.

User mode applications reach the kernel only through the system call interface; the kernel controls the hardwareUSER MODE (ring 3): limited, crashes stay inside one processBrowserWhatsAppTerminalMalware?same rules applysystem call interface: open, read, write, execve, CreateFile ... the only door downKERNEL MODE (ring 0): full control of the hardwareSchedulerMemory managerFile systemsDriversHardware: CPU, RAM, disk, network card
A crash in user mode kills one app. A bug in kernel mode can take down or take over the whole machine.
Kernel designs
Kernel designIdeaExamples
Monolithicmost OS services (drivers, file systems, networking) run inside the kernel for speedLinux
Hybrida monolithic style kernel with some microkernel ideas and parts moved outWindows NT family, macOS (XNU)
Microkernelonly the bare minimum in the kernel; drivers and services run as separate user processesQNX, seL4, MINIX 3
1.2.02

System calls: the only door into the kernel

When a program wants something only the kernel can do, it makes a system call: it puts a call number and arguments in registers and executes a special instruction (syscall on x86-64) that switches the CPU into kernel mode at a fixed entry point. The kernel checks permissions, does the work and returns.

System calls
TaskLinux system callWindows (documented API, then native call)
Open a fileopenatCreateFileW then NtCreateFile
Read datareadReadFile then NtReadFile
Start a programfork / clone then execveCreateProcessW then NtCreateUserProcess
Network connectionsocket, connectWinsock connect, handled by the AFD driver
Allocate memorymmap, brkVirtualAlloc then NtAllocateVirtualMemory

You can watch system calls happen. On Linux, strace prints every call a program makes:

$ strace -e trace=openat,execve cat /etc/hostname
execve("/usr/bin/cat", ["cat", "/etc/hostname"], ...) = 0
openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3
cwm-lab
1.2.03

Processes and threads: programs come alive

A program is a file on disk. A process is that program loaded into memory and running, with its own private memory, open files, a security identity and at least one thread (a single line of execution the scheduler can run). Threads in the same process share its memory.

Every process gets a PID (process ID) and remembers its parent's PID (PPID). Together they form a tree, and that tree is one of the best tools a defender has.

What happens when you type ls and press Enter

Linux shown; Windows does the same in one CreateProcess call.

    1. The shell reads your command

    Bash (PID 1201) parses ls -l and searches each folder in $PATH until it finds /usr/bin/ls.

    2. fork

    Bash calls fork() (in practice clone()). The kernel creates a near copy of bash, PID 1388, with PPID 1201.

    3. execve

    The child calls execve("/usr/bin/ls", ...). The kernel throws away the copied bash memory and loads the ls program, its libraries and a fresh stack. Same PID, new program.

    4. Scheduling

    The process is placed in the ready queue. The scheduler gives it CPU time slices, switching between processes many times per second (a context switch saves and restores registers).

    5. Waiting

    When ls asks for the directory contents it may wait for the disk. It moves to waiting (blocked) so other processes can use the CPU.

    6. Exit

    ls prints its output and calls exit. It becomes a zombie for a moment until bash collects its exit code with wait(), and then it is gone.

    $ ps -ef --forest | tail -5
    student   1201   1190  0 09:30 pts/0  00:00:00 -bash
    student   1388   1201  0 09:41 pts/0  00:00:00  \_ ps -ef --forest
    1.2.04

    Memory management: every process lives in its own illusion

    Each process believes it has a huge, private address space starting near zero. That is virtual memory. The CPU's memory management unit (MMU) translates every virtual address into a real physical RAM address using page tables the kernel maintains. Memory is handled in pages, usually 4 KiB each.

    • Isolation: process A simply has no mapping for process B's pages, so it cannot read them. That is a security boundary built into hardware.
    • Swapping: rarely used pages can be moved to disk (a swap partition on Linux, pagefile.sys on Windows) and brought back when touched.
    • Permissions per page: each page can be readable, writable and executable, or not.
    Typical layout of a process's virtual memory: kernel space, stack, free space, heap, data and text segmentsKernel spacenot readable from user modeStacklocal variables, return addressesgrows down ↓ free space ↑ grows upHeapmalloc, new: dynamic dataData and BSSglobal variablesText (code)read only, executablehigh addresseslow addressesoverflow a stack bufferand you can overwritethe saved return address
    Simplified layout. Real systems randomise where each region starts.

    Built in defences against memory attacks

    Memory protections
    DefenceWhat it doesWhat it stops
    DEP / NX bitmarks stack and heap pages as non-executablerunning shellcode placed in a data buffer
    ASLRrandomises where the stack, heap, libraries and program loadhard coded addresses in exploits
    Stack canariesa secret value before the return address, checked before returningsimple stack buffer overflows
    CFG, CET shadow stackcheck that indirect calls and returns go to valid placesreturn oriented programming
    1.2.05

    File systems: how names become bytes

    A file system turns a raw partition into folders and files. It stores the data, and separately the metadata: name, size, owner, permissions, timestamps and the list of blocks holding the content.

    • Linux ext4 keeps metadata in an inode per file. The file name lives in the directory entry that points to the inode, which is why one file can have several names (hard links). See inode numbers with ls -i.
    • Windows NTFS keeps a record for every file in the Master File Table ($MFT), a goldmine for forensic investigators.
    Common file systems
    File systemUsed byNotes for security
    NTFSWindows system drivespermissions (ACLs), journaling, encryption via BitLocker or EFS, alternate data streams
    ext4most Linux distributionsUnix permissions, journaling, inodes
    XFS, BtrfsRHEL family servers, Fedora, some NAS boxesBtrfs has snapshots useful for ransomware recovery
    APFSmacOS, iOSbuilt in encryption and snapshots
    FAT32old pen drives, EFI System Partitionno permissions at all, 4 GiB maximum file size
    exFATSD cards, large pen drivesno permissions, no journal

    Timestamps tell stories

    File systems record when a file was modified, accessed, had its metadata changed, and (on NTFS and newer ext4) created. Investigators build timelines from these to reconstruct an attack minute by minute.

    1.2.06

    Users, permissions and privilege

    Every process runs as some user, and the OS checks that identity on every file open and system call. That is what stops one user from reading another's files.

    Accounts and permissions
    Linux and macOSWindows
    Most powerful accountroot, user ID 0NT AUTHORITY\SYSTEM for the OS, plus members of Administrators
    Identity numberUID and GIDSID, for example S-1-5-18 is SYSTEM
    Who may do whatowner, group, others with read, write, execute bitsaccess control lists (ACLs) on each object
    Temporary elevationsudoUser Account Control (UAC) prompt
    Extra mandatory controlsSELinux, AppArmorintegrity levels, AppLocker, WDAC

    Most permission systems you meet are discretionary access control (DAC): the owner of a file decides who else can use it. Mandatory access control (MAC) adds rules set by the administrator that even owners cannot override, which is why a compromised web server process under SELinux still cannot read home folders.

    Privilege escalation

    Attackers usually land as a low privileged user, for example through a phishing document or a web bug, and then try to climb. Vertical escalation means becoming admin or root. Horizontal means becoming another user at the same level, perhaps one with access to payroll files.

    Flashcards: do you remember?

    Tap a card to flip it. Try to answer in your head first; recalling is what makes it stick.

    Quick quiz

    Instant feedback on every answer. Score 70% or more to pass this lesson's quiz.

    Q1A program wants to read a file. What must it do?

    Q2Which process tree is the strongest sign of a malicious document?

    Q3cat /proc/sys/kernel/randomize_va_space prints 0. What does that mean?

    Q4Why can malware avoid user mode API hooks?

    Q5A web server process is compromised, but SELinux prevents it reading users' home folders. That is an example of:

    Q6An attacker logged in as a normal user becomes root. This is:

    0 / 6

    Hands-on lab

    lab40 minutesyour own machines only

    Lab: watch the OS at work

    You need: Your Ubuntu VM from lesson 1.1 (restore the clean-install snapshot if you broke it). Optional: your own Windows PC.

    1. See the process tree

      $ ps -ef --forest | less
      $ pstree -p | head -30
      $ echo $$

      $$ is your shell's PID. Find it in the tree and follow the parents up to PID 1. What is PID 1 called?

    2. Trace system calls

      $ sudo apt install -y strace
      $ strace -c ls /etc > /dev/null
      $ strace -e trace=openat cat /etc/hostname

      The -c summary shows how many calls of each type a tiny command makes. Note how many files cat opens before it reaches the one you asked for (libraries and locale files).

    3. Look at a process's memory map

      $ cat /proc/self/maps | head -20
      $ cat /proc/sys/kernel/randomize_va_space
      $ cat /proc/self/maps | grep stack; cat /proc/self/maps | grep stack

      Run the last line twice: the stack address changes each run. That is ASLR working. Find the pages marked r-xp (code) and rw-p (data).

    4. Inodes, links and timestamps

      $ cd ~ && echo hello > a.txt
      $ ln a.txt b.txt && ls -li a.txt b.txt
      $ stat a.txt
      $ touch -d '2020-01-01 10:00' a.txt && stat a.txt

      Both names share one inode number. The touch -d line is a harmless timestomp on your own file: notice which timestamp changed and which one (Change) still shows the real time. Investigators use exactly that mismatch.

    5. Users and permissions

      $ id
      $ sudo useradd -m labuser
      $ sudo -u labuser cat /home/student/a.txt
      $ chmod 600 ~/a.txt && sudo -u labuser cat /home/student/a.txt
      $ sudo userdel -r labuser

      Notice the second read fails with Permission denied (if your home folder is not readable by others the first may fail too, which is also a lesson). Replace student with your own user name.

    6. Windows: the same ideas

      On your own Windows PC open Task Manager, Details tab, right click a column header, Select columns, and add Command line and Elevated. Then download Process Explorer from Microsoft Sysinternals (learn.microsoft.com/sysinternals) and view the process tree. Find lsass.exe and check its parent.

    You are done when: You can name PID 1, show ASLR changing addresses, explain why two file names had one inode, and point to a process's parent on both Linux and Windows.

    Download the lab checklist (.txt)

    Key takeaways

    • The kernel is the referee; system calls are the only legitimate way in.
    • Read processes as a family tree: parent, path and user tell you if something is wrong.
    • Virtual memory isolates processes. ASLR, DEP and canaries make memory bugs harder, not impossible.
    • Metadata and timestamps are evidence, and attackers try to fake them.
    • Least privilege limits how far one compromised account can go.

    Finished the sections, quiz and lab? Mark the lesson complete. Progress is saved only in this browser.