---
title: "Operating System Fundamentals for Security | CyberWithMadhav"
description: "Free lesson on how operating systems work: kernel and user mode, system calls, processes, virtual memory, ASLR, file systems, users and privilege escalation."
url: https://www.cyberwithmadhav.com/learn-operating-system-fundamentals.html
source_format: markdown rendering of the HTML page
---

[Learn](https://www.cyberwithmadhav.com/learn.html) / [Stage 1: Foundations](https://www.cyberwithmadhav.com/learn.html#stage-1) / 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

## In this lesson

1. What an operating system actually does
2. System calls: the only door into the kernel
3. Processes and threads: programs come alive
4. Memory management: every process lives in its own illusion
5. File systems: how names become bytes
6. Users, permissions and privilege
7. Flashcards
8. Quick quiz
9. Hands-on lab
10. Key takeaways

## 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.

A crash in user mode kills one app. A bug in kernel mode can take down or take over the whole machine.

| Kernel design | Idea | Examples |
| --- | --- | --- |
| Monolithic | most OS services (drivers, file systems, networking) run inside the kernel for speed | Linux |
| Hybrid | a monolithic style kernel with some microkernel ideas and parts moved out | Windows NT family, macOS (XNU) |
| Microkernel | only the bare minimum in the kernel; drivers and services run as separate user processes | QNX, seL4, MINIX 3 |

Think of it like this

A bank branch. Customers (programs) cannot walk into the vault (hardware). They fill a slip at the counter (a system call), and the staff (kernel) checks the slip and fetches what is allowed. A customer who forges slips is a malware author; a staff member who can be bribed is a kernel vulnerability.
How attackers abuse this

The prize for an attacker is code running in kernel mode, because from there security software can be blinded. That is why malicious or vulnerable drivers are so dangerous. In **BYOVD** (bring your own vulnerable driver) attacks, ransomware groups load a legitimately signed but buggy driver and use it to switch off endpoint protection.

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.

| Task | Linux system call | Windows (documented API, then native call) |
| --- | --- | --- |
| Open a file | `openat` | `CreateFileW` then `NtCreateFile` |
| Read data | `read` | `ReadFile` then `NtReadFile` |
| Start a program | `fork` / `clone` then `execve` | `CreateProcessW` then `NtCreateUserProcess` |
| Network connection | `socket`, `connect` | Winsock `connect`, handled by the AFD driver |
| Allocate memory | `mmap`, `brk` | `VirtualAlloc` 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
```
How attackers abuse this

Many security products watch Windows API calls by placing hooks in `ntdll.dll` inside each process. Malware answers with **direct or indirect system calls**, invoking the kernel itself so the hooks never see the request.
Defender move

Watch from where malware cannot easily hide: the kernel. Windows offers **ETW** (Event Tracing for Windows) and kernel callbacks used by modern EDR tools; Linux offers **eBPF**, which tools such as Falco and Tetragon use to observe system calls with low overhead.

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
```
How attackers abuse this

- **Suspicious parents**: Word or Excel starting `powershell.exe` or `cmd.exe` is a classic sign of a malicious macro.
- **Masquerading**: malware named `svch0st.exe` or a real name like `svchost.exe` running from the wrong folder.
- **Process injection**: writing code into another, trusted process so the malicious work appears to come from it.

Defender move

Always ask three questions about a process: *who is its parent*, *where is its file on disk*, and *which user is it running as*. On Windows, Sysinternals **Process Explorer** and **Sysmon** event ID 1 (process creation with command line and parent) answer all three.

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.

Simplified layout. Real systems randomise where each region starts.

### Built in defences against memory attacks

| Defence | What it does | What it stops |
| --- | --- | --- |
| DEP / NX bit | marks stack and heap pages as non-executable | running shellcode placed in a data buffer |
| ASLR | randomises where the stack, heap, libraries and program load | hard coded addresses in exploits |
| Stack canaries | a secret value before the return address, checked before returning | simple stack buffer overflows |
| CFG, CET shadow stack | check that indirect calls and returns go to valid places | return oriented programming |

How attackers abuse this

Attackers chain bugs: an **information leak** reveals an address to defeat ASLR, then a **buffer overflow** or **use-after-free** corrupts memory, and **return oriented programming** reuses small pieces of existing code to get around DEP. Browser and phone exploits sold for large sums usually chain several such bugs.
Defender move

Check that ASLR is on in Linux: `cat /proc/sys/kernel/randomize_va_space` should print `2`. On Windows, *Exploit protection* in Windows Security shows DEP, ASLR and CFG settings. Writing software in memory safe languages such as Rust removes whole classes of these bugs.

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.

| File system | Used by | Notes for security |
| --- | --- | --- |
| NTFS | Windows system drives | permissions (ACLs), journaling, encryption via BitLocker or EFS, alternate data streams |
| ext4 | most Linux distributions | Unix permissions, journaling, inodes |
| XFS, Btrfs | RHEL family servers, Fedora, some NAS boxes | Btrfs has snapshots useful for ransomware recovery |
| APFS | macOS, iOS | built in encryption and snapshots |
| FAT32 | old pen drives, EFI System Partition | no permissions at all, 4 GiB maximum file size |
| exFAT | SD cards, large pen drives | no 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.
How attackers abuse this

- **Timestomping**: malware resets its own timestamps to match old system files so it blends in.
- **Alternate data streams**: NTFS lets a file carry hidden extra streams, like `notes.txt:payload.exe`, that do not appear in normal listings.
- Copying files to FAT32 or exFAT pen drives silently strips all permissions.

Defender move

That hidden stream feature is also used for good. When you download a file, Windows adds a `Zone.Identifier` stream, the **Mark of the Web**, which triggers SmartScreen and Office's Protected View. View it with `Get-Item file.docx -Stream *` in PowerShell.

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.

|  | Linux and macOS | Windows |
| --- | --- | --- |
| Most powerful account | `root`, user ID 0 | `NT AUTHORITY\SYSTEM` for the OS, plus members of Administrators |
| Identity number | UID and GID | SID, for example S-1-5-18 is SYSTEM |
| Who may do what | owner, group, others with read, write, execute bits | access control lists (ACLs) on each object |
| Temporary elevation | `sudo` | User Account Control (UAC) prompt |
| Extra mandatory controls | SELinux, AppArmor | integrity 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.
Think of it like this

An office building. Your ID card opens your floor (user). Facilities staff have master keys (root or SYSTEM). A visitor badge (a web server account) should open only the lobby. Privilege escalation is finding a master key left in a drawer.
How attackers abuse this

Common climbs: misconfigured `sudo` rules, programs with the Linux SUID bit, Windows services whose files any user can overwrite, saved passwords in scripts, and unpatched kernel bugs. Lists such as GTFOBins and LOLBAS catalogue built in programs that can be abused this way.
Defender move

**Least privilege**: give each person and service only what it needs. Use a normal account day to day and a separate admin account only when needed. Remove old accounts. Patch quickly, because many escalations rely on public bugs.

## 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.

### Q1 A program wants to read a file. What must it do?

### Q2 Which process tree is the strongest sign of a malicious document?

### Q3 `cat /proc/sys/kernel/randomize_va_space` prints 0. What does that mean?

### Q4 Why can malware avoid user mode API hooks?

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

### Q6 An attacker logged in as a normal user becomes root. This is:

**0 / 6**

## Hands-on lab

lab  40 minutes  your 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.

**Only on machines you own.** Do this lab on your own VM or computer. Scanning, testing or accessing anyone else's system without written permission can be an offence under the Information Technology Act, 2000 (for example Sections 43 and 66).

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?  Done
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).  Done
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).  Done
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.  Done
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.  Done
6. Windows: the same ideasOn 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.  Done

**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)](https://www.cyberwithmadhav.com/assets/learn/learn-operating-system-fundamentals-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.

[Previous 1.1 How a Computer Works](https://www.cyberwithmadhav.com/learn-how-computers-work.html)[Next 1.3 Windows Essentials for Security](https://www.cyberwithmadhav.com/learn-windows-for-security.html)
