University of the Pacific seal
Welcome
System Admin and Security

Course: COMP 175-01 (CRN 80249)
Term: Fall 2026 (Aug 24 – Dec 11, 2026)
Time: 8:25 AM – 9:45 AM on Tuesday, Thursday
Location: CTC 214
Credits: 3.000
Office Hours: Tuesday, Thursday 1:30–2:30 PM, CTC 117 or Zoom

Week Dates Topic Notes Assignment Domain
Week 1 Aug 25, 27 Virtualization & Isolation apt, +7 more → Lab/HW 1 University
Week 2 Sep 1, 3 Command-Line & Permissions git clone, +16 more →
Week 3 Sep 8, 10 File Systems & Storage df, +9 more → Lab/HW 2
Week 4 Sep 15, 17 Access Control & Auditing getfacl, +15 more →
Week 5 Sep 22, 24 Process Mgmt & Remote Access ps, +12 more → Lab/HW 3
Week 6 Sep 29, Oct 1 Service Management systemctl status, +11 more → Project Part 1 (Individual) Automotive
Week 7 Oct 6, 8 Network Configuration ip addr, +14 more → Lab/HW 4
Week 8 Oct 13, 15 Name Resolution & Secure Transport nslookup, +9 more → Midterm: Oct 15 (in class)
Week 9 Oct 20, 22 Logging & Security Monitoring logrotate, +7 more → Lab/HW 5, Project Part 2 (Team)
Week 10 Oct 27, 29 Time Synchronization date, +3 more → Project Part 1 Presentation
Week 11 Nov 3, 5 Automation Scripting read, +1 more → Lab/HW 6 Hospital
Week 12 Nov 10, 12 Firewalls & Network Security iptables, +2 more →
Week 13 Nov 17, 19 Containerization docker, +5 more → Lab/HW 7
Week 14 Nov 24 Deployment & Network Segmentation No class Nov 26 (Thanksgiving)
ipcalc
Project Part 2 Presentation
Week 15 Dec 1, 3 Final Preparation & Course Wrap-up Project Showcase: Fri, Dec 4, 2–3:15 PM, Makerspace
ansible, +1 more →
Week 16 Dec 8 Final: Dec 8, 8:25–09:45 AM in CTC 214

Module 1

Welcome & Introduction: Virtualization

All Commands: Module 1

The Sysadmin Role

1950sComputer Operators runmainframes by hand, one job at a time1969UNIX built at Bell Labs– first real multi-user OS to manage1980s“SystemAdministrator” becomes a formal job title1995Windows NT Server splitsthe role into Windows & Unix tracks2006AWS EC2 launches –the cloud era beginsTodayDevOps / SRE –automation-first, infrastructure as code

What Does a System Admin & Security Do?

  • Manages the users network
  • Workstations, kiosks & laptops
  • Connected via network switch
jdoeworkstationmsmithworkstationpatient047kioskdsmithlaptopNetwork Switch

What Does a System Admin & Security Do?

  • Manages the machines network
  • Servers behind a switch
  • Foundation for services
srv-01srv-02srv-03srv-04Network Switch

What Does a System Admin & Security Do?

  • Manages the databases network
  • Primary, replicas & backup
  • Keeps data available
db-primarydb-replica-1db-replica-2db-backupNetwork Switch

What Does a System Admin & Security Do?

  • Manages the software network
  • Auth, web & API services
  • Keeps applications running
auth-serviceweb-appapi-gatewayemail-svcNetwork Switch

What Does a System Admin & Security Do?

  • Scales from 1 to 500,000 users
  • Personal, campus & hospital
  • Same skills, bigger scale
📱💻1–5 usersPersonalphone, laptop🎓~5,000 usersUniversitystudents, faculty, staff🏥~50,000 usersHospitalpatients, staff, IoT devices🚗~500,000 usersAutomotiveconnected vehicles, drivers

What Does a System Admin & Security Do?

  • Manages three kinds of user
  • Human, device & virtual
  • Each needs its own account
Usera broad, overloaded termHuman Usera person – student,patient, driver(e.g. jdoe)Device Usera computer or deviceon the network(e.g. laptop-042)Virtual Usera service, role, or groupnot a person or device(e.g. www-data, sudo)

What Does a System Admin & Security Do?

  • A person becomes a user
  • Then a computer user
  • Then an OS user account
Usera person – student,patient, driverComputer Useruses one or moredevicesOS Usersysadmin administratesusers at OS level
OS User Accounts
$ cat /etc/passwd | grep -E 'alex|jdoe|icu|veh' alex:x:1000:1000:Personal,,,:/home/alex:/bin/bash jdoe:x:1001:1001:Student,,,:/home/jdoe:/bin/bash icu047:x:1002:1002:Hospital,,,:/home/icu047:/bin/rbash veh3210:x:1003:1003:Vehicle,,,:/home/veh3210:/bin/sh

OS User Accounts: /etc/passwd

$ cat /etc/passwd | grep -E 'alex|jdoe|icu|veh' alex:x:1000:1000:Personal,,,:/home/alex:/bin/bash jdoe:x:1001:1001:Student,,,:/home/jdoe:/bin/bash icu047:x:1002:1002:Hospital,,,:/home/icu047:/bin/rbash veh3210:x:1003:1003:Vehicle,,,:/home/veh3210:/bin/sh

What Does a System Admin & Security Do?

  • Two computers, one OS each
  • Ubuntu & macOS shown here
  • Each OS has its own users
Computer AUbuntuoperating systemjdoeuser accountmsmithuser accountComputer CmacOSoperating systemowneruser accountComputersOS (each)Users (each)

What Does a System Admin & Security Do?

  • Builds & defends systems
  • Tests for weaknesses
  • Works across all three
🔴 Red Team(tests)🔵 Blue Team(defends)🟣 Purple Team(collaborates)Sysadminoften all three

⚠️ Without Purple Team collaboration, Red and Blue often repeat each other's mistakes.

What Does a System Admin & Security Do?

  • Confidentiality: private data
  • Integrity: accurate data
  • Availability: systems stay up
ConfidentialityKeep data privateIntegrityKeep data accurateAvailabilityKeep systems up

What Does a System Admin & Security Do?

  • Installs & configures systems
  • Manages users & permissions
  • Monitors & troubleshoots
Install &configure systemsManage users &permissionsConfigurenetworkingSecure OS &servicesMonitor &troubleshootSystemAdministrator

What Does a System Admin & Security Do?

  • One computer, two systems
  • Windows & Linux Mint installed
  • Each system has its own users
Computer BWindowsoperating systemLinux Mintoperating systemguestuser accountadminuser account

What Does a System Admin & Security Not Do? (AI/LLM)

  • Never runs AI/LLM unsupervised
  • Risks confidentiality
  • Risks integrity & availability
  • OpenClaw (2026): real incident
Autonomous AI/LLM AgentOpenClaw: Real 2026 IncidentConfidentiality, Integrity &Availability at Risk

“Researchers Expose OpenClaw AI Agent Credential Leak During Phishing Simulation” (2026) (Source: Cyber Press)

🚨 OpenClaw is a real autonomous AI agent given shell access and credentials. In a 2026 phishing test, one company's OpenClaw agent handed over a customer database and forwarded AWS keys in plaintext.

What Does a System Admin & Security Not Do? (User Content)

  • Doesn't own user data
  • Doesn't manage user software
  • Admin manages the platform
Admin ManagesOperating SystemNetwork & AccessUser AccountsUser OwnsTheir FilesTheir DataTheir Software

“Court Rules that Stored Communications Act Applies to Former Employee Emails” (2013) (Source: CloudNine)

⚠️ In Lazette v. Kulmatycki (2013), a supervisor read 48,000 of a former employee's personal emails over 18 months after she returned her company phone.

What Does a System Admin & Security Not Do? (App Code)

  • Doesn't write app code
  • That's the developer's job
  • Admin runs & secures it
Developerwrites the codeAdmin runs &secures it

“The $440 Million Software Error at Knight Capital” (2012) (Source: Henrico Dolfing)

🚨 In 2012, Knight Capital lost $460 million in 45 minutes after a technician's manual deployment left old code running on one server.

What Does a System Admin & Security Not Do? (Snooping)

  • Root access isn't a license
  • Doesn't snoop on private data
  • Ethics, not just capability
Root Access = Full CapabilityEthics & Policy = Real Limit

Robbins v. Lower Merion School District (2010) (Source: Wikipedia)

🚨 In the Lower Merion webcam case (2010), a network technician secretly activated laptop cameras, leading to a $610,000 settlement.

What Does a System Admin & Security Do? (RACI)

  • R: Responsible, does the work
  • A: Accountable, owns outcome
  • C: Consulted, gives input
  • I: Informed, kept in loop
Task Admin Dev Sec User
Patching R/A I C I
App Code I R/A C –
Access Review R I A C
Incident Resp. R I A I
AI/LLM Use R C A I
User Data I C C R/A
Network Setup R/A I C I
Backups & Snapshots R/A I C I
System Uptime R/A I C I
VM Configuration R/A I I I

If a Sysadmin Doesn't Write App Code and Doesn't Own User Data, What's Left to Manage?

  • Manages user accounts
  • Manages files & storage
  • Manages installed software

→ The Operating System.

Operating System👤Users📁Files⚙️Software

Questions?

Linux vs. other OSes

How Many Operating Systems Exist?

  • 50+ real names shown here
  • Desktop, mobile & embedded
  • Many trace to Unix or Linux
Windows 11macOS SequoiaUbuntuAndroidiOSDebianFedoraWindows Server 2025RHELLinux MintCentOS StreamArch LinuxopenSUSEFreeBSDChrome OSWindows 10Kali LinuxAlpine LinuxManjaroPop!_OSRocky LinuxAlmaLinuxSolarisAIXHP-UXiPadOSwatchOSRaspberry Pi OSWindows Server 2022SUSE Linux EnterpriseTailsQubes OSFreeDOSReactOSHaikuOpenBSDNetBSDSlackwareGentooVoid LinuxNixOSZorin OSelementary OSMX LinuxDeepinPuppy LinuxTiny Core LinuxtvOSVxWorksQNX

Where Is an Operating System Installed?

  • Not just PCs & phones
  • Cars, ATMs, appliances too
  • e.g., embedded Linux in cars
💻Laptop🖥️Desktop📱Phone⌚Smartwatch📺Smart TV🎮Console🖨️Printer📡Router🚗Car🚦Traffic Light🏧ATM🧺Washing Machine✈️Airplane🛗Elevator🛰️Satellite🤖Factory Robot

What Sits at the Base of Every System?

  • Every layer depends on it
  • Apps can't bypass it
  • e.g., Windows 11 on laptops
UsersApplicationsRuntime & ServicesOperating SystemHardware

What Does an OS Actually Do?

  • Manages memory & processes
  • Manages files & networking
  • Enforces security & access
Process MgmtSchedules & multitasksmany running programsMemory MgmtAllocates RAM, isolateseach process's spaceFile SystemOrganizes storage intofiles and directoriesDevice MgmtDrivers talk to disks,network cards, USB, etc.Security & AccessUsers, permissions,who can do whatNetworkingSends & receives dataover the networkOperatingSystem

Where Does Admin & Security Work Happen?

  • Across all 7 OSI layers
  • From cabling to app configs
  • e.g., Firewall rules (L4)
L7 · ApplicationHTTP, DNS, SSH, SMTPApp configs, WAFs, service hardeningL6 · PresentationTLS/SSL, encodingCertificate mgmt, encryption in transitL5 · SessionSession & connection stateVPN tunnels, session hijacking riskL4 · TransportTCP / UDP, portsFirewalls, port rules, load balancersL3 · NetworkIP addressing, routingRouters, VLANs, IP-based ACLsL2 · Data LinkMAC addresses, switchesARP spoofing, switch port securityL1 · PhysicalCabling, NICs, signalsPhysical security, cable plant

Where Does the OS Fit in the Network Stack?

  • Sits at Layer 7, technically
  • root has elevated privilege
  • e.g., sshd on a campus server
L7 · Application (User / Admin)User-space processBrowser, sshd, curlL6 · Presentation (User)User-space libraryTLS libraries (e.g. OpenSSL)L5 · Session (User)Sockets API boundaryconnect(), accept(), bind()Operating System boundaryL4 · Transport (Kernel)Kernel TCP/UDP stackConnection state, retransmissionL3 · Network (Kernel)Kernel IP stackRouting table, iptables/nftablesL2 · Data Link (Kernel)NIC driver + kernelARP table, frame deliveryL1 · Physical (Kernel)NIC hardwareElectrical/optical signaling

Admin isn't its own layer – admin tools (iptables, systemctl, ip) run at L7 like any app, but with elevated (root) privilege to reach across the boundary and reconfigure L4–L1 kernel state directly, instead of only using the unprivileged sockets API like an ordinary app.

Official UNIX trademark logo

Unix

Official UNIX trademark logo (Source: Wikipedia, Unix)

  • Born 1969, Bell Labs (AT&T)
  • Thompson & Ritchie
  • Direct descendants: Solaris,
  • AIX, HP-UX, macOS (Darwin)
  • "UNIX" is a trademark, not
  • a free label – certified only
Tux, the Linux mascot

Linux

Tux, the Linux mascot (Source: Wikipedia, Linux (illustration by Larry Ewing))

  • Born 1991, Linus Torvalds
  • A new kernel, Unix-like
  • Not built from Unix source
  • Free & open source (GPL)
  • Paired with GNU tools to
  • form a full OS

Don't call Linux "Unix" – wrong, and a trademark violation. Say "Unix-like" instead.

What's the Difference: Kernel vs. Distro?

Linux (the Kernel)
  • Just the kernel Torvalds wrote
  • Manages CPU, memory, devices
  • By itself, not usable
A Distribution
  • Kernel + GNU tools + pkg mgr
  • + sane defaults, installer
  • Ubuntu, Debian, Fedora, etc.
= A DistributionUbuntu, Debian, Fedora...Package Manager+GNU Tools(bash, coreutils, glibc)+Linux Kernel

From OS Concepts to Linux

  • Concepts apply to any OS
  • Now: Linux, specifically
  • e.g., Unix-like kernel
OS Concepts & FamiliesLinux, Specifically

How Did Linux Diverge Into Many Distros?

  • One kernel, many descendants
  • Debian, Red Hat, Arch branch
  • e.g., Kali forked from Debian
Linux distribution family tree, from the Linux kernel through Debian, Red Hat, Slackware, Arch, and Gentoo branches down to Kali Linux, Ubuntu, and other distros

Linux distro family tree (Source: LinkedIn, Hacker339)

How Did Windows Stay One Line?

  • One vendor, one line
  • NT branch replaced 9x line
  • e.g., Windows 11 from NT
Windows version history timeline, from Windows 1.0 in 1985 through the NT, 9x, CE, and Server branches to Windows 11 and Server 2022

Windows version history (Source: Wikimedia Commons)

Linux's Growth Over Time

  • 57.5% of websites, Aug 2025
  • 62.1% of websites, Aug 2026
  • Steady growth, no plateau
Chart: Linux usage share for websites, Aug 2025 to Aug 2026

Linux usage share for websites, 2025–2026 (Source: W3Techs, live server-side data, Aug 2026)

Which OS Runs Where?

  • Servers lean Linux (91.9%)
  • Desktops lean Windows (71.2%)
  • Phones lean Android/Linux
Servers (web-facing, W3Techs, Aug 2026)Linux / Unix-family91.9%Windows8.3%Desktop & Laptop (StatCounter, Jul 2026)Windows71.2%macOS19.8%Linux7.5%Chrome OS1.5%Phones (StatCounter, Jul 2026)Android (Linux kernel)68.4%iOS31.6%

Sources: W3Techs, StatCounter

Linux's Market Position

  • Used by low- and high-traffic
  • sites about equally
  • Windows skews toward
  • lower-traffic sites
Chart: Linux market position by site traffic vs. Windows and Unix

Linux market position by site traffic (Source: W3Techs, live server-side data, Aug 2026)

Where Do You Find & Install Packages (Software)?

  • Official repos (~70K pkgs)
  • Flatpak (~3K), Snap (~6K)
  • e.g., apt install curl (WSL)
  • e.g., apt-get remove curl
Diagram: package managers used across different Linux distributions

Package managers by Linux distribution (Source: Devopedia, Package Manager)

How Do You Install with apt?

  • Debian, Ubuntu format (.deb)
  • e.g., apt install mediawiki
  • Won't work with pacman
apt-get installing MediaWiki and its dependencies on Ubuntu

apt: Debian, Ubuntu (Source: Wikimedia Commons)

How Do You Install with pacman?

  • Arch Linux's package manager
  • e.g., pacman -S mediawiki
  • Won't work with apt
pacman resolving dependencies and upgrading packages on Arch Linux

pacman: Arch Linux (Source: Wikimedia Commons)

Where Does "Package" Come From?

  • 1530s: pack + -age (bundle)
  • 1990s: Linux borrows term
  • Same shipping metaphor
📦1530sEnglish "pack-age"📦1990sLinux package

Main Distributions

Distro Pkg Mgr Release Best For
Debian apt (.deb) Slow, stable Servers
Ubuntu apt (.deb) Fixed + LTS Beginners, cloud
Fedora dnf (.rpm) ~6 months Newest features
Arch pacman Rolling Full control, DIY
Debian logo
Ubuntu logo
Fedora logo
Arch Linux logo

Debian, Ubuntu, Fedora & Arch logos (Source: official project assets (debian.org, Wikipedia, archlinux.org))

Where Does "Distro" Come From?

  • Latin: distribuere, divide
  • 1990s: shortened by users
  • Hundreds of variants exist
📜Latindistribuere🐧1990sLinux distro

How Do You Interact with the OS?

  • Graphical interface (GUI)
  • No display: network or API

→ Command-line interface (CLI)

💻Laptop🖥️Desktop📱Phone⌚Smartwatch📺Smart TV🎮Console🖨️Printer📡Router🚗Car🚦Traffic Light🏧ATM🧺Washing Machine✈️Airplane🛗Elevator🛰️Satellite🤖Factory Robot

Highlighted: no display · Dashed: not stationary

Questions?

Shells: cmd, PowerShell & Bash

How Far Can One Shell Reach?

⌨️Shell☁️Internet💻Laptop🖥️Desktop📱Phone⌚Smartwatch📺Smart TV🎮Console🖨️Printer📡Router🚗Car🚦Traffic Light🏧ATM🧺Washing Machine✈️Airplane🛗Elevator🛰️Satellite🤖Factory Robot

Shells: cmd, PowerShell & Bash

  • A shell runs what you type
  • Windows: cmd.exe, PowerShell
  • Linux/macOS/WSL: Bash, zsh
  • You'll use all three here
Shell OS First Released Style
cmd.exe Windows 1981 Simple commands
PowerShell Windows 2006 Object-based, scriptable
Bash Linux/macOS/WSL 1989 POSIX, scriptable

Shells: Real Examples

Windows Command Prompt (cmd.exe) on Windows 11

cmd.exe (Source: Wikimedia Commons)

PowerShell 7.5 session on Windows

PowerShell (Source: Wikimedia Commons)

Bash running under WSL on Windows 10

Bash, via WSL (Source: Wikimedia Commons)

Commands don't transfer between shells. A Bash command will not run in cmd.exe, and vice versa.

Word Origin: "Shell"

1965, Multics (MIT)
  • Coins the term “shell”
  • A program around the OS
1971, Unix Shell
  • Ken Thompson brings it
  • to Unix First Edition

Word Origin: "GNU"

1983, Founding
  • Richard Stallman announces
  • the GNU Project, MIT
Recursive Acronym
  • "GNU's Not Unix" – a
  • programmer's inside joke

Bash

  • Reads the commands you type
  • Interprets & runs them
  • Passes work to the kernel
  • Runs your shell scripts
User (types commands)Bash (Shell)Linux KernelHardware

Bash sits between you and the kernel – every command passes through it.

Bash: Real Examples

Bash session in GNOME Terminal: ping, cd, ls, and yum commands

Bash in GNOME Terminal (Source: Wikimedia Commons)

Bash session in Xterm, listing the contents of /etc

Same Bash, a different terminal: Xterm (Source: Wikimedia Commons)

The terminal is just a window – Bash is the same shell either way. Don't confuse "terminal emulator" with "shell."

Word Origin: "Bash"

1979, The Bourne Shell
  • Stephen Bourne writes "sh"
  • at Bell Labs
1989, Bash
  • Brian Fox, GNU Project –
  • "Bourne-Again SHell," a pun

Why PowerShell, Not CMD, for Admins?

2002Monad ManifestoJeffrey Snover's whitepaper2006PowerShell 1.0 shipscmd is text; object pipelines possible2009v2.0 adds remotingmanage many machines at once2016Open-sourced by Microsoftruns on Linux and macOS too2020PowerShell 7 releasedunifies Windows & Core

→ Start your computer and open PowerShell

$ Get-Process # running processes $ Get-Service # Windows services $ Get-ChildItem # list files (ls) $ Get-Content # read a file $ Get-NetIPAddress # show IP config $ Get-EventLog # view event logs $ Get-Help # cmdlet docs $ Get-Member # object properties $ Set-ExecutionPolicy # allow/block scripts $ Get-History # past commands

PowerShell cmdlet reference (Source: Microsoft Learn)

Why PowerShell, Not CMD, for Admins?

$ Get-Process # running processes $ Get-Service # Windows services $ Get-ChildItem # list files (ls) $ Get-Content # read a file $ Get-NetIPAddress # show IP config $ Get-EventLog # view event logs $ Get-Help # cmdlet docs $ Get-Member # object properties $ Set-ExecutionPolicy # allow/block scripts $ Get-History # past commands

Questions?

Hands-on: install Linux

What Is Virtualization?

Shell / CLI / TerminalUbuntu ServerWindows ServerDebianAnother OSHypervisor (e.g., VirtualBox, WSL2)Native OS (e.g., Windows, macOS, Linux)Physical Hardware (CPU, RAM, Disk, NIC)
PowerShellKali OSWSL2 (Acts as the Hypervisor)Windows 11 (Native OS)Physical Hardware (CTC 214 Lab Machine)

⚠️ Don't assume the guest OS "knows" it's virtualized. It thinks the hardware is real.

Kali Install: Main Steps

1Verify WSL22Install Kali3Update Kali4Install Package Tools5Verify Setup

Why Kali Linux?

  • Debian-based: same apt
  • Ships 600+ security tools
  • Industry-standard, widely used
  • Officially supports WSL2
  • No admin rights needed here
Kali Linux logo

Kali Linux logo (Source: Wikimedia Commons)

Open PowerShell

  • Launch PowerShell normally
  • Do NOT run as Administrator
  • WSL2 is already enabled
$ wsl --status # --status: default distro, WSL version $ wsl --version # --version: WSL, kernel, and build info $ wsl -l -v # -l -v: every installed distro, running or not

Open PowerShell

$ wsl --status # --status: default distro, WSL version $ wsl --version # --version: WSL, kernel, and build info $ wsl -l -v # -l -v: every installed distro, running or not

Check for Kali

  • List installed distributions
  • Fresh account: none listed
  • Confirms WSL2, not WSL1
$ wsl --list --verbose

Check for Kali

$ wsl --list --verbose

Install Kali

  • wsl --install -d kali-linux
  • Blocked? Add --web-download
  • Create Kali username/password
  • Not your University password
  • Set Kali as your default
$ wsl --list --online $ wsl --set-default-version 2 $ wsl --install -d kali-linux $ wsl --list --verbose $ wsl --set-default kali-linux

⚠️ Kali login, sudo, and VNC passwords are all separate from your University password. Never reuse it here.

Install Kali

$ wsl --list --online $ wsl --set-default-version 2 $ wsl --install -d kali-linux $ wsl --list --verbose $ wsl --set-default kali-linux

Start Kali

  • Appears in the Start menu
  • Or start it from PowerShell
  • Opens a Linux shell prompt
$ wsl -d kali-linux

Start Kali

$ wsl -d kali-linux

Update Kali First

  • Run these inside Kali
  • full-upgrade, not upgrade
  • Kali is a rolling distro
$ sudo apt update $ sudo apt full-upgrade -y

Update Kali First

$ sudo apt update $ sudo apt full-upgrade -y

Word Origin: "sudo"

1980Bob Coggeshall & CliffSpencer write sudo, SUNY Buffalo1985Updated version postedto Usenet's net.sources1991The Root Group adds the“sudoers” policy file1994Todd Miller's first publicrelease; becomes maintainer2005Sudoers parser rewrittenfor modern featuresTodayStandard on nearly everyLinux & Unix distro

What Does sudo Do?

You (Regular User)sudo: Checks Password & sudoersCommand Runs as Root

⚠️ Privileges return to normal the moment the command finishes. sudo doesn't make you root permanently.

Install Win-KeX & Tools

  • Installs the GUI + toolset
  • kali-linux-default = full set
  • Ready-to-use security tools
  • Large download, start early
$ sudo apt install -y git # version control, ~30 MB $ sudo apt install -y curl # data transfer, ~5 MB $ sudo apt install -y nmap # port scanner, ~15 MB $ sudo apt install -y nikto # web scanner, ~3 MB $ sudo apt install -y hydra # login cracker, ~5 MB $ sudo apt install -y sqlmap # SQL injector, ~15 MB $ sudo apt install -y john # password cracker $ sudo apt install -y gobuster # directory scanner $ sudo apt install -y kali-win-kex # GUI desktop $ sudo apt install -y kali-linux-default # toolset

Full package list (Source: kali.org/tools)

⚠️ This step can take a long time and a lot of disk space. Start it during a lecture day, well before you need the GUI.

Install Win-KeX & Tools

$ sudo apt install -y git # version control, ~30 MB $ sudo apt install -y curl # data transfer, ~5 MB $ sudo apt install -y nmap # port scanner, ~15 MB $ sudo apt install -y nikto # web scanner, ~3 MB $ sudo apt install -y hydra # login cracker, ~5 MB $ sudo apt install -y sqlmap # SQL injector, ~15 MB $ sudo apt install -y john # password cracker $ sudo apt install -y gobuster # directory scanner $ sudo apt install -y kali-win-kex # GUI desktop $ sudo apt install -y kali-linux-default # toolset

Files & Windows Access

  • Local to this one computer
  • Home: /home/your-username
  • Windows C: at /mnt/c
  • sudo is not Windows admin
$ ls /home/$USER $ ls /mnt/c/Users

Files & Windows Access

$ ls /home/$USER $ ls /mnt/c/Users

Resetting Kali (Not Now)

  • Deletes everything, careful
  • Not routine troubleshooting
  • Reinstall fresh afterward
$ wsl --unregister kali-linux $ wsl --install -d kali-linux

🚨 This permanently deletes your entire Kali install, including your Linux home directory and any coursework stored only there.

Resetting Kali (Not Now)

$ wsl --unregister kali-linux $ wsl --install -d kali-linux

Choosing a Username

  • Lowercase, digits, hyphens
  • Starts with a letter
  • 32 characters or fewer
  • e.g., jsmith, jane.smith
  • Role-based: dbadmin, websvc
$ whoami # your own username $ id # UID and groups $ passwd # change your password $ sudo usermod -l new old # rename a username

Break this rule and Kali will flatly reject the username. It's not just a suggestion.

Choosing a Username

$ whoami # your own username $ id # UID and groups $ passwd # change your password $ sudo usermod -l new old # rename a username

Choosing a Password

  • Length beats complexity
  • 15+ characters, a passphrase
  • Unique per system or account
  • Use a password manager
  • No forced periodic changes
$ passwd # change your own password $ sudo passwd jsmith # change another user's $ passwd -S # check password status $ chage -l jsmith # view expiry info $ sudo chage -M 30 jsmith # expires in 30 days $ sudo chage -E 2026-11-21 jsmith # expires in 90 days

Password & account-aging commands (Source: NIST SP 800-63B)

Forced periodic password changes make passwords weaker, not stronger – don't do it.

Choosing a Password

$ passwd # change your own password $ sudo passwd jsmith # change another user's $ passwd -S # check password status $ chage -l jsmith # view expiry info $ sudo chage -M 30 jsmith # expires in 30 days $ sudo chage -E 2026-11-21 jsmith # expires in 90 days

Verify (CLI)

  • Confirm OS & kernel
  • Confirm Windows files visible
  • Update the system
$ uname -a $ ls /mnt/c/Users $ sudo apt update && sudo apt full-upgrade -y

Verify (CLI)

$ uname -a $ ls /mnt/c/Users $ sudo apt update && sudo apt full-upgrade -y

What Is Nmap?

TCP/SYN probesresultsYour Machinerunning nmapTarget Host: Operating SystemWell-Known Ports0–1023Registered Ports1024–49151Dynamic / Private49152–65535Scan Results22/tcpsshopen80/tcphttpopen443/tcphttpsclosed

Where Do You Find Nmap Docs?

  • man nmap: full reference
  • nmap -h: quick help
  • Official: Nmap Reference Guide
$ man nmap # full manual page $ nmap -h # quick help summary $ nmap --version # check installed version

Nmap Reference Guide (Source: nmap.org)

Where Do You Find Nmap Docs?

$ man nmap # full manual page $ nmap -h # quick help summary $ nmap --version # check installed version

What Are Some Sample Nmap Calls?

  • -sn: host discovery only
  • -p 22,80: specific ports
  • -A: OS & version detect
$ nmap scanme.nmap.org # default scan $ nmap -sn scanme.nmap.org # host discovery only $ nmap -p 22,80 scanme.nmap.org # specific ports $ nmap -A scanme.nmap.org # OS + version detect

Sample calls against Nmap's own test target (Source: scanme.nmap.org)

What Are Some Sample Nmap Calls?

$ nmap scanme.nmap.org # default scan $ nmap -sn scanme.nmap.org # host discovery only $ nmap -p 22,80 scanme.nmap.org # specific ports $ nmap -A scanme.nmap.org # OS + version detect

What Does the Output Mean?

  • Real scan: scanme.nmap.org
  • 4 open ports, OS guessed
  • 31337: a classic 'leet' port
Nmap scan report for scanme.nmap.org (45.33.32.156) Host is up (0.024s latency) # host responded Not shown: 996 filtered ports # most ports hidden PORT STATE SERVICE 22/tcp open ssh # remote login 80/tcp open http # web server 9929/tcp open nping-echo # Nmap's own test service 31337/tcp open Elite # classic "leet" backdoor port Running: Linux 4.X|5.X # OS guess Network Distance: 15 hops # hops to target

Live scan output, run by the instructor against scanme.nmap.org (Source: sudo nmap -O scanme.nmap.org, Aug 2026)

What Does the Output Mean?

Nmap scan report for scanme.nmap.org (45.33.32.156) Host is up (0.024s latency) # host responded Not shown: 996 filtered ports # most ports hidden PORT STATE SERVICE 22/tcp open ssh # remote login 80/tcp open http # web server 9929/tcp open nping-echo # Nmap's own test service 31337/tcp open Elite # classic "leet" backdoor port Running: Linux 4.X|5.X # OS guess Network Distance: 15 hops # hops to target

Why Does an Open Port Matter?

  • Each port = attack surface
  • Old software often unpatched
  • One flaw can mean full access
Reconnmap finds port 22 openFingerprintidentify OpenSSH versionCheck known CVEse.g. CVE-2024-6387ExploitregreSSHion race conditionRoot accessunauthenticated RCE

CVE-2024-6387 "regreSSHion," OpenSSH unauthenticated RCE (Source: Qualys, Jul 2024)

Where Can You Legally Practice?

  • scanme.nmap.org: official
  • TryHackMe, HackTheBox: labs
  • Metasploitable2: local VM
$ nmap scanme.nmap.org # Nmap's own test target $ nmap 10.10.x.x # TryHackMe VPN target $ nmap 10.10.x.x # HackTheBox VPN target $ nmap 192.168.56.101 # local Metasploitable2 VM

Public scan targets (Source: scanme.nmap.org)

Where Can You Legally Practice?

$ nmap scanme.nmap.org # Nmap's own test target $ nmap 10.10.x.x # TryHackMe VPN target $ nmap 10.10.x.x # HackTheBox VPN target $ nmap 192.168.56.101 # local Metasploitable2 VM

Only Scan What You're Authorized to Scan

  • scanme.nmap.org, THM, HTB
  • Metasploitable2: your own VM
  • Nothing else, ever

“The best way to avoid controversy when using Nmap is to always secure written authorization from the target network representatives before initiating any scanning.”

Nmap, Legal Issues (Source: nmap.org)

🚨 These public sandboxes are the only systems you may scan. Never point nmap at any other server, on or off campus, without written authorization.

How Do You Scan Just One Port?

  • Faster than a full scan
$ nmap -p 80 scanme.nmap.org # scan only port 80

How Do You Detect the OS?

  • Needs root / sudo privileges
$ sudo nmap -O scanme.nmap.org # guess the target OS

OS Detection: Real Output

  • Same 4 ports, still open
  • OS guess: Linux 4.15–5.19
  • 16 hops to the target
$ sudo nmap -O scanme.nmap.org PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 9929/tcp open nping-echo 31337/tcp open Elite Device type: general purpose # broad category Running: Linux 4.X|5.X # OS family guess OS details: Linux 4.15 - 5.19 # narrower range Network Distance: 16 hops

Live scan output, run by the instructor against scanme.nmap.org (Source: sudo nmap -O scanme.nmap.org, Aug 2026)

🔴 Red Team: the OS/version guess narrows which known exploits are worth trying against this target.

🔵 Blue Team: the same fingerprint tells defenders what to patch, and whether to suppress it from scanners.

OS Detection: Real Output

$ sudo nmap -O scanme.nmap.org PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 9929/tcp open nping-echo 31337/tcp open Elite Device type: general purpose # broad category Running: Linux 4.X|5.X # OS family guess OS details: Linux 4.15 - 5.19 # narrower range Network Distance: 16 hops

Heads Up: OS Guesses Aren't Certain

⚠️ Nmap warns that OS-scan results may be unreliable when it can't find at least one open and one closed port on the target. Treat the guess as a best estimate, not a certainty.

How Do You Scan All 65,535 Ports?

  • Slower, but thorough
$ nmap -p- scanme.nmap.org # scan every TCP port

How Do You Look Up Domain Info?

  • Public registration record
  • Needs the base domain
$ whois nmap.org # domain registration info

🔴 Red Team: registrant, registrar & name-server info feeds phishing pretexts and social engineering.

🔵 Blue Team: confirms your own domain hasn't expired or been hijacked; profiles lookalike phishing domains.

Heads Up: WHOIS Needs the Base Domain

⚠️ WHOIS looks up the registered domain, not a subdomain. `whois scanme.nmap.org` fails with "Malformed request" on some registries; use the base domain instead.

How Do You Look Up DNS Records?

  • Resolves hostname to IP
$ dig scanme.nmap.org # DNS lookup

🔴 Red Team: maps mail servers, subdomains & DNS infrastructure to find attack surface.

🔵 Blue Team: verifies DNS resolves correctly and that SPF/DKIM/DMARC anti-phishing records are published.

Questions?

University Domain: Plan VM

Scenario: University Domain

You're the new sysadmin at Pacific University. Every setup choice below follows this one VM for the rest of the course.

University Domain, By the Numbers

6,852Students890Faculty1,228Staff3Campuses9Schools & Colleges30,000 sq ftMedical Center, Sacramento

University of the Pacific, Fall 2025/2024 Fast Facts & Dugoni School newsroom (Source: pacific.edu)

VM Name

  • Pattern: role-env-number
  • Lowercase, hyphens only
  • Must be unique on network
University Domain
  • Registrar's web server
  • reg-web01
  • Instantly IDs owner & role

A vague name like "server1" becomes unmanageable once you have 50 VMs.

Why a Web Server First?

  • Top ports: 80/443 (web)
  • Most exposed service, by far
  • That's why reg-web01 is first
Most-Exposed Internet Ports443 (https)11.8%80 (http)11.5%80806%22 (ssh)4.1%

Share of devices exposing each port, Shodan scan data (Source: SecureBin, Open Port Security Risks)

Username

  • Lowercase, digits, hyphens
  • Must start with a letter
University Domain
  • Registrar staff need access
  • reg-jsmith
  • Ties account to department

A generic "admin" account can't be traced back to a person when something goes wrong.

Password

  • Length beats complexity
  • 15+ characters if no MFA
  • VM holds student records
  • FERPA protects that data
Table: time for a hacker to brute-force passwords by length and character set, 2026

Password crack-time by length & character set (Source: Hive Systems, 2026 Password Table)

A breach here isn't just an IT headache – it's a federal FERPA violation.

🎓 Which OS Do You Recommend?

→ Pick one and install it

$ wsl --install -d Ubuntu-24.04 # LTS build $ wsl --install -d Debian # very stable, slow-moving $ wsl --install -d kali-linux # 600+ security tools $ wsl --install -d AlmaLinux-9 # RHEL-compatible $ wsl --install -d openSUSE-Leap-15.6 # enterprise

🎓 Which OS Do You Recommend?

$ wsl --install -d Ubuntu-24.04 # LTS build $ wsl --install -d Debian # very stable, slow-moving $ wsl --install -d kali-linux # 600+ security tools $ wsl --install -d AlmaLinux-9 # RHEL-compatible $ wsl --install -d openSUSE-Leap-15.6 # enterprise

Which VM (OS)

  • Ubuntu Server LTS
  • Matches this course's build
  • Records systems run for years
  • Matches campus IT standards
Ubuntu LTS Support LifetimeA new LTS ships every 2 yearsStandard Support5 yearsExtended (Ubuntu Pro / ESM)up to 15 years totalYr 0Yr 5Yr 15

Ubuntu LTS support timeline (Source: Ubuntu, Release Cycle)

A fast-release distro here means re-certifying the whole system every 6 months – university IT can't move that fast.

How Do We Scale OS Across a University?

  • One OS per server, today
  • Servers sit mostly idle
  • Buying more is expensive

→ Does each OS need its own hardware?

Ubuntu ServerPhysicalServer 1Windows ServerPhysicalServer 2DebianPhysicalServer 3Another OSPhysicalServer 44 OSes = 4 physical machines?

Practice:
Log In & Go Home (Ubuntu)

  • Starts in your home dir
  • Only you can write here
  • ~ is shorthand for it
$ wsl -d Ubuntu-24.04 $ pwd /home/yourname $ whoami yourname

⚠️ Every user gets exactly one home directory (`/home/<username>`). It's the only place you're guaranteed write access without `sudo`, which is why every exercise in this course starts there instead of somewhere like `/etc` or `/var`.

Practice:
Log In & Go Home (Ubuntu)

$ wsl -d Ubuntu-24.04 $ pwd /home/yourname $ whoami yourname

Practice:
Create the Catalog Page (Ubuntu)

  • Create index.html locally
  • Book list = the response body
$ mkdir library && cd library $ cat > index.html << 'EOF' <h1>Pacific Library Catalog</h1> <ul><li>Introduction to System Admin and Security</li></ul> EOF

Practice:
Create the Catalog Page (Ubuntu)

$ mkdir library && cd library $ cat > index.html << 'EOF' <h1>Pacific Library Catalog</h1> <ul><li>Introduction to System Admin and Security</li></ul> EOF

Practice:
Serve lib-web01 (Ubuntu)

  • Serves the current directory
  • Listens on port 8080
$ python3 -m http.server 8080 Serving HTTP on 0.0.0.0 port 8080 ...

Practice:
Serve lib-web01 (Ubuntu)

$ python3 -m http.server 8080 Serving HTTP on 0.0.0.0 port 8080 ...

Practice:
Find lib-web01's IP (Ubuntu)

  • Every distro gets its own IP
  • Yours will differ, that's OK
$ hostname -I 172.20.145.10

Practice:
Find lib-web01's IP (Ubuntu)

$ hostname -I 172.20.145.10

Practice:
Two Machines, One Laptop

  • lib-web01 hosts the catalog
  • client tests the connection
lib-web01 (Ubuntu)172.20.145.10serves :8080client (Kali)172.20.145.11nmap + curlsame laptopUbuntu + Kali, one physical machine

Practice:
Confirm From the Client (Kali)

  • nmap confirms the port is open
  • curl fetches the real page
$ nmap -p 8080 172.20.145.10 $ curl http://172.20.145.10:8080

🔵 Blue Team: confirming a port from another machine is exactly how you'd verify your own service is actually reachable, not just "should be" reachable on paper.

Practice:
Confirm From the Client (Kali)

$ nmap -p 8080 172.20.145.10 $ curl http://172.20.145.10:8080

How Does a Firewall Block a Port?

  • Firewall = a rule checkpoint
  • Allow: packet passes through
  • Deny: packet just vanishes
rule: allowrule: denyclient (Kali) requests :8080Firewall (ufw) checks rulesService :8080replies normallyPacket droppedno reply at all

🔴 Red Team: at a university, attackers scan every public IP for forgotten open ports, like an old admin panel left listening on 8080.

🔵 Blue Team: campus IT firewalls every server down to only the ports a service actually needs. 8080 is a well-known dev/alt-HTTP port and should never be public.

Port 8080 is registered with IANA as "http-alt" (HTTP Alternate) (Source: IANA, Service Name and Transport Protocol Port Number Registry)

Practice:
Block the Port (Ubuntu)

  • ufw = simple firewall frontend
  • Deny inbound on port 8080
  • Allow just one trusted subnet
$ sudo apt install -y ufw $ sudo ufw enable $ sudo ufw deny 8080/tcp $ sudo ufw allow from 172.20.145.0/24 to any port 8080

Practice:
Block the Port (Ubuntu)

$ sudo apt install -y ufw $ sudo ufw enable $ sudo ufw deny 8080/tcp $ sudo ufw allow from 172.20.145.0/24 to any port 8080

Practice:
Try Again From the Client (Kali)

  • Port now blocked, not open
  • filtered = silently dropped
$ nmap -p 8080 172.20.145.10 $ curl http://172.20.145.10:8080

⚠️ nmap now reports port 8080 as filtered, not `closed`. `closed` means a host replied "nothing's listening here," while `filtered` means nothing replied at all, because ufw silently dropped the packet. `curl` just hangs until it times out.

Practice:
Try Again From the Client (Kali)

$ nmap -p 8080 172.20.145.10 $ curl http://172.20.145.10:8080

What Is IANA?

  • IANA = the global registry
  • Assigns port numbers & names
  • Free to search, no login

Not sure what a port is for? Look it up:

https://www.iana.org/assignments/service-names-port-numbers?search=8080

Try it: look up 3 ports (not 80, 443, or 8080) that you think are useful to know.

Practice:
Real Domain vs. Your Server (Kali)

  • nmap.org: real WHOIS + DNS
  • lib-web01: private, unlisted
$ whois nmap.org $ dig scanme.nmap.org $ whois 172.20.145.10 $ dig -x 172.20.145.10

Practice:
Real Domain vs. Your Server (Kali)

$ whois nmap.org $ dig scanme.nmap.org $ whois 172.20.145.10 $ dig -x 172.20.145.10

From Practice to Concept

You just ran two operating systems, Ubuntu and Kali, on one physical laptop, at the same time.

How can we have multiple OS on one physical machine?

Questions?

What is virtualization

Where Does "Virtual" Come From?

  • Latin: virtus, power
  • In effect, not yet real
  • Now: not physical, but real
📜Latinvirtus, power💻Todayvirtual machine

Virtualization

1967IBM CP-40 – the firsthypervisor, on a mainframe1972IBM VM/370 bringsvirtualization to production mainframes1998VMware founded –virtualization comes to x86 PCs2005Intel VT-x / AMD-V addhardware support to x86 CPUs2007KVM merges into the LinuxkernelTodayCloud computing runs almostentirely on virtualized hardware

Where Does "Hypervisor" Come From?

  • Hyper-: Greek, over/above
  • -visor: short for supervisor
  • Together: oversees the OS
🔼Hyper-over, above👁️-visorsupervisor

Why Use Virtualization?

  • Isolation, cost savings
  • Snapshots & portability
  • Better hardware utilization
IsolationOne VM crash or compromisedoesn't touch the othersCost SavingsFewer physical servers neededto run the same workloadsSnapshotsInstant rollback to a known-goodstate before a risky changePortabilityCopy or move a VM imagebetween hosts in minutesSafe ExperimentationBreak things freely, the hostmachine is never at riskBetter UtilizationSeveral OSes share one machine'sspare CPU / RAM / diskAdvantages ofVirtualization

Type 1 vs. Type 2 Hypervisors

  • Type 1: bare-metal (ESXi)
  • Type 2: hosted on your OS
  • We use Type 2 this course
Type 1: Bare MetalGuest OSHypervisor(ESXi, Proxmox)HardwareType 2: HostedGuest OSHypervisor(VMware, VirtualBox)Host OSHardware

Virtual Machine

  • A full computer, virtualized
  • Its own OS, CPU, RAM, disk
  • Many VMs, one physical box
VM 1VM 2VM 3Hypervisorallocates CPU / RAM / disk

Questions?

VirtualBox & WSL

Where Do "Host" & "Guest" Come From?

  • Latin: hospes, one word
  • Meant host, guest, stranger
  • 1972: IBM VM/370 usage
📜Latinhospes🖥️1972IBM VM/370

Top 5 Hypervisors

  1. VirtualBox (this course)
  2. VMware ESXi (vSphere)
  3. Microsoft Hyper-V
  4. Proxmox VE (KVM-based)
  5. XCP-ng (Xen-based)
Hypervisor Type License First Released
VirtualBox Type 2 Free/open source 2007
VMware ESXi Type 1 Paid (since 2023) 2001 (as ESX)
Hyper-V Type 1 Included w/ Windows 2008
Proxmox VE Type 1 Free/open source (GitHub) 2008
XCP-ng Type 1 Free/open source (GitHub) 2018

Popular hypervisor comparison, ranked (Source: virtualizationhowto.com)

Don't mistake this ranking for market share – VirtualBox is #1 here only because it's what we use.

Our Toolset: VMware & VirtualBox

  • Both are free to use
  • Same concepts, either tool
  • Pacific gives VMware access
VMware logo
VirtualBox logo

VMware & VirtualBox logos (Source: Wikipedia, VMware; Wikipedia, VirtualBox)

Feature VMware VirtualBox
Cost Free (Player) Free/open source
Snapshots Yes Yes
Networking modes NAT/Bridged/Host-only NAT/Bridged/Host-only/Internal

VirtualBox Architecture

  • One VirtualBox, many VMs
  • Each VM: its own Guest OS
  • Guest Additions improve it
VirtualBox component architecture: host, host OS, VMs, guest OS, VirtualBox layer

VirtualBox component architecture (Source: virtualbox.org/manual)

The VirtualBox Manager

  • One list of all your VMs
  • Start, stop, configure here
  • Same app on any host OS
VirtualBox Manager window, showing a list of virtual machines

The VirtualBox Manager window (Source: virtualbox.org/manual)

Choosing an OS: Linux Distributions

  • We use Ubuntu Server (LTS)
  • Debian (apt) vs Red Hat (dnf)
  • We standardize on one distro
Linux KernelDebian family (apt)Red Hat family (dnf)Ubuntu Server(we use this)DebianRockyFedora

Virtualization in Practice: WSL2

  • Host: Windows 11
  • Hypervisor: Hyper-V, built-in
  • Guest: Kali Linux kernel
  • No VM manager UI needed
Pattern Example What You See
Type 1 (bare-metal) VMware ESXi Runs directly on hardware
Type 2 (hosted) VirtualBox An app on your OS
WSL2 (Microsoft) Kali on Windows Auto-managed, no VM UI

⚠️ WSL2 is still real virtualization. A real Linux kernel runs inside a Microsoft-managed VM, using Hyper-V under the hood, even though you never see a VM manager window.

WSL2 vs. Virtualization

  • A real kernel, virtualized
  • No visible VM manager
  • Runs via Hyper-V, hidden
VirtualizationGuest OS (own kernel)Hypervisor(VirtualBox)Host OSWindows, Linux, or macOSHardwareWSL2Real Linux KernelHyper-V(built-in, hidden)Host OSWindows onlyHardware

⚠️ WSL2 skips a full guest OS. It runs a real Linux kernel directly, with no separate virtual BIOS or drivers to install.

Questions?

Anatomy of a VM

  • vCPU: slices of your real CPU
  • vRAM: reserved host memory
  • vDisk: a file as a hard drive
  • vNIC: connects VM to network
Virtual MachinevCPUvRAMvDisk(.vmdk/.vdi)vNICGuest OS

Source: microsoft/WSL, Issue #12567

Where Does "Virtual Machine" Come From?

  • 1960s: full simulated PC
  • 1972: VM/370 ships
  • "Virtual machine" sticks
🏢1960sIBM Research💻1972IBM VM/370

What's Inside a VM Image?

  • Data, software, config bundled
  • Packed into one image file
  • Export as .vdi/.vmdk/.ova
DataYour files & user dataSoftwareOS + installed appsConfigurationCPU / RAM / network settingsVM Image File.vdi / .vmdk / .ovaExportVBoxManage export /File > Export Appliance

CLI: Create a VM

  • VBoxManage: VirtualBox's CLI
  • Same steps as the GUI wizard
  • Scriptable & repeatable
$ VBoxManage createvm --name "lab1-ubuntu" \ --ostype Ubuntu_64 --register $ VBoxManage modifyvm "lab1-ubuntu" \ --cpus 2 --memory 2048 --nic1 nat $ VBoxManage createmedium disk \ --filename lab1-ubuntu.vdi --size 20000 $ VBoxManage storagectl "lab1-ubuntu" \ --name SATA --add sata

CLI: Create a VM

$ VBoxManage createvm --name "lab1-ubuntu" \ --ostype Ubuntu_64 --register $ VBoxManage modifyvm "lab1-ubuntu" \ --cpus 2 --memory 2048 --nic1 nat $ VBoxManage createmedium disk \ --filename lab1-ubuntu.vdi --size 20000 $ VBoxManage storagectl "lab1-ubuntu" \ --name SATA --add sata

The Linux Kernel & Userland

  • Kernel talks to hardware
  • Bash talks to the kernel
  • Utilities & apps sit on top
Applications & ServicesShell / Userland UtilitiesLinux KernelHardware

Where Does "Kernel" Come From?

  • Old English: cyrnel, corn
  • Soft part inside a seed
  • 1970s: Unix's protected core
🌾Old Englishcyrnel, corn🐧1970sUnix's core

VM Lifecycle

  • Create, configure, install OS
  • Snapshot before risky changes
  • Just a file, destroy freely
CreatedConfiguredRunningSnapshottedStoppedDestroyed

VM Networking Modes

  • NAT: shares host's IP
  • Bridged: own address on LAN
  • Host-only: talks to host only
  • Mode choice matters per lab
NATVMHost NATInternetBridgedVMPhysical LANHost-OnlyVMHost-only adapter

CLI: Configure Networking

  • Check or change NIC mode
  • No GUI required
  • Sets up automation later
$ VBoxManage showvminfo "lab1-ubuntu" \ | grep NIC $ VBoxManage modifyvm "lab1-ubuntu" \ --nic1 bridged \ --bridgeadapter1 "Wi-Fi" $ VBoxManage modifyvm "lab1-ubuntu" \ --nic1 hostonly \ --hostonlyadapter1 vboxnet0

CLI: Configure Networking

$ VBoxManage showvminfo "lab1-ubuntu" \ | grep NIC $ VBoxManage modifyvm "lab1-ubuntu" \ --nic1 bridged \ --bridgeadapter1 "Wi-Fi" $ VBoxManage modifyvm "lab1-ubuntu" \ --nic1 hostonly \ --hostonlyadapter1 vboxnet0

Sizing Your VM: CPU, RAM, Disk

  • Don't over-allocate resources
  • Thin-provision to save space
  • Start modest, resize later
Resource Lab minimum
vCPU 2 cores
vRAM 2 GB
vDisk 20 GB (thin)

Where Does "Snapshot" Come From?

  • 1808: hunting, no aim
  • 1860: photography borrows it
  • Now: VM point-in-time copy
🏹1808a quick shot📸1860photography

Snapshots in the Real Tool

  • Right-click a VM → Snapshot
  • Named, timestamped, listed
  • Restore with one click
VirtualBox Snapshots tool, showing snapshot properties for a VM

Snapshots panel in VirtualBox (Source: virtualbox.org/manual)

Install Git

  • apt-get installs from repos
  • -y skips the confirm prompt
  • One-time setup step
$ sudo apt-get update $ sudo apt-get install -y git

Install Git

$ sudo apt-get update $ sudo apt-get install -y git

Clone the Course Repo

  • git clone downloads a repo
  • Creates a new folder for it
  • Run once, from your home dir
$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175.git

Clone the Course Repo

$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175.git

From Building a VM to Securing It

You Can Build a VMWhat Can Go Wrong?

Questions?

Real-world risks

Common Setup Pitfalls

  • VT not enabled in BIOS/UEFI
  • Wrong mode blocks networking
  • Over-committing RAM/CPU
  • Forgetting to snapshot first
VM won'tboot?Check BIOS: virtualizationenabled?Check: correct ISOmounted?No network?Check: correctnetwork mode?Check: adapterenabled?

It's Happening Right Now: Oracle EBS

  • CVE-2025-61882: 9.8 zero-day
  • Exploited by Clop, Oct 2025
  • Patched Oct 5, after exploit
  • Unpatched = still exposed

Source: cybersecuritynews.com, infosecurity-magazine.com (Oct 2025)

CVE-2025-61882 disclosedClop exploits unpatchedinstancesData extortion campaignOracle emergency patch:Oct 5, 2025Unpatched systemsstill exposed

It's Happening Right Now: RMM Supply Chain

  • Unpatched SimpleHelp RMM tool
  • Hit a vendor, its customers
  • CISA warned since Jan 2025
  • One tool, many victims

Source: cisa.gov advisory AA25-163A (2025)

Unpatched SimpleHelpRMM toolAttacker compromisesthe RMM vendorUtility billingsoftware providerDownstream customers hit

Spot the Pattern

  • Both used patchable bugs
  • Both hit infrastructure
  • Spread via trusted tools
  • It's a sysadmin problem first
Vulnerability disclosed,patch availablePatched intime?System stays safeExploited by attackersYesNo

Misconfiguration, By the Numbers

  • 80% of firms breached in 2025
  • Misconfig ~ half of breaches
  • Exposed ~190 days, unnoticed
  • Avg cloud breach: $4.7M

Source: fidelissecurity.com, datastackhub.com (2025)

80% breached in past year
~45-50% caused by misconfig
190 days avg. exposure

Why Local VMs for This Course

  • It's a skill gap, not cloud
  • Local VMs give full control
  • No billing or cloud quotas
  • Skills transfer to any cloud
This Course:Local VMYou control thehypervisor directlyCloud ProviderConfig hidden behinda web console/APIsame skills

Review the Stack

  • Foundation: virtualization
  • Core skills: files & shells
  • Services: DHCP, DNS, logging
  • Applied: deploy & automate

Questions?

Lab 1 & Homework 1

Looking Ahead: Module 2

  • Core command-line tools
  • Search, I/O, permissions
  • Lab 2: command-line drills

Module 2

Command-Line & Permissions

All Commands: Module 2

History of the Command Line

What the CLI Manages

  • Six broad task categories
  • Each has its own commands
  • We'll cover each in turn
Permissionschmod, chown decide whocan read, write or run itFilescp, mv, rm, cat copy,move, delete & view themProcessesps, top, kill show &stop running programsDeviceslsblk, dmesg, mountinspect & attach storageUsersuseradd, passwd add &manage accountsNetworkip, ping, ssh reach &test other machinesCLI

A Short CLI History

1969Unix begins at Bell Labs,a shared multi-user machine1971Unix v1 ships with chmodand the rwx permission bits1973grep is written by KenThompson for fast text search1991Linux (Torvalds) reusesthe exact same rwx modelTodaySame rwx model runs Linux,macOS, Android & most servers

How the OS Decides

  • One machine, many people
  • Files must stay protected
  • Not everyone should see it
Permissions Decidewho can read, write, or run itEvery File Has an Ownerand a set of permissionsShared Unix Machinemany logged-in users at once

Authenticate vs. Authorize

  • A password: authentication
  • A permission: authorization
  • You genuinely need both
🔑Authenticationa password:who you are🔒Authorizationa permission:what you can do

What Happens Without Them?

  • Could expose private data
  • Could corrupt shared scripts
  • One mistake breaks the server
⚠️No Safety Net

Lock Down backup.sh

  • chmod NUM file sets rights
  • Staff-only, execute allowed
  • Nobody else gets in
⌨️Your Turn

Lock Down backup.sh

$ chmod 700 backup.sh

Archive Old Records

  • mv source dest moves it
  • Move overdue-2024.txt
  • Into the archive folder
⌨️Your Turn

Archive Old Records

$ mv overdue-2024.txt archive/

Check for a New Scanner

  • lsusb lists USB devices
  • A scanner was just plugged in
  • No arguments needed
⌨️Your Turn

Check for a New Scanner

$ lsusb

Add a Student Worker

  • useradd -m name: new user
  • New hire: jsmith
  • Needs a home directory
⌨️Your Turn

Add a Student Worker

$ sudo useradd -m jsmith

Reach the Branch Server

  • ping -c N host: test link
  • Branch server: 10.20.30.15
  • Confirm it's reachable
⌨️Your Turn

Reach the Branch Server

$ ping -c 1 10.20.30.15

Questions?

Command Syntax & Navigation

How Push & Pull Work

VM 1VM 2VM 3VM 4VM 5VM 6VM 7VM 8VM 9VM noriginGitHub repoEvery arrow runs both ways: push sends changes up, pull brings them down

Install Git

  • apt-get installs from repos
  • -y skips the confirm prompt
  • One-time setup step
$ sudo apt-get update $ sudo apt-get install -y git

Install Git

$ sudo apt-get update $ sudo apt-get install -y git

Clone the Course Repo

  • git clone downloads a repo
  • Creates a new folder for it
  • Run once, from your home dir
$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175.git $ git clone --depth 1 url # --depth 1: history only, faster clone

Clone the Course Repo

$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175.git $ git clone --depth 1 url # --depth 1: history only, faster clone

Pull the Practice Files

  • Already cloned? Just pull
  • git pull grabs updates
  • Run it before each lab
$ cd ~/2026-COMP-175 $ git pull

Pull the Practice Files

$ cd ~/2026-COMP-175 $ git pull

Why Learn the Command Line?

  • Faster than clicking menus
  • The only way into servers
  • Every sysadmin tool assumes it
🖥️The Command Line

Anatomy of a Command

  • command -flags argument
  • Flags change the behavior
  • Arguments say what to act on
lscommand-laflags (options)/homeargument$ ls -la /home

Good For

  • Fast, repeatable, scriptable
  • Remote servers, no GUI needed
  • Automation & administration

Not Good For

  • Writing & editing real code
  • Visual, GUI-heavy design work
  • A debugger's step-through view

Where Am I?

  • pwd prints your location
  • ls lists what's there
  • -l for details, -a for hidden
$ pwd /home/comp175user $ ls -la # -la: all files, long detail drwxr-xr-x 4 comp175user library 4096 notes $ ls -lh # -lh: sizes in K/M/G, not bytes

Where Am I?

$ pwd /home/comp175user $ ls -la # -la: all files, long detail drwxr-xr-x 4 comp175user library 4096 notes $ ls -lh # -lh: sizes in K/M/G, not bytes

Moving Around: cd

  • cd path, moves you there
  • cd .. goes up one level
  • cd ~ jumps to your home
/homebinetcvartmpusrsrvcomp175user

The Standard Linux Folders

  • Eight core system folders
  • Blue needs root access
  • Gray is user-writable
/: Root of the filesystem/bin: Essential command programs/etc: System-wide config files/home: Personal user directories/var: Logs, caches, changing data/tmp: Temporary, cleared on reboot/usr: Installed programs & libraries/srv: Data served to othersRequires root to modifyUser-writable

Changing Directory

  • cd changes location
  • .. means one level up
  • ~ is always your home
$ cd /home/comp175user # absolute path: always from root $ cd .. # one level up from here $ pwd /home $ cd ~ # jumps straight to your home $ cd - # back to the previous directory

Changing Directory

$ cd /home/comp175user # absolute path: always from root $ cd .. # one level up from here $ pwd /home $ cd ~ # jumps straight to your home $ cd - # back to the previous directory

Making & Removing Files

  • mkdir makes a folder
  • touch makes an empty file
  • rm removes; -r for folders
$ mkdir notes $ touch catalog/checkout.txt $ cp checkout.txt checkout-old.txt $ mv checkout-old.txt catalog/ $ rm catalog/checkout-old.txt

Making & Removing Files

$ mkdir notes $ touch catalog/checkout.txt $ cp checkout.txt checkout-old.txt $ mv checkout-old.txt catalog/ $ rm catalog/checkout-old.txt

Reading a File

  • cat prints the whole file
  • less lets you scroll it
  • q quits the less viewer
$ cat checkout.txt Restock mystery section Reshelve returns $ less checkout.txt

Reading a File

$ cat checkout.txt Restock mystery section Reshelve returns $ less checkout.txt

Organize Today's Notes

  • Make a checkin folder
  • Move today's notes into it
  • Confirm with ls -l
⌨️Your Turn

Organize Today's Notes

$ mkdir checkin $ mv notes.txt checkin/ $ cd checkin $ ls -l

Questions?

Search & Getting Help

Why Search, Not Scroll?

  • Too many files to remember
  • Memorizing paths doesn't scale
  • Searching is faster & reliable
🔍Search, Don't Scroll

Getting Help

  • man opens the full manual
  • Not installed by default
  • --help gives a quick summary
  • q quits the man viewer
$ sudo apt install -y man-db # not installed by default $ man ls # the full manual page $ ls --help # a quick summary, no paging $ man -k copy # -k: search man pages by keyword

Getting Help

$ sudo apt install -y man-db # not installed by default $ man ls # the full manual page $ ls --help # a quick summary, no paging $ man -k copy # -k: search man pages by keyword

Word Origin: "man"

1971The Unix Programmer'sManual ships, 61 commands1971Ken Thompson & DennisRitchie write it by handTodayman still opens that samemanual, updated daily

Finding a File: find

  • find searches by name
  • Starts from a given folder
  • * is a wildcard
$ find /home -name "*.txt" /home/comp175user/catalog/checkout.txt $ find /home -type d # -type d: directories only, no files $ find /home -mtime -1 # -mtime -1: modified in the last day

Finding a File: find

$ find /home -name "*.txt" /home/comp175user/catalog/checkout.txt $ find /home -type d # -type d: directories only, no files $ find /home -mtime -1 # -mtime -1: modified in the last day

Searching Text: grep

  • grep searches inside files
  • -r searches every subfolder
  • -i ignores upper/lowercase
$ grep "restock" checkout.txt Restock mystery section $ grep -ri "error" /var/log # -r: every subfolder, -i: any case $ grep -c "error" app.log # -c: count the matches, not show them

Searching Text: grep

$ grep "restock" checkout.txt Restock mystery section $ grep -ri "error" /var/log # -r: every subfolder, -i: any case $ grep -c "error" app.log # -c: count the matches, not show them

Word Origin: "grep"

1973Ken Thompson pulls thesearch code out of the ed editor1973Named for ed's owncommand: g/re/pTodayStandard on every Linux,macOS & Unix system

Find the Smith Patron

  • Check the manual first
  • Locate the patrons file
  • Search it for a name
⌨️Your Turn

Find the Smith Patron

$ man grep $ find /home -name "patrons*" $ grep -i "smith" patrons.txt

Hidden Files Aren't Hidden

  • ls -a shows dotfiles too
  • find searches hidden folders
  • grep -r reads through both
⌨️Your Turn

⚠️ A dot doesn't restrict access. Only permissions do.

Hidden Files Aren't Hidden

$ ls -a .passwords passwords README.md ... $ find . -iname "passwords.txt" ./.passwords/passwords.txt ./passwords/passwords.txt $ grep -r "Summer2024" . ./.passwords/passwords.txt:jdoe:Summer2024! ./passwords/passwords.txt:jdoe:Summer2024!

Questions?

Understanding Permissions

Who Should Read This?

  • Not all data should be public
  • Some scripts must stay locked
  • Wrong access causes breaches
🔐Not Everyone

Owner, Group & Other

  • Every file has one owner
  • One group can share access
  • Everyone else is "other"
catalog.txtOwnercomp175userGrouplibrary (team)Othereveryone else

Read, Write & Execute

  • rwx means different things
  • on a file vs. a folder
  • x on a folder = can enter it
LetterOn a FileOn a Folder
rRead contentsList contents
wEdit contentsAdd/remove files
xRun as a programEnter with cd

Who Counts as Each Role?

  • Every file has three roles
  • Each gets its own rights
  • Meet who's who
RoleWhoExample
OwnerCreates or owns itcomp175user
GroupShares team accesslibrary
OtherEveryone elsea guest

The Numeric Version

  • r = 4, w = 2, x = 1
  • Add them up per role
  • rwx = 4+2+1 = 7
LetterValue
r4
w2
x1
-0

What Number Is r--?

  • Read only, nothing else
  • w and x are both off
  • Add the letter values
🔢Compute It

What Number Is r--?

4

What Number Is r-x?

  • Read and execute
  • Write is off
  • Add the letter values
🔢Compute It

What Number Is r-x?

5

What Number Is rwx?

  • All three are on
  • Read, write, execute
  • Add the letter values
🔢Compute It

What Number Is rwx?

7

Convert catalog.txt's Mode

  • catalog.txt is rwxr-xr--
  • One digit per role
  • Owner, group, other
🔢Compute It

Convert catalog.txt's Mode

754

Reading ls -l Output

  • First char: file or folder
  • Next 9: owner, group, other
  • Each set is r, w, x or -
-rwxr-xr-- 1 comp175user library 548 catalog.txttypeownergroupother- = filerwxr-xr--

ls -l in Practice

  • -l shows the full listing
  • First column is permissions
  • Then owner, group, size, name
$ ls -l -rwxr-xr-- 1 comp175user library 548 catalog.txt -rw-r--r-- 1 comp175user library 288 overdue.txt

ls -l in Practice

$ ls -l -rwxr-xr-- 1 comp175user library 548 catalog.txt -rw-r--r-- 1 comp175user library 288 overdue.txt

List the Library Files

  • See every file's permissions
  • Include owner and group
  • Type the listing command
⌨️Your Turn

List the Library Files

$ ls -l -rw-r--r-- 1 comp175user comp175user 1760 README.md drwxr-xr-x 2 comp175user comp175user 4096 archive -rw-r--r-- 1 comp175user comp175user 346 backup.sh -rw-r--r-- 1 comp175user comp175user 548 catalog.txt -rw-r--r-- 1 comp175user comp175user 288 overdue.txt -rw-r--r-- 1 comp175user comp175user 375 patrons.txt

Questions?

Read & Change Permissions

Why Not Allow Everything?

  • Least privilege limits damage
  • A quick fix can become a habit
  • Changing access is risky too
🛡️Least Privilege

Symbolic vs. Octal

  • chmod takes either form
  • Symbolic: u, g, o + / -
  • Octal: one digit per set
SymbolOctalMeaning
rwx7read + write + execute
rw-6read + write
r-x5read + execute
r--4read only

chmod: Symbolic Form

  • u, g, o pick who changes
  • + adds, - removes a right
  • x is often the execute bit
$ chmod u+x backup.sh # u+x: owner may now run it $ chmod g-w catalog.txt # g-w: group loses write access $ chmod o-rwx patrons.txt # o-rwx: others get nothing at all $ chmod a+r notes.txt # a+r: everyone gets read access

chmod: Symbolic Form

$ chmod u+x backup.sh # u+x: owner may now run it $ chmod g-w catalog.txt # g-w: group loses write access $ chmod o-rwx patrons.txt # o-rwx: others get nothing at all $ chmod a+r notes.txt # a+r: everyone gets read access

chmod: Octal Form

  • One digit per rwx group
  • 755 = rwxr-xr-x
  • 644 = rw-r--r--
$ chmod 755 backup.sh $ chmod 644 catalog.txt $ chmod 700 patrons.txt

chmod: Octal Form

$ chmod 755 backup.sh $ chmod 644 catalog.txt $ chmod 700 patrons.txt

Word Origin: "chmod"

1971Ships in AT&T Unix v1,the first Unix release1971Short for "change mode,"mode meaning permission bitsTodaySame command, same bits,on every Linux & macOS box

Set the Right Mode

  • backup.sh: owner run only
  • catalog.txt: owner+group edit
  • patrons.txt: owner read-only
⌨️Your Turn

Set the Right Mode

$ chmod 700 backup.sh $ chmod 660 catalog.txt $ chmod 400 patrons.txt

Questions?

Ownership, sudo & Practice

Why Does Ownership Matter?

  • Ownership decides who can act
  • Wrong owner can lock you out
  • This is theory meeting your VM
🏷️Who Owns It?

Changing Ownership

  • chown changes the owner
  • chgrp changes the group
  • Usually needs sudo
$ sudo chown comp175user catalog.txt # owner only, group untouched $ sudo chgrp library catalog.txt # group only, owner untouched $ sudo chown comp175user:library catalog.txt # owner and group in one call $ sudo chown -R comp175user /srv/lib # -R: every file in the folder too

Changing Ownership

$ sudo chown comp175user catalog.txt # owner only, group untouched $ sudo chgrp library catalog.txt # group only, owner untouched $ sudo chown comp175user:library catalog.txt # owner and group in one call $ sudo chown -R comp175user /srv/lib # -R: every file in the folder too

Word Origin: "chown"

1971Ships the same day asthe first Unix manual1971Short for change owner,pairs with chmodTodayStill the standard way tohand a file to someone else

Requirements: Team Folder

  • Create /srv/library-team
  • Owner: comp175user; group lib
  • Team can edit; others can't
  • Kali verifies comp175user
📁Shared Folder

Word Origin: "srv"

1994FSSTND 1.0 -- no /srv yet,served data scattered around1997Renamed the FilesystemHierarchy Standard (FHS 2.0)2004FHS 2.3 adds /srv fordata this system servesTodayStandard home for aserver's site-specific data

The Goal

  • One folder, one team
  • comp175user owns; lib shares
  • Mode 770 locks out others
📁library-team/Owner: comp175userGroup: libraryMode: 770 (rwxrwx---)

Create the Team Group

  • groupadd creates a group
  • Group: library, for the team
  • Needed before chgrp works
⌨️Your Turn

Create the Team Group

$ sudo groupadd library

Create the Team Folder

  • mkdir makes the folder
  • chgrp sets its group
  • chmod 770 locks it down
⌨️Your Turn

Create the Team Folder

$ sudo mkdir /srv/library-team $ sudo chgrp library /srv/library-team $ sudo chmod 770 /srv/library-team

How Do You Check It Worked?

  • ls -l prints the real result
  • Compare it to the goal
  • rwxrwx--- means team-only
drwxrwx--- comp175user library↓Matches the goal?owner + group rwx, others none

Confirm the Result

  • ls -l confirms the change
  • drwxrwx--- is the target
  • Group: library, others: none
⌨️Your Turn

Confirm the Result

$ ls -l /srv

Questions?

Connect to Another VM

Phase 1: Connect to another Physical Machine

Connect to My Machine

  • Get connected first
  • Details come after
  • Instructor gives the address
⌨️Your Turn

Connect to My Machine

$ ssh comp175user@class-server

Explore Your Home Directory

  • pwd shows where you are
  • ls -la lists what's there
  • ls -d */ lists only folders
  • Poke around, get familiar
⌨️Your Turn

Explore Your Home Directory

$ pwd /home/comp175user $ ls -la .bashrc .ssh Documents Downloads $ ls -d */ Documents/ Downloads/

Which Homes Can You Access?

  • cd into your own home
  • Try another user's home
  • What happens each time?
📁?Try cd on each home folder
Your Home$ cd ~✅SuccessAnother's Home$ cd /home/other❌Permission denied

Read a File: cat

  • cat prints a file's content
  • Works well for short files
  • cat a b joins two files
⌨️Your Turn

Read a File: cat

$ cat notes.txt Buy more toner. Reboot lib-web01 Friday. $ cat notes.txt todo.txt Buy more toner. Reboot lib-web01 Friday. Email the team about the outage.

Where's the Password File?

  • Look inside /etc
  • Two files hold user info
  • Which one has the hash?
🔍?Find the password file
/etc/passwd$ cat /etc/passwd✅Readable by anyone/etc/shadow$ cat /etc/shadow❌Root only, real hash

Locate It Yourself: find

  • find searches by name
  • Start from /etc, not home
  • Figure out the rest
find?No answer given

Can You Edit It?

  • Try writing to /etc/shadow
  • As yourself, then with sudo
  • Compare the results
🔒?Try editing /etc/shadow
As comp175user$ nano /etc/shadow❌Permission deniedWith sudo$ sudo nano /etc/shadow✅Allowed, be careful

Try It: Search Your Home

  • Use find in your home dir
  • Look for password files
  • What comes back?
⌨️Your Turn

Can You Read It?

  • cat the file you found
  • Does it print?
  • Note what happens
⌨️Your Turn

Can You Rename It?

  • mv it to a new name
  • Does the rename work?
  • Note what happens
⌨️Your Turn

Can You Delete It?

  • rm the file you found
  • Does it disappear?
  • Note what happens
⌨️Your Turn

Who Else Is Logged In?

  • who shows active sessions
  • w adds what they're doing
  • Check right now
👥?Check who else is on this machine
Just You$ who✅One line: youOthers Too$ who✅Multiple lines

How Much Space Do You Have?

  • du checks your own usage
  • df checks the whole disk
  • Two very different answers
💾?Check your space two ways
du -sh ~$ du -sh ~✅Just your filesdf -h$ df -h✅The entire filesystem

Phase 2: Connect from Kali VM to Ubuntu VM

One More Thing First

  • comp175user has no account
  • 770 means nothing without one
  • The admin creates it first
👤comp175user?🔒library-team/No account = no way in

Add comp175user to Team

  • useradd creates the account
  • Password: comp175!!!
  • usermod -aG adds to a group
  • su - switches to that user
⌨️Your Turn

Add comp175user to Team

$ sudo useradd -m comp175user $ sudo passwd comp175user $ sudo usermod -aG library comp175user $ sudo su - comp175user $ whoami comp175user

What's the Group's Home?

  • Not /home, something else
  • srv is short for service
  • Hint: /srv/library-team
  • Create it first if missing
📁Your Turn

What's the Group's Home?

$ sudo mkdir -p /srv/library-team # -p: no error if exists $ sudo chgrp library /srv/library-team # sets the group $ sudo chmod 770 /srv/library-team # owner+group only $ ls -ld /srv/library-team # -d: the dir, not contents drwxrwx--- 2 comp175user library ... /srv/library-team

Return to Admin: exit

  • comp175user isn't a sudoer
  • exit returns to your shell
  • Admins run sudo, not members
  • Check with groups or sudo -l
⌨️Your Turn

⚠️ A regular team member should not be added to sudoers just to fix this.

Return to Admin: exit

$ sudo bash scripts/set-wsl-hostname.sh vm-ubuntu comp175user is not in the sudoers file. $ exit $ groups your-username sudo $ groups comp175user comp175user library
sudo grouplibrary group👤your-usernameadmin👤comp175usernot adminTwo separate groups, no overlap

Can Two VMs Talk?

  • Yes, if they share a network
  • Plain NAT isolates each VM
  • Test first: ping, then ssh
One physical hostKali VMUbuntu VMlib-web01Shared NetworkInternal, Host-only, or Bridged

Word Origin: "ssh"

1995Tatu Ylonen writes it atHelsinki University of Tech1995A response to passwordsniffing on campus networksTodayReplaced telnet & rloginas the standard remote login

Install & Start sshd

  • openssh-server provides sshd
  • WSL has no systemd by default
  • service ssh start, each boot
⌨️Your Turn

⚠️ sshd does not restart on its own after wsl --shutdown.

Install & Start sshd

$ sudo apt install -y openssh-server $ sudo service ssh start $ sudo service ssh status ssh start/running, process 1842

Find lib-web01's IP

  • Every VM gets its own IP
  • Yours will differ, that's OK
  • Type the hostname command
⌨️Your Turn

Find lib-web01's IP

$ hostname -I 172.20.145.10

Same IP on Two VMs?

  • Same IP = a real conflict
  • Goes to whichever VM replies
  • Flaky ping, wrong host reached
Shared Networklib-web01172.20.145.10lib-web02172.20.145.10⚠️Same IP, two different machines

Why They Share the Same IP

  • One shared WSL2 VM
  • All distros, one virtual NIC
  • Same IP, every time
  • Not the same as the host's IP
Windows HostWSL2 Utility VMKaliUbuntueth0: 172.x.x.xOne NIC, shared by every distro

⚠️ ssh still works, but only one distro can hold a port at once.

WSL2 (Default)Windows HostOne Shared Lightweight VMKaliUbuntuOne NICshared IPOne shared address for every distroVirtualBox / Real HypervisorPhysical HostKali VMown kernelown virtual NICUbuntu VMown kernelown virtual NICOwn IP.10Own IP.11A real, separate address per VM

⚠️ WSL distros are not separate VMs like VirtualBox creates.

How to Tell Them Apart

  • hostname is shared by default
  • Check /etc/os-release instead
  • cat it, look for the ID line
👤Your Turn

⚠️ Even the hostname matches the Windows PC by default.

How to Tell Them Apart

$ cat /etc/os-release | grep ^ID= ID=kali

Give a Distro Its Own Name

  • hostname: yes, run a script
  • IP: still shared, one NIC
  • True per-VM IPs need real VMs
⌨️Your Turn

⚠️ Only the hostname can be made unique; the IP still can't.

Give a Distro Its Own Name

$ cd ~/2026-COMP-175 $ git pull $ sudo bash scripts/set-wsl-hostname.sh kali-attack $ wsl --terminate kali-linux $ hostname kali-attack

Confirm comp175user Exists

  • Check before you ssh in
  • id shows the account
  • Type the id command
⌨️Your Turn

Confirm comp175user Exists

$ id comp175user uid=1002(comp175user) groups=library

Check the Connection: ping

  • Ping first, before ssh
  • Confirms basic connectivity
  • No reply? Check the network
⌨️Your Turn

Check the Connection: ping

$ ping -c 1 172.20.145.10

Check the SSH Port

  • nmap checks if a port is open
  • filtered means no reply back
  • Run this before ssh fails
⌨️Your Turn

Check the SSH Port

$ nmap -p 22 172.20.145.10 22/tcp filtered ssh

Unblock SSH: ufw

  • ufw manages the firewall
  • Install it first if missing
  • Allow first, then enable
  • Run this on the target VM
⌨️Your Turn

⚠️ Enabling before allowing ssh can lock you out.

Unblock SSH: ufw

$ sudo apt install -y ufw $ sudo ufw allow 22/tcp $ sudo ufw enable $ sudo ufw status Status: active

Enable & Disable a Port

  • allow opens a port
  • deny closes a port
  • delete removes a rule
⌨️Your Turn

Enable & Disable a Port

$ sudo ufw allow 8080/tcp $ sudo ufw deny 8080/tcp $ sudo ufw delete allow 22/tcp

Test Access: comp175user

  • comp175user is in the group
  • Should enter & write files
  • Outside users should be denied
⌨️Your Turn

Test Access: comp175user

$ ssh comp175user@172.20.145.10 $ cd /srv/library-team $ touch comp175user-overdue.txt

Fix: Permission Denied

  • Check if a password exists
  • passwd -S shows L or P
  • Reset it, then retry ssh
⌨️Your Turn

⚠️ useradd alone leaves the account locked until passwd is run.

Fix: Permission Denied

$ sudo passwd -S comp175user comp175user L 09/02/2026 0 99999 7 -1 $ sudo passwd comp175user

Deliverables

  • Screenshot: ls -l /srv output
  • Screenshot: comp175user writes
  • One line: why 770, not 777
📋Checklist

Questions?

Where We Are: Module 2

  • Module 2 done: CLI, perms
  • Next: File Systems & Storage

Module 3

File Systems & Storage

All Commands: Module 3

What Is a File System?

History of File Systems

  • Files existed before disks
  • Standards emerged over time
  • Unix set today's model
1960sTape drives, sequentialaccess only, no folders1974Unix File System addsreal hierarchical folders1980FAT ships with MS-DOS,simple but no permissions1993ext2 becomes Linux'sfirst native file systemTodayext4, NTFS, APFS allstill hierarchical trees
THE LIBRARY= A FILE SYSTEMCirculationReferenceCard Catalog= Directory ListingONE BOOK, PULLED OUT"UNIX and Linux SystemAdministration Handbook"= A FILETitle= FilenamePages inside= File contentsCall number= Path to find itShelf it sits on= Its folderWhole library= The file system

Data Before Disks

  • One card held one line
  • Holes encoded each character
  • A machine read the holes
  • No folders, no filenames
A real FORTRAN program statement punched on an 80-column card

A real FORTRAN program card (Source: Wikimedia Commons)

An IBM 1442 card reader/punch machine

An IBM 1442 card reader (Source: Wikimedia Commons)

An IBM reference card showing the full punch-hole encoding for every character

Hole pattern = character (Source: Wikimedia Commons)

Sequential Tape Storage

  • Tape reels held huge data
  • Had to read start to end
  • No random access at all
IBM 729 magnetic tape drives

IBM 729 magnetic tape drives (Source: Wikimedia Commons)

The First Hard Disk

  • IBM RAMAC shipped in 1956
  • Fifty 24-inch spinning disks
  • Enabled true random access
IBM 350 RAMAC disk mechanism

IBM 350 RAMAC disk mechanism (Source: Wikimedia Commons)

The Machine Unix Ran On

  • PDP-11: a 1970s minicomputer
  • Ran the first Unix systems
  • Small enough for a lab
A DEC PDP-11/70 minicomputer

DEC PDP-11/70 minicomputer (Source: Wikimedia Commons)

What the OS Gives You

  • Raw disk = just bytes
  • The OS adds 6 real services
The OSFile SystemBy FilenamePermissionsDirectoriesMetadataPortable I/OConsistency

Creators of Unix

  • Ken Thompson & Dennis Ritchie
  • Built Unix at Bell Labs
  • Also created the C language
  • Hierarchical folders (1974)
  • Permissions arrive (1971)
  • Inodes track data (1971)
Ken Thompson (sitting) and Dennis Ritchie at a PDP-11

Ken Thompson & Dennis Ritchie, 1972 (Source: Wikimedia Commons)

Early Portable Storage

  • 8-inch floppy, mid-1970s
  • Held under 1 MB of data
  • Introduced removable media
An 8-inch floppy disk

8-inch floppy disk (Source: Wikimedia Commons)

Floppy Disks Shrink

  • 8in, 5.25in, then 3.5in
  • Each shrink added capacity
  • FAT tracked files on each
8-inch, 5.25-inch, and 3.5-inch floppy disks side by side

8-inch, 5.25-inch & 3.5-inch floppies (Source: Wikimedia Commons)

Linux's Creator (Kernel)

  • Linus Torvalds, early 1990s
  • Built Linux as a student
  • ext2 followed a year later
  • Volkerding: Slackware, 1993
  • Murdock: Debian, same year

Slackware: Wikipedia. Debian: Wikipedia

Linus Torvalds

Linus Torvalds (Source: Wikimedia Commons)

Inside a Hard Disk

  • Spinning platters store bits
  • A head reads each track
  • Mechanical, so it's slower
Laptop hard disk drive platters, disassembled

Laptop hard disk drive platters (Source: Wikimedia Commons)

Today's Storage: SSD

  • No moving parts at all
  • Much faster than a platter
  • Now standard in laptops
A 1TB NVMe M.2 solid-state drive

1TB NVMe M.2 SSD (Source: Wikimedia Commons)

What Is a File System?

  • Organizes data on a disk
  • Tracks names, sizes, locations
  • Without it, disks are junk
Files & Folders (what you see)File System (ext4, NTFS, APFS)Raw Disk Blocks (0s and 1s)

Real File System Types

  • Each OS has a default
  • All are still hierarchical
  • Format matters when sharing
NameUsed ByNotable Trait
ext4LinuxJournaling, large volume support
NTFSWindowsBuilt-in permissions, encryption
APFSmacOSSnapshots, strong encryption
exFATPortable drivesCross-platform, no journaling

Which File System?

Which File System?

  • df shows mounted file systems
  • -h means human-readable
  • Look at the Filesystem column
df -h output on a real WSL2 Ubuntu terminal

df -h on a real WSL2 terminal

FilesystemWhat It Is
noneVirtual, no real backing device
driversWSL2's shared driver mount
/dev/sddThe real virtual disk (ext4)
rootfsInitial boot filesystem
C:\Windows C: drive, shared in
tmpfsTemporary, lives in RAM only

Command: df -h

  • Lists every mounted disk
  • Shows size, used, free space
  • -h: sizes in GB not bytes
$ df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 12G 7G 64% /

Command: df -h

$ df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 12G 7G 64% /

Command: mount

  • Shows what's attached where
  • Every drive needs one
  • No output line = not mounted
$ mount | grep sda1 /dev/sda1 on / type ext4 (rw,relatime)

Command: mount

$ mount | grep sda1 /dev/sda1 on / type ext4 (rw,relatime)

Word Origin: "Mount"

  • Attaching a disk to a folder
  • Unreachable until mounted
  • The folder is the mount point
1971Unix v1 introducesthe mount system call1980sUSB drives auto-mounton modern desktopsTodayLinux mounts almosteverything, even /proc

Common File System Errors

  • Wrong type = mount fails
  • Full disk = writes fail
  • Unmounted = path not found
ErrorLikely CauseFix
No space left on deviceDisk is fullFree space or resize
Wrong fs typeexFAT tools missingInstall exfat-utils
Not a directoryPath doesn't exist yetmkdir it first

Word Origin: "Filesystem"

  • Coined for early Multics work
  • "File" + "system" of rules
  • Now means the storage layer
1965Multics project usesthe term "file system"1974Unix popularizes itfor its own hierarchyTodayEvery OS textbookuses this exact term

Questions?

FHS Directory Standard

History of the FHS

  • How old is this standard?
  • See the real dates below

🔧 Admin task: Explains why an old server may still have legacy paths (e.g. symlinked /var/lock) an admin has to work around.

1993Effort begins torestructure Linux dirs1994FSSTND released,Linux-only standard1995BSD joins; renamedto FHS (broader scope)2015FHS 3.0 published,March 19 (current)

Why a Directory Standard?

  • Software must predict paths
  • Users must predict paths too
  • Same rules across distros

🔧 Admin task: Lets an admin write one deploy script that works unmodified on any FHS-compliant box.

Read: page 1, FHS 3.0 — Chapter 1.1, Purpose

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Gray = all 14, mandatory per FHS Sec. 3.2, none optional here

Who Actually Uses the FHS?

  • Software vendors build to it
  • OS makers: Ubuntu, Fedora
  • Sysadmins rely on it daily

🔧 Admin task: When a package misbehaves, checking whether it violates FHS is a real first diagnostic step.

Read: page 1, FHS 3.0 — Chapter 1.1, Purpose

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Gray = all 14; FHS Sec. 1.1 applies uniformly across them

What the FHS Does NOT Cover

  • Local placement is local
  • FHS won't override an admin

🔧 Admin task: An admin is free to lay out /srv/<project> however fits their own site, without violating the standard.

Read: page 1, FHS 3.0 — Chapter 1.1, Purpose

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /srv, FHS's cited example of admin-defined layout (Sec. 3.17.1)

Reading FHS Notation

  • <name> = a varying part
  • [name] = an optional part
  • * = any variable substring

🔧 Admin task: This same <angle-bracket> convention shows up in man pages and RFCs an admin reads constantly.

Read: page 1, FHS 3.0 — Chapter 1.2, Conventions

NotationMeaningExample
<pkg>Fill-in name/opt/<pkg>
[.ext]Optional piecefile[.ext]
*Any substringlibc.so.*

Real Distros That Follow It

  • Debian, Ubuntu, Fedora
  • RHEL, openSUSE, Arch
  • All place files the same way

🔧 Admin task: An admin's muscle memory (chmod /etc/passwd, tail /var/log) transfers directly across distros.

Read: page 1, FHS 3.0 — Chapter 1.1, Purpose

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Gray = all 14, identical across every FHS-compliant distro

Questions?

The Filesystem: Two Splits

Two Ways to Classify a File

  • Shareable vs. unshareable
  • Static vs. variable

🔧 Admin task: This exact classification is what an admin uses to decide backup frequency and mount policy.

Read: page 2, FHS 3.0 — Chapter 2

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Gray = all 14, shown before the shareable/static split (next slide)

Shareable vs. Unshareable

  • Shareable: OK on many hosts
  • Unshareable: this host only
  • Device lock files aren't

🔧 Admin task: Tells an admin which directories are safe to NFS-export to a whole lab without per-host conflicts.

Read: page 2, FHS 3.0 — Chapter 2

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = shareable, per FHS's own example table (Ch. 2): /usr, /opt

Static vs. Variable

  • Static: binaries, libraries
  • Only admin changes them
  • Variable: changes on its own

🔧 Admin task: Tells an admin which directories are safe to put on read-only or cheaper/slower storage.

🎓 Design rationale: Why does the static/variable split matter for hardware, not just organization? Static data can physically live on read-only media (a burned disc, a read-only NFS mount) -- variable data cannot. The split isn't just tidiness; it constrains what storage is even usable.

Read: page 2, FHS 3.0 — Chapter 2

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = static, per FHS's own example table (Ch. 2): /usr, /opt, /etc, /boot

The FHS Example Table

  • Combine both splits
  • Four resulting categories

🔧 Admin task: This table is the quick reference an admin checks before choosing a storage tier for a new server.

Read: page 2, FHS 3.0 — Chapter 2

ShareableUnshareable
Static/usr, /opt/etc, /boot
Variable/var/mail/var/run, /var/lock

Why /var Split From /usr

  • UNIX once mixed both types
  • /var now separates them
  • This lets /usr stay read-only

🔧 Admin task: Explains why an admin should never manually relocate data between /usr and /var -- the split is intentional.

Read: page 2, FHS 3.0 — Chapter 2

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /var, split out so /usr could stay static (FHS Ch. 2 Rationale)

What This Buys Admins

  • Back up /var often, not /usr
  • Read-only /usr resists attack

🔧 Admin task: Concretely: point backup software at /var, and mount /usr read-only (mount -o remount,ro /usr).

Read: page 2, FHS 3.0 — Chapter 2, Rationale

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /usr and /var, under opposite backup/mount policy (Ch. 2 Rationale)

Questions?

The Root Filesystem

Purpose of the Root FS

  • Boots, restores, repairs it
  • /usr, /opt, /var can move
  • Root itself must stay put

🔧 Admin task: Tells an admin exactly what a minimal rescue/recovery partition must include.

🎓 Design rationale: Why must / stay small even with plenty of disk to spare? A corrupted root partition is a far bigger problem than a corrupted data partition -- keeping it minimal limits how much can go wrong in the one place the whole boot depends on.

Read: page 3, FHS 3.0 — Section 3.1, Purpose

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue border = the root filesystem itself, per FHS Sec. 3.1

Required Root Directories

  • 14 directories, always there
  • Each has one specific job

🔧 Admin task: This is the checklist an admin walks when auditing a filesystem for non-standard or missing directories.

Read: page 4, FHS 3.0 — Section 3.2, Requirements

DirHoldsDirHolds
binCommandsbootBoot files
devDevicesetcHost config
libLibrariesmediaRemovable
mntTemp mountoptAdd-on apps
runRuntimesbinAdmin tools
srvService datatmpTemp files
usrSecondaryvarVariable

/bin: Commands for Everyone

  • Works in single-user mode
  • No subdirectories allowed

🔧 Admin task: These are the commands an admin can trust to work even in single-user/rescue mode during a repair.

Read: page 5, FHS 3.0 — Section 3.4.1-3.4.2

CommandJob
ls, cp, mv, rmFile basics
chmod, chownPermissions
mount, dfFilesystems

/etc: No Binaries Allowed

  • Must be static, plain-text
  • No binaries; scripts are OK

🔧 Admin task: Because it's guaranteed plain-text, an admin can always git-diff or grep /etc safely to audit config drift.

🎓 Design rationale: Why can't /etc contain binaries? Config files there must be readable and diffable by tools (and by an admin's own eyes) before any package manager has verified binary integrity -- a binary hiding in /etc would defeat the entire point of the directory.

Read: page 7, FHS 3.0 — Section 3.7.1-3.7.2

FilePurpose
passwdUser accounts
groupGroup list
fstabFilesystem info
hostsHostname map

/home vs. /root

  • /home: optional, per-site
  • /root: home for root user

🔧 Admin task: Tells an admin where to find a locked-out user's files vs. the root account's own history and crontab.

🎓 Design rationale: Why is /home optional, not required? Because its real layout varies too much across deployments (NFS-mounted, subdivided by department, or absent on an embedded system) for FHS to mandate one fixed path -- so it stays a strong default, not a hard rule.

Read: page 10, FHS 3.0 — Sections 3.8.1, 3.14.1

binbootdevetclibmediamntoptrunsbinsrvtmpusrvarhomeroot/

Blue = /home, /root, both optional per FHS Sec. 3.8.1 and 3.14.1

What This Means for Users

  • Files survive OS reinstalls
  • Dotfiles keep ls output clean

🔧 Admin task: Config-management tools (Ansible, Puppet) target ~/.config for exactly this reason -- it's the FHS-defined spot.

Read: page 10, FHS 3.0 — Sections 3.8.1-3.8.2

.bashrc.configdocs/home

Blue = dot-prefixed entries per FHS Sec. 3.8.2; docs is not one

/opt: Add-On Software

  • Big 3rd-party apps live here
  • Own tree: /opt/<package>
  • Never scattered into /usr

🔧 Admin task: This is the first place an admin checks (or cleans up) when auditing third-party software installs.

🎓 Design rationale: Why does FHS require a registered provider name for /opt subdirs? To prevent collisions -- if two unrelated vendors both name their tree /opt/tools, one silently overwrites the other; a registered (often reverse-DNS-style) name guarantees it's unique.

Read: page 13, FHS 3.0 — Section 3.13.1

pkgvendorbinlib/opt

Blue = /opt/<package>, the required static-objects subtree (Sec. 3.13.2)

/media vs. /mnt

  • /media: removable disks
  • /mnt: admin's manual mounts

🔧 Admin task: Scripts should target /mnt for a scheduled backup mount; leave /media for automatic removable-media handling.

Read: page 12, FHS 3.0 — Sections 3.11.1, 3.12.1

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /media, /mnt, FHS's two mount-point directories (Sec. 3.11.1, 3.12.1)

/run: What's Happening Now

  • Data since the last boot
  • Cleared every time it boots
  • Replaces old /var/run PIDs

🔧 Admin task: After a crashed daemon, an admin checks /run for a stale PID file -- and it's always safe to clear on reboot.

🎓 Design rationale: Why did FHS introduce /run instead of just keeping /var/run? Because /var might not be mounted yet very early in boot, but PID/socket data is needed before that -- /run is its own tmpfs directly on /, so it's guaranteed available from the earliest boot stage.

Read: page 14, FHS 3.0 — Section 3.15.1-3.15.2

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /run, holding data since the current boot (FHS Sec. 3.15.1)

Questions?

The /usr Hierarchy

/usr: Shareable, Read-Only

  • Same /usr on many machines
  • Must never be written to
  • Host data lives elsewhere

🔧 Admin task: Confirms it's safe practice to mount /usr read-only (mount -o remount,ro /usr) on a production server.

🎓 Design rationale: Why must /usr be read-only, not just 'usually is'? Because it's often mounted from one shared NFS server onto many clients at once -- a write from any one client would corrupt or race against every other client reading that same tree simultaneously.

Read: page 18, FHS 3.0 — Section 4.1

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /usr, the directory FHS Sec. 4.1 forbids writing to

Read-Only /usr: Security

🔴 Red Team: A writable /usr lets a compromised process silently replace ls, sudo, or ssh with a backdoored copy.

🔵 Blue Team: Mount /usr read-only in production; any change to it becomes a loud, detectable event.

Required /usr Directories

  • 5 directories, always there

🔧 Admin task: This is the checklist an admin uses to spot a package that installed itself somewhere it shouldn't have.

Read: page 18, FHS 3.0 — Section 4.2

DirHolds
binMost user commands
libLibraries
localAdmin's own installs
sbinNon-vital admin tools
shareArch-independent data

/usr/local: Update-Safe

  • For hand-installed software
  • Survives every system update

🔧 Admin task: ./configure --prefix=/usr/local is the correct install target for anything an admin compiles by hand.

🎓 Design rationale: Why must locally-installed software avoid /usr specifically, not just prefer /usr/local? A package manager tracks and may remove anything it believes it owns under /usr -- a hand-installed file there risks silent deletion on the next system upgrade.

Read: page 21, FHS 3.0 — Section 4.9.1

binliblocalsbinshare/usr

Blue = /usr/local, exempt from overwrite on update (FHS Sec. 4.9.1)

/usr/bin vs. /usr/sbin

  • /usr/bin: everyday commands
  • /usr/sbin: admin-only tools

🔧 Admin task: Tells an admin which commands are safe to expose in a restricted user's $PATH vs. keep admin-only.

Read: page 18, FHS 3.0 — Sections 4.4.1, 4.10.1

binsbin/usr

Blue = /usr/bin, /usr/sbin, both defined in FHS Sec. 4.4.1 and 4.10.1

/usr/share: Shared Data

  • Shared across one OS release
  • Man pages, dicts, timezones

🔧 Admin task: Safe to NFS-share across a whole lab of mixed-architecture machines without per-host duplication.

Read: page 22, FHS 3.0 — Section 4.11.1

binliblocalsbinshare/usr

Blue = /usr/share, architecture-independent per FHS Sec. 4.11.1

Man Pages: 8 Real Sections

  • Every page has a section #
  • 8 sections total, 1 to 8

🔧 Admin task: man 5 crontab vs. plain man crontab -- knowing the section jumps straight to the file-format docs an admin needs.

Read: page 24, FHS 3.0 — Section 4.11.6.1

#Covers
1User programs
4Special/device files
5File formats
8System admin tools

Questions?

The /var Hierarchy

/var: Where the Changes Go

  • Spool data, logs, temp files
  • Lets /usr stay read-only

🔧 Admin task: This is the directory an admin puts a disk-space monitoring alert on -- it's the one that actually fills up.

Read: page 30, FHS 3.0 — Section 5.1

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /var, the one root dir defined as variable data (FHS Sec. 5.1)

Required /var Directories

  • 9 directories, always there

🔧 Admin task: This is the checklist an admin walks when deciding separate partitions or quotas for logs vs. spool data.

Read: page 30, FHS 3.0 — Section 5.2

DirHoldsDirHolds
cacheRegenerablelibApp state
localFor /usr/locallockLock files
logLog filesoptFor /opt
runRuntime statespoolAwaiting work
tmpPersists reboots

/var/log: What's Recorded

  • Most logs live in /var/log
  • Some use a subdirectory

🔧 Admin task: lastlog and wtmp (read via last) are the first two files an admin checks investigating a suspicious login.

Read: page 36, FHS 3.0 — Section 5.10.1-5.10.2

FileRecords
lastlogEach user's last login
wtmpEvery login/logout
messagessyslogd output

/tmp vs. /var/tmp Revisited

  • /tmp: gone at next reboot
  • /var/tmp: survives reboots
  • Cleared less often overall

🔧 Admin task: A long-running batch job's temp files belong in /var/tmp, so a reboot mid-job doesn't silently wipe them.

Read: page 38, FHS 3.0 — Section 5.15.1

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /tmp, /var (stands in for /var/tmp), contrasted in Sec. 5.15.1

/var/spool: Work To Be Done

  • Data waiting on a process
  • Deleted once handled

🔧 Admin task: When a print job or an outgoing email seems stuck, /var/spool/<service> is where an admin looks first.

Read: page 37, FHS 3.0 — Section 5.14.1

DirQueue for
mqueueOutgoing mail
lpdPrint jobs
newsUsenet news

/var/lib & /var/mail

  • /var/lib: app state data
  • /var/mail: one file/user

🔧 Admin task: Never hand-edit files under /var/lib; a service's own tooling owns that data. /var/mail/<user> is the real mailbox.

🎓 Design rationale: Why is a mailbox one flat file, not a folder of messages? FHS mandates the classic UNIX mbox format for compatibility with decades of existing mail tooling -- a maildir-style folder tree is a newer alternative some servers use, but it's not what FHS itself defines.

Read: page 33, FHS 3.0 — Sections 5.8.1, 5.11.1

cacheliblocallocklogoptrunspooltmpmail/var

Blue = /var/lib, /var/mail, per FHS Sec. 5.8.1 and 5.11.1

Backup Strategy: /var First

  • /usr: just reinstall it
  • /var: real, unique data

🔧 Admin task: If disk space is tight, an admin can safely skip backing up /usr -- apt/yum reinstall it in minutes.

Read: page 30, FHS 3.0 — Section 5.1, Rationale

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /usr, /var, under contrasting backup priority (Sec. 5.1 Rationale)

Questions?

Linux-Specific Rules

/proc & /sys: Virtual Trees

  • Not real files on disk
  • /proc: process + kernel info
  • /sys: devices and drivers

🔧 Admin task: cat /proc/cpuinfo or /proc/meminfo gives live diagnostics with zero extra tools to install.

🎓 Design rationale: Why does Linux have both /proc and /sys? /proc came first (process/kernel info, somewhat unstructured over time); /sys was added later specifically to expose device and driver data in a clean, versioned, machine-parseable hierarchy /proc had never enforced.

Read: page 40, FHS 3.0 — Sections 6.1.5, 6.1.7

binbootdevetclibmediamntoptrunsbinsrvtmpusrvarprocsys/

Blue = /proc, /sys, Linux-annex virtual filesystems (Sec. 6.1.5, 6.1.7)

3 Devices Every Linux Needs

  • FHS requires these exactly

🔧 Admin task: Safe in any script on any Linux box: 2>/dev/null to silence errors, or dd if=/dev/zero to wipe a disk.

Read: page 39, FHS 3.0 — Section 6.1.3

DeviceDoes
/dev/nullDiscards all writes
/dev/zeroEndless zero bytes
/dev/ttyYour own terminal

Linux-Only Extras

  • setserial goes in /bin
  • lilo.conf goes in /etc
  • Not required on every UNIX

🔧 Admin task: A portable admin script shouldn't assume these exist -- check for them before relying on Linux-only files.

Read: page 39, FHS 3.0 — Sections 6.1.2, 6.1.4

binbootdevetclibmediamntoptrunsbinsrvtmpusrvar/

Blue = /bin, /etc, gaining Linux-only files per Sec. 6.1.2, 6.1.4

/sbin Extras: ldconfig

  • Rebuilds the library cache
  • Runs after any lib upgrade

🔧 Admin task: Forget to run ldconfig after copying a new .so by hand, and every program linking it fails at runtime.

Read: page 40, FHS 3.0 — Section 6.1.6

ldconfigslnssync/sbin

Blue = ldconfig, the command this slide covers (FHS Sec. 6.1.6)

cron & at: Scheduled Jobs

  • Holds data for cron and at
  • All scheduled jobs live here

🔧 Admin task: When a scheduled job silently stops running, this is the directory an admin checks for the actual job entry.

Read: page 41, FHS 3.0 — Section 6.1.10

cronlpdmqueuenews/var/spool

Blue = /var/spool/cron, storing both cron and at data (FHS Sec. 6.1.10)

Questions?

Everything Is a File

Everything Is a File

  • Unix's biggest idea
  • Same commands work on all
  • Simplifies the whole OS
Regular FileDirectoryDevice (/dev)PipeSocketFile

A Disk Is a File

  • /dev/sda is your whole disk
  • ls -l shows it like any file
  • Reading it reads raw bytes
$ ls -l /dev/sda brw-rw---- 1 root disk 8, 0 Sep 8 /dev/sda

A Disk Is a File

$ ls -l /dev/sda brw-rw---- 1 root disk 8, 0 Sep 8 /dev/sda

Processes Are Files

  • /proc exposes running programs
  • Each process gets a folder
  • Files inside are readable
$ cat /proc/version Linux version 6.8.0 (gcc 13.2.0)

Processes Are Files

$ cat /proc/version Linux version 6.8.0 (gcc 13.2.0)

Command: file

  • Not installed by default
  • Create the file if missing
  • Identifies a file's real type
$ sudo apt install -y file $ echo "Library opens at 9am" > notes.txt $ file notes.txt notes.txt: ASCII text $ file /dev/sda /dev/sda: block special

Command: file

$ sudo apt install -y file $ echo "Library opens at 9am" > notes.txt $ file notes.txt notes.txt: ASCII text $ file /dev/sda /dev/sda: block special

Special Files at a Glance

  • Each path exposes something
  • None are "real" disk files
  • The OS generates them live
PathWhat It Really Is
/dev/sdaThe physical disk itself
/proc/1Info about process ID 1
/dev/nullA file that discards everything

dev = device · proc = process · sda = SCSI/SATA disk A (1st disk) · null = the null device

Word Origin: "Inode"

  • Short for "index node"
  • Holds a file's metadata
  • The filename lives elsewhere
1970sUnix introduces theinode as a metadata record1974Documented in theUnix File System paperTodayext4, XFS, and most Linuxfile systems still use inodes

Reading a File's Metadata

  • ls -l already shows some
  • -i also prints the inode
  • Full detail comes later
$ ls -li notes.txt 130910 -rw-r--r-- 1 admin admin 21 notes.txt
FieldMeaning
130910Inode number (unique ID)
-rw-r--r--Permissions
1Hardlink count
admin adminOwner, then group
21Size in bytes
notes.txtThe filename

⚠️ On /mnt/c paths, WSL2 often shows huge inode numbers and -rwxrwxrwx for everything -- Windows drives don't track real Unix permissions.

Reading a File's Metadata

$ ls -li notes.txt 130910 -rw-r--r-- 1 admin admin 21 notes.txt

What's Inside an Inode?

  • Size, owner, permissions
  • Timestamps (access, modify)
  • Pointer to the data blocks
Filename (in the directory)Inode (owner, size, perms)Data Blocks (actual bytes)

Symlink vs. Hardlink

  • Symlink: a pointer to a path
  • Hardlink: shares the inode
  • Table below compares both
TypeOwn Inode?Breaks If Target Moves?
SymlinkYes (its own)Yes
HardlinkNo (shares one)No

How Links Point

  • Symlink = symbolic link
  • It stores a path string
  • Not a link to the inode
  • Hardlink = a second name
  • Same inode, same data
Symlinklink-s.txt"notes.txt"a path string, no inodeinodethen dataHardlinknotes.txtlink-h.txtinode 130910one inode, two names

A symlink points at a name; a hardlink is a name for the inode

Link Count on Delete

  • Inode holds a link count
  • rm one name: count drops 1
  • Data lives while count > 0
  • Last rm: inode + data freed
  • Symlink is not on the count
  • Delete its target: it dangles
notes.txt + link-h.txtinodelinks: 2datakeptlink-h.txtinodelinks: 1datakept(no names left)inodelinks: 0datafreedrm notes.txtrm link-h.txt

The data is freed only when the last hardlink is removed

Create & Access Both

Symlink

$ ln -s notes.txt link-s.txt $ ls -l link-s.txt lrwxrwxrwx 1 admin admin link-s.txt -> notes.txt $ cat link-s.txt Library opens at 9am

Hardlink

$ ln notes.txt link-h.txt $ ls -li link-h.txt 130910 -rw-r--r-- 2 admin admin link-h.txt $ cat link-h.txt Library opens at 9am

⚠️ Same inode (130910) for the hardlink; the symlink gets its own.

Delete the Original

Symlink

$ rm notes.txt $ cat link-s.txt cat: link-s.txt: No such file or directory $ ls -l link-s.txt lrwxrwxrwx 1 admin admin link-s.txt -> notes.txt

Hardlink

$ rm notes.txt $ cat link-h.txt Library opens at 9am $ ls -li link-h.txt 130910 -rw-r--r-- 1 admin link-h.txt

Why Symlinks & Hardlinks?

  • Names already locate files
  • So why need links at all?
  • One file, many paths
  • Hardlinks save real space
  • Symlinks cross drives/paths
  • Swap targets, keep same name

Why This Matters

  • Wrong access exposes the disk
  • Bad permissions are dangerous
  • Restrict device files to root

🔴 Red Team: A world-writable /dev/sda lets an attacker overwrite the whole disk directly.

🔵 Blue Team: Restrict device files to root/disk group; never widen /dev permissions.

Questions?

Ownership: Owner & Group

Multi-User History

  • Unix always was multi-user
  • Ownership prevents conflicts
  • Groups let teams share safely
1969Unix is born as atime-sharing system1973Owner-based permissionsare formalized in Unix1980sGroups added so teamscan share without "other"1988POSIX standardizesowner/group/other for all UnixTodayEvery Linux file stilluses this exact model

Ownership, Revisited

  • Ownership lives in the inode
  • Directory only holds the name
  • Metadata travels with the file
config.ymlOwneradminGroupdevteamOthereveryone else

Anatomy of ls -l Output

  • Permissions come first
  • Then owner, group, size, etc.
  • Order never changes
FieldExampleMeaning
Permissions-rw-r--r--type + rwx x3
Links1hardlink count
Owneradminwho owns it
Groupdevteamshared group
Size482bytes
Nameconfig.ymlthe filename

Command: stat

  • Create the file if missing
  • Shows far more than ls -l
  • Includes the inode number
$ touch config.yml $ stat config.yml File: config.yml Inode: 130842 Links: 1 Access: (0644/-rw-r--r--) Uid: (1001/admin) Gid: (1002/devteam)

Command: stat

$ touch config.yml $ stat config.yml File: config.yml Inode: 130842 Links: 1 Access: (0644/-rw-r--r--) Uid: (1001/admin) Gid: (1002/devteam)

Inode Metadata Revisited

  • stat reads the inode directly
  • ls -l only shows a summary
  • Same data, more detail
ls -l (summary view)Inode (owner, perms, times)stat (full detail view)

Command: id

  • Shows your numeric identity
  • uid = your user number
  • gid = primary group number
$ id uid=1001(admin) gid=1002(devteam) groups=1002(devteam),27(sudo)

Command: id

$ id uid=1001(admin) gid=1002(devteam) groups=1002(devteam),27(sudo)

Word Origin: "UID & GID"

  • Numeric ID behind every name
  • root is always UID 0
  • Names are just a lookup table
1970sUnix assigns a numberto every user account1988POSIX standardizesuid_t and gid_t typesToday/etc/passwd still mapsnames to these numbers

Practice: Who Owns This?

  • -rw-r----- alex staff notes
  • Who is the owner?
  • Who is the group?
notesOwneralexGroupstaffOtherothers

Blue = owner (alex) and group (staff), the two fields this line asks about

Owner & Group

alex : staff

Recall: chown Changes This

  • Module 2 already used chown
  • chown user:group file
  • Now you know WHY it matters
$ chown admin:devteam config.yml $ stat config.yml | grep Uid Uid: (1001/admin) Gid: (1002/devteam)

Recall: chown Changes This

$ chown admin:devteam config.yml $ stat config.yml | grep Uid Uid: (1001/admin) Gid: (1002/devteam)

Command: groups

  • Lists every group you're in
  • First is your primary group
  • Others are secondary groups
$ groups admin devteam sudo docker

Command: groups

$ groups admin devteam sudo docker

Why Ownership Matters

🔴 Red Team: A misconfigured owner can leave secrets readable by any account on the box.

🔵 Blue Team: Audit ownership on sensitive files regularly; prefer dedicated service accounts.

Questions?

Permission Bits: rwx

Who Should Read This?

  • Not all data should be public
  • Some scripts must stay locked
  • Wrong access causes breaches
secrets.txtOwnercan readGroupcan readOtherno access

Blue = owner and group, who CAN read this file; Other cannot

Read, Write & Execute

  • rwx means different things
  • on a file vs. a folder
  • x on a folder = can enter it
LetterOn a FileOn a Folder
rRead contentsList contents
wEdit contentsAdd/remove files
xRun as a programEnter with cd

The Numeric Version

  • r = 4, w = 2, x = 1
  • Add them up per role
  • rwx = 4+2+1 = 7
LetterValue
r4
w2
x1
-0

What Number Is r--?

  • Read only, nothing else
  • w and x are both off
  • Add the letter values

4

What Number Is r-x?

  • Read and execute
  • Write is off
  • Add the letter values

5

What Number Is rw-?

  • Read and write
  • Execute is off
  • Add the letter values

6

What Number Is rwx?

  • All three are on
  • Read, write, execute
  • Add the letter values

7

Symbolic vs. Octal

  • Letters or a digit, same idea
  • chmod accepts either form
  • Octal is faster to type
SymbolOctalMeaning
rwx7read + write + execute
rw-6read + write
r-x5read + execute
r--4read only

Recall: chmod Sets This

  • Module 2 already used chmod
  • chmod 770 file sets rwxrwx---
  • Now you know why it's 7
$ chmod 640 config.yml $ stat config.yml | grep Access Access: (0640/-rw-r-----)

Questions?

Practice Lab: Library

Scenario: The Library

  • You run the library file share
  • You do this on your own VM
  • Use your own real terminal
binetchomesrvusrvar/

Blue = /srv, where this lab's shared folder will actually live

Two Phases

  • First: build it solo
  • Then: fix it as a team
  • Same VM, same share
Phase 1Phase 2

Blue = the team phase you finish on

Three Library Roles

  • Cataloging: adds records
  • Circulation: check in / out
  • Archives: long-term store
/srv/librarycatalogingcirculationarchives

Roles will map to subfolders in Phase 2

Phase 1: Build the Share

Step 1: Make Library Dir

  • A shared folder for the lib
  • sudo needed for /srv
  • -p: no error if it exists
$ sudo mkdir -p /srv/library # -p also creates missing parent dirs

Step 1: Make Library Dir

$ sudo mkdir -p /srv/library # -p also creates missing parent dirs

Step 2: Check Who Owns It

  • New folders start as root
  • -d: the dir, not contents
  • Not usable by you yet
$ ls -ld /srv/library drwxr-xr-x 2 root root 4096 /srv/library # 2 = parent's entry for it, plus its own "." # not depth from /: every new dir starts at 2 # +1 for each subdir it holds (that subdir's "..") # 4096 = the entry list's size (4096 bytes, 4 KiB) # x on a folder = you may cd into it

Step 2: Check Who Owns It

$ ls -ld /srv/library drwxr-xr-x 2 root root 4096 /srv/library # 2 = parent's entry for it, plus its own "." # not depth from /: every new dir starts at 2 # +1 for each subdir it holds (its "..") # 4096 = the entry list's size (4096 bytes, 4 KiB) # x on a folder = you may cd into it

Check: Can You Write Yet?

  • You made /srv/library
  • Owner and group are root
  • You are only "other" here
fileOwnerrwxrootGroupr-xrootOtherr-xyou

Answer: other has no w, so writes fail

Step 3: Create the Group

  • One group for all lib staff
  • Every staff account joins it
  • groupadd needs sudo
$ sudo groupadd libstaff # groupadd makes the group, adds no members

Step 3: Create the Group

$ sudo groupadd libstaff # groupadd makes the group, adds no members

Step 4: Join the Group

  • -aG appends, never replaces
  • Log out/in for it to apply
  • groups confirms membership
$ sudo usermod -aG libstaff $USER $ groups libstaff sudo docker # -a appends; -G alone replaces your groups # $USER = your username, filled in by the shell

Step 4: Join the Group

$ sudo usermod -aG libstaff $USER $ groups libstaff sudo docker # -a appends; -G alone replaces your groups # $USER = your username, filled in by the shell

Check: Group Not Active

  • usermod added you to libstaff
  • Your shell has the old groups
  • What re-reads your groups?
usermod -aG libstaff youlog out and back inid now lists libstaff

Answer: group loads at the next login

Roles, Not People

  • Do not grant users one by one
  • Grant a role, add users to it
  • In Linux a group is a role
UsersRolesgroupsFolders

Blue = the role layer, the one thing you manage

Groups Are the Roles

  • libstaff: every staff account
  • cataloging / circ / archives
  • One person can hold many
libstaffcataloginga groupcirculationa grouparchivesa group

Each sub-team is its own group under libstaff

Why RBAC Scales

  • New hire: add to one group
  • Role changes: swap one group
  • Audit = list group members
per user x per folder = many grantsper role: a few groups to manage

Blue = RBAC: manage roles, not user-folder pairs

Users, Roles, Permissions

  • A user is put into roles
  • A role is a Linux group
  • Permissions sit on the role
  • carol holds two roles
  • Never grant a user a file
UsersRoles (groups)Permissionsalicecataloginggroupadd recordsrwx herebobcirculationgroupcheck in / outrwx herecarolarchivesgrouplong-term storerwx here

Dashed line: one user can hold more than one role

Step 5: Change Group Owner

  • Recall: chown changes both
  • chgrp changes just the group
  • Owner (root) stays the same
$ sudo chgrp libstaff /srv/library # chgrp changes the group only (chown does both)

Step 5: Change Group Owner

$ sudo chgrp libstaff /srv/library # chgrp changes the group only (chown does both)

Step 6: Set Permissions

  • 770: owner + group, no other
  • You already know this number
  • r+w+x = 7 for both roles
$ sudo chmod 770 /srv/library # digits are owner, group, other # 7 = rwx, 5 = r-x, 0 = ---

Step 6: Set Permissions

$ sudo chmod 770 /srv/library # digits are owner, group, other # 7 = rwx, 5 = r-x, 0 = ---

Check: What Does 770 Do?

  • You set the share to 770
  • Split it into three digits
  • Which role gets nothing?
fileOwnerrwx7Grouprwx7Other---0

Answer: owner and group full, other none

Check: What Does 000 Do?

  • You run chmod 000 on it
  • Owner, group, other: ---
  • Can even the owner open it?
fileOwner---0Group---0Other---0

Answer: nobody gets in; root and the owner can chmod it back

Step 7: Verify With ls -l

  • Confirm before moving on
  • Group should now be libstaff
  • Permissions should read 770
$ ls -ld /srv/library drwxrwx--- 2 root libstaff 4096 /srv/library # d = directory # then owner rwx, group rwx, other --- # root = owner, libstaff = group

Step 7: Verify With ls -l

$ ls -ld /srv/library drwxrwx--- 2 root libstaff 4096 /srv/library # d = directory # then owner rwx, group rwx, other --- # root = owner, libstaff = group

Step 8: Create the File

  • A real file inside the share
  • touch only creates it, empty
  • Everyone in libstaff can use
$ touch /srv/library/catalog.txt # also bumps the timestamp if it exists

Step 8: Create the File

$ touch /srv/library/catalog.txt # also bumps the timestamp if it exists

Check: Which Group?

  • You ran touch catalog.txt
  • Files take your primary group
  • Is that libstaff or staff?
/srv/librarycataloggrp stafflatergrp libstaff

Answer: primary group, not libstaff yet

Step 9: Check Its Metadata

  • Shows owner, inode, and time
  • Proves the file truly exists
  • More detail than ls -l alone
$ stat /srv/library/catalog.txt Inode: 55210 Links: 1 Access: (0644/-rw-r--r--) # Links = hard-link count (names on this inode) # 1 now; ln adds one, a symlink does not # file is gone only when the last name is removed (count 0) # 0644 octal = -rw-r--r-- in symbols

Step 9: Check Its Metadata

$ stat /srv/library/catalog.txt Inode: 55210 Links: 1 Access: (0644/-rw-r--r--) # Links = hard-link count (names on this inode) # 1 now; ln adds one, a symlink does not # file is gone only when the last name is removed (count 0) # 0644 octal = -rw-r--r-- in symbols

Step 10: Identify File Type

  • Confirms it truly has no data
  • Not just trusting the name
  • Not installed by default
$ sudo apt install -y file $ file /srv/library/catalog.txt catalog.txt: empty # -y = say yes to the install prompt # file checks the bytes, not the name

Step 10: Identify File Type

$ sudo apt install -y file $ file /srv/library/catalog.txt catalog.txt: empty # -y = say yes to the install prompt # file checks the bytes, not the name

Check: Name vs Content

  • The name ends in .txt
  • file read the bytes instead
  • Why not trust the name?
name says: catalog.txtfile says: empty

Answer: a name is a label, not proof

Step 11: Create a Symlink

  • A shortcut in your own home
  • Points at the shared file
  • ls -l shows the -> target
$ ln -s /srv/library/catalog.txt ~/catalog-link.txt $ ls -l ~/catalog-link.txt lrwxrwxrwx ... catalog-link.txt -> /srv/library/catalog.txt # -s = symbolic link: stores a path # leading l = it is a symlink

Step 11: Create a Symlink

$ ln -s /srv/library/catalog.txt ~/catalog-link.txt $ ls -l ~/catalog-link.txt lrwxrwxrwx ... catalog-link.txt -> /srv/library/catalog.txt # -s = symbolic link: stores a path # leading l = it is a symlink

Step 12: Create a Hardlink

  • A second name, same data
  • Survives if original deleted
  • Not a shortcut, real data
$ ln /srv/library/catalog.txt /srv/library/catalog-backup.txt # no -s = hardlink: same inode, new name

Step 12: Create a Hardlink

$ ln /srv/library/catalog.txt /srv/library/catalog-backup.txt # no -s = hardlink: same inode, new name

Check: Delete the Original

  • A hardlink shares the inode
  • A symlink stores only a path
  • You delete catalog.txt
  • Which one still opens?
catalog.txtbackup.txtinode 55210dataa hardlink is a name on the inodelink"/srv/library/catalog.txt"content: an absolute path stringthe symlink holds only that text

Answer: backup opens; the symlink now points at nothing

Step 13: Compare the Inodes

  • Both list the same number
  • Proves they share one file
  • The symlink's number differs
$ ls -li /srv/library/catalog* 55210 ... catalog.txt 55210 ... catalog-backup.txt # -i shows the inode number first # same number = the same file on disk

Step 13: Compare the Inodes

$ ls -li /srv/library/catalog* 55210 ... catalog.txt 55210 ... catalog-backup.txt # -i shows the inode number first # same number = the same file on disk

Step 14: Check Mount Point

  • Confirms which disk /srv uses
  • Same idea as Module 3, Item 1
  • Look at the Mounted on column
$ df -h /srv Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 13G 6G 69% / # -h = human sizes (K, M, G) # Mounted on / : /srv rides the root disk

Step 14: Check Mount Point

$ df -h /srv Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 13G 6G 69% / # -h = human sizes (K, M, G) # Mounted on / : /srv rides the root disk

Check: /srv On What Disk?

  • df -h /srv shows /dev/sda1
  • Mounted on column reads /
  • Is /srv its own disk?
/ is the root filesystem/srv is a folder inside it

Answer: no: /srv rides on the root disk

Step 15: Diagnose an Error

  • A classmate reports an error
  • "Permission denied" error
  • Check the folder, not the file
$ ls -ld /srv/library drwx------ 2 root libstaff 4096 /srv/library # drwx------ : only the owner can touch it

⚠️ Group lost its rwx bits -- someone ran chmod 700 by mistake.

Step 15: Diagnose an Error

$ ls -ld /srv/library drwx------ 2 root libstaff 4096 /srv/library # drwx------ : only the owner can touch it

Step 16: Fix Permissions

  • g+rwx adds back group access
  • Safer than retyping 770
  • Practice with symbolic chmod
$ sudo chmod g+rwx /srv/library $ ls -ld /srv/library drwxrwx--- 2 root libstaff 4096 /srv/library # g = group, +rwx = add; owner and other untouched

Step 16: Fix Permissions

$ sudo chmod g+rwx /srv/library $ ls -ld /srv/library drwxrwx--- 2 root libstaff 4096 /srv/library # g = group, +rwx = add; owner and other untouched

Check: Symbolic vs Numeric

  • chmod g+rwx added group bits
  • chmod 770 sets all three roles
  • When is g+rwx the safer pick?
chmod 770 -> replaces 9 bitschmod g+rwx -> edits group

Answer: g+rwx leaves owner and other alone

Phase 1: What You Built

  • /srv/library, group libstaff
  • Mode 770, a real file inside
  • One symlink, one hardlink
/srv/librarycatalog770backuphardlinklinksymlink

This is your Phase 1 end state

Now Work As a Team

Phase 2: Solve It Together

How Phase 2 Works

  • Each of you on your own VM
  • Talk through the approach
  • Try it, then check the key
  • Answers follow all 10
discusstrycheck key

Blue = the answer key at the end

Problem 1: New Staff

You were added to libstaff in Phase 1, but this shell opened before that, so writing to /srv/library still fails. Run newgrp libstaff (or log out and back in), then create a file in the share. In one sentence, say why the first attempt failed.

youshelllibstaffnot loaded/srv/library770

The shell opened before the group was added

Problem 2: Wrong Group

Cataloging made records.txt with group staff, so Circulation cannot edit it. Run sudo chmod g+s /srv/library so new files inherit libstaff, and fix the old file with sudo chgrp libstaff records.txt. Check that a brand-new file now shows group libstaff.

/srv/libraryrecordsgrp staffcataloggrp libstaff

New files inherit the creator primary group

Problem 3: Anyone Deletes

Everyone in libstaff has write on the share, so anyone can delete anyone's file. Add the sticky bit: sudo chmod +t /srv/library. Now try to delete a file a teammate owns — it should be refused. Confirm ls -ld shows drwxrws--T.

/srv/librarya.txtuser catb.txtuser circc.txtuser arch

Deleting a file needs write on the folder

Problem 4: Legacy Folder

The archives folder predates setgid, so its group is root and new files there miss libstaff. Fix the old files with sudo chgrp -R libstaff /srv/library/archives, then re-apply setgid: sudo chmod g+s /srv/library/archives. Verify with ls -lR that every line reads libstaff.

/srv/librarycataloginglibstaffcirculationlibstaffarchivesroot

setgid only affects files made after it was set

Problem 5: Broken Link

~/today.txt is a symlink showing red and "No such file" because its target was renamed. Run ls -l ~/today.txt to see the path it stores, then re-point it: ln -sfn /srv/library/<real-name> ~/today.txt. Confirm cat ~/today.txt works again.

linkpath texttarget renamed or goneX

A symlink stores a path string, not the file

Problem 6: Disk Is Full

df -h /srv reads 96% full. Archives made hardlink backups (cheap) but also cp-d some originals (real bytes). Run du -sh * in each folder and ls -li to spot files that share an inode. Report which files are true copies eating the space.

/ start70% full/ now96% full

Hardlinks add a name only; copies add real data

Problem 7: Wrong Disk

/srv/library is on the small root disk; a big /data disk is mounted. Write the ordered move: sudo mv /srv/library /data/library, then sudo ln -s /data/library /srv/library so the old path still works. Note which links break (hardlinks) and which survive (symlinks, data).

/ (sda1)96% full/data (sdb1)8% full

Inodes are per-filesystem; hardlinks cannot cross a mount

Problem 8: Read a Subdir?

circulation is set to 750 and Archives is in libstaff. Split 750 into owner / group / other and read the group digit (5 = r-x). Answer: can an Archives user cd into circulation and ls it? Can they add a file?

fileOwnerrwx7Groupr-x5Other---0

7 = rwx, 5 = r-x, 0 = --- : the group column decides

Problem 9: Root Owns It

policy.txt is -rw-r--r-- owned by root and staff must edit it. Do NOT run chmod 666 (that lets the whole world write). Instead: sudo chgrp libstaff policy.txt then sudo chmod g+w policy.txt. Confirm it ends -rw-rw-r--.

fileOwnerrw-rootGroupr--rootOtherr--world

chmod 666 would let the whole world write the policy

Problem 10: Final Audit

Produce one ls -lR /srv/library and explain every line: for each directory and file, say what the mode string grants and to whom (owner, libstaff, other). State clearly what "other" is allowed to do (nothing).

/srv/librarycatalogingdrwxrws--Tcirculationdrwxrws--Tarchivesdrwxrws--T

This is the state built across Problems 1 to 9

Answer Key

Answer 1: New Staff

  • Groups load at login only
  • newgrp libstaff or re-login
  • id must list libstaff
  • Then 770 lets them write
younew shelllibstaffloaded/srv/librarywrite ok

A fresh login re-reads group membership

Answer 2: Wrong Group

  • Set setgid on the dir
  • chmod g+s /srv/library
  • New files inherit libstaff
  • Old files: chgrp -R libstaff
fileOwnerrwxrootGrouprwss = setgidOther---none

setgid on a directory forces its group onto new files

Answer 3: Anyone Deletes

  • Add the sticky bit
  • chmod +t /srv/library
  • Only owner or root unlinks
  • ls shows drwxrws--T
fileOwnerrwxrootGrouprwssetgidOther--Tt = sticky

The sticky bit limits deletion to each file owner

Answer 4: Legacy Folder

  • chgrp -R libstaff archives
  • chmod -R g+w archives
  • Re-set setgid on the dir
  • Verify with ls -lR
/srv/librarycataloginglibstaffcirculationlibstaffarchiveslibstaff

Recursive chgrp fixes old files; setgid fixes new ones

Answer 5: Broken Link

  • Holds a path, not an inode
  • ln -s new-name ~/today.txt
  • Or restore the old filename
  • A hardlink survives a rename
symlink -> "returns.txt" (gone)recreate link OR restore name

Point the link at the new name, or rename the target back

Answer 6: Disk Is Full

  • Hardlinks share blocks: ls -li
  • du counts shared data once
  • The cp copies are the cost
  • Delete copies, keep the links
catalogcopyinode Ainode Bdata Adata Btwo copies, twice the space

Two copies use twice the blocks; two hardlinks use one set

Answer 7: Wrong Disk

  • Move dir to /data/library
  • Leave /srv/library as a link
  • Hardlinks break: recreate them
  • Symlinks and data survive
/srv/librarysymlink/data/libraryreal dir

A symlink at the old path keeps every reference working

Answer 8: Read a Subdir?

  • Group gets r-x on the dir
  • r lets them ls the names
  • x lets them cd into it
  • No w: they cannot add files
fileOwnerrwxownerGroupr-xArchivesOther---other

Read plus execute on a directory means list and enter, not modify

Answer 9: Root Owns It

  • sudo chgrp libstaff policy.txt
  • sudo chmod g+w policy.txt
  • Now -rw-rw-r--
  • Other stays read-only
fileOwnerrw-rootGrouprw-libstaffOtherr--world

Give the group write through group ownership, never through other

Answer 10: Final Audit

  • Dirs: drwxrws--T, grp libstaff
  • s=setgid, T=sticky, no other
  • Files: -rw-rw----, libstaff
  • World: no access anywhere
/srv/libraryfiles-rw-rw----dirsdrwxrws--Tgrouplibstaff

setgid keeps the group, sticky guards deletes, other is shut out

Team Debrief

  • setgid + sticky = safe share
  • Links: path vs inode
  • df / du before blaming backups
  • Group write, never world write
/srv/librarycatalogingokcirculationokarchivesok

Every role folder now shares safely

Phase 3: Design It on Paper

The Dining Hall

  • Campus dining hall, its data
  • You design the file layout
  • On paper only, no VM here
/srv/diningmenusposstaff...more

Same skills as Phase 1, a new scenario

Draw the Folder Tree

  • List every folder you need
  • Group data by who uses it
  • Give each folder a clear name
/srv/diningmenusrecipesposstaffHR

One folder per kind of record

Name the Roles

  • One group per job role
  • kitchen: menus & recipes
  • cashiers: the POS records
  • managers: reports & staff
  • diners: read the menu only
GroupsFolderskitchenmenus, recipescashiersposmanagersreports, staffdinersmenus (r--)

In Linux a group is the role

Set the Permissions

  • Mark rwx per role per folder
  • setgid keeps the group
  • sticky where all can write
  • menus folder: diners r--
pos/cashiersrwx7managersr-x5diners---0

Same 770 / setgid / sticky as Phase 1

Add Sample Files

  • Put 2-3 files per folder
  • week1-menu.md, chili.recipe
  • swipes-2026.csv under pos
  • Note who owns each file
recipes/chili.recipesoup.recipebread.recipe

Real names make the design concrete

What to Back Up?

  • Circle the folders to back up
  • recipes, pos, staff, reports
  • Skip caches and temp files
  • Where does changing data live?
Back upSkiprecipes/pos/staff/reports/cache/tmp/published menus

Back up what you cannot recreate

How Is It Used?

  • Which folder is read all day?
  • Which spikes at lunch rush?
  • Which needs the tightest lock?
  • Where do the logs go?
menus/read all day, few writespos/write spike at lunchstaff/rare, lock it down

Access pattern shapes the design

Phase 3 Deliverable

  • Hand in your paper diagram
  • A roles + permissions table
  • Your backup list
  • Your usage notes
submit.pdfdiagramtablebackupusage

One page or a photo, on Canvas

Phase 4: Class Project

Get the Repo

  • One repo for the whole class
  • Pull it onto your VM
  • Work lives in module-3
$ sudo apt install -y git $ git clone https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/modules/module-3

Repo: github.com/SE4CPS/2026-COMP-175

Get the Repo

$ sudo apt install -y git $ git clone https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/modules/module-3

Task 1: Build /srv/library

  • mkdir, group, join, chgrp
  • chmod 3770: setgid + sticky
  • stat reads drwxrws--T
sudo chmod 3770 /srv/librarydrwxrws--T libstaff

The Phase 1 + 2 end state, rebuilt for real

Task 2: Role Folders

  • mkdir the three subdirs
  • chgrp -R libstaff /srv/library
  • chmod 3770 on each one
/srv/librarycatalogingdrwxrws--Tcirculationdrwxrws--Tarchivesdrwxrws--T

Each role folder matches the parent

Task 3: Deploy Scripts

  • cp catalog-scripts/*.py in
  • chgrp libstaff, chmod 750
  • Run add_book.py to test it
cataloging/add_book.pylookup.pyoverdue.py

Real scripts, group-owned by libstaff

Task 4: Admin Banner

  • Append dotfiles/.bashrc
  • source it, open a new shell
  • Explain every line it prints
cat dotfiles/.bashrc >> ~/.bashrcsource ~/.bashrcbanner: id, df, /var

A real login habit: who am I, is the disk full

Task 5: Break and Diagnose

  • chmod 700 a role folder
  • Or break a symlink target
  • Write how you found the fix
chmod 700 /srv/library/circulationteammate: Permission deniedls -ld, then chmod g+rwx

Two or three sentences: how you diagnosed it

Task 6: Run verify.sh

  • bash class-project/verify.sh
  • Every line must read PASS
  • Fix each FAIL, run it again
  • Ends: All checks passed.
bash verify.shPASS x N -> submit

Green across the board means the share is done

Project Deliverable

  • ls -lR /srv/library output
  • verify.sh output, all PASS
  • Your banner + Task 5 write-up
  • One line per permission string
submit.txtls -lRverifyPASSbanner

One text file or PDF, submitted on Canvas

Deliverables

  • Shared folder, group, 770
  • Symlink and hardlink both work
  • Ready when instructor checks
catalogbackuplink/srv/library

Blue = catalog.txt, its hardlink (-backup), and its symlink (-link)

Questions?

Module 4

Access Control & Auditing

WHICH VM NEEDS THIS MODULE?Kali Linuxthe operator's seatssh clientnmap, security toolsauditor's vantage pointssh inUbuntu Serverthe managed systemsudoers, groupsACLs: getfacl / setfaclinotify watches this boxEvery command in this module configures Ubuntu.Kali is where you operate and verify from, not where changes happen.

All Commands: Module 4

ACCESS CONTROL: ONE GATE, THREE MODELSAccess requestThe Gate (Reference Monitor)DACowner decides: chmod, chownRBACrole decides: Linux groupsMACsystem decides: kernel policyThis module builds RBAC (groups, sudo) and adds Accounting (inotify)

Principle: Least Privilege

  • Grant only what's needed
  • Everything else: denied
  • Limits damage if compromised
✓backup.sh: granted✕payroll data: denied✕network config: denied✕user accounts: deniedOnly what's needed, nothing else.

Principle: Zero Trust

  • Verify every request, always
  • No standing trust, ever
  • Every check gets logged
Already authenticated onceZero trust checks again anywayResult: logged, not assumedMakes auditing and monitoring possible.

Subjects, Objects, Monitor

  • A subject wants to act
  • An object is the target
  • A monitor checks every ask
subject: a user or processreference monitor decidesobject: a file or resource

Word Origin: "Authorization"

auctor-
  • Latin: one who grants
-ize
  • to put into effect

Authentication proves who you are; authorization decides what that identity may do.

Check: DAC or MAC?

  • chmod 777: owner allows all
  • Policy can still block it
  • Which model wins here?
DAC: chmod 777owner says ALLOWEDMAC: policy still activekernel says NOResult: DENIED

Answer: the kernel policy has the final say

Real Software: PAM

  • Pluggable Auth Modules
  • Plugs auth into login, sudo
  • Config lives in /etc/pam.d
login or sudo asks to authenticatePAM runs its configured modulespassword, fingerprint, or 2FA check

What Is an ACL?

  • Extra rules past owner/group
  • Attached to the file itself
  • Names more than 3 parties
report.txtBase permissions (DAC)owner rw- / group r-- / other ---+ ACL entries (extra rules)user:daemon:rw-group:auditors:r--getfacl shows both; setfacl adds extras

ACL vs. DAC vs. RBAC

  • DAC: owner sets one triplet
  • ACL: DAC plus named extras
  • RBAC: groups define the role
DAC: Owner Decidesone rwx triplet, chmod/chownextendsACL: DAC, Extendednamed extras, getfacl/setfaclRBAC: Role DecidesLinux groups, gpasswd/groupsACL narrows one file; RBAC scales a role
HOW MAC COMPLEMENTS DAC & RBACAccess requestGate 1: DAC + RBACowner, group, ACL, role checksGate 2: MACkernel policy checks tooACCESS GRANTEDonly if both gates allowACCESS DENIEDeither gate can blockMAC never grants more than DAC/RBAC allow; it only adds a restriction.
MAC: EVEN ROOT CAN BE DENIEDRoot process wants:write /etc/shadowDAC: root bypasses owner checksnormally: ALLOWEDMAC: policy restricts this processto /var/www onlyResult: DENIEDeven though DAC said yesThis is exactly why MAC exists: DAC alone trusts root completely.

Dining Hall: The Problem

  • Kitchen group owns the file
  • Purchasing needs read-only
  • Group membership is too broad
inventory-count.txtOwner: kitchen-mgr (rw-)Group: kitchen (rw-), other: ---Purchasing analystnot in kitchen groupso: currently NO ACCESSAdding them to the group over-grants

Dining Hall: After ACL

  • One ACL rule solves it
  • Owner and group untouched
  • Revoke later with setfacl -x
inventory-count.txtOwner: kitchen-mgr (rw-)Group: kitchen (rw-), other: ---+ ACL: user:analystr-- (read-only)one entry, nothing else changesRevoke anytime with setfacl -x

Not Installed by Default

  • getfacl/setfacl need a pkg
  • Debian/Ubuntu: apt install acl
  • Kali has it too
$ sudo apt install -y acl # -y = auto-confirm install (no interactive prompt)

Not Installed by Default

$ sudo apt install -y acl # -y = auto-confirm install (no interactive prompt)

See a File's Full ACL

  • Shows owner, group, extras
  • Base three print by default
  • Empty means no ACL yet
$ touch /tmp/report.txt $ chmod 640 /tmp/report.txt # 640 = rw-r----- (group read, others none) $ getfacl /tmp/report.txt # no flags: print the file's full ACL user::rw- group::r-- other::---

⚠️ Uses /tmp on purpose: WSL's Windows-mounted drives (/mnt/c/...) don't support ACLs at all, wherever else on your system you might try this.

See a File's Full ACL

$ touch /tmp/report.txt $ chmod 640 /tmp/report.txt # 640 = rw-r----- (group read, others none) $ getfacl /tmp/report.txt # no flags: print the file's full ACL user::rw- group::r-- other::---

Grant One More Person

  • -m modifies the ACL
  • u:name:perms adds a rule
  • Owner and group untouched
$ setfacl -m u:daemon:rw /tmp/report.txt # -m modifies the ACL; owner needs no sudo # daemon: a real account on every Linux box $ getfacl /tmp/report.txt user:daemon:rw-

Grant One More Person

$ setfacl -m u:daemon:rw /tmp/report.txt # -m modifies the ACL; owner needs no sudo # daemon: a real account on every Linux box $ getfacl /tmp/report.txt user:daemon:rw-

Without ACL

$ getfacl /tmp/report.txt # no flags: print the file's full ACL user::rw- group::r-- other::--- # daemon has no rule: not in the list

With ACL

$ setfacl -m u:daemon:rw /tmp/report.txt # -m modifies the ACL; owner needs no sudo $ getfacl /tmp/report.txt user::rw- group::r-- user:daemon:rw- other::--- # daemon now has its own explicit rule

⚠️ ALLOWED here isn't final: MAC still checks afterward and can still deny it.

Without ACL

$ getfacl /tmp/report.txt # no flags: print the file's full ACL user::rw- group::r-- other::--- # daemon has no rule: not in the list

With ACL

$ setfacl -m u:daemon:rw /tmp/report.txt # -m modifies the ACL; owner needs no sudo $ getfacl /tmp/report.txt user::rw- group::r-- user:daemon:rw- other::--- # daemon now has its own explicit rule

Without ACL

$ setfacl -x u:daemon /tmp/report.txt # -x removes daemon's entry, if any $ sudo -u daemon test -r /tmp/report.txt \ && echo OK || echo DENIED # -u: run it as daemon (more on sudo soon) # test -r: exit 0 if readable, nonzero if not DENIED

With ACL

$ setfacl -m u:daemon:rw /tmp/report.txt # -m grants daemon read+write $ sudo -u daemon test -r /tmp/report.txt \ && echo OK || echo DENIED # test -r: exit 0 if readable, nonzero if not OK

⚠️ Uses /tmp, not your home folder: a private home directory (mode 750) blocks daemon before it ever reaches the file's own ACL.

Without ACL

$ setfacl -x u:daemon /tmp/report.txt # -x removes daemon's entry, if any $ sudo -u daemon test -r /tmp/report.txt \ && echo OK || echo DENIED # -u: run it as daemon (more on sudo soon) # test -r: exit 0 if readable, nonzero if not DENIED

With ACL

$ setfacl -m u:daemon:rw /tmp/report.txt # -m grants daemon read+write $ sudo -u daemon test -r /tmp/report.txt \ && echo OK || echo DENIED # test -r: exit 0 if readable, nonzero if not OK

What Is the ACL Mask?

  • Caps group + named entries
  • Owner and other skip it
  • Auto-set by setfacl -m
user::rw-user:daemon:rw-group::r--mask::rw-other::---maskedOwner (user::) and other:: skip the mask.

Setting the Mask

  • m:: or mask:: both work
  • Caps every named entry
  • Recalculates when ACLs change
$ setfacl -m m::rw- /tmp/report.txt # m:: sets the mask directly $ getfacl /tmp/report.txt user::rw- user:daemon:rw- group::r-- mask::rw- other::---

Setting the Mask

$ setfacl -m m::rw- /tmp/report.txt # m:: sets the mask directly $ getfacl /tmp/report.txt user::rw- user:daemon:rw- group::r-- mask::rw- other::---

When the Mask Contradicts

  • Entry still lists rwx
  • Mask caps what's granted
  • #effective shows the truth
$ setfacl -m m::r-- /tmp/report.txt # narrows the mask; daemon's entry is unchanged $ getfacl /tmp/report.txt user:daemon:rw- #effective:r-- mask::r-- # daemon still SAYS rw-, but write is masked out

When the Mask Contradicts

$ setfacl -m m::r-- /tmp/report.txt # narrows the mask; daemon's entry is unchanged $ getfacl /tmp/report.txt user:daemon:rw- #effective:r-- mask::r-- # daemon still SAYS rw-, but write is masked out

chmod Changes the Mask Too

  • chmod g+w hits the mask
  • Not the group:: line
  • Surprising once ACLs exist
$ chmod g+w /tmp/report.txt # looks like it changes the group, but... $ getfacl /tmp/report.txt group::r-- mask::rw- # mask moved, group:: line did not

⚠️ Once a file has an ACL, plain chmod on the group bits edits the mask, not group::.

chmod Changes the Mask Too

$ chmod g+w /tmp/report.txt # looks like it changes the group, but... $ getfacl /tmp/report.txt group::r-- mask::rw- # mask moved, group:: line did not

Questions?

Users, Groups & sudo

FROM USER TO PRIVILEGEalicea human usermember of registrara group is a rolesudo grants one scriptnot full rootrootfull privilege, kept narrowRBAC (the group) plus a narrow sudo rule beats logging in as root

Why Not Log In as root?

  • root can do anything at all
  • One mistake, no undo
  • sudo logs who did what
logged in as root, alwaysone typo can wipe the diskno record of which admin

Who Am I Right Now?

  • Prints your effective user
  • Useful inside scripts
  • Differs once you sudo
$ whoami # prints the currently logged-in username alice

Who Am I Right Now?

$ whoami # prints the currently logged-in username alice

Logged In as root

$ whoami root # every command now runs as root # nothing records who you really are

Using sudo Instead

$ whoami alice $ sudo whoami root # sudo logs this command's use # you're alice again right after

⚠️ Root leaves no name behind: sudo's log is what proves who ran it.

Logged In as root

$ whoami root # every command now runs as root # nothing records who you really are

Using sudo Instead

$ whoami alice $ sudo whoami root # sudo logs this command's use # you're alice again right after

Switching Identity: su

  • su alone targets root
  • su - name loads their shell
  • Needs that user's password
$ sudo useradd -m registrar_admin # -m also creates their home directory $ sudo passwd registrar_admin # sets their password (prompts interactively) $ su - registrar_admin # - = login shell (loads registrar_admin's own env) Password: $ exit

Switching Identity: su

$ sudo useradd -m registrar_admin # -m also creates their home directory $ sudo passwd registrar_admin # sets their password (prompts interactively) $ su - registrar_admin # - = login shell (loads registrar_admin's own env) Password: $ exit

sudo -i: A Root Shell

  • Full shell, like su -
  • Uses YOUR password though
  • sudo logs who started it
$ sudo -i # -i starts a full root login shell root@host:~# whoami root root@host:~# exit # back to alice, your own prompt

⚠️ Commands typed inside aren't individually logged; exit as soon as you're done.

sudo -i: A Root Shell

$ sudo -i # -i starts a full root login shell root@host:~# whoami root root@host:~# exit # back to alice, your own prompt

Reading a sudoers Line

  • Who: a user or %group
  • Where: ALL hosts
  • As whom, running what
%registrarALL=(root)backup.sh

Editing sudoers Safely

  • visudo locks the file
  • Checks syntax before saving
  • Never edit sudoers directly
$ sudo groupadd registrar # creates the group this rule targets $ sudo visudo # opens /etc/sudoers safely with syntax checking %registrar ALL=(root) NOPASSWD: \ /usr/local/bin/backup.sh # %group ALL=(role) NOPASSWD: cmd -- no password prompt

Editing sudoers Safely

$ sudo groupadd registrar # creates the group this rule targets $ sudo visudo # opens /etc/sudoers safely with syntax checking %registrar ALL=(root) NOPASSWD: \ /usr/local/bin/backup.sh # %group ALL=(role) NOPASSWD: cmd -- no password prompt

sudo

$ sudo whoami root # runs ONE command as root

visudo

$ sudo visudo # opens /etc/sudoers itself, safely

⚠️ A broken /etc/sudoers can lock out ALL sudo access; visudo checks syntax before saving so that can't happen.

sudo

$ sudo whoami root # runs ONE command as root

visudo

$ sudo visudo # opens /etc/sudoers itself, safely

What Can I Run?

  • Lists your sudo rules
  • Shows allowed commands
  • Good first debugging step
$ sudo -l # -l lists what commands you're allowed to run User alice may run: (root) /usr/local/bin/backup.sh

What Can I Run?

$ sudo -l # -l lists what commands you're allowed to run User alice may run: (root) /usr/local/bin/backup.sh

Real sudo -l Output

  • Defaults: config, not a grant
  • (ALL : ALL) ALL = full access
  • Common on your own dev VM
$ sudo -l Matching Defaults entries for alice: secure_path=/usr/sbin:/usr/bin:/sbin:/bin User alice may run the following commands: (ALL : ALL) ALL # any user, any group, any command

Real sudo -l Output

$ sudo -l Matching Defaults entries for alice: secure_path=/usr/sbin:/usr/bin:/sbin:/bin User alice may run the following commands: (ALL : ALL) ALL # any user, any group, any command

On the Registrar Server

$ sudo -l User alice may run: (root) /usr/local/bin/backup.sh # one script, nothing else

On Your Own Dev VM

$ sudo -l User alice may run the following commands: (ALL : ALL) ALL # every command, as anyone

⚠️ Scope matters: the same person can hold a narrow grant on one box and full access on another.

On the Registrar Server

$ sudo -l User alice may run: (root) /usr/local/bin/backup.sh # one script, nothing else

On Your Own Dev VM

$ sudo -l User alice may run the following commands: (ALL : ALL) ALL # every command, as anyone

Word Origin: "sudo"

su
  • already meant "switch user"
do
  • "do" this one thing as them

Read aloud as "superuser do": run one command with another user's privilege.

su -

$ su - registrar_admin Password: $ whoami registrar_admin $ exit # stays as registrar_admin until exit # needs registrar_admin's password

sudo

$ sudo whoami root # runs just this one command # needs YOUR OWN password instead

su -

$ su - registrar_admin Password: $ whoami registrar_admin $ exit # stays as registrar_admin until exit # needs registrar_admin's password

sudo

$ sudo whoami root # runs just this one command # needs YOUR OWN password instead

Check: sudo vs. su

  • sudo: one command, logged
  • su: a whole new shell
  • Which fits a backup script?
sudo: one command, logged

Answer: sudo; it runs just that script and records who ran it

Running as Someone Else

  • -u picks the target user
  • Still needs a sudoers rule
  • Not always root
$ sudo -u www-data whoami # -u runs the command as another user (www-data) www-data

Running as Someone Else

$ sudo -u www-data whoami # -u runs the command as another user (www-data) www-data

Managing Group Membership

  • -a adds, -d removes
  • Cleaner than usermod -aG
  • Confirm with groups
$ sudo gpasswd -a alice registrar # -a adds alice to the registrar group $ groups alice alice : registrar

Managing Group Membership

$ sudo gpasswd -a alice registrar # -a adds alice to the registrar group $ groups alice alice : registrar

usermod -aG

$ sudo usermod -aG registrar alice # -aG appends; omit -a and it WIPES # alice's other groups if you forget it

gpasswd -a

$ sudo gpasswd -a alice registrar # -a only ever adds this one group $ sudo gpasswd -d alice registrar # -d removes it just as safely

⚠️ Forgetting -a on usermod -aG can wipe every other group alice already had.

usermod -aG

$ sudo usermod -aG registrar alice # -aG appends; omit -a and it WIPES # alice's other groups if you forget it

gpasswd -a

$ sudo gpasswd -a alice registrar # -a only ever adds this one group $ sudo gpasswd -d alice registrar # -d removes it just as safely

Questions?

Questions?

AUTHENTICATION, AUTHORIZATION, ACCOUNTINGAuthentication: who you arewhoami, loginAuthorization: what you may dochmod, groups, sudoersAccounting: what you didlast, lastlog, inotifyThis item is about Accounting: why a record has to exist at all

Why Audit?

  • Prevention can still fail
  • Logs show who did what
  • Append-only, hard to change
  • Needed for compliance
Someone changes a fileinotify captures the eventAppended to a locked logYou review, alert, report

The AAA Model, Revisited

  • Authentication: who you are
  • Authorization: what you may do
  • Accounting: what you did
AuthenticationAuthorizationAccounting (audit)

Who Requires Audit Logs?

  • FERPA: student records
  • PCI-DSS: payment data
  • NIST 800-53: federal systems
FERPAPCI-DSSNIST 800-53all require: who, what, when

Frameworks That Require It

  • Each names what to log
  • None specifies the tool
  • inotify satisfies file logging
FrameworkProtects
FERPAStudent education records
PCI-DSSCard payment data
NIST SP 800-53Federal information systems

Who's On Right Now?

  • Shows logged-in sessions
  • Works on Kali and Ubuntu
  • No install needed
$ who # no flags: shows who is logged in right now alice pts/0 2026-09-12 09:15

Who's On Right Now?

$ who # no flags: shows who is logged in right now alice pts/0 2026-09-12 09:15

What Is Everyone Doing?

  • Adds idle time and load
  • WHAT column shows the shell
  • Good first audit glance
$ w # no flags: who's on, plus load and idle time 09:44 up 1:10, 1 user, load avg: 0.31 USER TTY LOGIN@ IDLE WHAT alice pts/0 09:15 0.02s -bash

What Is Everyone Doing?

$ w # no flags: who's on, plus load and idle time 09:44 up 1:10, 1 user, load avg: 0.31 USER TTY LOGIN@ IDLE WHAT alice pts/0 09:15 0.02s -bash

Word Origin: "Audit"

audire
  • Latin: to hear
-it
  • one who listens, examines

An auditor originally "heard" accounts read aloud; inotify listens for file events instead.

Check: What's in the Log?

  • Who did it
  • What they did, and when
  • Not: their plaintext password
who, what, when: yes

Answer: who/what/when belong in the log; secrets like passwords never do

Questions?

Watching Files with inotify

HOW inotify CAPTURES AN EVENTA watched action happensThe kernel's inotify hook firesEvent is appended to the loggrep / inotifywatch read it backinotifywait -e sets which actions trigger step two

History of inotify

  • dnotify arrives, 1998
  • inotify merged in 2005
  • Now everyone's file watcher
1998dnotify added to Linux 2.4:directories only, keeps files open2005inotify merged into kernel2.6.13, a cleaner replacement2006inotify-tools brings it to theshell: inotifywait, inotifywatch2010sBecomes the backbone ofsystemd, Docker, dev toolsTodayThe standard way Linuxwatches files, still maintained

What inotify Watches

  • Files and directories
  • Create, modify, delete
  • Attribute and rename too
createmodifydelete

Installing inotify-tools

  • Not on Ubuntu/Kali by default
  • One package, two tools
  • No service to enable
$ sudo apt install -y inotify-tools # -y = auto-confirm install (no interactive prompt)

Installing inotify-tools

$ sudo apt install -y inotify-tools # -y = auto-confirm install (no interactive prompt)

Is inotify Available?

  • No service to check
  • Kernel feature, always on
  • Confirm your watch limit
$ cat /proc/sys/fs/inotify/max_user_watches # no flags: prints your watch-count limit 524288

Is inotify Available?

$ cat /proc/sys/fs/inotify/max_user_watches # no flags: prints your watch-count limit 524288

Watch a File or Folder

  • -m keeps watching (monitor)
  • -e picks which events
  • & backgrounds it
$ sudo mkdir -p /srv/registrar # creates the watched folder first $ inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log & # -m keeps watching; -e picks event types

Watch a File or Folder

$ sudo mkdir -p /srv/registrar # creates the watched folder first $ inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log & # -m keeps watching; -e picks event types

Finding an Event

  • grep filters lines by text
  • Search for a filename
  • Same tool from Module 2
$ grep test.txt /tmp/registrar-watch.log # reuses grep from earlier: no new command /srv/registrar/ CREATE test.txt

Finding an Event

$ grep test.txt /tmp/registrar-watch.log # reuses grep from earlier: no new command /srv/registrar/ CREATE test.txt

Confirming a Write Happened

  • Confirms the write happened
  • No need to read whole log
  • Great for quick spot-checks
inotifywait watches /srv/registrartouch test.txt creates the fileEvent line appended to the loggrep test.txt searches the log/srv/registrar/ CREATE test.txtOne line confirms the whole watch worked.

A Readable Summary

  • Counts events per file
  • -e limits which types count
  • Runs until you press Ctrl+C
$ inotifywatch -e create,modify /srv/registrar # runs until Ctrl+C, then prints a table total create modify filename 2 1 1 test.txt

A Readable Summary

$ inotifywatch -e create,modify /srv/registrar # runs until Ctrl+C, then prints a table total create modify filename 2 1 1 test.txt
HOW inotify HEARS A KERNEL EVENTKERNEL SPACEUSERSPACEtouch test.txt runsinotifywait already listeningKernel detects inode changeEvent queued: the messageread() unblocks: event receivedPrinted as a log line / tableinotifywait and inotifywatch don't poll; the kernel wakes them.This is what makes inotify efficient: no busy-waiting.

Reading the Raw Log

  • -f follows new lines live
  • Same log grep reads
  • Useful while testing a watch
$ tail -f /tmp/registrar-watch.log # -f follows the log live as new lines arrive

Reading the Raw Log

$ tail -f /tmp/registrar-watch.log # -f follows the log live as new lines arrive

Keeping the Watch Running

  • nohup survives a closed shell
  • disown detaches the job
  • A reboot still kills it
$ nohup inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log & $ disown # nohup+disown: survives logout, not a reboot

Keeping the Watch Running

$ nohup inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log & $ disown # nohup+disown: survives logout, not a reboot

Choosing Which Events

  • create, modify, delete
  • attrib: permission changes
  • move_to / move_from: renames
$ inotifywait -m \ -e create,delete,attrib \ /srv/registrar & # -e takes a comma list, mix freely

Choosing Which Events

$ inotifywait -m \ -e create,delete,attrib \ /srv/registrar & # -e takes a comma list, mix freely

Reading an inotify Line

  • Directory: where it happened
  • Event: what happened
  • Filename: which file
/srv/registrar/CREATEtest.txt
WHAT AN inotify LOG LINE SHOWS✓ CAPTURED BY inotifyDIRECTORY/srv/registrar/EVENTCREATEFILENAMEtest.txtA TRADITIONAL AUDIT LOG ALSO SHOWS:?WHOnot captured?PERMITTED?not capturedinotify only logs actions that already happened.A denied attempt produces no event at all.

Word Origin: "inotify"

inode
  • a file's unique record
notify
  • tell me when it changes

Get notified the instant an inode -- a file or folder -- changes.

Check: Watch or Search?

  • Start watching a folder
  • Search what's already logged
  • inotifywait, or grep?
inotifywait watches; grep searches

Answer: inotifywait -m starts watching; grep finds it in the log afterward

Questions?

Practice Lab

THE REGISTRAR SERVER, AT A GLANCE/srv/registrarregistrar groupRBAC: who belongssudoers: one scriptprivilege, narrowinotifywait -m -eaccounting: every write

Scenario: Registrar Server

  • /srv/registrar holds records
  • Staff need a narrow sudo rule
  • Every write must be logged
/srv/registrarregistrar groupinotify watch

Why Group Registrar Staff?

  • One rule, many staff members
  • Add or remove people freely
  • Policy stays the same
before: one rule per person✓rule 1✓rule 2✓rule 3after: one group, one ruleregistrar group✓alice✓carol✓dan

Step 1: Make the Group

  • One group for registrar staff
  • groupadd needs sudo
  • Adds no members yet
$ sudo groupadd registrar # creates a new group named registrar

Step 1: Make the Group

$ sudo groupadd registrar # creates a new group named registrar

Why Not Give Full Root?

  • Full root: any command, ever
  • Staff only need one script
  • Narrow rules limit the risk
full rootevery command unlockedthis sudoers ruleonly backup_registrar.shregistrar groupgets the narrow key only

You, Setting This Up

$ sudo -i # broad, ongoing access while building

Registrar Staff

$ sudo /usr/local/bin/backup_registrar.sh # narrow: only this one script

⚠️ Never hand staff sudo -i as their everyday access; the narrow rule is the point of this lab.

You, Setting This Up

$ sudo -i # broad, ongoing access while building

Registrar Staff

$ sudo /usr/local/bin/backup_registrar.sh # narrow: only this one script

Step 2: Grant One Script

  • tee writes the file directly
  • chmod 440 or sudo ignores it
  • visudo -c -f: no editor opens
$ sudo tee /etc/sudoers.d/registrar << 'EOF' %registrar ALL=(root) NOPASSWD: \ /usr/local/bin/backup_registrar.sh EOF $ sudo chmod 440 /etc/sudoers.d/registrar # 440: sudo ignores the file otherwise $ sudo visudo -c -f /etc/sudoers.d/registrar # -c -f checks syntax, no editor opens

Step 2: Grant One Script

$ sudo tee /etc/sudoers.d/registrar << 'EOF' %registrar ALL=(root) NOPASSWD: \ /usr/local/bin/backup_registrar.sh EOF $ sudo chmod 440 /etc/sudoers.d/registrar # 440: sudo ignores the file otherwise $ sudo visudo -c -f /etc/sudoers.d/registrar # -c -f checks syntax, no editor opens

Why Watch at All?

  • Actions happen with no witness
  • Nothing is watching by default
  • Accounting needs a live watch
/srv/registrar?no witness (not watching)/srv/registrar👁inotify logs it

Step 3: Install the Watcher

  • Not installed by default
  • One package, two tools
  • No service to enable
$ sudo apt install -y inotify-tools # -y = auto-confirm install (no interactive prompt)

Step 3: Install the Watcher

$ sudo apt install -y inotify-tools # -y = auto-confirm install (no interactive prompt)

Who Can Touch This Folder?

  • Owner alone isn't enough
  • Group ownership plus chmod
  • Writes must be watched too
/srv/registrarregistrar group (mode 2770)✓alice✓carol✕danblocked

newgrp vs. groupadd

  • groupadd creates the group
  • Shell loaded groups at login
  • newgrp refreshes it now
/etc/group: registrar has aliceOld shellstill: no registraropen before gpasswdNew shellhas registrar nowstarted by newgrpGroups only reload when a new shell starts.

Step 4: Watch the Folder

  • Join registrar group first
  • Install newgrp, then apply it
  • -e picks event types
$ sudo gpasswd -a $(whoami) registrar # adds you to the group so you can watch it $ sudo apt install -y util-linux-extra # newgrp isn't installed on every distro $ newgrp registrar # newgrp reloads this shell; groupadd made it $ sudo mkdir -p /srv/registrar $ sudo chgrp registrar /srv/registrar $ sudo chmod 2770 /srv/registrar # 2770 = rwxrws--- (registrar group can write) $ inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log &

Step 4: Watch the Folder

$ sudo gpasswd -a $(whoami) registrar # adds you to the group so you can watch it $ sudo apt install -y util-linux-extra $ newgrp registrar # newgrp reloads this shell; groupadd made it $ sudo mkdir -p /srv/registrar $ sudo chgrp registrar /srv/registrar $ sudo chmod 2770 /srv/registrar $ inotifywait -m -e create,modify \ /srv/registrar >> /tmp/registrar-watch.log &

Does the Rule Really Work?

  • An untested rule is a guess
  • Trigger it, search the log
  • The key ties event to rule
test.txtwatch.loga write event lands heregrep finds it

Step 5: Append, No Editor

  • No editor touches this file
  • Creates the file if missing
  • Counts as a modify event
$ echo "New patron: J. Smith" \ >> /srv/registrar/test.txt

Step 5: Append, No Editor

$ echo "New patron: J. Smith" \ >> /srv/registrar/test.txt # appends; no editor ever opened

Step 6: Trigger and Confirm

  • Step 5 already made the edit
  • Search the log for its name
  • You should see the modify
$ grep test.txt /tmp/registrar-watch.log # reuses grep from earlier: no new command

Step 6: Trigger and Confirm

$ grep test.txt /tmp/registrar-watch.log # finds the echo append from Step 5

Check: Who Can Run It?

  • Group registrar has the rule
  • bob is not in that group
  • Can bob run the script?
No: the rule is group-scoped

Answer: no; only members of registrar inherit the sudoers rule

Did It Actually Stick?

  • chmod ran, but did it apply?
  • getfacl shows the real state
  • Compare it to what you meant
chmod 2770?getfaclgroup::rwxthe real, current statea command you ran is a claim;getfacl is the proof

Step 7: Verify with ACLs

  • Confirm the group can write
  • getfacl shows every rule
  • Compare to your sudoers line
$ getfacl /srv/registrar # no flags: print the directory's full ACL group::rwx

Step 7: Verify with ACLs

$ getfacl /srv/registrar # no flags: print the directory's full ACL group::rwx

Deliverables

  • A groupadd + visudo screenshot
  • Your watch.log showing a write
  • grep output finding that write
sudoersinotifywaitgrep

Questions?

Practice Lab Part 2

The Two-VM Setup

  • Kali: where you run commands
  • Ubuntu: the clinic server
  • SSH connects the two
Kaliyou run commandssshUbuntuclinic-recordsKali runs commands; Ubuntu holds the data

Clone the Project

  • Real, synthetic sample data
  • One-time download
  • Everything else builds on it
$ sudo apt install -y git $ git clone https://github.com/SE4CPS/2026-COMP-175.git

Sample data: github.com/SE4CPS/2026-COMP-175

Clone the Project

$ sudo apt install -y git # not installed on every minimal image $ git clone https://github.com/SE4CPS/2026-COMP-175.git # pulls the real, synthetic sample files

Create the Sample Files

  • Set up /srv/patient-records
  • You own the whole tree
  • Ready for every problem below
$ sudo mkdir -p /srv/patient-records $ sudo cp -r \ ~/2026-COMP-175/modules/module-4/lab2/sample-data/* \ /srv/patient-records/ $ sudo chown -R $(whoami) /srv/patient-records

Create the Sample Files

$ sudo mkdir -p /srv/patient-records # the tree the sample data copies into $ sudo cp -r \ ~/2026-COMP-175/modules/module-4/lab2/sample-data/* \ /srv/patient-records/ # record.txt, today/invoice.txt, notes.txt $ sudo chown -R $(whoami) /srv/patient-records # you own it now; setfacl below needs no sudo

Meet Clinic Records

  • Lives at /srv/patient-records
  • 4 groups: role by role
  • You never open the files
/srv/patient-recordsphysiciansnursesbillingadminFour groups, one folder tree

Create the Groups

  • Four roles, four real groups
  • One groupadd per role
  • Confirm each one exists
$ sudo groupadd physicians $ sudo groupadd nurses $ sudo groupadd billing $ sudo groupadd admin $ getent group nurses

Create the Groups

$ sudo groupadd physicians # creates the physicians group $ sudo groupadd nurses # creates the nurses group $ sudo groupadd billing # creates the billing group $ sudo groupadd admin # creates the admin group $ getent group nurses # confirms the group now exists

Seed a Broken Link

  • A link already exists
  • Its target is outside records
  • Problem 13 traces + fixes it
$ sudo ln -s /etc/hostname \ /srv/patient-records/today/shortcut

Seed a Broken Link

$ sudo ln -s /etc/hostname \ /srv/patient-records/today/shortcut # pretend IT made this link; wrong target

Command-Only: No Edits

  • Manage access, not content
  • No editors on patient files
  • Every change is a command
✕Text editors: never✓Admin commands: always

Problem 1: Who Am I?

  • Freshly logged into the VM
  • Get your bearings first
  • How would you address this?
You?whoami

Options: Who Am I?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
AwhoamiBsudo su -Ccat /etc/shadow

The Fix: Who Am I?

  • A is correct: just one command
  • B: full root, not needed here
  • C touches a sensitive file
$ whoami

The Fix: Who Am I?

$ whoami # prints the currently logged-in user # works on any account, nothing assumed

Problem 2: Who Else Here?

  • Before creating any account
  • See who already exists
  • How would you address this?
You?user list

Options: Who Else Here?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Acat /etc/passwdBwhoCls /home

The Fix: Who Else Here?

  • A is correct: lists everyone
  • B shows online users, not all
  • C misses some real accounts
$ cat /etc/passwd

⚠️ This lists every account on the VM, including built-in system accounts like daemon and bin, not just ones you created.

The Fix: Who Else Here?

$ cat /etc/passwd # one line per account on this VM # username, uid, gid, home, shell # includes system accounts, not just yours

Problem 3: Read the Manual

  • Unsure what setfacl does
  • man isn't installed yet
  • How would you address this?
You?man setfacl

Options: Read the Manual

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Aman setfaclBapt install man-db; man setfaclCguess from the command name

The Fix: Read the Manual

  • B is correct: install first
  • A: man isn't there by default
  • C: guessing risks mistakes
$ sudo apt install -y man-db $ man setfacl

The Fix: Read the Manual

$ sudo apt install -y man-db # man-db isn't installed by default $ man setfacl # opens the real manual; q to quit

Problem 4: Practice setfacl

  • The manual gave you the syntax
  • Try it: grant daemon read only
  • daemon: a real system account
  • Owns background services
  • How would you address this?
You?record.txt

Options: Practice setfacl

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asetfacl daemon r-- record.txtBsetfacl -m u:daemon:r-- record.txtCsetfacl -m daemon:r-- record.txt

The Fix: Practice setfacl

  • B is correct: real syntax
  • A is missing -m: bad syntax
  • C is missing the u: prefix
$ setfacl -m u:daemon:r-- \ /srv/patient-records/record.txt $ getfacl /srv/patient-records/record.txt

The Fix: Practice setfacl

$ setfacl -m u:daemon:r-- \ /srv/patient-records/record.txt # -m modifies; u:daemon:r-- grants read only $ getfacl /srv/patient-records/record.txt # confirms the new rule is really there

Problem 5: New Nurse

  • Dana joins the nursing staff
  • Needs today's patients only
  • How would you address this?
Dana?today/

Options: New Nurse

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Achmod 777 /srv/patient-records/todayBgpasswd -a dana nursesCsudo cp -r today /home/dana

The Fix: New Nurse

  • B is correct: join the group
  • A opens it to everyone
  • C copies data out, no access
$ sudo useradd -m dana $ sudo gpasswd -a dana nurses

The Fix: New Nurse

$ sudo useradd -m dana # creates dana's account first $ sudo gpasswd -a dana nurses # -a adds dana to the nurses group $ groups dana # confirm the membership took

Problem 6: Billing Access

  • One file, not the whole folder
  • Morgan shouldn't join nurses
  • How would you address this?
Morgan?one file

Options: Billing Access

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Agpasswd -a morgan nursesBchmod -R o+w /srv/patient-recordsCsetfacl -m u:morgan:rw file

The Fix: Billing Access

  • C is correct: one file only
  • A joins the wrong group
  • B opens everything to everyone
$ sudo useradd -m morgan $ setfacl -m u:morgan:rw \ /srv/patient-records/today/invoice.txt

The Fix: Billing Access

$ sudo useradd -m morgan # creates morgan's account first $ setfacl -m u:morgan:rw \ /srv/patient-records/today/invoice.txt # -m modifies the ACL; adds morgan $ getfacl /srv/patient-records/today/invoice.txt # confirm the new rule is there

Problem 7: After Hours

  • Flag any change after hours
  • Don't touch the files yourself
  • How would you address this?
IT?after hrs

Options: After Hours

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo nano today/file.txtBls -la /srv/patient-records/todayCinotifywait -m -e modify dir

The Fix: After Hours

  • C is correct: only watches
  • A opens an editor: forbidden
  • B checks once, not ongoing
$ inotifywait -m -r -e modify \ --timefmt '%Y-%m-%d %H:%M:%S' \ --format '%T %w%f %e' \ /srv/patient-records >> /tmp/watch.log &

The Fix: After Hours

$ inotifywait -m -r -e modify \ --timefmt '%Y-%m-%d %H:%M:%S' \ --format '%T %w%f %e' \ /srv/patient-records >> /tmp/watch.log & # -m keeps watching; -r covers subfolders # --format adds a real timestamp per line # log lives outside the watched folder

Problem 8: Add a Note

  • Add a note, no editor allowed
  • Content still needs updating
  • How would you address this?
Nurse?today/notes.txt

Options: Add a Note

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Anano today/notes.txtBecho "note" >> notes.txtCrm notes.txt; echo new

The Fix: Add a Note

  • B is correct: appends, no edit
  • A opens an editor: forbidden
  • C destroys the original file
$ echo "Called in sick, back Monday" \ >> /srv/patient-records/today/notes.txt

The Fix: Add a Note

$ echo "Called in sick, back Monday" \ >> /srv/patient-records/today/notes.txt # >> appends; no editor ever opened

Problem 9: Try grep

  • Need to search inside a log
  • grep finds lines by text
  • How would you address this?
You?watch.log

Options: Try grep

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Agrep notes.txt /tmp/watch.logBgrep /tmp/watch.log notes.txtCcat /tmp/watch.log

The Fix: Try grep

  • A is correct: pattern first
  • B: arguments are reversed
  • C shows everything, unfiltered
$ grep notes.txt /tmp/watch.log

The Fix: Try grep

$ grep notes.txt /tmp/watch.log # searches for that text inside the log # pattern first, file to search second

Problem 10: Spot the Change

  • A note was added after hours
  • Confirm it, don't guess
  • How would you address this?
Admin?watch.log

Options: Spot the Change

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Acat today/notes.txtBgrep notes.txt watch.logCsudo systemctl status inotify

The Fix: Spot the Change

  • B is correct: confirms the log
  • A shows content, not a change
  • C: inotify isn't a service
$ grep notes.txt /tmp/watch.log

The Fix: Spot the Change

$ grep notes.txt /tmp/watch.log # confirms the After Hours watch caught it # proof the change was logged, not guessed

Problem 11: Last Day

  • Their last day is today
  • Access must end immediately
  • How would you address this?
HR?access

Options: Last Day

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo passwd -l danaBgpasswd -d dana nursesCsudo rm -rf /home/dana

The Fix: Last Day

  • B is correct: leaves the group
  • A blocks login, not access
  • C deletes the wrong thing
$ sudo gpasswd -d dana nurses $ groups dana $ setfacl -x u:dana \ /srv/patient-records/today/invoice.txt

The Fix: Last Day

$ sudo gpasswd -d dana nurses # -d removes dana from nurses $ groups dana # confirm the group is gone $ setfacl -x u:dana \ /srv/patient-records/today/invoice.txt # also revoke any personal ACL rule

A Suspicious Write

  • Someone wrote after hours
  • No editor, straight to disk
  • The log should catch this
$ echo "TOTAL: 9450.00" >> \ /srv/patient-records/today/invoice.txt

A Suspicious Write

$ echo "TOTAL: 9450.00" >> \ /srv/patient-records/today/invoice.txt # simulates the unauthorized after-hours write

Problem 12: Who Touched It?

  • Audit request: who did this?
  • You can only check the log
  • How would you address this?
Auditor?the log

Options: Who Touched It?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo auditctl -w fileBgrep file watch.logCwhoami

The Fix: Who Touched It?

  • B is correct: search the log
  • A: auditd doesn't run on WSL2
  • C only shows current user
$ grep invoice.txt /tmp/watch.log

The Fix: Who Touched It?

$ grep invoice.txt /tmp/watch.log # searches for that filename # shows WHAT and WHEN, never WHO # inotify can't answer that part

Problem 13: Too Much Access

  • A doctor got write, not read
  • Base permission looks correct
  • How would you address this?
Doctor?the mask

Options: Too Much Access

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Achmod 640 fileBsetfacl -m m::r-- fileCsetfacl -x u:doctor file

The Fix: Too Much Access

  • B is correct: narrow the mask
  • A only edits mask by accident
  • C removes doctor's access
$ setfacl -m m::r-- \ /srv/patient-records/record.txt

The Fix: Too Much Access

$ setfacl -m m::r-- \ /srv/patient-records/record.txt # caps every named/group entry at r-- $ getfacl /srv/patient-records/record.txt # doctor's entry now shows #effective:r--

Problem 14: Which Group?

  • A nurse says access is broken
  • Don't guess, check first
  • How would you address this?
Nurse?today/

Options: Which Group?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Agpasswd -a dana nursesBid danaCchmod 777 today/

The Fix: Which Group?

  • B is correct: diagnose first
  • A re-adds before checking
  • C is a blind, risky guess
$ id dana

The Fix: Which Group?

$ id dana # lists every group dana belongs to # compare against what today/ requires

Problem 15: Locked Out

  • Dana forgot their password
  • No sudo needed to fix this
  • How would you address this?
Dana?login

Options: Locked Out

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo usermod -aG sudo danaBsudo passwd danaCsudo useradd dana

The Fix: Locked Out

  • B is correct: resets it
  • A grants sudo, unrelated
  • C: the account already exists
$ sudo passwd dana

The Fix: Locked Out

$ sudo passwd dana # resets their password only # no group or ACL change at all

Problem 16: Two Roles

  • Alex covers nursing, billing
  • Keep both sets of access
  • How would you address this?
Alex?2 groups

Options: Two Roles

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Agpasswd -a alex billingBgpasswd -a alex nurses (again)Cusermod -G billing alex

The Fix: Two Roles

  • A is correct: adds the second
  • B: already in nurses, no-op
  • C: -G alone drops nurses!
$ sudo useradd -m alex $ sudo gpasswd -a alex nurses $ sudo gpasswd -a alex billing

The Fix: Two Roles

$ sudo useradd -m alex # creates alex's account first $ sudo gpasswd -a alex nurses # alex already covers nursing duty $ sudo gpasswd -a alex billing # -a only adds; nurses is kept too

Problem 17: Wrong Owner

  • A file was created as root
  • Owner should be alex instead
  • How would you address this?
IT?a file

Options: Wrong Owner

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo chown alex fileBsudo chmod 700 fileCsudo chgrp admin file

The Fix: Wrong Owner

  • A is correct: fixes owner
  • B changes mode, not owner
  • C only changes the group
$ sudo chown alex \ /srv/patient-records/record.txt

The Fix: Wrong Owner

$ sudo chown alex \ /srv/patient-records/record.txt # chown changes the owner field only $ ls -l /srv/patient-records/record.txt # confirm alex now owns the file

Problem 18: Broken Symlink

  • A link points outside records
  • Trace it before you trust it
  • How would you address this?
IT?a link

Options: Broken Symlink

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Arm the link, recreate it rightBchmod 777 the linkCignore it, links are harmless

The Fix: Broken Symlink

  • A is correct: rebuild it right
  • B: permission isn't the issue
  • C: a bad target is a real risk
$ ls -l /srv/patient-records/today/shortcut $ readlink /srv/patient-records/today/shortcut $ rm /srv/patient-records/today/shortcut $ ln -s /srv/patient-records/today/notes.txt \ /srv/patient-records/today/shortcut

The Fix: Broken Symlink

$ ls -l /srv/patient-records/today/shortcut # l at the start means it's a symlink $ readlink /srv/patient-records/today/shortcut # shows exactly where the link points # outside patient-records: needs fixing $ rm /srv/patient-records/today/shortcut # removes only the broken link itself $ ln -s /srv/patient-records/today/notes.txt \ /srv/patient-records/today/shortcut # relinks it to a real file inside

Problem 19: All Can Delete

  • Any group member can delete
  • One mistake affects everyone
  • How would you address this?
IT?billing/

Options: All Can Delete

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Achmod g-w billing/, ACL per fileBchmod 777 billing/Cdelete the whole folder

The Fix: All Can Delete

  • A is correct: grant per file
  • B makes the risk worse
  • C destroys real records
$ sudo mkdir -p /srv/patient-records/billing $ chmod g-w /srv/patient-records/billing $ setfacl -m u:morgan:rw \ /srv/patient-records/today/invoice.txt

The Fix: All Can Delete

$ sudo mkdir -p /srv/patient-records/billing # the shared billing folder itself $ chmod g-w /srv/patient-records/billing # group can no longer write by default $ setfacl -m u:morgan:rw \ /srv/patient-records/today/invoice.txt # write granted per file, not per folder

Problem 20: Who's Online?

  • About to make a risky change
  • Check who's active first
  • How would you address this?
IT?sessions

Options: Who's Online?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
AwBsudo rebootCskip the check, proceed

The Fix: Who's Online?

  • A is correct: shows who's on
  • B reboots on active users
  • C: risky, unaware of who's on
$ w

The Fix: Who's Online?

$ w # shows who is on, and what they run # wait until their session is done

Problem 21: Weekly Summary

  • A week of raw log lines
  • You need counts, not raw text
  • How would you address this?
IT?watch.log

Options: Weekly Summary

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Acat the whole watch.logBinotifywatch -e modify dirCdelete old log lines

The Fix: Weekly Summary

  • B is correct: a summary table
  • A: readable, not summarized
  • C loses the record entirely
$ inotifywatch -r -e modify \ /srv/patient-records

The Fix: Weekly Summary

$ inotifywatch -r -e modify \ /srv/patient-records # runs until Ctrl+C, then prints a table # counts, not a wall of raw log lines

Problem 22: Keep Watching

  • The watch must outlive login
  • Your on-call shift is ending
  • How would you address this?
IT?the watch

Options: Keep Watching

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Ajust leave the terminal openBnohup inotifywait ... & ; disownCrun it again tomorrow

The Fix: Keep Watching

  • B is correct: survives logout
  • A: closing the laptop kills it
  • C leaves gaps, nothing logged
$ nohup inotifywait -m -r -e modify \ --timefmt '%Y-%m-%d %H:%M:%S' \ --format '%T %w%f %e' \ /srv/patient-records >> /tmp/watch.log & $ disown

The Fix: Keep Watching

$ nohup inotifywait -m -r -e modify \ --timefmt '%Y-%m-%d %H:%M:%S' \ --format '%T %w%f %e' \ /srv/patient-records >> /tmp/watch.log & # nohup: ignore the hangup on logout $ disown # detaches it from this shell fully

Problem 23: New Admin

  • A new admin needs full setup
  • Account, password, right group
  • How would you address this?
HR?admin group

Options: New Admin

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo useradd -m -G admin raviBgpasswd -a ravi adminCusermod -aG sudo ravi

The Fix: New Admin

  • A is correct: all in one
  • B alone: no account made yet
  • C grants full sudo: too broad
$ sudo useradd -m -G admin ravi $ sudo passwd ravi

The Fix: New Admin

$ sudo useradd -m -G admin ravi # -m home dir; -G admin group at once $ sudo passwd ravi # sets ravi's own password $ groups ravi # confirm admin membership took

Problem 24: Port Open?

  • Ready to manage this remotely
  • Confirm sshd is reachable now
  • How would you address this?
You?port 22

Options: Port Open?

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Aping clinic-recordsBsudo ss -tlnp | grep :22Csudo ufw disable

The Fix: Port Open?

  • B is correct: checks the port
  • A only proves the host is up
  • C drops protection everywhere
$ sudo ss -tlnp | grep :22 $ sudo ufw allow 22/tcp $ hostname -I

The Fix: Port Open?

$ sudo ss -tlnp | grep :22 # lists listening ports; empty = not open $ sudo ufw allow 22/tcp # if it was closed, this opens just port 22 $ hostname -I # reveals this VM's own IP address

Problem 25: Connect via SSH

  • No shared admin account exists
  • Use YOUR OWN login instead
  • How would you address this?
You?remote login

Options: Connect via SSH

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Assh clinic-records (bare name)Bset your password, map, then sshCssh as root directly

The Fix: Connect via SSH

  • B is correct: nothing skipped
  • A: bare name won't resolve
  • C: root login usually off
$ sudo passwd $(whoami) # on Ubuntu, run: hostname -I (its own address) $ echo "<VM-IP> clinic-records" \ | sudo tee -a /etc/hosts $ ssh $(whoami)@clinic-records

The Fix: Connect via SSH

$ sudo passwd $(whoami) # sets a password for YOUR OWN account # <VM-IP>: on Ubuntu, run hostname -I $ echo "<VM-IP> clinic-records" \ | sudo tee -a /etc/hosts $ ssh $(whoami)@clinic-records # run this from Kali, not from Ubuntu

Problem 26: Remote New Hire

  • Now connected in from Kali
  • Same job, new access method
  • How would you address this?
New Hire?an account

Options: Remote New Hire

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Aping the new hire insteadBuseradd + passwd, same as localCshare your own password

The Fix: Remote New Hire

  • B is correct: same commands
  • A creates no account at all
  • C: never share one account
$ sudo useradd -m newhire $ sudo passwd newhire

The Fix: Remote New Hire

$ sudo useradd -m newhire # same command, whether local or ssh $ sudo passwd newhire # sets their password (prompts you)

Problem 27: Access Report

  • Compliance wants a full report
  • Every rule, every user
  • How would you address this?
Auditor?3 users

Options: Access Report

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asudo -l; getfacl; groups, for eachBls -la /srv/patient-recordsCask each user what they can do

The Fix: Access Report

  • A checks every real source
  • B only shows base permissions
  • C: self-reports aren't proof
$ sudo -l -U morgan $ getfacl /srv/patient-records $ groups morgan dana alex

The Fix: Access Report

$ sudo -l -U morgan # -U checks another user's sudo rules $ getfacl /srv/patient-records # every ACL rule on the tree, at once $ groups morgan dana alex # group membership for the report

Problem 28: Root Bypassed

  • Root wrote the file directly
  • ACLs never stopped it at all
  • How would you address this?
Auditor?DAC limit

Options: Root Bypassed

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Asetfacl -m u:root:--- fileBthis needs MAC, not an ACLCchmod 000 file

The Fix: Root Bypassed

  • B is correct: DAC exempts root
  • A: root ignores ACLs too
  • C: root ignores chmod as well
$ stat /srv/patient-records/record.txt

The Fix: Root Bypassed

$ stat /srv/patient-records/record.txt # Modify: shows it really did change $ ls -l /srv/patient-records/record.txt # owner unchanged; root wrote through it # DAC (chmod/ACL) never governs root # MAC is the only real answer here

Problem 29: Incident Report

  • Suspicious write, after hours
  • Find who, confirm, then act
  • How would you address this?
IT?everything

Options: Incident Report

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Agrep the log for a usernameBcross-check groups + getfacl, revokeCrestore backup, move on

The Fix: Incident Report

  • B is correct: narrows suspects
  • A: the log has no username
  • C fixes nothing; recurs
$ grep invoice.txt /tmp/watch.log $ getfacl /srv/patient-records/today $ groups morgan dana alex

The Fix: Incident Report

$ grep invoice.txt /tmp/watch.log # confirms WHEN, never WHO $ getfacl /srv/patient-records/today # lists everyone with real access $ groups morgan dana alex # cross-check who is in each group # narrow the suspects, then revoke

Problem 30: Back on Kali

  • Clinic Records work is done
  • Confirm you're truly local
  • How would you address this?
You?exit

Options: Back on Kali

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
AexitBclose the terminal windowCsudo shutdown -h now

The Fix: Back on Kali

  • A is correct: clean exit
  • B leaves it hanging, not clean
  • C shuts down the clinic's VM
$ exit $ hostname

The Fix: Back on Kali

$ exit # leaves the SSH session, back to Kali $ hostname # confirms you're on kali, not clinic-records

Problem 31: Save the Log

  • Findings need a local copy
  • Keep evidence off that VM too
  • How would you address this?
You?watch.log

Options: Save the Log

  • Pick the one that fixes it
  • Some look tempting, but wrong
  • Which is safest here?
Ascp user@clinic-records:file .Bretype it by handCscreenshot the terminal

The Fix: Save the Log

  • A is correct: copies over SSH
  • B is error-prone, not proof
  • C isn't searchable or proof
$ scp $(whoami)@clinic-records:/tmp/watch.log \ ~/incident-watch.log

The Fix: Save the Log

$ scp $(whoami)@clinic-records:/tmp/watch.log \ ~/incident-watch.log # copies the file itself over ssh # same login you already set up earlier

Deliverables

  • Answers to all 31 problems
  • Real gpasswd/setfacl output
  • No editor ever touched data
setfaclgpasswdgrep

Questions?

Practice Lab Part 3

Pair Up: User & Admin

  • One types User, one Admin
  • User asks; Admin explains
  • Click reveals the real answer

Problem 1: How Many Roles?

User: "How many roles do we have on this system?"

Admin: Four: physicians, nurses, billing, and admin. Each one is its own Linux group.

Problem 2: Nurses in today/

User: "What can the nurses role actually do in today/?"

Admin: Dana's account is in the nurses group, so anyone in that group can read and write inside today/ per its group permissions.

Problem 3: ACL vs. Group

User: "Why did morgan get an ACL instead of joining a group?"

Admin: Morgan only needed one file, today/invoice.txt. A per-file ACL grants exactly that without giving access to everything else billing can see.

Problem 4: Who Can Read It?

User: "Who can currently read record.txt?"

Admin: Run getfacl /srv/patient-records/record.txt. It lists the owner, group, and any extra ACL entries. Don't guess; check.

Problem 5: Dana's Access?

User: "Does dana still have access to invoice.txt?"

Admin: No. Last Day removed her from nurses and revoked her personal ACL entry on today/invoice.txt.

Problem 6: Check Who's On

User: "Can you tell who's logged in right now?"

Admin: Yes: w shows every logged-in user and what they're currently running.

Problem 7: Still Open?

User: "Is port 22 still open on this VM?"

Admin: Check with sudo ss -tlnp | grep :22. If it's closed, sudo ufw allow 22/tcp opens it.

Problem 8: Why No Editors?

User: "Why can't I just open a file in an editor?"

Admin: House rule for this VM: every change has to be a logged, auditable command. An editor session isn't tied to one specific action in the log.

Problem 9: Just chmod 777?

User: "Wouldn't chmod 777 just fix any access problem?"

Admin: No. That opens the file to literally everyone, including people who should never touch patient records. Use a narrow ACL grant instead.

Problem 10: Why No Access?

User: "Why can't I access the system at all?"

Admin: A few real possibilities: your account doesn't exist yet, you're not in the right group, or, if it's root's own doing, DAC just doesn't apply to root. Check groups and id first, then getfacl, before assuming it's broken.

Questions?

Practice Lab Part 4

Real Questions, Verified

  • Real sysadmins, real questions
  • From Stack Exchange, not us
  • Checked before adding them

Problem 1: chmod vs. ACL

User: "What's the actual difference between chmod and ACLs?"

Admin: Neither replaces the other; both apply to the same file at once. POSIX permissions (chmod) only cover owner, group, and everyone else; ACLs let you grant extra individual users or groups beyond that base set.

Source: unix.stackexchange.com/q/364517

Problem 2: Hard Link a Dir?

User: "Why can't I hard-link a directory?"

Admin: It would break the filesystem's tree structure: there'd be no way to tell an original directory from a link to it, which risks creating loops that crash tools like fsck.

Source: unix.stackexchange.com/q/22394

Problem 3: Copy Over SSH

User: "How do I copy a file to another machine over SSH?"

Admin: scp source destination. For example, scp file.txt user@host:/path/ pushes a file there, and scp user@host:/path/file.txt . pulls one back.

Source: unix.stackexchange.com/q/106480

Problem 4: apt vs aptitude

User: "What's the real difference between apt-get and aptitude?"

Admin: aptitude adds a terminal menu UI on top of very similar core behavior. Both track which packages you installed manually vs. as dependencies, for cleaner auto-removal later.

Source: unix.stackexchange.com/q/767

Problem 5: Why 'wheel'?

User: "Where did the wheel group even get its name?"

Admin: From old BSD slang: a "wheel" meant a powerful person, so the group allowed to perform privileged, system-wide operations got that name.

Source: unix.stackexchange.com/q/1262

Questions?

Looking Ahead: Module 5

Module 5

Process Mgmt & Remote Access

MODULE 5 COMMANDS AT A GLANCEKALI -- your workstationssh-keygenssh-copy-idssh-addssh -LrsyncUBUNTU -- the serversshd -tpstoppgrepjobskillnicetmux

One VM Is Enough

  • Ubuntu is client and server
  • Steps 1, 3-9: ssh to localhost
  • Step 2: a key, Kali to Ubuntu
  • Only Step 2 needs Ubuntu's IP
ONE UBUNTU VMsshthe clientsshdthe daemon, :22~/.sshyour keys/etc/sshserver policy

All Commands: Module 5

History of Processes

  • Daemons date back to 1963
  • Unix: fork() makes a process
  • systemd is PID 1 today
1963MIT Project MAC coins"daemon" for background jobs1970sUnix creates processes withfork(), borrowed from GENIE1991Linux 0.01 brings the Unixprocess model to the PC2010systemd is announced toreplace the old initTodaysystemd runs as PID 1 onnearly every distro

Program vs Process

  • A program is a file on disk
  • A process is it, running
  • One program, many processes
  • Each process gets its own PID
sshthe program: a fileprocessPID 812processPID 977
EVERY PROCESS SHARES THE SAME VMsshdbashcurlpython3ALL COMPETE FOR THE SAME FIVE RESOURCESCPURAMI/ODiskNetworkMore processes competing means less of each resource to go around.top and ps are how you see who is using how much, right now.

Word Origin: "Process"

processus
  • Latin: a going forward
procedere
  • to go forward, proceed

A process is a program that has gone forward into running.

Source: etymonline: process

The Process Tree

  • PID: this process's number
  • PPID: who started it
  • PID 1 starts everything else
systemdPID 1, the ancestorsshdPID 840, child of 1bashPID 2210, child of 840ps auxPID 2301, child of 2210

Process States

  • Most are sleeping (S)
  • D means waiting on disk
  • Z is finished, not reaped
Rrunning or readySsleeping, waits for workDwaiting on disk (deep sleep)Tstopped, e.g. Ctrl+ZZzombie: done, not reaped

Why Processes Matter

  • Every service is a process
  • Slow? Find the process
  • Attacks show up as processes
The portal is slowstudents cannot registerOne process hogs the CPUa runaway report scriptFind it, then control itps, top, kill, nice

Word Origin: "Daemon"

Maxwell's demon
  • an imaginary sorting agent
daemon
  • a background helper, 1963

MIT's Project MAC borrowed the name for jobs that work quietly in the background. sshd is one.

Source: Wikipedia: Daemon (computing)

Check: Program or Process?

  • /usr/bin/ssh sits on disk
  • ssh running as PID 812
  • Which one is the process?
PID 812

Answer: the running ssh; the file is only the program

Questions?

Watching Processes

WATCHING PROCESSES: WHAT TO REACH FORSomething Is RunningSee It Onceps -- a snapshot, right nowWatch It Livetop -- the same table, refreshedFind It by Namepgrep -- just the PID you needThree ways to look, from a single check to a running display to a quick search.Each gets its own closer look next.
ps IS A SNAPSHOT, NOT A LIVE VIEWps aux (T0)sshd, bash1s laterps aux (T1)sshd, bash, curl1s laterps aux (T2)sshd, bashNothing updates the last ps output on its own.Run it again to see the current table -- curl already finished by T2.Need it LIVE, not a snapshot?Use top, or watch -n 2 ps aux

List Processes: ps

  • ps aux: every user, full list
  • A snapshot from THAT INSTANT
  • Pipe to grep to filter
$ ps aux # every user, one line per process USER PID %CPU STAT COMMAND root 1 0.0 Ss /sbin/init student 812 0.0 Ss -bash student 901 0.0 R+ ps aux # columns trimmed to fit the slide $ ps aux | grep sshd # filter: only the line(s) you want # grep itself briefly shows up too

List Processes: ps

$ ps aux # every user, one line per process USER PID %CPU STAT COMMAND root 1 0.0 Ss /sbin/init student 812 0.0 Ss -bash student 901 0.0 R+ ps aux # columns trimmed to fit the slide $ ps aux | grep sshd # filter: only the line(s) you want # grep itself briefly shows up too

More Examples: ps

  • Filter by service name
  • See who is the parent
  • Repeat it automatically
$ ps aux | grep sshd # one running service, by name $ ps -ef --forest # --forest: shows parent -> child # tree, e.g. sshd starting a shell $ watch -n 2 ps aux # watch: reruns ps every 2 seconds # Ctrl+C to stop watching

More Examples: ps

$ ps aux | grep sshd # one running service, by name $ ps -ef --forest # --forest: shows parent -> child # tree, e.g. sshd starting a shell $ watch -n 2 ps aux # watch: reruns ps every 2 seconds # Ctrl+C to stop watching

Use Case: ps

  • Is the service running at all?
  • Who owns it, and since when?
  • Scripts and audits use ps too
Ticket: catalog is downthe librarian cannot searchps aux | grep catalogis the service running?Not listed: restart itback online in minutes

Use Case: Incident Response

  • A strange process is running
  • Confirm it exists, then look
  • Don't kill it before you know
Alert: unknown processa monitoring tool flagged itps aux | grep NAMEconfirm PID, user, commandInvestigate, then actkill only once you are sure

Reading ps aux

  • One line per process
  • STAT holds the state code
  • Find yours by the USER column
USERwho owns the processPIDits process ID%CPUshare of one CPU usedSTATstate: R S D T ZCOMMANDwhat it is running
top IS ps, LOOPEDps auxprints once, then returns youtopstays open, redraws every 3sYou must re-run itto see the table changeThe screen updates itselfwhile you keep watchingtop is ps, looped: same process table, redrawn on a timer.q quits • P sorts by CPU • M sorts by memory • the loop keeps running until you quit

Live View: top

  • top redraws every 3 seconds
  • q quits, P sorts by CPU
  • M sorts by memory
$ top # stays open; q to quit top - 19:08:23 up 1 day, 1 user Tasks: 31 total, 1 running %Cpu(s): 0.7 us, 98.6 id MiB Mem : 7768.6 total PID USER %CPU COMMAND 812 root 0.0 sshd # press P: sort by CPU # press M: sort by memory

Live View: top

$ top # stays open; q to quit top - 19:08:23 up 1 day, 1 user Tasks: 31 total, 1 running %Cpu(s): 0.7 us, 98.6 id MiB Mem : 7768.6 total PID USER %CPU COMMAND 812 root 0.0 sshd # press P: sort by CPU # press M: sort by memory

More Examples: top

  • Watch one user only
  • Sort by memory at start
  • One snapshot, no live screen
$ top -u student # only this user, less noise $ top -o %MEM # starts already sorted by memory $ top -bn1 | head -15 # -b: batch mode, no live screen # -n1: one iteration, then exit # safe to pipe or save to a file

More Examples: top

$ top -u student # only this user, less noise $ top -o %MEM # starts already sorted by memory $ top -bn1 | head -15 # -b: batch mode, no live screen # -n1: one iteration, then exit # safe to pipe or save to a file

Use Case: top

  • See load as it happens
  • Spot the CPU or memory hog
  • Sort live, no scripts needed
Registration week, site slowload average keeps climbingtop, then press Psorts by CPU useA report job uses 99%stop or slow that one job

Use Case: Live Triage

  • CPU is at 100% right now
  • top, then press P
  • The worst one is now on top
CPU pinned at 100%the machine feels frozentop, then press Psorts live by CPU useOne process stands outstop it, or renice it

Reading the top Header

  • Header: machine health
  • Rows: one per process
  • Load above CPU count = busy
Taskshow many, in which states%Cpu(s)us user, sy system, id idleload averagedemand over 1, 5, 15 minMiB Memtotal, free, used memory
ps | grep vs pgrepps aux | grep bashthe grep PROCESS matches toops aux901 ... grep bashEXTRA LINEpgrep -a bashdoesn't search its own namepgrep812 -bash (clean)pgrep searches the process TABLE directly, by name or pattern,and prints just the PIDs -- built for scripts, not for reading by eye.

Find by Name: pgrep

  • Prints matching PIDs only
  • -a adds the full command
  • -c counts the matches
$ pgrep -a bash # -a: PID plus the full command 812 -bash $ pgrep -c bash # -c: how many matches, not which 1 # ps | grep would also match itself # pgrep never has that problem

Find by Name: pgrep

$ pgrep -a bash # -a: PID plus the full command 812 -bash $ pgrep -c bash # -c: how many matches, not which 1 # ps | grep would also match itself # pgrep never has that problem

More Examples: pgrep

  • Scope to one user
  • Match the full command line
  • Require an exact name
$ pgrep -u student sleep # only this user's matching jobs $ pgrep -f "http.server 8000" # -f: matches ANYWHERE in the # full command line, not just the name $ pgrep -x bash # -x: exact name only, not "bash-ish"

More Examples: pgrep

$ pgrep -u student sleep # only this user's matching jobs $ pgrep -f "http.server 8000" # -f: matches ANYWHERE in the # full command line, not just the name $ pgrep -x bash # -x: exact name only, not "bash-ish"

Use Case: pgrep

  • Get a PID without reading ps
  • Avoid running a job twice
  • Feeds kill and monitoring
Nightly backup startsthe last one is still goingpgrep -a backupis one already running?Yes: skip this runno double load on the disk

Use Case: Script Guard Clause

  • A cron job might overlap
  • pgrep checks before starting
  • Skip this run if one is active
Nightly backup.sh runsthe last one may still be goingpgrep -f backup.shtrue if one is already runningExit early, log, and skipno double load on the disk

Check: Find the Busy One

  • One process uses 99% CPU
  • You need its PID fast
  • Which tool, which key?
top, then P

Answer: top shows live CPU use; press P to sort, read the PID column

Questions?

Signals, Jobs & Priority

SIGNALS, JOBS & PRIORITY: TAKING CONTROLA Process Is RunningMove Itjobs -- foreground, backgroundStop Itkill -- send it a signalSlow It Downnice -- ask it to yield CPUThree ways to manage a process once it exists: place it, end it, or throttle it.Each gets its own closer look next.

What Is a Signal?

  • A message sent to a process
  • You or the kernel can send it
  • It may catch or ignore it
You: kill PIDKernel delivers the signalProcess reacts

Why Signals Matter

  • Stop a service cleanly
  • Reload config, no downtime
  • Force-stop only if it hangs
Change the web configa restart drops visitorskill -HUP PIDask it to reloadNew settings, no downtimevisitors never notice

Common Signals

  • Number or name both work
  • TERM is the polite default
  • KILL cannot be ignored
1 HUPhangup, or reload config2 INTCtrl+C from the keyboard9 KILLcannot be caught or ignored15 TERMplease stop (the default)19 STOPpause it, cannot be ignored

Source: man7: signal(7)

Word Origin: "Hangup"

hang up
  • end a phone call
SIGHUP
  • the terminal line dropped

Signal 1 began as a warning that a serial line had dropped. Closing a terminal still sends it.

Source: Wikipedia: Signal (IPC)

Foreground, Suspended, BackgroundForegroundyou see its output liveSuspendedCtrl+Z: paused, not runningBackground& or bg: keeps runningCtrl+Zfgbgjobs lists every job in THIS state, per shell, numbered %1, %2, ...Close the terminal and every job here, in any state, is gone (unless disowned).

Background Jobs

  • & sends a job to background
  • jobs lists your jobs
  • fg %1 brings job 1 forward
$ sleep 300 & # & starts it, already in the [1] 2411 # background; 2411 is its PID $ jobs # lists every job THIS shell owns [1]+ Running sleep 300 & # Ctrl+Z pauses, bg resumes it

Background Jobs

$ sleep 300 & # & starts it, already in the [1] 2411 # background; 2411 is its PID $ jobs # lists every job THIS shell owns [1]+ Running sleep 300 & # Ctrl+Z pauses, bg resumes it

More Examples: jobs

  • See the PID next to it
  • Resume a paused job quietly
  • Detach it from this shell
$ jobs -l # -l adds the PID next to %1 $ bg %1 # resume a Ctrl+Z-paused job # in the background, not foreground $ disown %1 # detach it: survives you logging out # (it keeps no connection to this shell)

More Examples: jobs

$ jobs -l # -l adds the PID next to %1 $ bg %1 # resume a Ctrl+Z-paused job # in the background, not foreground $ disown %1 # detach it: survives you logging out # (it keeps no connection to this shell)

Use Case: Background Jobs

  • Run a long job, keep working
  • Pause and resume with Ctrl+Z
  • Ends at logout unless nohup
Grade export takes 20 minit blocks your terminalCtrl+Z, then bgthe job runs in the backgroundTerminal is free againcheck on it with jobs

Use Case: Free the Terminal

  • A long build blocks typing
  • Ctrl+Z, then bg
  • Terminal is free, job runs on
make blocks the terminalyou cannot type anything elseCtrl+Z, then bgsuspends it, resumes in bgTerminal is free againjobs still shows it running
A Request vs an Orderkill -TERM (default)a request the process can catchkill -9 (KILL)the kernel ends it, no sayIt may clean up, then exitclose files, save state, log outGone immediatelyno cleanup happens at allSIGKILL cannot be caught, blocked, or ignored -- that is what makes it a last resort.Try TERM first. Wait a moment. Only reach for -9 if it is still there.

Stop a Process: kill

  • kill sends TERM by default
  • TERM: a request, can be caught
  • -9 KILL: kernel enforces it
$ kill 2411 # TERM: asks it to exit cleanly $ kill -9 2411 # KILL: kernel ends it, no cleanup $ pkill sleep # pkill: same idea, matched by name # not by PID -- careful with wide names

Stop a Process: kill

$ kill 2411 # TERM: asks it to exit cleanly $ kill -9 2411 # KILL: kernel ends it, no cleanup $ pkill sleep # pkill: same idea, matched by name # not by PID -- careful with wide names

More Examples: kill

  • List every signal by name
  • Ask a daemon to reload
  • Signal a whole process group
$ kill -l # lists every signal name and number $ kill -HUP 812 # HUP: many daemons reload config # on HUP, instead of exiting $ kill -- -2411 # a NEGATIVE pid signals the whole # process group, not just one PID

More Examples: kill

$ kill -l # lists every signal name and number $ kill -HUP 812 # HUP: many daemons reload config # on HUP, instead of exiting $ kill -- -2411 # a NEGATIVE pid signals the whole # process group, not just one PID

Use Case: kill

  • Free memory from a stuck job
  • TERM lets it clean up first
  • KILL is the last resort
Export job is frozenit holds 4 GB of memorykill PID, wait, kill -9polite first, force lastMemory is free againother users can work

Use Case: Graceful Shutdown

  • Server holds open connections
  • TERM first, then wait
  • Only -9 if it will not stop
Web server, live trafficconnections still in progresskill -TERM, then waitlets it finish and close upStill running? kill -9last resort, may drop work

TERM Before KILL

  • Try TERM first, then wait
  • KILL skips all cleanup
  • Locks and temp files stay
kill PIDsends TERMcan be caughtcloses files firstexits cleanlykill -9 PIDsends KILLcannot be caughtno cleanup at alllast resort only
THE NICENESS SCALENICENESS: HOW WILLING A PROCESS IS TO YIELD THE CPU-20most selfish, root only0the normal default19most polite, yields mostA LOWER number wins more CPU time when processes compete for it.nice sets it at start; renice changes a job already running.Same idea, for disk instead of CPUionice gives disk I/O priority, not nice

Priority: nice, renice

  • Niceness runs -20 to 19
  • Lower number wins more CPU
  • Only root can go below 0
$ nice -n 10 sleep 300 & # starts already at niceness 10 $ ps -o pid,ni,cmd -C sleep # -o ni: show just the NI column PID NI CMD 2411 10 sleep 300 $ renice -n 15 -p 2411 # renice: changes a job already # running, by its PID

Priority: nice, renice

$ nice -n 10 sleep 300 & # starts already at niceness 10 $ ps -o pid,ni,cmd -C sleep # -o ni: show just the NI column PID NI CMD 2411 10 sleep 300 $ renice -n 15 -p 2411 # renice: changes a job already # running, by its PID

More Examples: nice

  • No -n: defaults to 10
  • Only root goes negative
  • A cousin command, for disk
$ nice sleep 300 & # no -n given: niceness 10, not 0 $ sudo renice -n -5 -p 2411 # negative: needs root; more CPU # than a normal process gets $ ionice -c3 rsync src/ dst/ # ionice: same idea, for DISK I/O # nice never touches disk priority

More Examples: nice

$ nice sleep 300 & # no -n given: niceness 10, not 0 $ sudo renice -n -5 -p 2411 # negative: needs root; more CPU # than a normal process gets $ ionice -c3 rsync src/ dst/ # ionice: same idea, for DISK I/O # nice never touches disk priority

Use Case: nice

  • Background work stays polite
  • Interactive users stay fast
  • Change priority while running
Backup runs at peak hoursthe registrar site slowsnice -n 19, or renicethe backup yields to othersSite stays fastthe backup still finishes

Use Case: Shared Server

  • A backup competes with logins
  • nice -n 15 on the backup
  • Logins stay fast; backup waits
Backup runs at 2 AMbut some students log in earlynice -n 15 backup.shbackup yields CPU on demandLogins stay responsivebackup still finishes overnight

Why It Is Called nice

nice
  • kind to the others
niceness
  • how much you defer

A high nice value lets everyone else go first. -20 is the most favored, 19 the least.

Source: man7: nice(1)

Check: Which Signal?

  • A hung app ignores TERM
  • You already waited
  • Which signal is left?
kill -9

Answer: KILL, only after a polite TERM failed

Questions?

Remote Access & SSH

History of Remote Login

  • Remote login predates the web
  • Old tools sent plaintext
  • SSH encrypted everything
1969Telnet appears on ARPANET,the first remote logins1983Telnet becomes an Internetstandard: RFC 8541995Tatu Ylönen writes SSH after apassword-sniffing attack1999OpenSSH is released by theOpenBSD developersTodaySSH is the standard way tomanage servers remotely
REMOTE ACCESS & SSH: THE THREE QUESTIONSConnecting to Another MachineIs It Encrypted?ssh replaces plaintext telnetIs This the Real Server?a fingerprint proves its identityAm I Really Me?a password, or a key -- coming upEvery remote login answers all three, whether you notice it or not.Each gets its own closer look next.

Word Origin: "Telnet"

teletype
  • a typewriter-style terminal
network
  • reach it across a network

Telnet let a terminal reach a distant machine over a network, with no encryption at all.

Source: Wikipedia: Telnet

Why Remote Access?

  • Servers rarely have a screen
  • Admins work from anywhere
  • One door, many machines
Your laptopssh clientNetworknot trustedServersshd daemon

Telnet vs SSH

  • Telnet: anyone can read it
  • SSH: encrypted end to end
  • Never telnet to log in
Telnetplaintextpassword visibleno host check1969 designSSHencryptedkeys or passwordhost key verified1995 design

Use Case: Public Wi-Fi

  • Others on the Wi-Fi can listen
  • Telnet shows your password
  • SSH scrambles the session
Admin logs in from a cafeon shared Wi-Fitelnet leaks it; ssh hides itplaintext vs encryptedOnly ssh is safe to usea sniffer sees gibberish

Client and Server

  • ssh: the client you run
  • sshd: the daemon that listens
  • Default port: 22
sshyour clientport 22sshdthe daemon

Install the Server

  • Not installed by default
  • The service is named ssh
  • Confirm it listens on 22
$ sudo apt install -y openssh-server $ sudo systemctl enable --now ssh $ ss -tln | grep :22 LISTEN 0 128 0.0.0.0:22 0.0.0.0:* # sshd is now listening on port 22

Install the Server

$ sudo apt install -y openssh-server $ sudo systemctl enable --now ssh $ ss -tln | grep :22 LISTEN 0 128 0.0.0.0:22 0.0.0.0:* # sshd is now listening on port 22

First Connection

  • First contact: verify the host
  • Fingerprint = host key hash
  • yes saves it: known_hosts
$ ssh localhost The authenticity of host 'localhost' can't be established. ED25519 key fingerprint is: SHA256:HVKYQ0EDw40gswozBkMR7BQmdOC... Continue connecting (yes/no)? yes # sample output, abbreviated

First Connection

$ ssh localhost The authenticity of host 'localhost' can't be established. ED25519 key fingerprint is: SHA256:HVKYQ0EDw40gswozBkMR7BQmdOC... Continue connecting (yes/no)? yes # sample output, abbreviated
WHAT IS A FINGERPRINT?Your server's real keyssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI0h3H...(a very long string)too long to read at a glanceIts fingerprintSHA256:HVKYQ0E7XwPn2m... (short, easy to compare)A fingerprint is a short stand-in for the real key -- same idea as a human fingerprint:small, unique enough to check, without carrying around the whole person.

Word Origin: "Fingerprint"

finger
  • the body part
print
  • a mark it leaves behind

A key fingerprint is a short hash that identifies a key, the way a person's print identifies them.

Source: etymonline: fingerprint

known_hosts Warns You

  • ~/.ssh/known_hosts keeps keys
  • A changed key stops the login
  • Rebuilt server, or an attacker
WARNING: REMOTE HOST IDENTIFICATIONHAS CHANGED!Host key verification failed.

⚠️ Deleting the old key without asking why it changed defeats the warning.

Check: Trust This Prompt?

  • First login asks yes or no
  • The fingerprint is unfamiliar
  • What do you do first?
Verify it

Answer: compare it with the owner's published fingerprint, then type yes

Questions?

SSH Keys & Hardening

SSH KEYS & HARDENING: FOUR STEPSLogging In Without a PasswordMake a Keyssh-keygenInstall Itssh-copy-idRemember Itssh-agent, ssh-addLock the Doorsshd -t, then turn off passwordsEach step only makes sense once the one before it is done.Each gets its own closer look next.
ASYMMETRIC VS. SYMMETRIC ENCRYPTIONTWO WAYS SSH KEEPS A CONNECTION SAFEAsymmetric: Two Different Keys• Public key: safe to hand out• Private key: never shared, ever• Used to log in (ssh-keygen)• Slower, used only at the startSymmetric: One Shared Key• Same key locks and unlocks• Both sides must already have it• Used for your actual session data• Much faster, used the whole timeSSH uses both: asymmetric to prove who you are, then a fast symmetric key for everything you type after that.The ssh-keygen keypair you made is the asymmetric half. The symmetric half is negotiated automatically, every connection.
A KEY PAIR, IN PLAIN TERMSTHINK OF IT LIKE A PADLOCK AND ITS KEYYour PRIVATE keythe one real key -- only you hold it, everYour PUBLIC keya copy of the padlock -- fine to hand outServer AServer BServer CIf someone else sees your padlock,nothing bad happens -- it only LOCKS.Only your real key can open anything it locked.Give the padlock (public key) to every server you use. Never give the key (private key) to anyone, ever.This pair is made together, once, by a command called ssh-keygen -- more on that soon.

History of SSH Keys

  • Public keys arrived in 1976
  • SSH added key login
  • Ed25519 is now the default
1976Diffie and Hellman publishpublic-key cryptography1977RSA is described publicly,a public-key cipher2014OpenSSH 6.5 adds Ed25519keys, small and fast2023OpenSSH 9.5 makes Ed25519the ssh-keygen defaultTodayKeys replace passwords onwell-run servers

How Key Login Works

  • Server holds your public key
  • Server sends a challenge
  • Private key never leaves you
1. Server has your public key2. Server sends a challenge3. Your private key signs it4. Signature checks out: in

Word Origin: "Cipher"

cifre
  • Old French: zero, nought
cipher
  • secret writing, 1520s

A cipher began as the word for zero. Early codes swapped numbers for letters, so the name stuck.

Source: etymonline: cipher

TWO KEYS, ONE STAYSONE KEY PAIR, TWO VERY DIFFERENT JOBSid_ed25519 (PRIVATE)never leaves this machineid_ed25519.pub (PUBLIC)safe to copy anywhereServer AServer BServer CNo outgoing arrow, on purpose:the private key is never copied,not even to a server you trust.ssh-keygen makes both files at once. Only the .pub half ever travels.

Make a Key Pair

  • ed25519: small key, strong
  • -C labels which key this is
  • A passphrase locks the file
$ ssh-keygen -t ed25519 -C lab5 # -t: which key algorithm to use Enter passphrase (empty for none): # empty: convenient, but less safe Your identification has been saved in /home/student/.ssh/id_ed25519 # id_ed25519: PRIVATE, .pub: PUBLIC

Make a Key Pair

$ ssh-keygen -t ed25519 -C lab5 # -t: which key algorithm to use Enter passphrase (empty for none): # empty: convenient, but less safe Your identification has been saved in /home/student/.ssh/id_ed25519 # id_ed25519: PRIVATE, .pub: PUBLIC

More Examples: ssh-keygen

  • A custom filename
  • Recover a lost public key
  • Check a key's fingerprint
$ ssh-keygen -t ed25519 -f ~/.ssh/id_lab # -f: a custom filename, not the # default -- lets you keep 2+ keys $ ssh-keygen -y -f ~/.ssh/id_ed25519 # -y: print the PUBLIC half from # the private file, if .pub is lost $ ssh-keygen -l -f ~/.ssh/id_ed25519.pub # -l: show the key's fingerprint

More Examples: ssh-keygen

$ ssh-keygen -t ed25519 -f ~/.ssh/id_lab # -f: a custom filename, not the # default -- lets you keep 2+ keys $ ssh-keygen -y -f ~/.ssh/id_ed25519 # -y: print the PUBLIC half from # the private file, if .pub is lost $ ssh-keygen -l -f ~/.ssh/id_ed25519.pub # -l: show the key's fingerprint

Use Case: One Key, Many Servers

  • 12 servers, one admin
  • ssh-keygen once
  • Copy it to each, no passwords
12 servers to manageone admin, one laptopssh-keygen oncessh-copy-id to each serverOne key, no more passwordsper-server passwords, gone

Use Case: Separate Keys Per Purpose

  • Work and personal, same laptop
  • ssh-keygen -f a 2nd file
  • Revoke just one, not both
Work GitHub, personal GitHubsame laptop, different accountsssh-keygen -f id_worka separate key pair for workRevoke just one keythe personal key is untouched
BEFORE / AFTERBEFORE: NO KEY TRUSTED YETauthorized_keysempty or missingAFTER: ssh-copy-id APPENDS YOUR KEYid_ed25519.pubyour public keyssh-copy-idauthorized_keysyour key, one more lineYour PASSWORD is asked once here, to prove it is really youbefore the key gets trusted. Every login after this uses the key instead.

Install Your Public Key

  • Appends to authorized_keys
  • Creates ~/.ssh if missing
  • Asks for the password once
$ ssh-copy-id localhost # asks your PASSWORD once, to # prove it's really you Number of key(s) added: 1 # your public key is now trusted Now try logging into the machine: ssh 'localhost' # output abbreviated

Install Your Public Key

$ ssh-copy-id localhost # asks your PASSWORD once, to # prove it's really you Number of key(s) added: 1 # your public key is now trusted Now try logging into the machine: ssh 'localhost' # output abbreviated

More Examples: ssh-copy-id

  • Copy a specific key
  • A non-default port
  • The manual equivalent
$ ssh-copy-id -i ~/.ssh/id_lab.pub host # -i: copy THIS key, not the default $ ssh-copy-id -p 2222 user@host # -p: server listens on a non-default port $ cat ~/.ssh/id_ed25519.pub | \ ssh user@host 'cat >> ~/.ssh/authorized_keys' # the manual version, automated by ssh-copy-id

More Examples: ssh-copy-id

$ ssh-copy-id -i ~/.ssh/id_lab.pub host # -i: copy THIS key, not the default $ ssh-copy-id -p 2222 user@host # -p: server listens on a non-default port $ cat ~/.ssh/id_ed25519.pub | \ ssh user@host 'cat >> ~/.ssh/authorized_keys' # the manual version, automated by ssh-copy-id

Use Case: Lost Laptop

  • Revoke one key, not everyone
  • Remove its line on the server
  • No shared password to change
An admin laptop is lostits private key is on itEdit authorized_keysremove that one key lineThat laptop is locked outother admins are unaffected

Use Case: Onboarding a New Admin

  • A new admin joins the team
  • ssh-copy-id to every server
  • No shared password, ever
New admin joinsneeds access to every serverssh-copy-id their keyto each server they will manageNo shared password existseach admin has their own key
WITHOUT vs WITH THE AGENTWITHOUT ssh-agentEvery ssh, scp, rsync callasks for the passphraseType it EVERY timeno memory between callsWITH ssh-addssh-addtype it ONCEunlocksssh-agentholds it in memoryreusedEvery later callno prompt at allThe agent only holds the key for THIS login session.ssh-add -l lists what is loaded; ssh-add -D forgets everything.

Remember It: ssh-agent

  • The agent holds unlocked keys
  • ssh-add loads one key
  • Type the passphrase once
$ eval "$(ssh-agent -s)" # starts the agent for this shell Agent pid 3120 $ ssh-add ~/.ssh/id_ed25519 # unlocks once, holds it in memory Identity added: id_ed25519 (lab5) $ ssh-add -l # -l: list what the agent has loaded 256 SHA256:HVKYQ0E... lab5 (ED25519)

Remember It: ssh-agent

$ eval "$(ssh-agent -s)" # starts the agent for this shell Agent pid 3120 $ ssh-add ~/.ssh/id_ed25519 # unlocks once, holds it in memory Identity added: id_ed25519 (lab5) $ ssh-add -l # -l: list what the agent has loaded 256 SHA256:HVKYQ0E... lab5 (ED25519)

More Examples: ssh-add

  • Auto-expire after an hour
  • Forget every loaded key
  • Print the full public keys
$ ssh-add -t 3600 ~/.ssh/id_ed25519 # -t: auto-expires in 1 hour, safer # on a machine you don't fully trust $ ssh-add -D # -D: forget every key in the agent $ ssh-add -L # -L: print the FULL public keys # (lowercase -l shows fingerprints)

More Examples: ssh-add

$ ssh-add -t 3600 ~/.ssh/id_ed25519 # -t: auto-expires in 1 hour, safer # on a machine you don't fully trust $ ssh-add -D # -D: forget every key in the agent $ ssh-add -L # -L: print the FULL public keys # (lowercase -l shows fingerprints)

Use Case: Many Logins

  • One passphrase, many logins
  • Every ssh tool reuses it
  • The key never leaves the agent
Deploy to 12 serverseach one needs a loginssh-add, onceunlock the key one time12 logins, one passphrasethe agent signs each one

Use Case: Forwarded Agent

  • Jump through a bastion
  • ssh -A bastion, then ssh on
  • Key never leaves your laptop
Bastion, then a private hosttwo hops to reach the serverssh -A bastionforwards agent access onlyssh the private hostkey never left your laptop

Case: Password Refused

  • Since Aug 13, 2021
  • Git rejects account passwords
  • Use an SSH key or a token
  • A mistyped URL asks too
Username for github.com: studentremote: Invalid username or token.Password authentication is notsupported for Git operations.fatal: Authentication failed

Source: GitHub blog: token authentication

Log In With an SSH Key

  • Add your .pub key to GitHub
  • Test: ssh -T git@github.com
  • GitHub gives Git, not a shell
$ cat ~/.ssh/id_ed25519.pub ssh-ed25519 AAAAC3NzaC1... lab5 # paste this into GitHub, SSH keys $ ssh -T git@github.com Hi USERNAME! You've successfully authenticated, but GitHub does not provide shell access.

Log In With an SSH Key

$ cat ~/.ssh/id_ed25519.pub ssh-ed25519 AAAAC3NzaC1... lab5 # paste this into GitHub, SSH keys $ ssh -T git@github.com Hi USERNAME! You've successfully authenticated, but GitHub does not provide shell access.

Case: Host Key Rotated

  • Private RSA host key exposed
  • Replaced on March 24, 2023
  • Users saw a scary warning
Key exposed in a public repoGitHub replaces the RSA keyknown_hosts no longer matchesFix: ssh-keygen -R github.com

Source: GitHub blog: RSA SSH host key

Fix a Changed Host Key

  • Read GitHub's announcement
  • Compare the new fingerprint
  • Then remove the old entry
$ ssh-keygen -R github.com # drops the old key from known_hosts $ ssh -T git@github.com # verify the new fingerprint, then yes

⚠️ Only accept a new key after checking the published fingerprints.

Source: GitHub docs: SSH key fingerprints

Fix a Changed Host Key

$ ssh-keygen -R github.com # drops the old key from known_hosts $ ssh -T git@github.com # verify the new fingerprint, then yes

Deploy Keys: One Repo

  • A key tied to one repository
  • Read-only by default
  • Least privilege for servers
deploykeycourse-siteread onlyother-repodeniedprivate-repodenied

Source: GitHub docs: deploy keys

The sshd_config File

  • /etc/ssh/sshd_config is policy
  • Drop-ins live in sshd_config.d
  • First value wins: name it 10-
PasswordAuthenticationyes or noPermitRootLoginno blocks rootPubkeyAuthenticationyes: allow keysMaxAuthTriestries per connectionAllowUsersonly these accounts

Source: man7: sshd_config(5)

Write a Hardening File

  • Test key login FIRST
  • Then turn passwords off
  • Root over ssh: no
$ echo "PasswordAuthentication no" | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf $ echo "PermitRootLogin no" | \ sudo tee -a \ /etc/ssh/sshd_config.d/10-lab.conf

⚠️ Turn passwords off before keys work and you are locked out.

Write a Hardening File

$ echo "PasswordAuthentication no" | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf $ echo "PermitRootLogin no" | \ sudo tee -a \ /etc/ssh/sshd_config.d/10-lab.conf
CHECK, THEN RELOAD, THEN CONFIRMEdit the configa drop-in filesudo sshd -tsilent = validreloadapply it livesudo sshd -Tconfirm what is liveA syntax error caught here never reaches a live reload.Skipping -t is exactly how a remote session gets locked out for good.

Check Before You Reload

  • -t checks syntax, silently
  • Silent means it is valid
  • -T prints the live settings
$ sudo sshd -t # silent output = the config is valid $ sudo systemctl reload ssh # apply it without dropping sessions $ sudo sshd -T | grep -i passwordauth # -T prints every EFFECTIVE setting passwordauthentication no $ echo $? # 0: the last command succeeded

Check Before You Reload

$ sudo sshd -t # silent output = the config is valid $ sudo systemctl reload ssh # apply it without dropping sessions $ sudo sshd -T | grep -i passwordauth # -T prints every EFFECTIVE setting passwordauthentication no $ echo $? # 0: the last command succeeded

More Examples: sshd -t

  • Chain the check and reload
  • Preview a DRAFT file first
  • Check one setting is live
$ sudo sshd -t && sudo systemctl reload ssh # reload runs ONLY if -t passed $ sudo sshd -T -f ~/draft-sshd.conf # -T -f: preview a DRAFT file's # effect before it is ever installed $ sudo sshd -T | grep -i permitroot # check one specific setting is live

More Examples: sshd -t

$ sudo sshd -t && sudo systemctl reload ssh # reload runs ONLY if -t passed $ sudo sshd -T -f ~/draft-sshd.conf # -T -f: preview a DRAFT file's # effect before it is ever installed $ sudo sshd -T | grep -i permitroot # check one specific setting is live

Use Case: Safe Change

  • A typo can stop sshd
  • Remote, that means no way back
  • sshd -t catches it first
Edit sshd_config remotelyone typo is enoughsudo sshd -tchecks syntax, silentlyOnly then: reloadyou keep your way in

Use Case: Config Review

  • A teammate proposes 1 setting
  • sshd -T -f their-draft.conf
  • See it before it goes live
One new setting proposednot yet installed anywheresshd -T -f draft.confpreviews the effective resultReviewed before going liveno live risk taken to check it

Case: The xz Backdoor

  • xz 5.6.0 and 5.6.1, 2024
  • A backdoor aimed at sshd
  • Caught by one engineer
Malicious code in xz releasesSome sshd builds load liblzmasshd could be compromisedFound by Andres Freund, Mar 29

Source: oss-security: xz/liblzma backdoor

Case: regreSSHion

  • CVE-2024-6387, July 2024
  • A race condition in sshd
  • Root code execution possible
OpenSSH 8.5p1 to 9.7p1Vulnerable: sshd race conditionOpenSSH 9.8 fixes it

Source: OpenSSH 9.8 release notes

Check: Lock Passwords Now?

  • PasswordAuthentication no
  • Your key login is untested
  • What could go wrong?
Locked out

Answer: test key login in a second session first, then lock passwords

Questions?

Tunnels, Sync & tmux

History of Remote Tools

  • Screen came first, in 1987
  • rsync arrived in 1996
  • tmux and -J came later
1987GNU Screen: many terminalsin one window1996rsync announced by Tridgelland Mackerras2007tmux is first released,a modern multiplexer2016OpenSSH 7.3 adds ProxyJump,the -J jump-host optionTodayTunnels, syncs and sessionsare standard admin kit
BEYOND LOGIN: THREE MORE JOBS FOR sshOne SSH Connectionalready logged in, already trustedTunnel a Portssh -L -- reach a private serviceSync Filesrsync -- copy only what changedPersistent Sessiontmux -- survives a dropped linkThree different jobs -- one thing in common: all three run over the ssh connection you already have.Each gets its own closer look next.

Config File Shortcuts

  • One block per host
  • An alias replaces options
  • ssh, scp, rsync all read it
# ~/.ssh/configHost lab HostName localhost ServerAliveInterval 30

Use the Alias

  • Append the block with tee
  • Keep config private: 600
  • Then: ssh lab
$ tee -a ~/.ssh/config << 'EOF' Host lab HostName localhost ServerAliveInterval 30 EOF $ chmod 600 ~/.ssh/config $ ssh lab # one word replaces the options

Use the Alias

$ tee -a ~/.ssh/config << 'EOF' Host lab HostName localhost ServerAliveInterval 30 EOF $ chmod 600 ~/.ssh/config $ ssh lab # one word replaces the options

Word Origin: "Bastion"

bastion
  • a fortress's strong point
bastion host
  • credited to Marcus Ranum, 1990

A bastion host is the one hardened machine you must pass through to reach the rest.

Source: Wikipedia: Bastion host

Jump Through a Bastion

  • One hardened door in front
  • -J hops through it
  • Private servers stay hidden
ssh -J bastion app1LaptopyousshBastionpublic doorsshApp serverprivate

⚠️ bastion and app1 are example names; define them in your config first.

Use Case: One Front Door

  • One hardened entry point
  • One place to log and audit
  • Private servers stay hidden
40 servers, no public IPsonly the bastion is exposedssh -J bastion app1hop through the front doorOne log of every logineasy to audit and patch

Word Origin: "Tunnel"

tonnelle
  • Old French: a bird net
tunnel
  • a covered passage

A network tunnel is a covered passage: traffic goes in one end and comes out the other, out of sight.

Source: etymonline: tunnel

Local Port Forwarding

  • -L opens a local port
  • Traffic rides the ssh link
  • The far side sees ssh only
ssh -L 9000:localhost:8000 hostcurlport 9000sshencryptedweb appport 8000
WHY YOU NEED A TUNNEL: ssh -LWITHOUT -L: THE SERVICE REFUSES AN OUTSIDE CONNECTIONYour laptopwants server:8000REFUSEDThe server8000 bound to 127.0.0.1 onlyWITH ssh -L: THE TUNNEL CARRIES YOUR TRAFFIC INYour laptoplocalhost:9000ssh tunnelsshdforwards the portsame portThe serverlocalhost:8000, unchangedSame port number, same private service.Only the path changes: through the encrypted ssh session, not the open network.ssh -N -L 9000:localhost:8000 user@host-N: no remote shell, tunnel only • -L local_port:host:remote_port

Forward a Port: ssh -L

  • -L local:host:port
  • host:port: seen by the SERVER
  • -N: tunnel only, no shell
  • Runs until you close it
$ sudo apt install -y curl # curl: to prove the tunnel works $ python3 -m http.server 8000 \ --bind 127.0.0.1 & # a private service, localhost only $ ssh -N -L 9000:localhost:8000 \ localhost & # -N: no shell -L: forward this port $ curl -s localhost:9000 | head -3 # arrives through the tunnel, not direct

Forward a Port: ssh -L

$ sudo apt install -y curl # curl: to prove the tunnel works $ python3 -m http.server 8000 \ --bind 127.0.0.1 & # a private service, localhost only $ ssh -N -L 9000:localhost:8000 \ localhost & # -N: no shell -L: forward this port $ curl -s localhost:9000 | head -3 # arrives through the tunnel, not direct

More Examples: ssh -L

  • Reach a private service
  • 2nd host: resolved by server
  • -f -N: keeps tunnel running
$ ssh -L 9000:localhost:8000 user@host # reach the SERVER's own port 8000 # from YOUR OWN localhost:9000 $ ssh -L 5432:db.internal:5432 bastion # db.internal: resolved by the SERVER # not looked up on your own machine $ ssh -f -N -L 9000:localhost:8000 host # -f: keep running after login # -N: no shell, tunnel only

More Examples: ssh -L

$ ssh -L 9000:localhost:8000 user@host # reach the SERVER's own port 8000 # from YOUR OWN localhost:9000 $ ssh -L 5432:db.internal:5432 bastion # db.internal: resolved by the SERVER # not looked up on your own machine $ ssh -f -N -L 9000:localhost:8000 host # -f: keep running after login # -N: no shell, tunnel only

Use Case: Private Page

  • Admin pages stay off the web
  • Reach them through ssh only
  • No new firewall holes
A web admin page listenson the server localhost onlyssh -L 9000:localhost:8000tunnel to that pageOpen localhost:9000reachable, never exposed

Use Case: Reaching a Database

  • App needs an internal DB
  • Reach it through one bastion
  • No new firewall holes
App needs db.internalnot reachable directlyTunnel to the databasessh -L 5432:db.internal:5432psql via localhost:5432reaches db.internal safely
COPY EVERYTHING vs COPY THE DIFFERENCEcp / scp: RESENDS THE WHOLE FILE, EVERY TIME10 MB file, 1 line changedsame file, one small editresendsALL 10 MB, againno memory of the last copyrsync: COMPARES FIRST, SENDS ONLY THE DIFFERENCE10 MB file, 1 line changedthe exact same editcomparesOnly the changed BLOCKa few KB, not 10 MBOn a slow link, or a nightly job over many files, this difference is the whole point.

Sync Folders: rsync

  • Copies only what changed
  • -a keeps modes and times
  • -n is a safe dry run
$ sudo apt install -y rsync # not installed by default $ mkdir -p ~/lab5 $ rsync -avn ~/lab5/ localhost:lab5-copy/ # -n: DRY RUN, shows the plan only sending incremental file list $ rsync -av ~/lab5/ localhost:lab5-copy/ # trailing / copies the folder's contents

Sync Folders: rsync

$ sudo apt install -y rsync # not installed by default $ mkdir -p ~/lab5 $ rsync -avn ~/lab5/ localhost:lab5-copy/ # -n: DRY RUN, shows the plan only sending incremental file list $ rsync -av ~/lab5/ localhost:lab5-copy/ # trailing / copies the folder's contents

More Examples: rsync

  • Also delete removed files
  • Compress for a slow link
  • Skip matching files
$ rsync -av --delete ~/lab5/ dst/ # --delete: ALSO remove files at dst # that no longer exist at the source $ rsync -avz ~/lab5/ localhost:dst/ # -z: compress in transit $ rsync -av --exclude '*.log' ~/lab5/ dst/ # skip files matching this pattern

More Examples: rsync

$ rsync -av --delete ~/lab5/ dst/ # --delete: ALSO remove files at dst # that no longer exist at the source $ rsync -avz ~/lab5/ localhost:dst/ # -z: compress in transit $ rsync -av --exclude '*.log' ~/lab5/ dst/ # skip files matching this pattern

Use Case: Nightly Backup

  • Copy only what changed
  • A dry run shows it first
  • A re-run picks up the rest
Copy 50 GB every nightmost files never changersync -av src/ host:dst/sends only the differencesMinutes, not hourssafe to re-run anytime

Use Case: Safe Delete Sync

  • A local folder was cleaned up
  • rsync -av --delete
  • Backup matches exactly now
Files removed locallythe source folder was cleaned uprsync -av --deletealso removes them at dstBackup matches exactlynothing orphaned, nothing stale

Word Origin: "Multiplexer"

multi
  • Latin: many
plex
  • Latin: fold

A terminal multiplexer folds many terminals into one window. tmux is one.

Source: etymonline: multiplex

A DROPPED LINK, TWO OUTCOMESWITHOUT tmux: THE LINK OWNS YOUR JOBssh sessionyour long job runs herelink dropsSIGHUP sentthe job dies with the shellWITH tmux: THE SESSION OWNS YOUR JOBtmux sessionyour long job runs INSIDE itlink dropsJob keeps runningreattach any time: tmux attachThe job is a child of tmux, not of your ssh session -- the link dropping is now beside the point.

Keep a Session: tmux

  • Dropped links kill shells
  • tmux keeps the session alive
  • Detach, then attach later
$ sudo apt install -y tmux # not installed by default $ tmux new -s work # starts a NEW named session # run a long job, then Ctrl+b and d # Ctrl+b d: DETACHES, job keeps going $ tmux ls work: 1 windows (created ...) $ tmux attach -t work # reattach: right where you left off

Keep a Session: tmux

$ sudo apt install -y tmux # not installed by default $ tmux new -s work # starts a NEW named session # run a long job, then Ctrl+b and d # Ctrl+b d: DETACHES, job keeps going $ tmux ls work: 1 windows (created ...) $ tmux attach -t work # reattach: right where you left off

More Examples: tmux

  • Create it already detached
  • End a session you are done
  • Split the window, one keybind
$ tmux new -s upgrade -d # -d: create it ALREADY detached $ tmux kill-session -t work # ends a session you no longer need # Ctrl+b % splits the pane vertically # Ctrl+b " splits it horizontally # both stay in the SAME session

More Examples: tmux

$ tmux new -s upgrade -d # -d: create it ALREADY detached $ tmux kill-session -t work # ends a session you no longer need # Ctrl+b % splits the pane vertically # Ctrl+b " splits it horizontally # both stay in the SAME session

Use Case: Long Upgrade

  • Wi-Fi drops, the job survives
  • Reattach and check progress
  • Half-finished upgrades hurt
OS upgrade over hotel Wi-Fithe link may droptmux new -s upgraderun it inside a sessionReconnect, tmux attachthe upgrade kept going

Use Case: Watch Two Things at Once

  • Watch a log, run a command
  • Ctrl+b % splits the pane
  • One window, two views
Watch a log, run a commandneed both visible at onceCtrl+b % splits the panetwo panes, one tmux windowOne window, two live viewsno second terminal app needed

Why tmux Survives

  • Closing a terminal sends HUP
  • nohup ignores that signal
  • tmux runs its own server
Plain shelllink dropsSIGHUP is sentthe job diestmuxlink dropsserver keeps onthe job lives on

Check: Copy a Big Folder

  • 10,000 files, one changed
  • The link is slow
  • scp or rsync?
rsync

Answer: it sends only the changed file; scp would resend all 10,000

Questions?

Practice Lab

Lab at a Glance

  • Everything runs on one VM
  • Nine short steps
  • Proof: screenshots and output
1. sshd is up2. Key login works3. Passwords are off4. Jobs, tunnel, sync

Step 1: Watch and Filter

  • ps: one snapshot, right now
  • pgrep: filter by name only
  • jobs: your shell's own list
$ sleep 300 & # start a background job to look for $ ps aux | grep sleep # ps: a one-time snapshot, PID here $ pgrep -a sleep # pgrep: just the match, no ps needed $ top -bn1 | head -8 # top -bn1: one snapshot, no live screen $ jobs [1]+ Running sleep 300 &

Step 1: Watch and Filter

$ sleep 300 & # start a background job to look for $ ps aux | grep sleep # ps: a one-time snapshot, PID here $ pgrep -a sleep # pgrep: just the match, no ps needed $ top -bn1 | head -8 # top -bn1: one snapshot, no live screen $ jobs [1]+ Running sleep 300 &

Step 2: Install sshd

  • Not installed by default
  • Add curl, rsync, tmux too
  • Confirm port 22 listens
$ sudo apt install -y openssh-server \ curl rsync tmux python3 # sshd plus the tools used in this lab $ sudo systemctl enable --now ssh # start sshd now and at every boot $ ss -tln | grep :22 # confirm something listens on port 22

Step 2: Install sshd

$ sudo apt install -y openssh-server \ curl rsync tmux python3 # sshd plus the tools used in this lab $ sudo systemctl enable --now ssh # start sshd now and at every boot $ ss -tln | grep :22 # confirm something listens on port 22

Step 3: Key Login

  • Keygen on KALI, not Ubuntu
  • Copies to Ubuntu's account
  • Then log in with no password
# On Ubuntu: find its IP and user $ hostname -I $ whoami # On Kali: make a key, no passphrase $ ssh-keygen -t ed25519 -N "" -C lab5 $ ssh-copy-id UBUNTU_USER@UBUNTU_IP # yes to the fingerprint, then password $ ssh UBUNTU_USER@UBUNTU_IP hostname # prints Ubuntu's hostname, no password

Step 3: Key Login

# On Ubuntu: find its IP and user $ hostname -I $ whoami # On Kali: make a key, no passphrase $ ssh-keygen -t ed25519 -N "" -C lab5 $ ssh-copy-id UBUNTU_USER@UBUNTU_IP # yes to the fingerprint, then password $ ssh UBUNTU_USER@UBUNTU_IP hostname # prints Ubuntu's hostname, no password

Check: Which Port?

  • Back on Ubuntu's terminal
  • sshd is installed and up
  • Something must listen
  • On which port?
Port 22

Answer: ss -tln | grep :22 shows the listener

Step 4: Write the Policy

  • Drop-in file named 10-lab
  • Passwords off, root off
  • Keep this terminal open
$ echo "PasswordAuthentication no" | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf # passwords off: keys only from now on $ echo "PermitRootLogin no" | \ sudo tee -a \ /etc/ssh/sshd_config.d/10-lab.conf # -a adds a second line to the same file

Step 4: Write the Policy

$ echo "PasswordAuthentication no" | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf # passwords off: keys only from now on $ echo "PermitRootLogin no" | \ sudo tee -a \ /etc/ssh/sshd_config.d/10-lab.conf # -a adds a second line to the same file

Step 5: Test and Reload

  • -t checks, silently
  • reload keeps live sessions
  • Password login must fail
$ sudo sshd -t # silent means the config is valid $ sudo systemctl reload ssh # apply it without dropping sessions $ sudo sshd -T | grep -i passwordauth # shows the effective setting $ ssh -o PubkeyAuthentication=no localhost # expect: Permission denied (publickey)

Step 5: Test and Reload

$ sudo sshd -t # silent means the config is valid $ sudo systemctl reload ssh # apply it without dropping sessions $ sudo sshd -T | grep -i passwordauth # shows the effective setting $ ssh -o PubkeyAuthentication=no localhost # expect: Permission denied (publickey)

Check: Password Refused?

  • Password login is now off
  • ssh -o PubkeyAuthentication=no
  • What error do you expect?
Permission denied (publickey)

Answer: only key logins are offered, so the password path is gone

Step 6: Run a Job

  • nice starts it politely
  • ps -o shows the NI column
  • pkill stops it by name
$ nice -n 10 sleep 600 & # start a low-priority background job $ ps -o pid,ni,cmd -C sleep # the NI column shows the niceness, 10 $ pkill sleep # stop it by name

Step 6: Run a Job

$ nice -n 10 sleep 600 & # start a low-priority background job $ ps -o pid,ni,cmd -C sleep # the NI column shows the niceness, 10 $ pkill sleep # stop it by name

Step 7: Tunnel a Page

  • A tiny web server on 8000
  • A tunnel from 9000 to it
  • curl proves it works
$ python3 -m http.server 8000 \ --bind 127.0.0.1 & # a tiny web server on port 8000 $ ssh -N -L 9000:localhost:8000 \ localhost & # forward local port 9000 through ssh $ curl -s localhost:9000 | head -3 # the page arrives through the tunnel

Step 7: Tunnel a Page

$ python3 -m http.server 8000 \ --bind 127.0.0.1 & # a tiny web server on port 8000 $ ssh -N -L 9000:localhost:8000 \ localhost & # forward local port 9000 through ssh $ curl -s localhost:9000 | head -3 # the page arrives through the tunnel

Step 8: A Second Tunnel

  • Two ports, one ssh command
  • -L can repeat per tunnel
  • ss confirms both listening
$ python3 -m http.server 5000 \ --bind 127.0.0.1 & # a second private service, port 5000 $ ssh -N \ -L 9000:localhost:8000 \ -L 9500:localhost:5000 \ localhost & # -L can repeat: one tunnel, 2 ports $ ss -tln | grep -E '9000|9500' # both local ports are now listening

Step 8: A Second Tunnel

$ python3 -m http.server 5000 \ --bind 127.0.0.1 & # a second private service, port 5000 $ ssh -N \ -L 9000:localhost:8000 \ -L 9500:localhost:5000 \ localhost & # -L can repeat: one tunnel, 2 ports $ ss -tln | grep -E '9000|9500' # both local ports are now listening

Step 9: Sync and Persist

  • rsync copies over ssh
  • tmux -d starts it detached
  • pkill -f stops the helpers
$ mkdir -p ~/lab5 && touch ~/lab5/a.txt # a folder with one empty file $ rsync -av ~/lab5/ localhost:lab5-copy/ # copy it over ssh $ tmux new -s work -d # a session that survives logout $ pkill -f "http.server|ssh -N" # stop the web server and the tunnel

Step 9: Sync and Persist

$ mkdir -p ~/lab5 && touch ~/lab5/a.txt # a folder with one empty file $ rsync -av ~/lab5/ localhost:lab5-copy/ # copy it over ssh $ tmux new -s work -d # a session that survives logout $ pkill -f "http.server|ssh -N" # stop the web server and the tunnel

Deliverables

  • Screenshot: key login works
  • Screenshot: password refused
  • Paste: sshd -T passwordauth
  • Paste: ps line with NI 10
  • Paste: curl via the tunnel
  • Paste: ss shows both ports
  • Paste: jobs shows it running
✓Key login, no password✓Password login refused✓Effective sshd setting✓Niceness 10 in ps✓Page fetched by tunnel

Questions?

Practice Lab Part 2

Practice Lab Part 2, Q1

How do you find the process using the most CPU?

$ ps aux --sort=-%cpu | head -5 # --sort=-%cpu: busiest # process first

Practice Lab Part 2, Q2

How do you save one live snapshot of top's output to a file?

$ top -bn1 > snapshot.txt # -b: batch, -n1: one pass, # then exit

Practice Lab Part 2, Q3

How do you check if nginx is already running?

$ pgrep -a nginx # -a: shows the PID and # full command

Practice Lab Part 2, Q4

How do you free your terminal without stopping the job in it?

$ Ctrl+Z $ bg # Ctrl+Z pauses; bg resumes # it in the background

Practice Lab Part 2, Q5

How do you stop a process that won't respond to a normal request?

$ kill -9 PID # -9 (KILL): kernel forces # it, no cleanup

Practice Lab Part 2, Q6

How do you run a heavy job without slowing down other users?

$ nice -n 15 command # 15: low priority, yields # CPU on demand

Practice Lab Part 2, Q7

How do you make a new SSH key with no passphrase, for a lab only?

$ ssh-keygen -t ed25519 -N "" # -N "": empty passphrase, # less safe but convenient

Practice Lab Part 2, Q8

How do you avoid retyping your key's passphrase all day?

$ eval "$(ssh-agent -s)" $ ssh-add ~/.ssh/id_ed25519 # unlocks it once, holds it # in memory

Practice Lab Part 2, Q9

How do you reach a database that only listens on the server's own localhost?

$ ssh -L 5432:localhost:5432 \ user@host # -L: tunnels the remote # port to your own machine

Practice Lab Part 2, Q10

How do you copy a folder without resending files already up to date?

$ rsync -av src/ user@host:dst/ # -a: archive mode, -v: # verbose; only diffs sent

Questions?

Practice Lab Part 3

Scenario: Your Medical Unit

  • Ubuntu VM = a medical unit server
  • Kali VM = your operator machine
  • You connect Kali → Ubuntu over SSH
  • Task: find which processes belong
Kali(you)medical-unit(Ubuntu)4 processes runningssh (key)Which processes are needed?ps · top · pgrep · kill

Step 1: Confirm You're on Kali

  • Check your own machine first
  • whoami shows the logged-in user
  • hostname shows the machine name
$ whoami # confirms which account you are using kali $ hostname # confirms which machine you are on kali

Step 1: Confirm You're on Kali

$ whoami # confirms which account you are using kali $ hostname # confirms which machine you are on kali

Step 2: Find the Unit's Real IP

  • Run this on the Ubuntu VM
  • hostname -I: this machine's IP
  • Write it down for the next step
$ hostname -I # -I: this machine's own IP address 10.0.2.15

Step 2: Find the Unit's Real IP

$ hostname -I # -I: this machine's own IP address 10.0.2.15

Step 3: Ping the Unit

  • Still on Kali, using the raw IP
  • Confirms basic reachability
  • Do this before trying SSH at all
$ ping -c 3 10.0.2.15 # -c 3: send exactly 3 pings, then stop 64 bytes from 10.0.2.15: icmp_seq=1 64 bytes from 10.0.2.15: icmp_seq=2 64 bytes from 10.0.2.15: icmp_seq=3 0% packet loss

Step 3: Ping the Unit

$ ping -c 3 10.0.2.15 # -c 3: send exactly 3 pings, then stop 64 bytes from 10.0.2.15: icmp_seq=1 64 bytes from 10.0.2.15: icmp_seq=2 64 bytes from 10.0.2.15: icmp_seq=3 0% packet loss

Step 4: Verify Your Sudo Account

  • On the medical unit's own console
  • sudo -l: what you are allowed to run
  • Confirm this before Step 6 needs it
$ sudo -l # -l: list what you are allowed to run User ubuntu may run: (ALL : ALL) ALL

Step 4: Verify Your Sudo Account

$ sudo -l # -l: list what you are allowed to run User ubuntu may run: (ALL : ALL) ALL

Step 5: Name the Medical Unit

  • Back on Kali now
  • Map a friendly name to that IP
  • Avoids clashing with a real DNS name
$ echo "10.0.2.15 medical-unit" \ | sudo tee -a /etc/hosts # tee -a: appends to /etc/hosts as root $ getent hosts medical-unit # confirms the mapping now resolves 10.0.2.15 medical-unit

Step 5: Name the Medical Unit

$ echo "10.0.2.15 medical-unit" \ | sudo tee -a /etc/hosts # tee -a: appends to /etc/hosts as root $ getent hosts medical-unit # confirms the mapping now resolves 10.0.2.15 medical-unit

Step 6: Make Your SSH Key

  • Generate a keypair on Kali
  • ed25519: modern, short, fast
  • Private key never leaves Kali
$ ssh-keygen -t ed25519 # -t ed25519: modern, compact key type Enter file: (press Enter) Enter passphrase: (press Enter) $ ls ~/.ssh/id_ed25519.pub # confirms the public key was created /home/kali/.ssh/id_ed25519.pub

Step 6: Make Your SSH Key

$ ssh-keygen -t ed25519 # -t ed25519: modern, compact key type Enter file: (press Enter) Enter passphrase: (press Enter) $ ls ~/.ssh/id_ed25519.pub # confirms the public key was created /home/kali/.ssh/id_ed25519.pub

Step 7: Set a Password Once

  • On the medical unit, one time only
  • ssh-copy-id needs a first login
  • passwd sets it for your account
$ sudo passwd $(whoami) # sets a login password for this account New password: ******** $ passwd -S $(whoami) # -S: shows the account's password status ubuntu P 09/24/2026 0 99999 7 -1

Step 7: Set a Password Once

$ sudo passwd $(whoami) # sets a login password for this account New password: ******** $ passwd -S $(whoami) # -S: shows the account's password status ubuntu P 09/24/2026 0 99999 7 -1

Step 8: Copy Your Public Key

  • Back on Kali
  • ssh-copy-id sends the public half
  • Only *.pub ever leaves your machine
$ ssh-copy-id $(whoami)@medical-unit # sends only your *.pub file to the unit Password: ******** Number of key(s) added: 1 $ ssh-copy-id $(whoami)@medical-unit # re-run: 0 added means it is already there Number of key(s) added: 0

Step 8: Copy Your Public Key

$ ssh-copy-id $(whoami)@medical-unit # sends only your *.pub file to the unit Password: ******** Number of key(s) added: 1 $ ssh-copy-id $(whoami)@medical-unit # re-run: 0 added means it is already there Number of key(s) added: 0

Step 9: Connect With Your Key

  • Same command as always: ssh
  • No password prompt this time
  • You are logged in to the unit
$ ssh $(whoami)@medical-unit # no -i needed: ssh-agent offers it for you Welcome to Ubuntu 24.04 LTS

Step 9: Connect With Your Key

$ ssh $(whoami)@medical-unit # no -i needed: ssh-agent offers it for you Welcome to Ubuntu 24.04 LTS

Check: Why No Password?

SSH just let you in with no password prompt. What actually proved who you are?

Your private key, still only on Kali, mathematically proved you hold the matching public key already sitting in the unit's authorized_keys file. Nothing secret ever crossed the network.

Step 10: Get the Lab From GitHub

  • Still connected to the unit
  • Clone the class repository
  • Every module's labs live here
$ git clone https://github.com/ SE4CPS/2026-COMP-175 # clones the whole class repo, once $ ls 2026-COMP-175 # confirms the clone actually landed modules README.md

Step 10: Get the Lab From GitHub

$ git clone https://github.com/ SE4CPS/2026-COMP-175 # clones the whole class repo, once $ ls 2026-COMP-175 # confirms the clone actually landed modules README.md

Step 11: Go to This Lab's Folder

  • cd into module 5's practice lab
  • ls shows the scripts inside
  • spawn.sh starts everything
$ cd 2026-COMP-175/modules/ module-5/practicelab3 # this lab's own folder $ ls # spawn.sh is what starts everything spawn.sh vitals-logger.sh ...

Step 11: Go to This Lab's Folder

$ cd 2026-COMP-175/modules/ module-5/practicelab3 # this lab's own folder $ ls # spawn.sh is what starts everything spawn.sh vitals-logger.sh ...

Step 12: Start the Unit's Processes

  • Runs 4 background jobs at once
  • nohup + disown: survive logout
  • Returns right away, not stuck
$ bash spawn.sh # launches all 4 jobs, nohup'd + disowned Started 4 background processes. $ pgrep -c -f "logger|sync|job|nightly" # -c: just count the matches 4

Step 12: Start the Unit's Processes

$ bash spawn.sh # launches all 4 jobs, nohup'd + disowned Started 4 background processes. $ pgrep -c -f "logger|sync|job|nightly" # -c: just count the matches 4

Check: Why Does "Right Away" Matter?

spawn.sh printed its message and gave your prompt back immediately instead of hanging. Why is that the point of nohup and disown here?

A medical unit's monitoring jobs have to keep running after you log out; if the command hung waiting on your terminal, closing the SSH session would kill everything with it instead of leaving it running unattended.

Step 13: List Every Process

  • ps aux: every process, every user
  • A busy list, hard to scan
  • Next step narrows it down
$ ps aux # aux: every process, every user, full cmd USER PID %CPU COMMAND ...

Step 13: List Every Process

$ ps aux # aux: every process, every user, full cmd USER PID %CPU COMMAND ...

Step 14: Narrow to This Lab's Jobs

  • pgrep -a: match by name pattern
  • Only the 4 processes we started
  • Note each PID for later
$ pgrep -a -f "logger|sync|job|nightly" # -a: also show each match's full command 2201 vitals-logger.sh 2202 labsync.sh 2203 stuck-job.sh 2204 backup-nightly.sh

Step 14: Narrow to This Lab's Jobs

$ pgrep -a -f "logger|sync|job|nightly" # -a: also show each match's full command 2201 vitals-logger.sh 2202 labsync.sh 2203 stuck-job.sh 2204 backup-nightly.sh

Check: Low CPU Means Safe?

Two of these four barely use any CPU right now. Does low CPU usage alone prove a process is needed?

No. CPU usage only measures how busy something is, not whether the unit still needs it; a forgotten job can sit idle and low-CPU for days while still being the wrong thing to leave running.

Step 15: Watch Live Usage

  • top: a live, sorted view
  • Sorted by CPU, highest first
  • One process should stand out
$ top # live view, sorted by CPU by default PID %CPU COMMAND 2203 98.7 stuck-job.sh 2204 4.1 backup-nightly.sh 2201 0.1 vitals-logger.sh

Step 15: Watch Live Usage

$ top # live view, sorted by CPU by default PID %CPU COMMAND 2203 98.7 stuck-job.sh 2204 4.1 backup-nightly.sh 2201 0.1 vitals-logger.sh

Check: Is High CPU Alone the Proof?

stuck-job.sh is pinned near 100% CPU with no sign of slowing down. Is high CPU by itself always a reason to kill something?

Not always: a real batch job can legitimately max a core for a while; what actually condemns stuck-job.sh here is that it never lets up and does not match anything the unit is supposed to be running.

Step 16: Check the Schedule, Not Just Load

  • backup-nightly is meant for overnight
  • It is running right now, mid-shift
  • Timing is the real problem here
$ date # confirms the unit's own current time Mon Sep 23 02:14:00 PM PDT 2026

Step 16: Check the Schedule, Not Just Load

$ date # confirms the unit's own current time Mon Sep 23 02:14:00 PM PDT 2026

Check: Why Flag backup-nightly Too?

backup-nightly.sh only used about 4% CPU in Step 15, far below stuck-job.sh. Why does it still belong on your list?

A process can be "needed" in general but wrong right now: backup-nightly.sh is only supposed to run overnight, so seeing it mid-afternoon is the actual problem, not how much CPU it happens to be using.

Step 17: End the Runaway Job

  • kill takes a PID, not a name
  • Use the PID pgrep found earlier
  • Default signal: SIGTERM, ask nicely
$ kill 2203 # default signal: SIGTERM, ask nicely first $ pgrep -f stuck-job; echo $? # exit 1 = no match = the process is gone 1

Step 17: End the Runaway Job

$ kill 2203 # default signal: SIGTERM, ask nicely first $ pgrep -f stuck-job; echo $? # exit 1 = no match = the process is gone 1

Check: Why kill and Not pkill Here?

You could have run pkill stuck-job instead of kill 2203. Why use the exact PID in a real triage like this?

kill with a specific PID only ever ends the one process you already confirmed; pkill matches by name across the whole system, which risks catching something else with a similar name you never meant to touch.

Step 18: End the Mistimed Job

  • Same idea, different PID
  • backup-nightly can run tonight
  • Not now, during the shift
$ kill 2204 # same signal, different PID this time $ pgrep -f backup-nightly; echo $? # exit 1 confirms it is no longer running 1

Step 18: End the Mistimed Job

$ kill 2204 # same signal, different PID this time $ pgrep -f backup-nightly; echo $? # exit 1 confirms it is no longer running 1

Step 19: Confirm the Cleanup

  • Re-run the same pgrep as Step 14
  • Only 2 processes should remain
  • Both are ones the unit needs
$ pgrep -a -f "logger|sync|job|nightly" # same command as Step 14, run again 2201 vitals-logger.sh 2202 labsync.sh

Step 19: Confirm the Cleanup

$ pgrep -a -f "logger|sync|job|nightly" # same command as Step 14, run again 2201 vitals-logger.sh 2202 labsync.sh

Deliverable

  • Screenshot: pgrep before you killed anything
  • Screenshot: top showing stuck-job.sh's CPU
  • Screenshot: pgrep after, only 2 remain
  • One sentence: why each kill was correct

Questions?

Looking Ahead: Module 6

Module 6

Service Management

Services (units)what systemd managesControl (systemctl)start, stop, enableLogs (journalctl)why it did what it didSchedule (timers, cron)run work on a clock
WHERE A PROCESS COMES FROMTwo different triggers, one same kind of thingSERVICE SCOPEsystemctl startsystemctl stoponBootthe system startsA Processsame either wayonShutdownthe system stops./programonUserStartyou type a commandA Processsame either wayNo service scope: ends on its own, no onShutdown involved
MODULE 6 COMMANDS AT A GLANCECHECKsystemctl statussystemctl list-unitsCONTROLsystemctl startsystemctl restartsystemctl enablesystemctl daemon-reloadsystemctl maskINSPECTjournalctlsystemd-analyzesystemctl catSCHEDULEsystemctl list-timerscrontab

All Commands: Module 6

WHAT IS A SERVICE? THE BIG PICTUREA ServiceStarts Itselfno login neededManaged by systemdstart, stop, enableRuns as a Processhas its own PIDOne program, three angles: what it does, who runs it, what it becomes.The rest of this module is about that middle box: managing it.

Two Ways a Program Runs

  • Some programs need a person
  • Others start on their own
  • That second kind: a service
You Run a Programtype a command, it runsA Service Runs Itselfstarts at boot, no typing

What Happens at Boot

  • Boot runs in a fixed order
  • Enabled services need no login
  • Enable vs start comes next
Power Onthe machine startsKernel Loadsthe OS core wakes upsystemd Starts (PID 1)the very first processEnabled Services Startno person involvedYou Log Innow you can type commandsYou Run Programs by Handstarted, not enabled
COMMON SERVICES AND THEIR PURPOSEsshdRemote login and file transfercronRuns jobs on a fixed schedulesystemd-journaldCollects and stores system logsNetworkManagerManages network connectionsufw / firewalldFilters incoming network trafficcupsManages printers and print jobssystemd-timesyncdKeeps the system clock in syncdockerRuns and manages containersnginx / apache2Serves web pages to visitorsavahi-daemonFinds devices on the local network

History of Init

  • Init started services in order
  • systemd starts in parallel
  • Nearly all distros use it now
1980sSystem V init runs shellscripts by runlevel2006Ubuntu 6.10 ships Upstart,an event-based init2010Poettering posts "RethinkingPID 1": systemd begins2011Fedora is the first big distroto enable systemd by defaultTodaySince 2015 nearly all distrosrun systemd as PID 1

Service vs Process

  • A service is a managed unit
  • Its process is the live copy
  • systemd starts and watches it
cron.servicethe unit: name and settingssystemd starts itPID 1 is the managerPID 512 (cron)the process that results

Word Origin: "Init"

initium
  • Latin: a beginning
init
  • the first program at boot

Init is short for initialization: the program that begins everything else.

Source: etymonline: initial

Unit Types

  • A unit is what systemd runs
  • The suffix names the type
  • Most of your work is .service
.servicea daemon or a job.socketa listening socket.timera scheduled trigger.targeta group of units.mounta mounted filesystem

Word Origin: "Service"

servitium
  • Latin: servitude, a duty owed
service
  • work done for others

A service is a program that does its work quietly for everyone else.

Source: etymonline: service

Where Unit Files Live

  • Packages install to /usr/lib
  • Your edits go to /etc
  • /etc wins over /usr/lib
/usr/libshipped by packages/etcyours: overrides win~/.configper-user units only

Word Origin: "Unit"

unity
  • a single whole, Latin unus
unit
  • a single thing, 1560s

A unit is one manageable piece: a service, a timer, a mount.

Source: etymonline: unit

Check: Service or Process?

cron runs in the background all day. Is it a service, a process, or both?

Answer
Both. It is a process (it has a PID) that systemd manages as the service cron.service.

Questions?

Checking Services

CHECKING SERVICES: WHAT TO REACH FORIs It Running?See Onestatus: state and recent logsJust Yes or Nois-active: one wordSee Them Alllist-units: every unitFrom one service to the whole machine.Each gets a closer look next.

One Service: status

  • status shows one service
  • State, PID and recent logs
  • No sudo needed to read it
$ systemctl status cron # state of one service ● cron.service - Regular ... Loaded: loaded (...; enabled) Active: active (running) Main PID: 512 (cron) # q quits; output trimmed $ systemctl is-active cron # one word: active or inactive active

One Service: status

$ systemctl status cron # state of one service ● cron.service - Regular ... Loaded: loaded (...; enabled) Active: active (running) Main PID: 512 (cron) # q quits; output trimmed $ systemctl is-active cron # one word: active or inactive active

Reading status

  • Loaded: is the file found?
  • Active: running, failed...
  • Bottom lines: recent logs
Loadedunit file + enabled?Activerunning, failed, deadMain PIDthe process IDCGroupall its processesLogslast few journal lines

List All: list-units

  • Every loaded unit, one a line
  • --type=service: services only
  • --state narrows it further
$ systemctl list-units \ --type=service --state=running # only services running now UNIT ACTIVE SUB cron.service active running ssh.service active running # 3 columns kept to fit

List All: list-units

$ systemctl list-units \ --type=service --state=running # only services running now UNIT ACTIVE SUB cron.service active running ssh.service active running # 3 columns kept to fit

Use Case: Failed Portal

  • The portal reports errors
  • status shows Active: failed
  • The log lines say why
Ticket: portal errorsstaff cannot sign insystemctl status portalActive: failedRead the log, then fixrestart once it is fixed

Check: Read the Status

status shows Active: failed. Where do you look first to learn why?

Answer
The log lines at the bottom of systemctl status, or run journalctl -u NAME for the full log.

Check: Script Test

Which command prints only active or inactive, so a script can test it?

Answer
systemctl is-active NAME. It prints one word and sets the exit code.

Questions?

Starting & Stopping

STARTING AND STOPPING: CHANGE A SERVICE NOWChange the Running StateStart / Stopbegin or end it nowRestartstop, then start againReloadreread config, no outageThese change the running state only.They do not change what happens at boot.

Start and Stop

  • start runs it now
  • stop ends it now
  • Both need sudo
$ sudo systemctl start cron # no output means it worked $ sudo systemctl stop cron # stop it now $ systemctl is-active cron # check the result inactive

Start and Stop

$ sudo systemctl start cron # no output means it worked $ sudo systemctl stop cron # stop it now $ systemctl is-active cron # check the result inactive

Restart and Reload

  • restart: stop, then start
  • reload: reread the config
  • Reload needs service support
$ sudo systemctl restart cron # stop, then start again $ sudo systemctl reload ssh # reread config, keep running # not every service can reload

⚠️ Restart drops open connections; reload keeps them.

Restart and Reload

$ sudo systemctl restart cron # stop, then start again $ sudo systemctl reload ssh # reread config, keep running # not every service can reload

Use Case: Config Change

  • You edited the settings
  • Users must stay connected
  • Reload applies it in place
Edit ssh settingssessions are opensudo systemctl reload sshno restart, no dropNew settings, no outageusers never notice

Check: Restart or Reload?

You edited a service's settings, and users must stay connected. Restart or reload?

Answer
Reload, if the service supports it. Restart stops the service first, so connections drop.

Check: Stopped Means Gone?

You ran systemctl stop cron. Will cron be running after the next reboot?

Answer
Yes, if it is enabled. stop only ends it now. Boot behavior is set by enable and disable.

Questions?

Boot & Enable

BOOT AND ENABLE: WHAT RUNS AT STARTUPBoot BehaviorEnablestart it at every bootDisablestop starting it at bootAnalyzefind what slows the bootenable is about the NEXT boot.start is about right now.

Word Origin: "Boot"

bootstrap
  • a loop of leather on a boot
boot
  • pull yourself up, 1970s

A computer boots by pulling itself up: a tiny program loads the rest.

Source: etymonline: boot

Word Origin: "Target"

targe
  • a light, round shield
target
  • the mark aimed at

A target is a goal state that boot aims at, like multi-user.target.

Source: etymonline: target

Boot Targets

  • A target groups units
  • Boot aims at one target
  • get-default shows which
multi-usertext mode, all servicesgraphicaldesktop login on toprescuesingle-user repair moderebootrestart the machine

Boot Behavior: enable

  • enable: start at every boot
  • disable: stop doing that
  • --now also acts right away
$ sudo systemctl enable cron # start automatically at boot $ systemctl is-enabled cron enabled $ sudo systemctl disable cron # not at boot; runs until stop $ sudo systemctl enable --now \ cron # enable and start together

Boot Behavior: enable

$ sudo systemctl enable cron # start automatically at boot $ systemctl is-enabled cron enabled $ sudo systemctl disable cron # not at boot; runs until stop $ sudo systemctl enable --now \ cron # enable and start together

Enable vs Start

  • start: now, this boot only
  • enable: every boot, not now
  • enable --now: both
startruns now, gone after rebootenableruns at boot, not right nowenable --nowruns now and every boot

Slow Boot: analyze

  • Total boot time, split up
  • blame: slowest units first
  • Numbers differ per machine
$ systemd-analyze # total boot time Startup finished in 12.9s $ systemd-analyze blame | \ head -3 # slowest units first 3.2s apt-daily.service # example numbers only

Slow Boot: analyze

$ systemd-analyze # total boot time Startup finished in 12.9s $ systemd-analyze blame | \ head -3 # slowest units first 3.2s apt-daily.service # example numbers only

Use Case: Survive a Reboot

  • The service died after reboot
  • It was started, never enabled
  • enable fixes the next boot
Reboot: catalog is downit was only ever startedsystemctl is-enabled catalogprints disabledsudo systemctl enable catalogit now returns after reboot

Check: Start or Enable?

You ran systemctl start NAME. Will it run after the next reboot?

Answer
Not unless it is enabled. start acts now; enable links it into the boot process.

Check: Slow Boot

Which command lists the units that took the longest to start?

Answer
systemd-analyze blame. It lists every unit with its start time, slowest first.

Questions?

Reading Logs

READING LOGS: WHAT THE JOURNAL HOLDSRead the JournalBy Unit-u NAME: one serviceBy Time--since, -b: a windowBy Priority-p err: only problemsjournalctl reads one central log.Filters cut it down to the answer.

Word Origin: "Journal"

diurnalis
  • Late Latin: daily
jornel
  • Old French: a day's record

A journal is a daily record, and journald keeps one for every service.

Source: etymonline: journal

Read the Log: journalctl

  • One central log for everything
  • -n 3: the last 3 lines
  • Reading it may need sudo
$ journalctl -n 3 # last 3 lines, all services Sep 26 18:09 vm-ubuntu ... Sep 26 18:09 systemd[1]: ... $ journalctl -b # everything since this boot

Read the Log: journalctl

$ journalctl -n 3 # last 3 lines, all services Sep 26 18:09 vm-ubuntu ... Sep 26 18:09 systemd[1]: ... $ journalctl -b # everything since this boot

More Examples: journalctl

  • -u: one service only
  • -p err: errors and worse
  • -f: follow live
$ journalctl -u cron # just the cron service $ journalctl -p err # errors only $ journalctl --since \ "10 min ago" # a time window $ journalctl -u cron -f # live; Ctrl+C to stop

More Examples: journalctl

$ journalctl -u cron # just the cron service $ journalctl -p err # errors only $ journalctl --since \ "10 min ago" # a time window $ journalctl -u cron -f # live; Ctrl+C to stop

Use Case: Trace an Outage

  • Users lost service at 9:40
  • Filter the journal by time
  • The first error is the cause
Outage reported: 9:40nobody knows why yetjournalctl --since 09:30read around that timeFirst error line foundthat is the cause to fix

Word Origin: "Log"

log-book
  • a ship's daily record
log
  • a record of events

Sailors logged speed with a weighted log on a line; the record kept the name.

Source: etymonline: log

Check: Find the Error

How do you show only error-level messages from the ssh service?

Answer
journalctl -u ssh -p err. On Ubuntu the unit is ssh, not sshd.

Check: Which Folder?

The journal stores these entries somewhere real on disk. Which folder?

Answer
/var/log/journal/ if it exists (persists across reboots). Otherwise /run/log/journal/, which is cleared at every reboot.

Check: Where Do Logs Live?

Where does a service's output go, if it never writes its own log file?

Answer
To the journal. journald captures a service's output, and journalctl -u NAME shows it.

Questions?

Writing a Unit File

WHY WRITE A UNIT FILE? A Plain Script systemd doesn't know it exists You Write a Unit File a plain-text description of it Now systemd Manages It like any other service This is the missing step from earlier in the module: Checking, Starting & Stopping, Boot & Enable, and Reading Logs all now apply to your service too.
WHAT IS A UNIT FILE? dyno-monitor.sh the program: real code that runs and actually does the work dyno-monitor.service the unit file: plain text that describes how to run it ExecStart= The unit file is not the program: it never runs any code itself. It just tells systemd which program to run, and how to run it.
WHY DOES SYSTEMD NEED ONE? Every program is different: the unit file makes them all manageable the same way No Unit Filejust running the script by handsystemd doesn't know it existsNo start, stop, or restart ruleNo dependency orderNo systemctl status to checkWith a Unit Filesystemd owns it nowOne consistent way to manage itSame commands as every serviceCan wait on other unitssystemctl status just works Same idea as beat.service, cron.service, or sshd: every service has one.
WRITING A UNIT FILE: YOUR OWN SERVICEWrite Your Own UnitRead Onesystemctl cat: see the fileReloaddaemon-reload: reread filesBlock Onemask: forbid all startsA unit file is plain text.systemd only rereads it on demand.

Anatomy of a Unit

  • Three sections, in order
  • [Unit]: describe and order it
  • [Service]: how it runs
[Unit]Description=, After=[Service]ExecStart=, Restart=[Install]WantedBy= for enable

Word Origin: "Dependency"

dependere
  • Latin: to hang from
dependency
  • a thing that hangs on another

A dependency is something a service hangs from: it needs it to exist first.

Source: etymonline: depend

Restart Policies

  • Restart= sets the recovery
  • on-failure is a common pick
  • always never stays down
nonever restart (default)on-failurerestart if it crashesalwaysrestart on any exit

Read a Unit: cat

  • cat prints the unit file
  • Shows where it came from
  • Overrides show together
$ systemctl cat cron # /usr/lib/systemd/system/ # cron.service [Unit] Description=Regular background [Service] ExecStart=/usr/sbin/cron -f Restart=on-failure # output trimmed

Read a Unit: cat

$ systemctl cat cron # /usr/lib/systemd/system/ # cron.service [Unit] Description=Regular background [Service] ExecStart=/usr/sbin/cron -f Restart=on-failure # output trimmed

After Editing: reload

  • systemd caches unit files
  • daemon-reload rereads them
  • Then restart the service
$ sudo sed -i \ 's/Restart=on-failure/Restart=always/' \ /etc/systemd/system/beat.service # stream-edit one line, no editor $ sudo systemctl daemon-reload # needed after every change

⚠️ Skip daemon-reload and systemd may keep using the old file.

After Editing: reload

$ sudo sed -i \ 's/Restart=on-failure/Restart=always/' \ /etc/systemd/system/beat.service # stream-edit one line, no editor $ sudo systemctl daemon-reload # needed after every change

Word Origin: "Mask"

masca
  • Medieval Latin: a mask
maschera
  • Italian: a face covering

A masked unit is covered over: nothing can start it, even by hand.

Source: etymonline: mask

Block a Unit: mask

  • mask links it to /dev/null
  • Even a manual start fails
  • unmask undoes it
$ sudo systemctl mask cups # now it cannot be started $ sudo systemctl start cups Failed to start cups.service: Unit cups.service is masked. $ sudo systemctl unmask cups # allowed to start again

Block a Unit: mask

$ sudo systemctl mask cups # now it cannot be started $ sudo systemctl start cups Failed to start cups.service: Unit cups.service is masked. $ sudo systemctl unmask cups # allowed to start again

Use Case: Block a Service

  • A service must never run
  • disable still allows starts
  • mask blocks every start
Policy: no print servicekiosk machines onlysudo systemctl mask cupslink to /dev/nullNothing can start itnot even by hand

Check: Edited a Unit File

You changed a unit file, but systemd still uses the old settings. Why?

Answer
systemd caches unit files. Run sudo systemctl daemon-reload, then restart the service.

Check: Masked or Disabled?

What is the difference between disable and mask?

Answer
disable only stops the start at boot. mask blocks every start, even a manual one.

Questions?

Timers & Cron

TIMERS AND CRON: WORK ON A SCHEDULERun Work on a ScheduleTimerssystemd: list-timersCroncrontab: per-user jobsChoosetimers log and order workBoth run a job at a set time.Timers add logging and dependencies.
CRON VS. SYSTEMD TIMERTwo different tools for the same basic job: run something at a set timecronthe older, simpler toolOne plain-text line per jobEdited with crontab -eNo logging built inCan't wait on another servicesystemd timerthe newer, richer toolA .timer paired with a .serviceManaged with systemctlEvery run logged to the journalCan use After= and Requires=Neither replaces the other: pick cron for something quick and simple,a timer when you need logging or it has to wait on another service.

Word Origin: "Cron"

chronos
  • Greek: time
cron
  • the scheduler daemon

The Unix scheduler took its name from the Greek word for time.

Source: Wikipedia: Cron

Cron vs Timer

  • Cron: one line per job
  • Timer: a unit with a schedule
  • Timers log to the journal
cronsimple, per usertimerlogged, ordered, unitatrun once, later

Scheduled Units: timers

  • Every timer and its next run
  • LEFT counts down to it
  • ACTIVATES names the job
$ systemctl list-timers NEXT LEFT UNIT 18:50 41min apt-daily-upgrade 20:45 2h36m apt-daily # times trimmed to fit

Scheduled Units: timers

$ systemctl list-timers NEXT LEFT UNIT 18:50 41min apt-daily-upgrade 20:45 2h36m apt-daily # times trimmed to fit

A Timer Unit File

  • Same name as the .service
  • OnCalendar sets the clock
  • Persistent catches up
# nightly.timer [Timer] OnCalendar=*-*-* 02:00:00 Persistent=true [Install] WantedBy=timers.target

A Timer Unit File

# nightly.timer [Timer] OnCalendar=*-*-* 02:00:00 Persistent=true [Install] WantedBy=timers.target

Per-User Jobs: crontab

  • crontab -e edits your jobs
  • crontab -l lists them
  • Five time fields, then a cmd
$ crontab -e # an editor opens; add a line: */5 * * * * date >> ~/tick # every 5 minutes $ crontab -l # list your scheduled jobs

Build and check a schedule: crontab.guru

⚠️ Cron runs with a tiny PATH: use full command paths.

Per-User Jobs: crontab

$ crontab -e # an editor opens; add a line: */5 * * * * date >> ~/tick # every 5 minutes $ crontab -l # list your scheduled jobs

Cron Time Fields

  • Five fields, left to right
  • minute, hour, day, month
  • weekday: 0 and 7 both mean Sun
* * * * *minute0–59hour0–23day1–31month1–12weekday0–6, Sun=0

⚠️ A bare * in every field means "run every minute of every day."

Use Case: Nightly Backup

  • Copy the reports at 2 AM
  • A timer runs the service
  • The journal shows each run
Need: nightly report copyno one should run itnightly.timer at 02:00starts nightly.serviceRuns, and is loggedcheck with journalctl

Check: Cron or Timer?

Which one can start a job only after another service is running?

Answer
A systemd timer: its .service can declare After= and Requires=. Plain cron cannot.

Check: Read the Clock

Which crontab line runs a job every day at 2:30 AM?

Answer
30 2 * * * command. The fields are minute, hour, day, month, weekday.

Check: How Often? (1)

How often will this run? * * * * * command

Answer
Every minute, of every hour, every day. All five fields are a bare *, meaning "any value."

Check: How Often? (2)

How often will this run? */15 * * * * command

Answer
Every 15 minutes, every day. */15 in the minute field means "every 15th value starting at 0."

Check: How Often? (3)

How often will this run? 30 6 * * 1-5 command

Answer
Once a day at 6:30 AM, but only Monday through Friday. 1-5 in the weekday field is a range.

Check: Every Monday at 8 AM

How would you configure a crontab line to run a job every Monday at 8 AM?

Answer
0 8 * * 1 command. Minute 0, hour 8, any day/month, weekday 1 (Monday).

Questions?

Practice Lab

Scenario: Heartbeat Service

  • Build a tiny service: beat
  • Start it, log it, break it
  • Watch systemd bring it back
Write beat.servicea unit file you createStart, read the logsystemctl and journalctlKill it, watch it returnRestart=on-failure

Step 1: Confirm systemd

  • systemd is PID 1
  • The state should be running
  • degraded is also fine here
$ ps -p 1 -o comm= systemd $ systemctl is-system-running # running, or degraded running

Step 1: Confirm systemd

$ ps -p 1 -o comm= systemd $ systemctl is-system-running # running, or degraded running

Step 2: Create the Unit

  • Create the file as root
  • One command writes it all
  • No editor, no typing
$ sudo tee /etc/systemd/system/beat.service \ > /dev/null << 'EOF' [Unit] Description=Registrar heartbeat [Service] ExecStart=/usr/bin/sleep infinity Restart=on-failure [Install] WantedBy=multi-user.target EOF

Step 2: Create the Unit

$ sudo tee /etc/systemd/system/beat.service \ > /dev/null << 'EOF' [Unit] Description=Registrar heartbeat [Service] ExecStart=/usr/bin/sleep infinity Restart=on-failure [Install] WantedBy=multi-user.target EOF

Check: Why Reload?

You saved beat.service. Why run daemon-reload before you start it?

Answer
So systemd rereads the unit files. Skipping it can leave systemd on stale settings.

Step 3: Reload and Start

  • daemon-reload rereads files
  • start runs the new service
  • is-active confirms it
$ sudo systemctl daemon-reload # systemd reads the new file $ sudo systemctl start beat # no output means it worked $ systemctl is-active beat active

Step 3: Reload and Start

$ sudo systemctl daemon-reload # systemd reads the new file $ sudo systemctl start beat # no output means it worked $ systemctl is-active beat active

Step 4: Read Its Log

  • -u beat: only this service
  • -n 3: the last 3 lines
  • status also shows Main PID
$ journalctl -u beat -n 3 # what systemd logged for beat Started beat.service - Registrar heartbeat. $ systemctl status beat | head -4 # note the Main PID

Step 4: Read Its Log

$ journalctl -u beat -n 3 # what systemd logged for beat Started beat.service - Registrar heartbeat. $ systemctl status beat | head -4 # note the Main PID

Step 5: Kill It

  • Force-kill all its processes
  • on-failure brings it back
  • A NEW Main PID appears
$ sudo systemctl kill -s KILL beat # force-kill it $ systemctl status beat | head -4 # a new Main PID: it returned $ systemctl show beat \ -p NRestarts NRestarts=1

Step 5: Kill It

$ sudo systemctl kill -s KILL beat # force-kill it $ systemctl status beat | head -4 # a new Main PID: it returned $ systemctl show beat \ -p NRestarts NRestarts=1

Check: Read the Restart

Which journal line proves systemd restarted beat after the kill?

Answer
Scheduled restart job, restart counter is at 1. Run journalctl -u beat -n 6 to see it.

Step 6: Enable and Clean Up

  • enable: start at every boot
  • Then disable and delete it
  • daemon-reload forgets the file
$ sudo systemctl enable beat $ systemctl is-enabled beat enabled $ sudo systemctl disable --now \ beat $ sudo rm \ /etc/systemd/system/beat.service $ sudo systemctl daemon-reload

Step 6: Enable and Clean Up

$ sudo systemctl enable beat $ systemctl is-enabled beat enabled $ sudo systemctl disable --now \ beat $ sudo rm \ /etc/systemd/system/beat.service $ sudo systemctl daemon-reload

Check: Enabled, Running?

You enabled beat but never started it. Is it running right now?

Answer
No. enable only sets it to start at boot. Use enable --now to do both at once.

Deliverable

  • Screenshot: status, active
  • Screenshot: new PID after kill
  • Screenshot: restart log line
  • One sentence: enable vs start

Questions?

Practice Lab 3: Scheduling

Get the Repo

  • Four safe, real cron jobs
  • Medical-unit scheduling server
  • Scripts live in one folder
$ git clone https://github.com/SE4CPS/2026-COMP-175 $ cd 2026-COMP-175/modules/module-6/practicelab3 $ chmod +x *.sh

Sample scripts and crontab: GitHub

Get the Repo

$ git clone https://github.com/SE4CPS/2026-COMP-175 $ cd 2026-COMP-175/modules/module-6/practicelab3 $ chmod +x *.sh

Install the Jobs

  • crontab needs a real path
  • SCRIPTDIR becomes a real path
  • Four lines get added at once
$ (crontab -l 2>/dev/null; \ sed "s|SCRIPTDIR|$(pwd)|" crontab.sample) \ | crontab - # installs all four jobs

Install the Jobs

$ (crontab -l 2>/dev/null; \ sed "s|SCRIPTDIR|$(pwd)|" crontab.sample) \ | crontab - # installs all four jobs

Check: Why Not a Relative Path?

Why does crontab.sample need SCRIPTDIR swapped for a real path first?

Answer
cron runs each job with no fixed working directory and a tiny PATH. A relative path only works by accident; an absolute one always resolves.

Verify

  • Confirm the four lines landed
  • No SCRIPTDIR left in
  • Run one job by hand to check
$ crontab -l $ bash appointment-reminders.sh $ cat /tmp/appointment-reminders.log

Verify

$ crontab -l $ bash appointment-reminders.sh $ cat /tmp/appointment-reminders.log

Deliverable

  • Screenshot: crontab -l, all 4 jobs
  • Screenshot: one script's log line
  • One sentence: why SCRIPTDIR mattered

Questions?

Practice Lab 2: A Simple Cron Job

Scenario: A Running Clock

  • Log the time, once a minute
  • Confirm cron picked it up
  • Watch it tick, then clean up
Schedule Itcrontab -e, every minuteConfirm Itcrontab -l shows the lineWatch, Then Clean Uptail -f, then crontab -r

Step 1: Schedule the Job

  • crontab -e opens your jobs
  • Use the full path: /bin/date
  • * * * * * means every minute
$ crontab -e # add this line, then save: * * * * * /bin/date >> ~/time.log

Step 1: Schedule the Job

$ crontab -e # add this line, then save: * * * * * /bin/date >> ~/time.log

Step 2: Confirm It’s Scheduled

  • crontab -l lists your jobs
  • Confirms it saved correctly
  • No output: no jobs exist
$ crontab -l * * * * * /bin/date >> ~/time.log

Step 2: Confirm It’s Scheduled

$ crontab -l * * * * * /bin/date >> ~/time.log

Check: Why the Full Path?

Why does the line use /bin/date instead of just date?

Answer
Cron runs with a tiny PATH. A bare command name may not be found there; a full path always works.

Step 3: Watch It Run

  • tail -f follows new lines
  • A new line appears each min
  • Ctrl+C stops watching
$ tail -f ~/time.log Mon Sep 30 12:01:00 PDT 2026 Mon Sep 30 12:02:00 PDT 2026 # Ctrl+C to stop watching

Step 3: Watch It Run

$ tail -f ~/time.log Mon Sep 30 12:01:00 PDT 2026 Mon Sep 30 12:02:00 PDT 2026 # Ctrl+C to stop watching

Check: How Often?

The job uses * * * * * with no numbers anywhere. How often does it run?

Answer
Every minute: each of the five fields is a bare *, meaning "any value" in that field.

Step 4: Clean Up

  • crontab -r deletes it all
  • No confirmation prompt
  • crontab -l proves it's gone
$ crontab -r # removes ALL your cron jobs $ crontab -l no crontab for you

⚠️ crontab -r deletes every job you have, not just this one.

Step 4: Clean Up

$ crontab -r # removes ALL your cron jobs $ crontab -l no crontab for you

Deliverable

  • Screenshot: crontab -l output
  • Screenshot: 2+ log timestamps
  • One sentence: what changes if
  • the line reads */5 * * * *

Questions?

Looking Ahead: Module 7

Module 7

Network Configuration

All Commands: Module 7

What Is Network Config?

Why This Matters

  • 50+ years of real evolution
  • Now declarative, not manual
  • Same jobs: address and route
1969ARPANET: the first packet-switched network link1983TCP/IP becomes the standard(the ARPANET "flag day")1993DHCP defined (RFC 1531),automatic IP assignmentLate 1990siproute2 (the ip command)replaces old net-tools2017Netplan ships in Ubuntu17.10: YAML network configTodayMost machines configurenetworking declaratively

Why Config Matters

  • No config, no service at all
  • Every layer depends on it
  • Automotive: AVAILABILITY first
The ScenarioA dealership's diagnostic terminalscan't reach the parts database.METRIC AT RISKAVAILABILITYWhy It MattersCars sit unrepaired, mechanicsidle, until config is fixed.

Where This Module Fits

  • 7 layers, one job each
  • L2/L3/L4/L7: this module
  • L1/L5/L6: out of scope
THE OSI MODELL7: ApplicationDNS, hostnames (resolvectl)L6: PresentationTLS / encoding (openssl)L5: Sessionss -tn, look for ESTABL4: TransportTCP/UDP ports (ss -tuln)L3: NetworkIP & routing (ip, traceroute)L2: Data LinkInterfaces, links (ip link)L1: PhysicalCables, NICs, radioOrange = covered in Module 7Gray = not covered this term
WHAT EVERY MACHINE NEEDSA Working Connectionthree things, one goalAn Addressip addr: who am IA Routeip route: how do I leaveA ResolverDNS: names to addressesThree pieces, configured together, not one at a time.Miss any one and the network looks "broken" with no obvious cause.
web01192.168.1.10/24ip addr · hostnamectldb01192.168.1.11/24ip addr · hostnamectlapp01192.168.1.12/24ip addr · hostnamectlRouter (Gateway): 192.168.1.1ip route · ip linknetplan / DHCP assign each addresseth0eth0eth0DNS Resolver: 8.8.8.8resolvectl · names to addressestraceroute shows every hop to get here

Three Things, One Connection

  • An address: who you are
  • A route: how to leave
  • A resolver: names to IPs
192.168.1.50/24the addressvia 192.168.1.1the route (gateway)8.8.8.8the resolver (DNS)

Existing Software

  • iproute2: the ip command suite
  • Netplan: Ubuntu's config tool
  • NetworkManager: desktops
ipnetplanNetworkManager

Check: Which Piece?

A machine can reach 192.168.1.1 but not google.com. Which of the three pieces is most likely missing?

Answer
The resolver. Reaching the gateway proves the address and route work; only DNS resolution is failing.

Questions?

L2/L3: Viewing Interfaces

Why Check Interfaces?

  • Confirm before you diagnose
  • A DOWN interface stops all
  • Cheapest, fastest first check
The ScenarioA telematics gateway's eth0 isDOWN after a reboot.METRIC AT RISKAVAILABILITYWhy It MattersNo vehicle can phone home withdiagnostic data until noticed.
VIEWING INTERFACES: WHAT TO REACH FORWhat Do I See?two anglesAddressesip addr: every interfaceUp or Downip link: the on/off switchBefore changing anything, see what is already there.Both commands are read-only unless you add set.

See Every Interface: ip addr

  • Lists every network interface
  • Shows each one's IP address
  • No sudo needed to just look
$ ip addr show # every interface on this machine 1: lo: <LOOPBACK,UP> inet 127.0.0.1/8 scope host lo 2: eth0: <BROADCAST,UP> inet 192.168.1.50/24 ...

See Every Interface: ip addr

$ ip addr show # every interface on this machine 1: lo: <LOOPBACK,UP> inet 127.0.0.1/8 scope host lo 2: eth0: <BROADCAST,UP> inet 192.168.1.50/24 ... # ip -br addr show: compact, one line per interface # ip addr show eth0: just that one interface # ip -4 addr show: IPv4 addresses only

Reading ip addr

  • lo: the loopback, always there
  • eth0: a real network interface
  • inet: the IPv4 address itself
loloopback, 127.0.0.1eth0the real NICinetthe IPv4 address

Bring an Interface Up: ip link

$ ip link show eth0 # state is UP or DOWN $ sudo ip link set eth0 up # turn the interface on # ip link show: every interface, not just one # sudo ip link set eth0 down: turn it off instead # ip -s link show eth0: adds packet/error counts

eth0: Down vs. Up

  • Down: carries no traffic
  • No ping, SSH, or DHCP
  • Up: ready to send/receive
  • Still needs an IP to route
eth0: DOWNno link, no trafficip link set upeth0: UPready to send/receive

Check: Address vs Link?

eth0 shows state UP but ip addr shows no inet line for it. What does that tell you?

Answer
The interface itself is active, but it has no IP address assigned yet: a configuration step is still missing.

Questions?

L3: IP Addresses & Subnets

Why Subnets Matter

  • One scheme, every location
  • Overlap breaks routing
  • Confidentiality crosses shops
The ScenarioTwo dealership locations bothuse 192.168.1.0/24 over VPN.METRIC AT RISKCONFIDENTIALITYWhy It MattersOne shop's session data ends upon another shop's internal server.
IP ADDRESSES & SUBNETSWho Can Talk to Whomone idea, two partsThe Address192.168.1.50The Mask (CIDR)/24: how much is networkAn address alone is not enough.The mask says which part is "this network" and which is "this host".

Finding Your Own IP

  • Quickest IP lookup there is
  • No need to parse ip addr
  • Handy inside quick scripts
$ hostname -I 10.0.0.192

Finding Your Own IP

$ hostname -I # prints every IP this host has 10.0.0.192 # hostname: name only, no IP # hostname -i: lowercase, unreliable # hostname -I: uppercase, all addrs

CIDR Notation

  • /24 means 24 network bits
  • Fewer host bits, fewer hosts
  • /24 = 256 addrs, 254 usable
192.168.1.50/24192.168.1 : network.50 : host/24 = mask 255.255.255.0/16 = mask 255.255.0.0/8 = mask 255.0.0.0USABLE RANGE FOR /24192.168.1.1 to 192.168.1.254

Private Address Ranges

  • Reserved, never public
  • Free to reuse on any LAN
  • A router/NAT bridges out
10.0.0.0/8172.16.0.0/12192.168.0.0/16
CIDR
  • Classless Inter-Domain
  • Routing
1993
  • RFC 1519, replacing fixed
  • Class A/B/C sizes

⚠️ Before CIDR, every network was a fixed Class A/B/C size: wasteful and inflexible.

Source: RFC 1519: Classless Inter-Domain Routing

Check: Same Network?

Are 192.168.1.50/24 and 192.168.1.90/24 on the same network?

Answer
Yes. Both share the same first 24 bits (192.168.1), which is all /24 checks.

Questions?

L3: Static vs DHCP

Why Static vs DHCP?

  • Servers need a stable address
  • DHCP can hand out a new one
  • Pick it on purpose, not luck
The ScenarioA parts server stays on DHCP;a weekend outage re-leases it.METRIC AT RISKAVAILABILITYWhy It MattersEvery saved shortcut breaksdealership-wide on Monday.
STATIC VS DHCPWho Picks the Address?two answersStatic: You Decidefixed, written in a fileDHCP: Asked Fora server hands one outA server usually wants static; a laptop usually wants DHCP.Netplan configures either, in the same file format.

Static vs DHCP

  • Static: same address always
  • DHCP: address can change
  • Servers usually run static
Staticfixed, in netplanDHCPleased from a serverServers: static. Laptops: DHCP.Netplan configures either one.

Netplan: DHCP

  • dhcp4: true is the whole file
  • Written with tee, not nano
  • Simplest working config
$ sudo tee /etc/netplan/01-dhcp.yaml << 'EOF' network: version: 2 ethernets: eth0: dhcp4: true EOF $ sudo netplan apply

Netplan: DHCP

$ sudo tee /etc/netplan/01-dhcp.yaml << 'EOF' network: version: 2 ethernets: eth0: dhcp4: true EOF $ sudo netplan apply # netplan status: show what's active now # netplan generate: build config, don't apply it

Netplan: Static IP

  • addresses: a list, CIDR form
  • routes: the default route
  • nameservers: DNS to use
  • Use YOUR subnet, not this
$ sudo tee /etc/netplan/01-static.yaml << 'EOF' network: version: 2 ethernets: eth0: # use real ip addr/route values addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo netplan apply

⚠️ A subnet that doesn't match your real network can disconnect the VM entirely once applied: always use your own values from ip addr/ip route, never a copied example.

Netplan: Static IP

$ sudo tee /etc/netplan/01-static.yaml << 'EOF' network: version: 2 ethernets: eth0: # use real ip addr/route values addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo netplan apply

Check: Try Before Apply?

netplan try previews a config and auto-reverts if you never confirm it. Why is that useful over netplan apply?

Answer
A bad static config over SSH can lock you out immediately. try rolls back automatically if you lose the connection.

Questions?

L3: Routing & Gateway

Why Routing Matters

  • Local traffic still works fine
  • Everything outside fails
  • The gateway is the one exit
The ScenarioA service bay's gateway is wrong;local tools still work.METRIC AT RISKAVAILABILITYWhy It MattersNo terminal can reach themanufacturer's warranty system.
ROUTING & THE DEFAULT GATEWAYHow Traffic Leavesone key lineOn This Networkdirect, no gateway neededEverywhere Elsesent via the gatewayThe routing table decides, packet by packet, which path to take.A missing default route means "local only, nothing beyond it."

See the Routing Table: ip route

  • default via ...: the gateway
  • Local networks need no gateway
  • No sudo needed to just look
$ ip route show # the routing table default via 192.168.1.1 dev eth0 192.168.1.0/24 dev eth0 ...

See the Routing Table: ip route

$ ip route show # the routing table default via 192.168.1.1 dev eth0 192.168.1.0/24 dev eth0 ... # ip route get 8.8.8.8: which route wins # ip -4 route show: IPv4 routes only # ip route show table all: every table

Reading the Routing Table

  • default: the catch-all route
  • via: the next hop (gateway)
  • dev: which interface to use
defaultcatch-all routeviathe next hopdevwhich interface

Routing Table: Other Fields

  • proto kernel: auto-installed
  • metric: lower number wins
  • onlink: skip gateway check
  • scope link: same L2, no hop
proto kernelset automaticallymetriclower number winsonlinkskip the subnet checkscope linksame L2, no hop needed

ip route show: Real Output

$ ip route show default via 10.0.0.1 dev eth2 proto kernel metric 35 onlink # the default route: via gateway 10.0.0.1 10.0.0.0/24 dev eth2 proto kernel scope link metric 291 # the connected subnet: reach these directly 10.0.0.1 dev eth2 proto kernel scope link metric 35 # the gateway's own host route, for onlink
geat
  • Old English: an opening, gap
gateway
  • the passage through it

⚠️ No gateway means no path out: only the local network is reachable.

Source: etymonline: gateway

Check: No Default Route?

ip route show lists only 192.168.1.0/24, no default line. What can this machine reach?

Answer
Only other devices on its own local network. Nothing outside it: no gateway means no path out.

Questions?

L3: Tracing the Path

Find the Broken Hop: traceroute

  • Shows every hop along the way
  • The hop that stops answering
  • Not installed by default
$ sudo apt install -y traceroute $ traceroute 8.8.8.8 # each line: one hop, its time 1 192.168.1.1 0.4 ms 2 10.20.0.1 3.1 ms 3 * * *

Find the Broken Hop: traceroute

$ sudo apt install -y traceroute $ traceroute 8.8.8.8 # each line: one hop, its time 1 192.168.1.1 0.4 ms 2 10.20.0.1 3.1 ms 3 * * * # hop #, IP, round-trip time; *** = no reply # traceroute -n 8.8.8.8: skip slow DNS lookups

Check: Which Hop?

traceroute shows hops 1-3 answering, then 4 onward all show *. What failed?

Answer
Hop 4, or the link just past hop 3: everything up to hop 3 is proven reachable.

Layer 2/3 Commands

#CommandExamplePurpose
1ip addrip addr showList every interface and its IP
2ip linkip link set eth0 upBring a network interface up/down
3netplansudo netplan applyApply a netplan config file
4netplansudo netplan applyApply a static netplan config
5ip routeip route showShow the routing table
6traceroutetraceroute 8.8.8.8Show the path, hop by hop
7hostname -Ihostname -IShow every IP this host has
    

Questions?

L4: Checking Ports

See Open Ports: ss

  • Replaces the older netstat
  • -t TCP, -u UDP, -l listening
  • -n: numbers, not slow lookups
$ ss -tuln # listening TCP/UDP ports tcp LISTEN 0.0.0.0:22 tcp LISTEN 0.0.0.0:80

See Open Ports: ss

$ ss -tuln # listening TCP/UDP ports tcp LISTEN 0.0.0.0:22 tcp LISTEN 0.0.0.0:80 # ss -tulnp: also show which process owns it # ss -s: just a summary count, no rows

Testing Reachability: nc

  • Not always preinstalled
  • Tests IP + port together
  • Different job than ss
$ dpkg -l netcat-openbsd $ sudo apt install -y netcat-openbsd $ nc -zv 10.0.0.50 5432 Connection to 10.0.0.50 5432 succeeded!

Testing Reachability: nc

$ dpkg -l netcat-openbsd # "ii" means installed; "no packages" means missing $ sudo apt install -y netcat-openbsd $ nc -zv 10.0.0.50 5432 # -z: scan only, don't send data # -v: verbose, show success or failure Connection to 10.0.0.50 5432 succeeded! # nc -zv host 20-25: scan a port range

Layer 4 Commands

#CommandExamplePurpose
1ssss -tulnList listening network ports
2ncnc -zv 10.0.0.50 5432Test if an IP + port is reachable
    
    
    
    
    
    

Questions?

L7: Checking DNS

Why DNS Integrity?

  • A resolve isn't always right
  • A stale record misdirects
  • Verify what you actually reach
The ScenarioA stale DNS entry sends"parts.dealer-portal.com" to anMETRIC AT RISKINTEGRITYWhy It Mattersold server. Technicians connect,but order the wrong parts.
CHECKING DNS: IS THE RESOLVER WORKING?Names to Addressesone more pieceWho Am I Asking?resolvectl statusDid It Work?dig, from Module 1Module 1's dig proved lookups work from anywhere.This item checks THIS machine's own resolver configuration.

Resolver Status: resolvectl

  • Not installed by default
  • Shows which DNS server is used
  • Per interface, not just global
$ sudo apt install -y systemd-resolved $ resolvectl status # which DNS server, per interface Link 2 (eth0) Current DNS Server: 8.8.8.8 DNS Servers: 8.8.8.8

Resolver Status: resolvectl

$ sudo apt install -y systemd-resolved $ resolvectl status # which DNS server, per interface Link 2 (eth0) Current DNS Server: 8.8.8.8 DNS Servers: 8.8.8.8 # resolvectl query example.com: resolve one name # resolvectl dns eth0: just that interface's server

/etc/resolv.conf

  • The traditional resolver file
  • Often a symlink, not static
  • netplan writes it indirectly
/etc/resolv.confsymlink to systemd-resolved

Testing the App: curl

  • Not always preinstalled
  • Full HTTP request & reply
  • Proves the app truly answers
$ sudo apt install -y curl $ curl -I https://parts.dealer-portal.com HTTP/1.1 200 OK Content-Type: text/html

Testing the App: curl

$ sudo apt install -y curl $ curl -I https://parts.dealer-portal.com # -I: headers only, no page body HTTP/1.1 200 OK Content-Type: text/html # 200 OK: the app layer responded # curl -v: show the full handshake # curl -s: silent, no progress bar

Check: Right Tool?

You want to confirm a domain actually resolves to an IP, end to end. resolvectl or dig?

Answer
dig. resolvectl shows which server THIS machine would ask; dig actually performs the lookup and shows the answer.

Questions?

L7: Hostname & /etc/hosts

Why Naming Matters

  • Clones inherit the same name
  • Alerts become hard to place
  • Unique names, every machine
The ScenarioEvery shop's VM was cloned fromone template: all named the same.METRIC AT RISKAVAILABILITYWhy It MattersThe outage drags on while on-callhunts for which machine is down.
HOSTNAME & /etc/hostsNaming This Machinetwo different jobsMy Own NamehostnamectlNames I Resolve Myself/etc/hostsA hostname names THIS machine; /etc/hosts maps OTHER names.Module 4's own DNS-collision lesson used exactly this file.

Set the Hostname: hostnamectl

  • Shows or sets the hostname
  • set-hostname needs sudo
  • Takes effect without a reboot
$ hostnamectl # current hostname and OS info Static hostname: ubuntu-server $ sudo hostnamectl set-hostname web01

Set the Hostname: hostnamectl

$ hostnamectl # current hostname and OS info Static hostname: ubuntu-server $ sudo hostnamectl set-hostname web01 # --pretty "Web Server 1": a display name only # hostnamectl status: same as the bare command

/etc/hosts: Local Overrides

  • Checked before real DNS
  • For a name with no DNS entry
  • Can cause a silent collision
10.0.2.15 clinic-recordsone line: an IP, then a name

Check: Which Wins?

/etc/hosts has an entry for api.example.com, and real DNS has a different one. Which wins?

Answer
/etc/hosts. It is checked first, so its entry overrides whatever real DNS would have returned.

Layer 7 Commands

#CommandExamplePurpose
1resolvectlresolvectl statusShow the active DNS resolver
2hostnamectlhostnamectl set-hostname web01View or set this machine's hostname
3curlcurl -I https://example.comTest the application layer directly
    
    
    
    
    

Questions?

Troubleshooting

Why Method Matters

  • Guessing wastes bay time
  • Work outward, layer by layer
  • Isolate the fault, then fix it
The ScenarioDealership-wide "no internet":every bay reports the same thing.METRIC AT RISKAVAILABILITYWhy It MattersChecking gateway, then WAN, thenDNS finds the cause in minutes.
TROUBLESHOOTING: PROVE IT, DON'T GUESSWork Outwardone layer at a timeCan I Reach It? (ping)already known, Module 2Where Does It Stop?traceroute: the hop that failsCheck the closest layer first: gateway, then DNS, then the host.Jumping straight to "the internet is down" skips real evidence.

Start With ping

  • ping already taught, Module 2
  • Test gateway, then the host
  • No reply: look closer here
ping -c 1 192.168.1.1ping -c 1 8.8.8.8ping -c 1 google.com
WORK THE STACK, DON'T GUESSFour Checks, In Orderone per layer, in sequenceL2: Link Up?ip linkL3: Address & Route?ping, tracerouteL4: Port Listening?ssL7: DNS Resolving?resolvectl, digCheck each layer in order: don't skip to a guess.ping/traceroute confirm L2-L3; ss confirms L4; resolvectl/dig confirm L7.

Use Case 1: DB Unreachable

LayerCheckResultMeaning
L2ip linkUPOK, not the cause
L3ping gatewayRepliesOK, not the cause
L4ss -tulnPort 5432 missingDatabase isn't running
L7skippedn/aFound it already, stop here

Use Case 2: Stale DNS

LayerCheckResultMeaning
L2ip linkUPOK, not the cause
L3ping gatewayRepliesOK, not the cause
L4ss -tulnPort 443 listeningOK, not the cause
L7resolvectl / curl -IResolves to old IPStale DNS record

Use Case 3: No Network

LayerCheckResultMeaning
L2ip linkDOWNCable unplugged or NIC disabled
L3skippedn/aFound it already, stop here
L4skippedn/an/a
L7skippedn/an/a

Use Case 4: Firewall Blocks

LayerCheckResultMeaning
L2ip linkUPOK, not the cause
L3ping 10.0.0.50RepliesOK, server itself is reachable
L4nc -zv 10.0.0.50 5432Connection refusedFirewall blocks this port
L7skippedn/aFound it already, stop here

⚠️ ss on the diagnostic terminal can't see this: it only shows local sockets, not whether a remote port is actually reachable over the network.

Questions?

Lab: L2/L3 Config

Scenario: Configure the Server

  • Kali: your admin workstation
  • Ubuntu: the diagnostics server
  • Give it a working static IP
KaliUbuntuConfigure Ubuntu's network from Kali, over SSH

Requirements

  • A real static IP via netplan
  • A working default route
  • A working DNS resolver
Static addressDefault routeWorking DNS

Verify Ubuntu's Packages

  • Confirm ssh server exists
  • Confirm netplan & DNS exist
  • Install/start if missing
$ dpkg -l openssh-server netplan.io \ systemd-resolved # "ii" means installed; "no packages" means missing $ sudo apt install -y openssh-server \ netplan.io systemd-resolved # safe to re-run even if already installed $ sudo systemctl enable --now ssh # starts sshd now, and on every boot

Verify Ubuntu's Packages

$ dpkg -l openssh-server netplan.io \ systemd-resolved # "ii" means installed; "no packages" means missing $ sudo apt install -y openssh-server \ netplan.io systemd-resolved # safe to re-run even if already installed $ sudo systemctl enable --now ssh # starts sshd now, and on every boot

Kali & Ubuntu Share One IP

  • Both WSL2 distros, one IP
  • sshd picks up port 22 first
  • Give Kali its own port
$ echo 'Port 2222' | \ sudo tee -a /etc/ssh/sshd_config $ sudo systemctl restart ssh # still "connection refused" on 22? # on Ubuntu: sudo systemctl enable --now ssh

⚠️ Skip this and ssh may land on Kali's own banner instead of Ubuntu's: both answer the same IP.

Kali & Ubuntu Share One IP

$ echo 'Port 2222' | \ sudo tee -a /etc/ssh/sshd_config $ sudo systemctl restart ssh # run this on Kali only, once # Ubuntu keeps the default port 22 # Kali answers on 2222 instead # still "connection refused" on 22? # on Ubuntu: sudo systemctl enable --now ssh

Clear Any Stale Host Key

  • Rebuilt VM? Old key remains
  • ssh refuses to connect
  • Remove it before sshing in
# no SSH yet? open Ubuntu's own console, run hostname -I $ IP=<ubuntu-ip> $ ssh-keygen -f ~/.ssh/known_hosts -R $IP # safe to run even if nothing's stale

⚠️ Skipping this is fine until the VM gets rebuilt; then ssh refuses with "Host key verification failed" instead of connecting.

Clear Any Stale Host Key

# no SSH yet? open Ubuntu's own console, run hostname -I $ IP=<ubuntu-ip> $ ssh-keygen -f ~/.ssh/known_hosts -R $IP # safe to run even if nothing's stale # removes any old entry for this IP

Still Stuck? Reset WSL

  • Last resort, not routine
  • Resets the shared network
  • Run on Windows, not in WSL
$ wsl --shutdown # wait ~10 seconds, then reopen both tabs

⚠️ ssh hanging (not refusing) after everything else checks out usually means the shared WSL2 network state itself is stuck, not a service.

Still Stuck? Reset WSL

$ wsl --shutdown # wait ~10 seconds, then reopen both tabs # resets the whole shared network stack, # not just one distro

Step 1: Check the Starting Point

  • See what interface exists now
  • Note any current address
  • Note the gateway (ip route)
  • This is your before picture
$ ssh <username>@$IP # "username" is literal text, not a $var $ ip addr show # note your subnet, e.g. 10.0.0.0/24 $ ip route show # note "default via X.X.X.X": your gateway

Step 1: Check the Starting Point

$ ssh <username>@$IP # "username" is literal text, not a $var $ ip addr show # note your subnet, e.g. 10.0.0.0/24 $ ip route show # note "default via X.X.X.X": your gateway

Step 2: Write the Netplan File

  • Use YOUR subnet & gateway
  • From Step 1's ip addr/route
  • Pick an unused host number
  • Still on Ubuntu, via SSH
$ sudo tee /etc/netplan/01-lab.yaml << 'EOF' network: version: 2 ethernets: eth0: # from Step 1's ip addr/route, above addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo chmod 600 /etc/netplan/01-lab.yaml

⚠️ <new-ip>/<gateway> must match YOUR real subnet from Step 1, not a guess: a different subnet can disconnect the VM entirely once applied.

Step 2: Write the Netplan File

$ sudo tee /etc/netplan/01-lab.yaml << 'EOF' network: version: 2 ethernets: eth0: # from Step 1's ip addr/route, above addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo chmod 600 /etc/netplan/01-lab.yaml

Step 3: Apply It

  • netplan apply: live, no reboot
  • A typo here can drop your SSH
  • try is the safer choice
  • Run inside the SSH session
$ sudo netplan try # "Configuration accepted." then it waits # press ENTER to confirm, or it reverts in 120s $ sudo netplan apply

Step 3: Apply It

$ sudo netplan try # "Configuration accepted." then it waits # press ENTER to confirm, or it reverts in 120s $ sudo netplan apply

Step 4: Verify the Config

  • Address: ip addr
  • Route: ip route
  • Still inside Ubuntu's shell
$ ip addr show eth0 $ ip route show

Step 4: Verify the Config

$ ip addr show eth0 $ ip route show

Questions?

Lab: L4 Ports

Verify sshd Is Listening

  • Confirms port 22 is open
  • ss -tlnp lists listeners
  • Run this before you ssh in
$ sudo ss -tlnp | grep :22 # confirms sshd is actually listening

Verify sshd Is Listening

$ sudo ss -tlnp | grep :22 # confirms sshd is actually listening

Questions?

Lab: L7 Names

Verify DNS Resolution

  • Resolver: resolvectl status
  • Confirms the DNS piece works
  • Still inside Ubuntu's shell
$ resolvectl status

Verify DNS Resolution

$ resolvectl status

Change the DNS Server

  • Edit nameservers, reapply
  • 8.8.8.8: Google's public DNS
  • resolvectl status confirms it
$ sudo tee /etc/netplan/01-lab.yaml << 'EOF' network: version: 2 ethernets: eth0: # same values you set in Step 2 addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo netplan apply $ resolvectl status

⚠️ If the new DNS server is unreachable, resolution breaks until you revert it. Test connectivity to it first.

Change the DNS Server

$ sudo tee /etc/netplan/01-lab.yaml << 'EOF' network: version: 2 ethernets: eth0: # same values you set in Step 2 addresses: [<new-ip>/24] routes: [{to: default, via: <gateway>}] nameservers: {addresses: [8.8.8.8]} EOF $ sudo netplan apply $ resolvectl status

Questions?

Lab: Mirrored Network

Scenario: Mirrored Network

  • Pair up with a lab partner
  • Each laptop: own WSL2, NAT
  • WSL instances can't reach
  • Cable links the two laptops
Partner ALaptopWSL2 insidePartner BLaptopWSL2 insidecableBy default: still can't reacheach other over this cable
WSL2: DEFAULT VS MIRRORED MODEDEFAULT MODEMIRRORED MODEWindows HostPrivate NATWSL2own private IPUnreachable from other hostsWindows Host= WSL2 (mirrored)shares host's real IP✓ Reachable from other hostsImpact: the WSL instance now answersat the host's own real LAN address. No port-forwarding needed.

Prerequisites Check

  • Need a lab partner
  • Laptop needs Ethernet port
  • Or a USB-Ethernet adapter
  • Mirrored needs recent WSL
$ wsl --version # confirms the installed WSL version $ wsl --update # updates WSL if it's too old

Prerequisites Check

$ wsl --version # confirms the installed WSL version $ wsl --update # updates WSL if it's too old

Get the Setup Scripts

  • Pulled from course GitHub
  • Not hand-typed by students
  • Needs git on Windows too
$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175 $ cd 2026-COMP-175 $ cd modules\module-7\mirrored-networking

Get the Setup Scripts

$ cd ~ $ git clone https://github.com/SE4CPS/2026-COMP-175 $ cd 2026-COMP-175 $ cd modules\module-7\mirrored-networking

Turn On Mirrored Mode

  • Writes .wslconfig for you
  • Then restarts WSL to apply
  • No editor opened, ever
$ .\enable-mirrored.ps1 # writes .wslconfig, then restarts WSL

Turn On Mirrored Mode

$ .\enable-mirrored.ps1 # writes .wslconfig, then restarts WSL

Verify: Host's Real IP

  • Find the host's real IP
  • WSL will come to share it
$ ipconfig # find "IPv4 Address" under your # real Ethernet adapter

Verify: Host's Real IP

$ ipconfig # find "IPv4 Address" under your # real Ethernet adapter

Verify: WSL's New IP

  • Same IP now inside WSL
  • Mirrored mode is active
$ ip addr show # the host's IP now appears here too

Verify: WSL's New IP

$ ip addr show # the host's IP now appears here too

Connect the Cable

  • Plug cable into both laptops
  • Find the adapter's real name
$ Get-NetAdapter # lists every adapter and its real name

Connect the Cable

$ Get-NetAdapter # lists every adapter and its real name

Assign Static IPs

  • Same subnet, different host
  • Partner A: .77.1, B: .77.2
  • Use your own adapter name
$ .\set-static-ip.ps1 "Ethernet" "192.168.77.1" 24 # Partner A runs this $ .\set-static-ip.ps1 "Ethernet" "192.168.77.2" 24 # Partner B runs this; same script, own IP

Assign Static IPs

$ .\set-static-ip.ps1 "Ethernet" "192.168.77.1" 24 # Partner A runs this $ .\set-static-ip.ps1 "Ethernet" "192.168.77.2" 24 # Partner B runs this; same script, own IP

Confirm the New IP

  • Re-check with ipconfig
  • New static IP now showing
$ ipconfig # your Ethernet adapter now shows # 192.168.77.x, not the old address

Confirm the New IP

$ ipconfig # your Ethernet adapter now shows # 192.168.77.x, not the old address

Ping Across, WSL to WSL

  • From Partner A's WSL shell
  • Target: Partner B's new IP
  • Works: real, shared IP now
$ ping 192.168.77.2 # from Partner A, targeting Partner B $ ping 192.168.77.1 # from Partner B, targeting Partner A

Ping Across, WSL to WSL

$ ping 192.168.77.2 # from Partner A, targeting Partner B $ ping 192.168.77.1 # from Partner B, targeting Partner A

Why This Worked

  • As introduced earlier: NAT
  • Mirrored: shares host's IP
  • That's why the ping worked
Default: blocked by NATMirrored: ping succeeds

Heads Up: Mirrored Mode

⚠️ If the ping still fails, confirm the static IP really landed on the Ethernet adapter the cable is plugged into, not Wi-Fi or a different port; Get-NetAdapter's own Status column shows which one is really Up.

Deliverable

  • Screenshot: ipconfig output
  • Screenshot: ip addr (WSL)
  • Screenshot: ping, both ways
Turn on mirrored modeCable + static IPsPing both directions

Questions?

Looking Ahead: Module 8

Module 8

Name Resolution & Secure Transport

DNS Hierarchyhow a name resolvesQuerying DNSdig, nslookupTLS & Certificateswho do you trustHTTPS in Practiceprove it, don't guess

Resolving a URL

  • Check: is it localhost?
  • Not local? Query DNS
  • DNS: application layer
  • Distributed: root, TLD, auth
Is It localhost?127.0.0.1, no network neededAsk DNSexample.com -> 93.184.216.34

DNS Across the OSI Layers

  • L7: DNS query formed
  • L4: DNS over UDP, port 53
  • L4 needs L3's IP for TCP
  • L3: IP is the DNS answer
L7: ApplicationDNS query formed hereL6: PresentationNot used yet (TLS is next)L5: SessionNo session until IP is knownL4: TransportDNS over UDP/53; TCP needs the IPL3: NetworkDNS answer becomes this IPL2: Data LinkFrames carry the query/replyL1: PhysicalCables, NICs, radioBlue = directly involved in resolving a nameTCP (L4) cannot connect until L3 provides the IP

Why UDP and Port 53?

  • UDP: no handshake needed
  • Fast: one question, one answer
  • Port 53: DNS's fixed port
  • Same idea as 22, 80, 443
DNS Query PacketProtocol: UDPno handshake, just send and waitSource Port: 51234random, picked by your OSDestination Port: 53DNS's reserved, well-known portSame idea as 22 (SSH), 80 (HTTP), 443 (HTTPS)a fixed port, so clients know where to ask

All Commands: Module 8

What Is Name Resolution?

Why This Matters

  • DNS: names since 1983
  • Encryption went free in 2015
  • Both now run by default
1983DNS invented (Paul Mockapetris,RFC 882/883): names, not numbers1994SSL and HTTPS introduced(Netscape), encrypting the web1999TLS 1.0 standardized (IETF),SSL's open successor2015Let's Encrypt launches:free certificates for everyoneTodayMost of the web runs overHTTPS by default
WHAT IS NAME RESOLUTION?Name ResolutionDNS resolution and TLS authenticationDNS Resolutionresolves hostname to IP addressTLS Authenticationverifies identity via certificateModule 1 already used dig and whois for ad hoc DNS queries.This module covers the DNS resolution process and TLS certificate validation.

Two Different Questions

  • DNS: where do I send this?
  • TLS: am I talking to them?
  • Both must work for HTTPS
example.com -> 93.184.216.34DNS: where to send itCertificate: verifiedTLS: who you are really talking to

Check: Which One Failed?

A browser shows "cannot find server" versus "certificate not trusted". Which failed: DNS or TLS?

Answer
"Cannot find server" is a DNS failure (the name never resolved). "Certificate not trusted" is a TLS failure.

The URL

https://pacific.eduscheme : // host : path

Which part of this URL does DNS actually resolve?

Answer
Just the host, pacific.edu. The scheme (https://) and any path after it are never looked up in DNS.
CACHED LOOKUPS: DNS, VMs & REMOTE ACCESSKali VMclient, wants to connectssh ubuntu-vmIn DNS Cache?checked before any queryCache Hitreuse the cached IPHITCache Missask the DNS resolverMISSAnswer CachedTTL 300s, then expiresOpen Remote AccessSSH to the resolved IPUbuntu VMtarget, reached by IPThe cache check happens before any network request, DNS is only asked on a miss.

Questions?

The DNS Hierarchy

THE DNS HIERARCHYRoot ( . ).com.edu.orgpacific.edu203.0.113.10the resolved IP addressYour resolver asks root, then the TLD, then the real owner.Each server narrows it down until one returns a real IP address.

203.0.113.0/24 is reserved for documentation, not a real routable address (Source: RFC 5737)

Root, TLD, Authoritative

  • Root: 13 servers, worldwide
  • TLD: runs .com, .edu, ...
  • Authoritative: its real DNS
Root ( . )TLD (.edu)Authoritative (pacific.edu)

Check: Who Answers First?

Resolving www.pacific.edu for the first time. Which server does your resolver ask first?

Answer
A root server. It does not know the final answer, only which TLD server to ask next for .edu.

Root Servers

A – M13 letters, hundreds of real machines

How many root server letters are there (A through ?)?

Answer
13 letters, A through M. Each letter is served by many real machines worldwide via anycast.

Asking the TLD

.edu → ?TLD server for pacific.edu

Does the .edu TLD server know pacific.edu's IP address directly?

Answer
No. It only knows which authoritative server to ask next, it hands off, it doesn't answer.

The Final Answer

203.0.113.10returned only by the authoritative server

Which server in the chain is the only one that can return a real IP address?

Answer
The authoritative server for that domain, root and TLD servers only ever return referrals.

Questions?

Querying DNS

QUERYING DNS: TWO TOOLSAsk Directlyskip the guessworkdigdetailed, already used, Module 1nslookupsimpler, interactive-friendlydig already proved a name resolves; nslookup is a lighter alternative.Both ask the same question. dig shows far more of the real answer.

dig, Revisited

  • dig +short: just the answer
  • dig MX: another record type
  • The same tool, more uses
dig +short scanme.nmap.orgdig MX pacific.edu

A Simpler Tool: nslookup

  • Asks the same basic question
  • Shorter output than dig
  • Good for a quick sanity check
$ nslookup scanme.nmap.org # a quick name-to-address check Name: scanme.nmap.org Address: 45.33.32.156

A Simpler Tool: nslookup

$ nslookup scanme.nmap.org # a quick name-to-address check Name: scanme.nmap.org Address: 45.33.32.156

Check: dig or nslookup?

You need the full DNS response, including the TTL and the authoritative server. Which tool?

Answer
dig. It shows the full response by default; nslookup only shows a short summary.

dig Output

ANSWER SECTIONexample.com. 300 IN A 93.184.216.34

In dig's output, which section actually holds the resolved IP address?

Answer
The ANSWER SECTION. The rest of the output is metadata about the query itself.

dig vs nslookup

digscriptablenslookupinteractive

Which tool is built to show more raw protocol detail?

Answer
dig. It is the standard diagnostic tool; nslookup is simpler but shows less of the underlying protocol.

Questions?

DNS Record Types

DNS RECORD TYPESOne Name, Many Answersdepends what you askA / AAAAthe IPv4 / IPv6 addressMX / TXTmail server, verification textDifferent record types answer different questions.A name has an A record for its address, an MX record for its mail, and so on.
THE INTERNET OF THINGS NEEDS ADDRESSESEvery DeviceNeeds an IPAddressSmartphoneLaptopSmart ThermostatSecurity CameraSmart SpeakerConnected CarSmartwatchWi-Fi Router16.6 billion IoT devices were connected worldwide in 2023 (IoT Analytics)This scale is exactly why IPv4's ~4.3 billion addresses ran out, and why IPv6 exists

Source: IoT Analytics, via Wikipedia

IPv4 Address

192.0.2.101928 bits08 bits28 bits108 bits32 bits total~4.3 billion addresses

192.0.2.0/24 is reserved for documentation (Source: RFC 5737)

IPv6 Address

2001:db8::10:: compresses repeated zero groups20010db8000000000000000000000010128 bits total340 undecillion addresses

2001:db8::/32 is reserved for documentation (Source: RFC 3849)

IPv4 vs IPv6: MARKET SHARE & COMPATIBILITYIPv4~52% of trafficIPv6~48% of trafficGoogle-measured IPv6 adoption first crossed 50% of traffic on March 28, 2026As of April 2026, varies by day of weekCompatible? Not directly.They are separate protocols; dual-stack or NAT64 bridges themFeatureIPv4IPv6Address length32-bit128-bitHeaderMore complexSimplified, fixed sizeAddress configManual or DHCPAutoconfig (SLAAC)BroadcastYesNo, multicast only

Source: Google IPv6 Statistics

Root Servers A-G

A198.41.0.4B170.247.170.2C192.33.4.12D199.7.91.13E192.203.230.10F192.5.5.241G192.112.36.4

Source: IANA Root Servers

Root Servers H-M

H198.97.190.53I192.36.148.17J192.58.128.30K193.0.14.129L199.7.83.42M202.12.27.33

Source: IANA Root Servers

The Common Record Types

  • A: the IPv4 address
  • CNAME: an alias to a name
  • MX: where mail gets delivered
AIPv4 addressCNAMEalias to another nameMXmail delivery target

Check: Which Record?

You want to know which server handles email for pacific.edu. Which DNS record type answers that?

Answer
MX. The mail exchange record names the server responsible for accepting mail for that domain.

A vs AAAA

AIPv4 addressAAAAIPv6 address

Which record type would resolve a name to an IPv6 address?

Answer
AAAA. The A record only holds an IPv4 address.

MX Priority

10 mail.pacific.edulower number means tried first

What does the number in front of an MX record's mail server control?

Answer
Priority. Mail servers try the lowest-numbered MX record first, and fall back to higher numbers.

Questions?

Why Secure Transport?

WHY SECURE TRANSPORT?Plaintext Is Readableby anyone on the pathHTTPpasswords, cookies, in the clearHTTPSencrypted, tamper-evidentAnyone between you and the server can read plain HTTP.TLS turns that same connection into something only the two endpoints can read.

What a Snooper Sees

  • HTTP: the whole page, readable
  • HTTPS: scrambled bytes
  • Same network, different risk
password=hunter2HTTP: plainly readablea8f3...e91c (encrypted)HTTPS: unreadable in transit

Check: What Does a Snooper Learn?

You log into a site over plain HTTP on public Wi-Fi. What can someone else on that Wi-Fi see?

Answer
Everything sent in plain text, including the password itself, since nothing on HTTP is encrypted.

Plaintext Risk

HTTPplaintextHTTPSencrypted

Can a network attacker read HTTP traffic as it travels?

Answer
Yes. HTTP sends data in plaintext, anyone on the path can read or alter it.

What TLS Protects

Login Formsubmitted over HTTPS

What exactly does TLS protect here: the form itself, or something else?

Answer
The data in transit. TLS protects it from eavesdropping and tampering on the way, not what the server does with it after.

Questions?

TLS & Certificates

A CERTIFICATE IS A PUBLIC KEY, WITH PROOFSSHTLSPrivate Keystays on your laptop, secretPublic Keycopied into authorized_keysTrust: Manualyou accept it on first connectPrivate Keystays on the server, secretCertificate= public key + identity+ a Certificate Authority's signatureTrust: a CA Vouchesthe browser already trusts the CABoth prove “I hold the matching private key.”TLS adds a trusted third party (the CA); plain SSH usually just trusts on first use.
TLS & CERTIFICATESEncrypt, and Prove Identitytwo jobs, one handshakeThe Certificatesigned proof of who you areThe Certificate Authoritythe one who signs itA certificate is only trusted if a trusted authority signed it.Your browser already trusts a built-in list of these authorities.

The Handshake, Simplified

  • Server shows its certificate
  • Browser checks who signed it
  • Trusted: session starts
Server shows its certificateBrowser checks the signerTrusted: encrypted session begins
certus
  • Latin: settled, sure
certificate
  • a document proving a fact

⚠️ A certificate only proves identity, not that the site is safe or honest.

Source: etymonline: certificate

Check: Trusted by Whom?

A browser trusts a certificate signed by a Certificate Authority it already knows. Who decides that initial list?

Answer
The browser/OS vendor. They ship a built-in list of trusted Certificate Authorities.

Certificate Fields

Subject / Issuer / Expiryevery certificate has these

If a certificate's domain matches but it expired yesterday, does the browser still trust it?

Answer
No. An expired certificate fails validation regardless of a correct domain name.

Chain of Trust

Root CAoffline, protectedIntermediate CAsigns server certs

Why use an intermediate CA instead of signing every certificate with the root CA directly?

Answer
It keeps the root CA's private key offline and protected; if an intermediate is compromised, the root does not have to be revoked.

Session Keys

New Key Each Sessionforward secrecy

Does TLS reuse the same encryption key for every session with a server?

Answer
No. A fresh session key is negotiated each time, so one leaked key does not expose past sessions.

Questions?

Inspecting Certificates

INSPECTING CERTIFICATESDo Not Just Trust the Lock Iconcheck it yourselfopensslreads a cert directlyExpiration, Issuer, Domainwhat to checkA valid-looking padlock can still be close to expiring.openssl shows the real certificate, not just a browser icon.

Read a Live Certificate: openssl

  • Connects, shows the real cert
  • Not installed by default
  • Check the dates and issuer
$ sudo apt install -y openssl $ openssl s_client -connect pacific.edu:443 -servername pacific.edu < /dev/null # scroll up: issuer, dates, subject

Read a Live Certificate: openssl

$ sudo apt install -y openssl $ openssl s_client -connect pacific.edu:443 -servername pacific.edu < /dev/null # scroll up: issuer, dates, subject

What to Check

  • notAfter: has it expired?
  • Issuer: a trusted authority?
  • Subject: matches the domain?
notAfter: not expiredIssuer: a trusted CASubject: matches the domain

Check: Subject Mismatch

A certificate's Subject says mail.example.com, but you connected to www.example.com. Should your browser trust it?

Answer
No. A mismatched subject means the certificate was not issued for the domain you are actually visiting.

Fetching a Cert

openssl s_client -connect host:443

What command actually fetches a live certificate from the CLI?

Answer
openssl s_client -connect host:443. It opens a real TLS connection and prints the certificate.

Browser Shortcut

Click the Padlocknext to the address bar

What is the fastest way to check a certificate's expiry date in a browser, without the CLI?

Answer
Click the padlock icon next to the URL, it shows the certificate details directly.

Questions?

HTTPS in Practice

HTTPS IN PRACTICESee It From the Command Linenot just the browsercurl -Iheaders, status, no bodycurl -vthe full TLS handshakeA browser hides most of this behind a padlock icon.curl shows the real HTTP response and the real TLS handshake.

Check HTTPS from the CLI: curl

  • -I: headers only, fast check
  • -v: verbose, shows handshake
  • Already proves HTTPS works
$ curl -I https://pacific.edu # status code and response headers HTTP/2 200 $ curl -v https://pacific.edu # -v: see the TLS handshake itself

Check HTTPS from the CLI: curl

$ curl -I https://pacific.edu # status code and response headers HTTP/2 200 $ curl -v https://pacific.edu # -v: see the TLS handshake itself

Check: -I vs -v?

You just want to confirm a site returns 200 OK over HTTPS, nothing more. Which flag: -I or -v?

Answer
-I. It fetches only the headers quickly; -v dumps the entire handshake and is slower to read.

Default Ports

HTTPport 80HTTPSport 443

What is the default port for HTTPS?

Answer
443. Plain HTTP defaults to port 80.

Auto Redirect

301 → HTTPShttp:// forces a redirect

Why would a well-configured server redirect plain HTTP requests to HTTPS automatically?

Answer
So a user who types the plain http:// URL still ends up encrypted, instead of staying on an insecure connection.

Questions?

Practice Lab

Scenario: Verify a Real Site

  • Pick a real, public domain
  • Trace its name, then its cert
  • Prove both pieces work
Resolve the name (DNS)Check the cert (TLS)Confirm HTTPS works

Requirements

  • Resolve the domain with dig
  • Confirm the same with nslookup
  • Verify the cert with openssl
  • Confirm HTTPS works with curl
dig + nslookup agreeopenssl shows a valid certcurl -I returns 200

Step 1: Resolve with dig

  • The A record: the real address
  • Note the TTL too
  • This is your baseline answer
$ dig +short pacific.edu # the IPv4 address, nothing else

Step 1: Resolve with dig

$ dig +short pacific.edu # the IPv4 address, nothing else

Step 2: Confirm with nslookup

  • A second, independent tool
  • Should agree with dig's answer
  • A mismatch is a real problem
$ nslookup pacific.edu # compare this address to dig's

Step 2: Confirm with nslookup

$ nslookup pacific.edu # compare this address to dig's

Step 3: Check the Certificate

  • Connect on port 443 directly
  • Read the issuer and expiration
  • No browser involved at all
$ openssl s_client -connect pacific.edu:443 -servername pacific.edu < /dev/null 2>&1 | grep -A2 "Validity"

Step 3: Check the Certificate

$ openssl s_client -connect pacific.edu:443 -servername pacific.edu < /dev/null 2>&1 | grep -A2 "Validity"

Step 4: Confirm HTTPS Works

  • A real request, from the CLI
  • HTTP/2 200 means it all worked
  • DNS, TLS, or the server
$ curl -I https://pacific.edu # status 200 proves the whole chain

Step 4: Confirm HTTPS Works

$ curl -I https://pacific.edu # status 200 proves the whole chain

Check: Which Layer, If It Fails?

curl times out completely, no response at all. Is that more likely DNS, TLS, or the server itself?

Answer
Check DNS first: if dig never resolved a real address, curl never even had anywhere to connect.

Deliverable

  • Screenshots: dig and nslookup
  • Screenshot: openssl cert dates
  • Screenshot: curl -I, 200
Resolve it, two waysVerify the cert, then HTTPS

Before Testing HTTPS

dig firstthen test HTTPS

Before testing whether HTTPS works on a server, what should you confirm first?

Answer
That DNS actually resolves the name. TLS cannot even start if the name never resolves to the right host.

NXDOMAIN

NXDOMAINno such domain

If dig returns NXDOMAIN for a hostname, is that a DNS problem or a TLS problem?

Answer
A DNS problem. The name does not resolve at all, TLS never gets a chance to run.

Questions?

Practice Lab 2

Scenario: Something Is Wrong

  • A site's HTTPS is misbehaving
  • Could be DNS, cert, or server
  • Work outward, prove each layer
Does it even resolve?Is the cert valid?Does curl get 200?

Step 1: Does It Resolve?

  • Start at the DNS layer
  • No answer: it is DNS
  • An answer: check next layer
$ dig +short expired.badssl.com # confirm a real address comes back

Step 1: Does It Resolve?

$ dig +short expired.badssl.com # confirm a real address comes back

Step 2: Is the Cert Valid?

  • DNS worked, check TLS next
  • Look at notAfter specifically
  • A past date means it expired
$ openssl s_client -connect expired.badssl.com:443 -servername expired.badssl.com < /dev/null 2>&1 | grep notAfter

Step 2: Is the Cert Valid?

$ openssl s_client -connect expired.badssl.com:443 -servername expired.badssl.com < /dev/null 2>&1 | grep notAfter

Step 3: Confirm with curl

  • curl refuses an invalid cert
  • The error names the reason
  • Matches what openssl showed
$ curl -I https://expired.badssl.com # curl: certificate has expired

Step 3: Confirm with curl

$ curl -I https://expired.badssl.com # curl: certificate has expired

Check: Localize the Fault

dig resolves fine. openssl shows a notAfter date in the past. Where is the actual problem?

Answer
TLS, specifically an expired certificate. DNS already proved fine, so there is no reason to touch it.

Deliverable

  • Screenshot: dig resolves it
  • Screenshot: notAfter date
  • One sentence: the real cause
Check each layer in orderName the real cause

Reading the Error

NET::ERR_CERT_DATE_INVALID

This error means the name resolved fine. Is the actual problem DNS or TLS?

Answer
TLS. The certificate itself has an issue (its dates), not the name lookup.

DNS vs TLS, by Port

DNSport 53TLS / HTTPSport 443

Which of DNS or TLS uses port 53?

Answer
DNS uses port 53. TLS/HTTPS uses port 443.

Questions?

Looking Ahead: Module 9

Module 9

Logging & Security Monitoring

Log Lifecyclerotation, not foreverCentralize Itsend logs elsewhere tooWatch Auth Logswho tried, and failedAuto-Block: fail2banreact, not just watch

All Commands: Module 9

Logging & Monitoring

Why This Matters

  • Logging predates the standard
  • Response became automatic
  • Now centralized, not per-host
1980syslog created (Eric Allman,BSD sendmail project)2001RFC 3164 formalizes syslogas a real standard2004fail2ban created (CyrilJaquier): auto-ban attackers2009RFC 5424: a modern,structured syslog formatTodayCentralized logging plusautomated response is standard
LOGGING & SECURITY MONITORINGFrom Watching to Actingthree stepsKeep the Logsrotate, do not lose themReact Automaticallyfail2ban watches and blocksModule 6 taught journalctl; Module 4 taught auditd.This module asks: what do you DO with everything those tools already capture?

Watching Is Not Enough

  • A log must be read in time
  • Logs grow forever, fill disk
  • fail2ban reacts automatically
Collect (journald, auditd)Keep (rotation)React (fail2ban)

Check: Collect vs React

journald collecting a failed login is one thing. fail2ban blocking the attacker's IP is another. Which is which?

Answer
journald collects; fail2ban reacts. Collecting alone never stops a second attempt from the same attacker.

journalctl, Revisited

  • Already taught in Module 6
  • -p err: error priority only
  • -u sshd: just the ssh service
$ journalctl -p err --since today # -p err: show only error-level and worse # --since today: skip everything older $ journalctl -u sshd # -u sshd: just the ssh service

journalctl, Revisited

$ journalctl -p err --since today # -p err: show only error-level and worse # --since today: skip everything older $ journalctl -u sshd # -u sshd: just the ssh service

Use Case: journalctl

  • Service fails, cause unclear
  • journalctl -u name narrows it
  • The exact line, timestamped
Vague Failure Reporteda service misbehaves, cause unclearjournalctl -u sshd --since todaysearch just that unit, todayExact Line, With a Timestampcause found, time to fix narrowed

Use Case: Compliance

  • Auditor asks who logged in
  • Already recorded, nothing new
  • No extra tracking needed
Audit Request: Last Month's Loginsauditor needs proof, not a guessjournalctl --since "1 month ago"filter the existing recordA Timestamped, Complete Answernothing had to be built for this

Questions?

Word Origin: "Syslog"

  • sys + log: a system log
  • Written 1980 by Eric Allman
  • For BSD's Sendmail project
  • Became the standard, 1980–2009

Every log line a modern Linux tool writes still traces back to this 1980 format.

Source: Wikipedia: Syslog

Log Rotation

LOG ROTATIONrotate Nhow many old copies to keepcompressgzip old logs after rotatingdaily / weekly / monthlyrotation schedulemaxage Ndelete by age, not just countcopytruncatelog stays open: copy, then clear-d / -f-d: dry run, -f: force it nowlogrotateA log file left alone can eventually fill the whole disk.logrotate runs on a schedule and handles all of this automatically.

Rotate Logs: logrotate

  • -d: dry run, no real action
  • Reads /etc/logrotate.d/ rules
  • Usually run daily, automated
$ sudo logrotate -d /etc/logrotate.conf # dry run: shows planned actions only rotating pattern /var/log/syslog log needs rotating

Rotate Logs: logrotate

$ sudo logrotate -d /etc/logrotate.conf # dry run: shows planned actions only rotating pattern /var/log/syslog log needs rotating

A Rotation Rule

  • One block per log file
  • weekly, rotate 4: keep a month
  • compress: save disk space
weeklyrotate 4compress

copytruncate: Stays Open

  • For a log that stays open
  • Copies the log, then clears it
  • No restart needed afterward
$ cat /etc/logrotate.d/myapp /var/log/myapp.log { daily copytruncate } # process keeps its open handle, # file is copied then zeroed out

copytruncate: Stays Open

$ cat /etc/logrotate.d/myapp /var/log/myapp.log { daily copytruncate } # process keeps its open handle, # file is copied then zeroed out

Check: What Happens at Rotation 5?

rotate 4 keeps 4 old copies. On the 5th rotation, what happens to the oldest one?

Answer
It gets deleted. rotate 4 caps the history at 4 old copies, so the oldest is dropped to make room.

Force It Now: logrotate -f

  • -f: rotate right now
  • Useful before a disk fills up
  • Still reads the same rules
$ sudo logrotate -f /etc/logrotate.conf # -f: force rotation right now

Force It Now: logrotate -f

$ sudo logrotate -f /etc/logrotate.conf # -f: force rotation right now

Use Case: logrotate

  • A log file grows unchecked
  • Disk usage climbs toward full
  • logrotate -f frees space now
Disk Alert: 95% Fullone huge log file is most of itlogrotate -frotate and compress it immediatelyDisk Space Reclaimedno waiting for the weekly schedule

Use Case: Retention

  • Policy: keep 90 days of logs
  • weekly + rotate 12 covers it
  • Old copies expire on their own
Policy: Keep 90 Daysnot less, and not forever eitherweekly, rotate 12 in the rule12 weekly copies is about 90 daysOld Logs Expire on Scheduleno manual cleanup, no overrun

Questions?

Centralized Logging

CENTRALIZED LOGGINGOne Place for Every Machinethe real reasonA Compromised Host Lieslocal logs can be deletedA Remote Copy Survivesforwarded before the attackIf an attacker gets root, they can erase the local log.A copy already sent elsewhere survives even if the original is wiped.

Why Forward Logs at All

  • One dashboard for many servers
  • Survives a local compromise
  • Easier to correlate events
Host AHost BHost CCentral log server

Check: Why Not Just Local Logs?

An attacker gains root and deletes /var/log entirely. What survives if logs were also forwarded?

Answer
The forwarded copy on the central server. It was already sent before the attacker deleted the local file.

Forward Logs: rsyslog

  • Not configured by default
  • @@ means TCP, not UDP
  • Restart to apply the new rule
$ echo "*.* @@logserver:514" | \ sudo tee -a /etc/rsyslog.d/50-forward.conf $ sudo systemctl restart rsyslog

Forward Logs: rsyslog

$ echo "*.* @@logserver:514" | \ sudo tee -a /etc/rsyslog.d/50-forward.conf $ sudo systemctl restart rsyslog

Use Case: Forensics

  • A web server is compromised
  • The attacker wipes local logs
  • The remote copy survives
Server Compromised, Logs Wipedthe local copy is goneCheck the central log serverthe forwarded copy was unaffectedThe Attack Is Reconstructedforwarding happened before the wipe

Use Case: One Dashboard

  • 20 servers, 20 separate logs
  • Forwarding merges all of them
  • One grep, not twenty logins
20 Servers, 20 Separate Logschecking each one takes all daygrep on the central serverone search across every hostOne Answer, Not Twenty Loginsminutes instead of hours

Questions?

Word Origin: "Jail"

  • fail2ban's own config term
  • Filter paired with actions
  • Named per service: sshd, nginx
  • A banned IP stays out, bantime

fail2ban's own manual defines a jail as a filter-plus-action pair; a banned IP is effectively locked out for the bantime.

Source: fail2ban: jail.conf(5) manual

Reading Auth Logs

READING AUTH LOGSEvery Login Attempt, Loggedsuccess or failure/var/log/auth.logDebian/UbuntuFailed passwordthe line fail2ban watches forgrep already taught in Module 2 is the right tool here too.A burst of Failed password lines from one IP is a brute-force attempt.

grep, Revisited

  • Same tool from Module 2
  • Search for "Failed password"
  • Reveals repeated attempts fast
grep "Failed password" auth.loggrep -c "Failed" auth.log

Check: One Attempt, or an Attack?

auth.log shows 40 Failed password lines from the same IP in one minute. What does that suggest?

Answer
A brute-force attempt, not a typo. A real user does not mistype their password 40 times in 60 seconds.

More grep Examples

  • Reuses grep from Module 2
  • tail -20: just recent lines
  • wc -l: a quick failure count
$ sudo grep "Failed password" \ /var/log/auth.log | tail -20 $ sudo grep -c "Failed password" \ /var/log/auth.log

More grep Examples

$ sudo grep "Failed password" \ /var/log/auth.log | tail -20 $ sudo grep -c "Failed password" \ /var/log/auth.log

Use Case: Daily Triage

  • A habit, not a crisis step
  • A count sets a daily baseline
  • A spike means check further
Morning Check-Inis anything unusual overnight?grep -c "Failed password" auth.loga one-line failure countA Number to Compare Tomorrowa spike tomorrow now means something

Use Case: Timeline

  • A breach is suspected at 2 AM
  • grep around that exact time
  • Confirms access was attempted
Suspected Breach Near 2 AMneed to confirm what happenedgrep "Jan 5 02:" auth.lognarrow the log to that hourTimeline Confirmed or Ruled Outevidence either way, not a guess

Questions?

Word Origin: "Brute Force"

  • Early 1900s engineering term
  • Raw power, not precision
  • Later adopted in cryptography
  • Every combination, no skill

40 failed logins from one IP in a minute is brute force: no cleverness, just repetition.

Source: NIST Glossary: Brute-Force Attack

Why fail2ban?

WHY FAIL2BAN?Watching Alone Does Not Stop Itthe gap fail2ban fillsIt Reads the Logssame auth.log you just greppedIt Calls ufwModule 2's firewall, automaticallyYou already know how to spot an attack by hand.fail2ban does that same check, continuously, and blocks automatically.

The Loop fail2ban Runs

  • Watch auth.log for failures
  • Count failures per IP
  • Past the limit: ban via ufw
Watch auth.logCount failures per IPBan it with ufw

Check: What Does fail2ban Actually Call?

fail2ban decides to ban an IP. What Module 2 tool does it use to actually block that IP?

Answer
ufw. fail2ban does not reinvent firewalling; it drives the same firewall tool already taught in Module 2.

Confirm fail2ban Is Active

  • Reuses systemctl from Module 6
  • Shows if the service is active
  • Check before trusting a ban
$ sudo systemctl status fail2ban # look for "active (running)"

Confirm fail2ban Is Active

$ sudo systemctl status fail2ban # look for "active (running)"

Use Case: 24/7 Response

  • A team can't watch all night
  • fail2ban never stops watching
  • Attacks blocked in seconds
Attack Starts at 3 AMno one is watching the dashboardfail2ban's own watch looprunning continuously, unattendedBlocked Before Anyone Wakes Upno human had to be paged

Use Case: Alert Fatigue

  • Thousands of failed logins
  • Most never need a human to see
  • fail2ban clears the noise
Inbox: 3,000 Login Alertsalmost none need a real responsefail2ban auto-bans before alertingmost attempts never reach the inboxOnly Real Threats Remainthe team reviews a short list instead

Questions?

Word Origin: "fail2ban"

  • Literal name: fail + 2 + ban
  • "2" stands in for "to"
  • Written 2004 by Cyril Jaquier
  • Watches failures, then bans

The tool's own name is its job description: too many failed logins, and it bans you.

Source: Wikipedia: Fail2ban

Configuring fail2ban

CONFIGURING FAIL2BANOne Jail per Servicesshd, nginx, and moremaxretryhow many failures allowedbantimehow long the ban lastsA jail watches one service's own log for failures.The sshd jail is the one most relevant to everything taught so far.

Check fail2ban: fail2ban-client

  • Not installed by default
  • status: which jails are active
  • status sshd: who is banned
$ sudo apt install -y fail2ban $ sudo fail2ban-client status # lists every active jail $ sudo fail2ban-client status sshd # shows banned IPs for sshd

Check fail2ban: fail2ban-client

$ sudo apt install -y fail2ban $ sudo fail2ban-client status # lists every active jail $ sudo fail2ban-client status sshd # shows banned IPs for sshd

The sshd Jail

  • enabled = true turns it on
  • maxretry = 5: 5 tries allowed
  • bantime = 1h: an hour ban
[sshd] enabled = truemaxretry = 5bantime = 1h

Check: Fifth or Sixth Try?

maxretry = 5. On which attempt does fail2ban actually ban the IP: the 5th or the 6th?

Answer
The 6th. maxretry = 5 means 5 failures are allowed before the ban triggers on the next one.

Query a Jail's Settings

  • get: read a jail's own setting
  • No change made, just a lookup
  • Confirm it before trusting it
$ sudo fail2ban-client get sshd bantime $ sudo fail2ban-client get sshd maxretry

Query a Jail's Settings

$ sudo fail2ban-client get sshd bantime $ sudo fail2ban-client get sshd maxretry

Use Case: A Web App Jail

  • nginx login page is attacked
  • A custom jail watches its log
  • Same auto-ban, new service
nginx Login Brute-Forcedsshd's jail does not cover thisA new [nginx-login] jailwatches nginx's own access logSame Protection, New Servicefail2ban is not sshd-only

Use Case: Tuning bantime

  • A real user mistypes 5 times
  • A long ban punishes a mistake
  • A short ban stops attacks too
A Real User, 5 Typoslocked out by their own mistakebantime = 10m instead of 1henough to stop a real attacker tooA Mistake Recovers in Minutesa genuine attack is still stopped

Questions?

Practice Lab

Scenario: Install and Confirm

  • Install fail2ban on Ubuntu
  • Confirm the sshd jail works
  • Check it with fail2ban-client
Install fail2banConfirm the sshd jail

Step 1: Install fail2ban

  • Not on the machine by default
  • Starts automatically
  • Default config includes sshd
$ sudo apt install -y fail2ban $ sudo systemctl status fail2ban # confirm it is active

Step 1: Install fail2ban

$ sudo apt install -y fail2ban $ sudo systemctl status fail2ban # confirm it is active

Step 2: Confirm the Jail

  • status: every active jail
  • status sshd: just this jail
  • Currently banned: likely empty
$ sudo fail2ban-client status $ sudo fail2ban-client status sshd # Currently banned: 0 (so far)

Step 2: Confirm the Jail

$ sudo fail2ban-client status $ sudo fail2ban-client status sshd # Currently banned: 0 (so far)

Step 3: Trigger a Real Failure

  • Try SSH with a bad password
  • Writes a real failure line
  • Confirm with grep (Module 2)
$ ssh wronguser@localhost # enter any wrong password $ sudo grep "Failed password" \ /var/log/auth.log | tail -1

Step 3: Trigger a Real Failure

$ ssh wronguser@localhost # enter any wrong password $ sudo grep "Failed password" \ /var/log/auth.log | tail -1

Check: Why localhost?

Step 3 SSHes to localhost itself to fail on purpose. Why is that a safe way to test this?

Answer
It only affects your own machine: no real external attacker involved, and the failure is still logged for real.

Deliverable

  • Screenshot: fail2ban status
  • Screenshot: sshd jail status
  • Screenshot: the failed login
Install and confirm the jailTrigger and log a failure

Questions?

Practice Lab 2

Scenario: Lower the Threshold and Ban

  • Set maxretry to a small number
  • Fail that many times, on cue
  • Watch fail2ban ban you
maxretry = 2Fail 3 times: get banned

Step 1: Lower maxretry

  • Edit the jail's local override
  • Written with tee, not nano
  • System config stays untouched
$ sudo tee /etc/fail2ban/jail.d/ test.local << 'EOF' [sshd] maxretry = 2 EOF $ sudo systemctl restart fail2ban

Step 1: Lower maxretry

$ sudo tee /etc/fail2ban/jail.d/ test.local << 'EOF' [sshd] maxretry = 2 EOF $ sudo systemctl restart fail2ban

Step 2: Trigger the Ban

  • Three bad logins on purpose
  • Third attempt may be refused
  • Checked the same way as Lab 1
$ ssh wronguser@localhost $ ssh wronguser@localhost $ ssh wronguser@localhost # the third attempt may be refused

Step 2: Trigger the Ban

$ ssh wronguser@localhost $ ssh wronguser@localhost $ ssh wronguser@localhost # the third attempt may be refused

Step 3: Confirm the Ban

  • Banned count should now be 1
  • Proves fail2ban actually acted
  • Really blocks, not just logs
$ sudo fail2ban-client status sshd # Currently banned: 1

Step 3: Confirm the Ban

$ sudo fail2ban-client status sshd # Currently banned: 1

Check: Undo the Ban

Your own testing IP is now banned and you need back in. What fail2ban-client command undoes a ban?

Answer
fail2ban-client set sshd unbanip <ip> removes a specific IP from that jail's ban list immediately.

Deliverable

  • Screenshot: lowered maxretry
  • Screenshot: 3 failed logins
  • Screenshot: ban count is 1
Lower the thresholdTrigger it, prove the ban

Questions?

Looking Ahead: Module 10

Module 10

Time Synchronization

All Commands: Module 10

Why Time Matters

Why This Matters

  • Every clock starts at 1970
  • NTP: decades of synced clocks
  • chrony is the modern default
1970Unix epoch defined: Jan 1,1970, 00:00 UTC, time zero 1985NTP created (David Mills,U. of Delaware) 2003NTP Pool Project launches:volunteer public time servers 2009chrony released: faster syncfor laptops, VMs, containers Todaychrony is Ubuntu's defaultsync daemon
UTC vs. GMT: A WORLD TIME MAPOne global standard, read differently by longitudeLos AngelesUTC-8New YorkUTC-5London (GMT)UTC+0BerlinUTC+1TokyoUTC+9SydneyUTC+11GMT: mean solar time measured at Greenwich.UTC: the atomic-clock standard chrony and NTP actually sync to.Offsets shown are standard time; some regions shift for daylight saving.

What Is GMT?

  • Mean solar time at Greenwich
  • Set by the Royal Observatory
  • The old world time standard
Sun crosses Greenwich: noonRoyal Observatory records it= Greenwich Mean Time (GMT)

What Is UTC?

  • Tracked by atomic clocks
  • A single global time zero
  • No daylight saving shifts
Atomic clock: cesium-133One global second, counted= Coordinated Universal Time
A HISTORY OF GMT AND UTCFrom a London observatory to the atomic-clock standard1675Greenwich Observatory founded1880GMT: UK's legal time1884Prime Meridian set at Greenwich1955First atomic clock built1972UTC adopted worldwideTodayUTC syncs every clockGMT started the standard; UTC made it precise.Both still share the same zero point: Greenwich.
GMT vs. UTC: THE DIFFERENCESame zero point, two different definitionsGMTUTCBasisMean solar timeBasisAtomic clock (cesium)Daylight SavingShifts to BSTDaylight SavingNever changesDefined ByRoyal ObservatoryDefined ByInt'l standards (BIPM)Servers and logs use UTC: one standard, no DST surprises.

Local Time = UTC + Offset

  • Every zone offsets from UTC
  • West is behind, east is ahead
  • Zones follow UTC, not GMT
UTC time: 17:02Offset: Los Angeles UTC-7Local time: 10:02 PDT

What Does the Z Mean?

  • Z = Zulu = zero offset
  • NATO's word for the letter Z
  • Seen in logs and flight plans
2026-10-16T17:02:15ZZ means UTC+0 exactly= Zulu Time (NATO alphabet)

Reading a +/- Offset

  • Offset shows hours from UTC
  • Minus: behind, plus: ahead
  • Same instant, different label
2026-10-16T10:02-07:00-07:00 = 7h behind UTCSame instant: ...17:02Z

See It: date vs. date -u

  • Same moment, two time zones
  • -u prints UTC, no flag: local
  • Full command ahead
$ date Fri Oct 16 10:02:15 PDT 2026 $ date -u Fri Oct 16 17:02:15 UTC 2026

See It: date vs. date -u

$ date # Local time: whatever zone this VM is in Fri Oct 16 10:02:15 PDT 2026 $ date -u # -u: force UTC output instead Fri Oct 16 17:02:15 UTC 2026

Why Servers Log in UTC

  • Avoids DST's repeated hour
  • Same meaning in every country
  • Logs from 5 VMs line up
Fall DST: clocks repeat 1 AMLocal log: which 1:30 AM?UTC log: always unambiguous

See It: Both Times at Once

  • One command, two readings
  • Local time and UTC together
  • Full command ahead
$ timedatectl Local time: Fri 2026-10-16 10:02:15 PDT Universal time: Fri 2026-10-16 17:02:15 UTC

See It: Both Times at Once

$ timedatectl # One call shows local AND UTC Local time: Fri 2026-10-16 10:02:15 PDT # Same instant, UTC reference Universal time: Fri 2026-10-16 17:02:15 UTC

Check: Is GMT Just UTC?

London shows GMT in winter and BST in summer, but a server's logs always say UTC. Are GMT and UTC the same thing?

Only in winter, when both sit at +0. GMT shifts for daylight saving; UTC never does, which is why logs use UTC instead.
WHY A WRONG CLOCK BREAKS THINGSThe System Clockeverything else trusts itLog TimestampsModule 9: ordering an incidentTLS CertificatesModule 8: expiry is a real dateScheduled Jobscron fires at the wrong hourA clock a few minutes off can reject a valid certificate outright.This module keeps that one shared clock trustworthy.

A Clock a Few Minutes Off

  • SSH key auth can silently fail
  • TLS handshakes get rejected
  • Distributed logs misalign
Client time: 10:02:15Server time: 10:00:00Cert check: NOT YET VALID

Check: Which Fails First?

A VM is 6 hours behind. SSH still works. A website load fails with a certificate error. Why that one first?

TLS certificate validity windows are checked to the second; SSH key auth mostly ignores wall-clock time entirely.

Hospital Case: Cert Fails

  • Dashboard calls Clinical Data
  • HTTPS cert checked by time
  • Clock drift breaks the link
Web Interface clock: 09:58Clinical Data clock: 10:00TLS check: CERT REJECTED

Use Case: Log Order

  • Situation: 5 VMs, 1 incident
  • Tool: synced clocks, logs
  • Result: true event order
5 VM Logs: MismatchedSync Clocks + LogsTrue Incident Order

NTP & Stratum

Clocks Drift on Their Own

  • A quartz crystal is not exact
  • Drift adds up: seconds per day
  • NTP corrects it continuously
Real time: 10:00:00.000System clock: 10:00:02.700NTP: nudge back in sync

Stratum: Layers of Trust

  • Stratum 0: atomic clocks, GPS
  • Stratum 1: directly wired
  • Your VM: stratum 3 or 4
Stratum 0: GPS / atomic clockStratum 1: directly attachedStratum 2-4: pool, then you

Check: Why Not Stratum 1?

Every stratum-1 server is directly wired to a real reference clock. Why not just point every VM at one?

A handful of stratum-1 servers cannot answer millions of clients; the stratum tree spreads that load.
PROBLEM: FIVE CLOCKS, FIVE STORIESSame login event, five different VM clocksMonitor Read10:02:15Monitor Write10:01:48Attacker09:58:03Clinical Data10:02:50Clinical Web10:03:11Five VMs, one event, five different times.Without one shared reference, no timeline can be trusted.
SOLUTION: ONE SOURCE, FIVE VMsEvery VM points at the same pool serverchronypool.ntp.orgMonitor Read10:02:50Monitor Write10:02:50Attacker10:02:50Clinical Data10:02:50Clinical Web10:02:50All five VMs now agree on one time.This is why Project Part 2 requires chrony on every VM.

Check: Does Attacker Count?

The Attacker VM is on your shared network but is not your team's to configure. Does its clock still need to agree with yours?

Yes: every VM on the class network points at the same public pool, so even another team's timestamps stay comparable to yours.

Checking the Time

date: The Simple Check

  • Plain, no flags, prints now
  • Shows local time and zone
$ date Fri Oct 16 10:02:15 PDT 2026

date: The Simple Check

$ date # No flags: just the current time Fri Oct 16 10:02:15 PDT 2026

timedatectl: Full Picture

  • Shows local, UTC, sync state
  • NTP service: active or not
$ timedatectl Local time: Fri 2026-10-16 10:02:15 PDT Universal time: Fri 2026-10-16 17:02:15 UTC NTP service: active

timedatectl: Full Picture

$ timedatectl # Local time, zone, and NTP state Local time: Fri 2026-10-16 10:02:15 PDT # NTP service: active means synced NTP service: active

Check: date vs. timedatectl

date just prints a timestamp. timedatectl prints a whole status block. When would you reach for date instead?

Inside a script that only needs the current value, not a human status report: date is simpler to parse.

Use Case: Confirm Trust

  • Backup log says 2:00 AM
  • Incident report says 5:00 AM
  • timedatectl finds the bug
Backup Log: 2:00 AMCheck Both VMs' TimeRe-Sync, Logs Agree

Setting the Time Zone

Time Zone: A Named Offset

  • /usr/share/zoneinfo holds them
  • Region/City, not just a number
  • Handles daylight saving too
UTC: the one true referenceAmerica/Los_Angeles: UTC-7/-8Asia/Tokyo: UTC+9

Setting the Zone

  • Takes a Region/City name
  • list-timezones shows all zones
$ timedatectl set-timezone America/Los_Angeles

Setting the Zone

$ timedatectl list-timezones | grep Los_Angeles # Find the exact zone name first America/Los_Angeles $ timedatectl set-timezone America/Los_Angeles # Then set it; takes effect right away

Check: Why a Name?

A zone could just be stored as "UTC-7". Why does Linux use "America/Los_Angeles" instead?

A fixed offset breaks every daylight-saving switch; a named zone carries the whole rule set for that region.

chrony: Staying in Sync

chrony: A Background Daemon

  • Installed, running by default
  • Talks to pool servers over NTP
  • Nudges the clock continuously
chronyd: the background servicepool.ntp.org: remote serversSystem clock: kept in sync

chronyc tracking: Synced?

  • Shows the current offset
  • Last offset: how far off
$ chronyc tracking Reference ID : A29FC87B System time : 0.000012 seconds fast

chronyc tracking: Synced?

$ chronyc tracking # Reference ID: which server it trusts Reference ID : A29FC87B # System time: current drift, in seconds System time : 0.000012 seconds fast

chronyc sources: Who to Ask

  • Lists every candidate server
  • * marks the one it trusts most
$ chronyc sources ^* time.cloudflare.com 3 6 377 ^- time.google.com 1 6 377

chronyc sources: Who to Ask

$ chronyc sources # ^* marks the currently-selected source ^* time.cloudflare.com 3 6 377 # ^- is a candidate, not chosen yet ^- time.google.com 1 6 377

Check: No * in sources?

chronyc sources lists several servers but none has a * next to it. What does that mean?

No source is trusted yet, usually right after boot or a network outage: the clock is not yet confirmed synced.

Hospital Case: Backups

  • Backup cron fires at 2 AM
  • One VM's clock has drifted
  • Backup lands at wrong hour
Backup Cron: fires at 2 AMOne VM's Clock DriftsBackup Lands Wrong Hour

The Hardware Clock

Two Clocks, Not One

  • Hardware clock: battery-backed
  • System clock: what Linux uses
  • They can drift apart over time
Hardware clock: ticks while offBoot: system clock reads itchrony then corrects it live

hwclock: The Battery Clock

  • Needs sudo to read directly
  • --systohc copies system to it
$ sudo hwclock --show 2026-10-16 10:02:11.293211-07:00

hwclock: The Battery Clock

$ sudo hwclock --show # Reads straight from the battery-backed clock 2026-10-16 10:02:11.293211-07:00 $ sudo hwclock --systohc # Copies the now-synced system time to it

Check: Sync Hardware Too?

chrony already keeps the system clock correct while Linux is running. Why also fix the hardware clock?

The hardware clock is what the next boot starts from, before chrony has had any time to correct it.

Use Case: Snapshot Jump

  • VM restored from old snapshot
  • hwclock + chrony re-sync it
  • Logs trust real time again
VM Resumed From Snapshothwclock + chrony Re-SyncLogs Trust Real Time Again

Word Origin: "Stratum"

  • Latin: a layer, spread out
  • Geology: rock layers, stacked
  • NTP borrows it for trust
Layers, stacked, like rock

Word Origin: "GMT"

  • Greenwich: a London borough
  • Mean: an average solar day
  • Royal Observatory set it
Fixed at Greenwich, shared worldwide

Word Origin: "Epoch"

  • Greek: epokhe, a fixed point
  • Unix epoch: Jan 1, 1970, UTC
  • Every timestamp counts from it
Epoch: 1970-01-01 00:00 UTCSeconds since then: a timestamp

Practice Lab

Scenario: The Drifting VM

  • A VM sat suspended for a week
  • Its clock is now badly wrong
  • Fix it, then prove it stuck
Before: clock drifted, wrong zoneFix: zone set, chrony re-syncedProof: chronyc tracking checked

Step 1: Current Status

  • See the drift before fixing it
  • Confirm NTP service state
$ timedatectl

Step 1: Current Status

$ timedatectl # Note the current local time and zone

Step 2: Set Correct Zone

  • Set America/Los_Angeles
$ timedatectl set-timezone America/Los_Angeles

Step 2: Set Correct Zone

$ timedatectl set-timezone America/Los_Angeles # Takes effect immediately, no reboot

Step 3: chrony Is Running

  • Install it if missing
  • Then check its service state
$ sudo apt install -y chrony $ systemctl status chrony

Step 3: chrony Is Running

$ sudo apt install -y chrony # Not installed by default on every image $ systemctl status chrony # Confirm it is active and running

Step 4: Watch It Re-Sync

  • Offset shrinks over checks
  • Run it more than once
$ chronyc tracking | grep System time

Step 4: Watch It Re-Sync

$ chronyc tracking | grep System time # Re-run after a minute: offset should shrink

Step 5: A Trusted Source

  • Look for the * marker
  • Means a source is now trusted
$ chronyc sources

Step 5: A Trusted Source

$ chronyc sources # ^* on a row means it is now trusted

Check: Proving It Worked

A screenshot of timedatectl right after the fix looks correct. Why is that not proof the sync held?

A one-time correct reading could be luck; chronyc tracking showing a shrinking offset over time is the real proof.

Deliverable

  • Correct time zone set
  • chrony installed and running
  • chronyc tracking: synced
$ chronyc tracking System time : 0.000031 seconds fast

Questions?

Practice Lab Part 2

THE STORY SO FAR: CLICK THROUGH THIS LAB VM justbooted simulate.shwrites log Dashboardreads log Clock mustsync first Ahead: check,sync, prove VM justbooted simulate.shwrites log Dashboardreads log Clock mustsync first Ahead: check,sync, prove MONITORING DASHBOARD 2026-10-27 10:42:03 nurse1 read record #4821 2026-10-27 10:44:17 physician1 updated #3390 2026-10-27 10:45:52 guest1 viewed dashboard Is every timestamp here accurate?
WHAT setup.sh CREATES Created once, the same on every team's Ubuntu VM /srv/clinical-data/ patients.csv 644, world-readable .patients.csv.bak 644, world-readable /opt/hospital-vm/ legacy-notify.sh disabled, legacy stub simulate.sh optional, background /var/log/ clinical-activity.log guest1 group: guests nurse1 group: nurses physician1 group: physicians patient1 group: patients

/srv/clinical-data/ (1/4)

  • Shared clinical records
  • 2 files, both 644
  • Starts world-readable
$ ls -la /srv/clinical-data/ -rw-r--r-- 1 root root 2048 patients.csv -rw-r--r-- 1 root root 512 .patients.csv.bak $ cat patients.csv | cut -d, -f1-4 mrn,name,dob,unit ER-1001,Jordan Ellis,1990-03-14,ER-A ER-1002,Priya Nandakumar,1985-07-02,ER-B

/opt/hospital-vm/ (2/4)

  • Legacy notify script
  • Marked for retirement
  • Still on disk, still runs
$ ls -l /opt/hospital-vm/legacy-notify.sh -rw-r--r-- 1 root root 118 legacy-notify.sh $ cat legacy-notify.sh #!/bin/bash # TODO: retire, replaced by new pipeline # patient1 / Patient123! echo "legacy notify: disabled"

simulate.sh (3/4)

  • Optional background script
  • Simulates clinic activity
  • Full walkthrough coming up
$ ls -l /var/log/clinical-activity.log -rw-r--r-- 1 root root 4096 clinical-activity.log $ tail -3 clinical-activity.log 10-27 10:42:03 persona=nurse1 action=read 10-27 10:43:03 action=vitals-update row=ER-1001 10-27 10:43:33 persona=guest1 action=read

4 Persona Accounts (4/4)

  • guest1, nurse1, physician1
  • ...and patient1
  • Each in its own group
👤 guest1 group: guests 🩺 nurse1 group: nurses 🧑‍⚕️ physician1 group: physicians 🛏️ patient1 group: patients

How simulate.sh Runs

while true; do pick a persona act on a row sleep 30s Never exits: not a cron job Not in crontab: background it yourself
$ nohup ./simulate.sh & # loops forever, must be backgrounded 10-27 10:42:03 persona=nurse1 action=read 10-27 10:43:03 action=vitals-update row=ER-1001 10-27 10:43:33 persona=guest1 action=read 10-27 10:44:03 persona=patient1 action=read

Disabled Is Not Removed

Permissions: 644 World-readable Old password in comment Disabled script, not removed An audit would still find it
$ cat /opt/hospital-vm/legacy-notify.sh #!/bin/bash # TODO: retire, replaced by new pipeline # patient1 / Patient123! echo "legacy notify: disabled" $ ls -l /opt/hospital-vm/legacy-notify.sh -rw-r--r-- 1 root root 118 legacy-notify.sh # an accurate audit would flag this

Join the Hospital VM

  • Clone the shared repo
  • Run setup.sh
  • Confirm SETUP OK
$ sudo apt install -y git # not installed by default $ git clone \ https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/project/part-2/Hospital-VM $ chmod +x setup.sh $ ./setup.sh SETUP OK

Q1: Unknown Clock State

  • New VM, unknown state
  • Can't trust logs blindly
  • Check status first

A wrong clock makes a log entry timestamped 10:42 actually be from an hour earlier: Monitor Read/Write can't correlate a dashboard alert with the real event until the clock is proven reliable.

MONITORING DASHBOARD10:42:03 nurse1 read #4821✗ Without this check:NTP service: inactive10:42:03 nurse1 read #4821← UNVERIFIED (clock never checked)✓ Fixed by:timedatectl→ NTP service: active10:42:03 nurse1 read #4821← verified, synced 0.3s ago

Q1: What's the Clock State?

Before trusting any log timestamp, what command shows the current time, zone, and NTP service state?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ timedatectl Local time: ... Time zone: ... NTP service: active

Answer: timedatectl

  • Shows local time & zone
  • Shows NTP service state
  • The starting diagnostic
$ timedatectl | grep "NTP service" NTP service: active

Q2: Zone Set, But Synced?

  • A zone can look correct
  • That's not the same as
  • actually being synced

A VM suspended for days can still report "America/Los_Angeles" correctly while having drifted underneath: the dashboard would show stale or out-of-order events without this check.

MONITORING DASHBOARDVM suspended 4 days, drifted✗ Without this check:NTPSynchronized=no14:02:11 physician1 update #3390← zone right, NOT synced✓ Fixed by:timedatectl show -p NTPSynchronized→ NTPSynchronized=yes14:02:11 physician1 update #3390← zone right, synced (yes)

Q2: Is It Actually Synced?

A zone can be set correctly while the clock is still unsynced. What confirms real sync, not just a zone?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ timedatectl show -p NTPSynchronized NTPSynchronized=yes

Answer: show -p NTPSynchronized

  • yes means truly synced
  • Zone alone can mislead
  • This is the real check
$ timedatectl show -p \ NTPSynchronized --value yes
10 VMs, EACH CLOCK LOOKS FINE ALONEProject Part 2: five teams, 1 Ubuntu + 1 Kali each, one shared networkUbuntu VMsKali VMsMonitor Read14:32:07 ✓Monitor Read14:32:11 ✓Monitor Write14:31:52 ✓Monitor Write14:31:49 ✓Attacker14:32:41 ✓Attacker14:32:33 ✓Clinical Data14:32:03 ✓Clinical Data14:32:19 ✓Web Interface14:31:58 ✓Web Interface14:32:02 ✓EVERY VM REPORTS ITS OWN LOCAL TIME AS CORRECTBUT THE FLEET IS UP TO 52 SECONDS APARTMonitor Write 14:31:49 vs. Attacker 14:32:41: 52s apart, same instant"Looks fine locally" is not the same as "in sync with the rest of the fleet."A log-correlation check across teams needs all 10 clocks agreeing, not each one alone.
WHAT CHRONY DOESpool.ntp.orgexternal time sourcechrony (this VM)small, gradual correctionsAccurate Local Clocknever jumps abruptlyEVERY VM IN THE FLEET RUNS ITS OWN chronyMonitor Read/Write VMchronyClinical Data &Access Control VMchronyOther Team VMschronyTIMESTAMPS AGREE ACROSS THE FLEETWithout chrony running on every VM, each clock drifts independentlyand timestamps from different teams' machines can no longer be compared.

Q3: chrony Isn't There Yet

  • chrony is not installed
  • No sync without it
  • Install it first

Without chrony actually running, nothing corrects drift over time: a clock can drift minutes per week, enough to make two near-simultaneous log entries appear out of real order on the dashboard.

MONITORING DASHBOARDchrony: not installed✗ Without this check:chrony: command not found09:15:40 guest1 viewed dashboard← no sync service running✓ Fixed by:sudo apt install -y chrony→ Active: active (running)09:15:40 guest1 viewed dashboard← chrony active and syncing

Q3: Install and Confirm chrony

chrony isn't installed by default. What two commands install it and confirm its service is running?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ sudo apt install -y chrony # not installed by default $ sudo systemctl enable --now chrony # enable on boot + start now $ systemctl status chrony Active: active (running)

Answer: install, then status

  • apt install -y chrony first
  • systemctl status confirms
  • active (running) is the goal
$ systemctl is-active chrony active

Q4: Running, But How Far Off?

  • chrony running isn't
  • the same as synced tight
  • Check the real offset

Confirms how accurate the sync really is, not just that it's turned on: a sub-second offset proves the dashboard can tell which of two near-simultaneous reads happened first.

MONITORING DASHBOARDchrony: active, offset ?✗ Without this check:System time: +847.3 seconds fast10:44:17 physician1 update #3390← off by +847.3s (unverified)✓ Fixed by:chronyc tracking→ System time: 0.000031s fast10:44:17 physician1 update #3390← off by 0.000031s (tight)

Q4: Check the Sync Offset

chrony is running. What command shows exactly how far off the system clock currently is?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ chronyc tracking System time : 0.000031 seconds fast

Answer: chronyc tracking

  • System time line is key
  • A shrinking offset = good
  • Re-check after a minute
$ chronyc tracking | grep "System time" System time : 0.000031 seconds fast

Q5: Which Source Is Trusted?

  • Several NTP sources
  • Only one is trusted
  • Look for the marker

Shows where the time is actually coming from: a compromised or misconfigured NTP source could skew the clock deliberately, making the activity log's event order unreliable.

MONITORING DASHBOARD3 NTP sources configured✗ Without this check:ntp.ubuntu.com 2 6 377 1 +12uschronyc sources: 3 listed← no source marked trusted✓ Fixed by:chronyc sources→ ^* ntp.ubuntu.com 2 6 377 1 +12uschronyc sources: 3 listed← ^* ntp.ubuntu.com trusted

Q5: Confirm the Trusted Source

Several NTP sources are configured. Which command shows which one is actually trusted right now?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ chronyc sources ^* ntp.ubuntu.com 2 6 377 1 +12us # ^* = trusted/synced source # stratum 2, polls every 64s # reach 377(oct): last 8 polls OK # +12us = clock 12us ahead

Answer: chronyc sources

  • ^* marks the trusted row
  • Other rows are candidates
  • Confirms a real source
$ chronyc sources | grep "\^\*" ^* ntp.ubuntu.com 2 6 377 1 +12us # ^* = trusted/synced source # stratum 2, polls every 64s # reach 377(oct): last 8 polls OK # +12us = clock 12us ahead

Q6: Reading an Epoch Log Line

  • Epoch: seconds since 1970
  • clinical-activity.log
  • logs a raw epoch time
  • Needs a readable form

simulate.sh logs human-readable timestamps, but other tools like databases and APIs often log raw epoch numbers: converting one lets you cross-reference a database transaction with a specific logged read event.

MONITORING DASHBOARDclinical-activity.log: 1730000000✗ Without this check:1730000000clinical-activity.log: 1730000000← raw epoch, unreadable✓ Fixed by:date -d @1730000000→ 2026-10-27_14:13:20clinical-activity.log: 1730000000← 2026-10-27 14:13:20

Q6: Convert an Epoch Timestamp

clinical-activity.log logs a raw epoch timestamp. What command converts it to a readable date?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ date -d @1730000000 Mon Oct 27 ... 2026

Answer: date -d @epoch

  • -d @epoch reads seconds
  • Converts to local time
  • Lets you compare to now
$ date -d @1730000000 +%F_%T 2026-10-27_14:13:20

Epoch's Reference Zone

Q: date -d @0 prints "Dec 31, 1969 4:00 PM PST," not Jan 1, 1970. Whose midnight does epoch 0 actually use?

A: UTC's own midnight: epoch 0 is 1970-01-01 00:00:00 UTC exactly, since UTC is the reference zone itself, not an offset from another one. PST's −8h offset just shifts the local display back across the date line; the underlying epoch number never changes.

Q7: One Zone for Every Team

  • Different VMs, different
  • zones means logs never
  • line up across teams

If every team's VM uses a different zone, the same real event looks like it happened at different times on different dashboards: Monitor Write's backup logs and Monitor Read's access logs must agree on wall-clock time to line up a write with a suspicious read.

MONITORING DASHBOARDMonitor VM: PT, Audit VM: ET✗ Without this check:Time zone: America/New_YorkMonitor 14:02 PT vs Audit 17:02 ET← looks 3h apart (same event)✓ Fixed by:timedatectl set-timezone America/Los_Angeles→ Time zone: America/Los_AngelesMonitor 14:02 PT, Audit 14:02 PT← both read as 14:02 PT

Q7: Set a Shared Time Zone

Every team's clock needs the same zone so logs line up. What command sets it?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ timedatectl set-timezone \ America/Los_Angeles

Answer: set-timezone

$ timedatectl show -p Timezone --value America/Los_Angeles # proves the zone change stuck $ timedatectl | grep "Time zone" Time zone: America/Los_Angeles

Q8: Will It Survive a Reboot?

  • System clock is correct
  • Hardware clock separate
  • Write it before reboot

VMs get rebooted, for example after a security update; if the hardware clock wasn't written, the VM could boot with a stale time until chrony catches up, mistiming the first few minutes of log entries after every reboot.

MONITORING DASHBOARDreboot pending after update✗ Without this check:hwclock: 2026-10-20 09:02:11post-reboot clock: 2026-10-20← boots 7 days in the past✓ Fixed by:sudo hwclock --systohc→ hwclock: 2026-10-27 14:13:21post-reboot clock: 2026-10-27← boots at the real time

Q8: Survive a Reboot

The system clock is now correct. What command makes sure it is still correct after a reboot?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ sudo hwclock --systohc # writes time to the hw clock

Answer: hwclock --systohc

  • Writes system to hw clock
  • hwclock alone reads it back
  • Confirms it actually stuck
$ hwclock 2026-10-27 14:13:21.123456-07:00

Q9: UTC or GMT?

  • Two names, not synonyms
  • Only one never shifts
  • DST ends this weekend

If this VM's zone were casually labeled GMT instead of UTC, every dashboard timestamp would be off by one hour for roughly seven months a year while the UK observes British Summer Time.

MONITORING DASHBOARDzone label: GMT (ambiguous)✗ Without this check:Time zone: GMT (BST +1 active)zone label shown as GMT← silently +1h during BST✓ Fixed by:timedatectl set-timezone UTC→ Time zone: UTCzone label shown as UTC← UTC: never shifts

Q9: UTC or GMT?

This weekend (Nov 1), US clocks "fall back" for the end of Daylight Saving Time, so 1:30 AM happens twice in local time. For this VM's clock, would you recommend UTC or GMT, and why?

guest1guestsnurse1nursesphysician1physicianspatient1patients
$ sudo timedatectl set-timezone UTC # UTC never shifts for daylight saving

Answer: UTC, Not GMT

  • GMT ~ UK winter clock only
  • BST (UTC+1) runs Mar-Oct
  • UTC is the one fixed point
$ timedatectl show -p Timezone --value UTC # confirms it stuck: never GMT $ timedatectl | grep "Time zone" Time zone: UTC

Deliverable

  • Zone set correctly
  • chrony installed & synced
  • Trusted source confirmed
  • hwclock written
$ chronyc tracking System time : 0.000031 seconds fast

Questions?

Practice Lab Part 3

THE STORY SO FAR: CLICK THROUGH THIS LAB Audit aboutto begin Found oldlegacy script Credentiallooks old mtime needstrusted clock Ahead: check,sync, prove Audit aboutto begin Found oldlegacy script Credentiallooks old mtime needstrusted clock Ahead: check,sync, prove ACCESS AUDIT REPORT /srv/clinical-data/patients.csv Last Modified: 2026-10-27 14:02:11 /opt/hospital-vm/legacy-notify.sh Last Modified: 2026-10-27 09:15:40 Is every mtime here accurate?
WHAT setup.sh CREATES Created once, the same on every team's Ubuntu VM /srv/clinical-data/ patients.csv 644, world-readable .patients.csv.bak 644, world-readable /opt/hospital-vm/ legacy-notify.sh disabled, legacy stub simulate.sh optional, background /var/log/ clinical-activity.log guest1 group: guests nurse1 group: nurses physician1 group: physicians patient1 group: patients

/srv/clinical-data/ (1/4)

  • Shared clinical records
  • 2 files, both 644
  • Starts world-readable
$ ls -la /srv/clinical-data/ -rw-r--r-- 1 root root 2048 patients.csv -rw-r--r-- 1 root root 512 .patients.csv.bak $ cat patients.csv | cut -d, -f1-4 mrn,name,dob,unit ER-1001,Jordan Ellis,1990-03-14,ER-A ER-1002,Priya Nandakumar,1985-07-02,ER-B

/opt/hospital-vm/ (2/4)

  • Legacy notify script
  • Marked for retirement
  • Still on disk, still runs
$ ls -l /opt/hospital-vm/legacy-notify.sh -rw-r--r-- 1 root root 118 legacy-notify.sh $ cat legacy-notify.sh #!/bin/bash # TODO: retire, replaced by new pipeline # patient1 / Patient123! echo "legacy notify: disabled"

simulate.sh (3/4)

  • Optional background script
  • Simulates clinic activity
  • Full walkthrough coming up
$ ls -l /var/log/clinical-activity.log -rw-r--r-- 1 root root 4096 clinical-activity.log $ tail -3 clinical-activity.log 10-27 10:42:03 persona=nurse1 action=read 10-27 10:43:03 action=vitals-update row=ER-1001 10-27 10:43:33 persona=guest1 action=read

4 Persona Accounts (4/4)

  • guest1, nurse1, physician1
  • ...and patient1
  • Each in its own group
👤 guest1 group: guests 🩺 nurse1 group: nurses 🧑‍⚕️ physician1 group: physicians 🛏️ patient1 group: patients

How simulate.sh Runs

while true; do pick a persona act on a row sleep 30s Never exits: not a cron job Not in crontab: background it yourself
$ nohup ./simulate.sh & # loops forever, must be backgrounded 10-27 10:42:03 persona=nurse1 action=read 10-27 10:43:03 action=vitals-update row=ER-1001 10-27 10:43:33 persona=guest1 action=read 10-27 10:44:03 persona=patient1 action=read

Disabled Is Not Removed

Permissions: 644 World-readable Old password in comment Disabled script, not removed An audit would still find it
$ cat /opt/hospital-vm/legacy-notify.sh #!/bin/bash # TODO: retire, replaced by new pipeline # patient1 / Patient123! echo "legacy notify: disabled" $ ls -l /opt/hospital-vm/legacy-notify.sh -rw-r--r-- 1 root root 118 legacy-notify.sh # an accurate audit would flag this

Join the Hospital VM

  • Clone the shared repo
  • Run setup.sh
  • Confirm SETUP OK
$ sudo apt install -y git # not installed by default $ git clone \ https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/project/part-2/Hospital-VM $ chmod +x setup.sh $ ./setup.sh SETUP OK

Q1: Clock State Before the Audit

  • Audit about to start
  • Clock state unknown
  • Check it first

The audit's whole job is to say when access happened: if this VM's own clock state is unverified going in, every timestamp the audit later relies on is suspect before a single file is even checked.

ACCESS AUDIT REPORTaudit started, clock state: ?✗ Without this check:NTP service: inactiveaudit entry #1: timestamp pending← timestamp basis unverified✓ Fixed by:timedatectl→ NTP service: activeaudit entry #1: timestamp pending← timestamp basis confirmed

Q1: What's the Clock State?

Before auditing any file timestamp, what command shows the VM's current time, zone, and NTP state?

$ timedatectl Local time: ... Time zone: ... NTP service: active

Answer: timedatectl

  • Shows local time & zone
  • Shows NTP service state
  • Starting point for the audit
$ timedatectl | grep "NTP service" NTP service: active

Q2: One Zone for the Audit

  • Wrong zone on this VM
  • Audit timestamps mislead
  • Fix the zone first

If this audit VM's zone doesn't match the rest of the fleet, a finding like "patient1 read a record at 2:00 PM" could actually describe an event an hour earlier or later than every other machine's logs.

ACCESS AUDIT REPORTzone: UTC-7 (unconfirmed)✗ Without this check:Time zone: America/Chicagofinding logged at 14:02 (zone ?)← zone mismatch vs. the fleet✓ Fixed by:timedatectl set-timezone America/Los_Angeles→ Time zone: America/Los_Angelesfinding logged at 14:02 PT← zone matches the fleet

Q2: Set the Audit's Time Zone

Audit timestamps need to match the rest of the class. What command sets the correct zone?

$ timedatectl set-timezone \ America/Los_Angeles

Answer: set-timezone

$ timedatectl show -p Timezone --value America/Los_Angeles # proves the zone change stuck $ timedatectl | grep "Time zone" Time zone: America/Los_Angeles
10 VMs, EACH CLOCK LOOKS FINE ALONEProject Part 2: five teams, 1 Ubuntu + 1 Kali each, one shared networkUbuntu VMsKali VMsMonitor Read14:32:07 ✓Monitor Read14:32:11 ✓Monitor Write14:31:52 ✓Monitor Write14:31:49 ✓Attacker14:32:41 ✓Attacker14:32:33 ✓Clinical Data14:32:03 ✓Clinical Data14:32:19 ✓Web Interface14:31:58 ✓Web Interface14:32:02 ✓EVERY VM REPORTS ITS OWN LOCAL TIME AS CORRECTBUT THE FLEET IS UP TO 52 SECONDS APARTMonitor Write 14:31:49 vs. Attacker 14:32:41: 52s apart, same instant"Looks fine locally" is not the same as "in sync with the rest of the fleet."A log-correlation check across teams needs all 10 clocks agreeing, not each one alone.
WHAT CHRONY DOESpool.ntp.orgexternal time sourcechrony (this VM)small, gradual correctionsAccurate Local Clocknever jumps abruptlyEVERY VM IN THE FLEET RUNS ITS OWN chronyMonitor Read/Write VMchronyClinical Data &Access Control VMchronyOther Team VMschronyTIMESTAMPS AGREE ACROSS THE FLEETWithout chrony running on every VM, each clock drifts independentlyand timestamps from different teams' machines can no longer be compared.

Q3: Is chrony Even Installed?

  • chrony is not installed
  • No real sync without it
  • Install it, then check

An audit that trusts file timestamps without confirming the auditing machine itself keeps accurate time is building its findings on an unverified assumption: install and enable chrony before trusting anything it reports.

ACCESS AUDIT REPORTchrony: not installed✗ Without this check:chrony: command not foundaudit VM: sync status unknown← no sync service running✓ Fixed by:sudo apt install -y chrony→ Active: active (running)audit VM: sync status active← chrony active and syncing

Q3: Install and Confirm chrony

Assume chrony isn't installed on this VM. What two commands install it and confirm it's running?

$ sudo apt install -y chrony # not installed by default $ sudo systemctl enable --now chrony # enable on boot + start now $ systemctl status chrony Active: active (running)

Answer: install, then status

  • apt install -y chrony first
  • systemctl status confirms
  • active (running) is the goal
$ systemctl is-active chrony active

Q4: Offset Before Trusting mtime

  • chrony running isn't
  • proof of a tight offset
  • Check it before trusting

If this VM's own clock is still seconds or minutes off, the audit could misjudge the order of two closely timed events, like a backup write versus a suspicious read it's meant to flag.

ACCESS AUDIT REPORTlegacy-notify.sh mtime: ?✗ Without this check:System time: +847.3 seconds fastlegacy-notify.sh mtime check← off by +847.3s (unverified)✓ Fixed by:chronyc tracking→ System time: 0.000031s fastlegacy-notify.sh mtime check← off by 0.000031s (tight)

Q4: Check the Sync Offset

Before trusting any file's mtime, what command shows exactly how far off this clock is?

$ chronyc tracking System time : 0.000031 seconds fast

Answer: chronyc tracking

  • System time line is key
  • Small offset = trustworthy
  • Big offset = investigate
$ chronyc tracking | grep "System time" System time : 0.000031 seconds fast

Q5: Which Source Is Trusted?

  • Several NTP sources
  • Only one is trusted
  • Look for the marker

The audit record should name which source the clock actually trusted, not just that some source existed: a rogue or misconfigured source could have skewed the clock the audit itself relied on.

ACCESS AUDIT REPORT3 NTP sources configured✗ Without this check:ntp.ubuntu.com 2 6 377 1 +12uschronyc sources: 3 listed← no source marked trusted✓ Fixed by:chronyc sources→ ^* ntp.ubuntu.com 2 6 377 1 +12uschronyc sources: 3 listed← ^* ntp.ubuntu.com trusted

Q5: Confirm the Trusted Source

For the audit record, which command shows which NTP source is actually trusted right now?

$ chronyc sources ^* ntp.ubuntu.com 2 6 377 1 +12us # ^* = trusted/synced source # stratum 2, polls every 64s # reach 377(oct): last 8 polls OK # +12us = clock 12us ahead

Answer: chronyc sources

  • ^* marks the trusted row
  • Worth noting in the audit
  • Confirms a real source
$ chronyc sources | grep "\^\*" ^* ntp.ubuntu.com 2 6 377 1 +12us # ^* = trusted/synced source # stratum 2, polls every 64s # reach 377(oct): last 8 polls OK # +12us = clock 12us ahead

Q6: How Old Is That Credential?

  • legacy-notify.sh is old
  • Need "now" to compare
  • against its file date

A leftover credential in an old script like legacy-notify.sh is only a real finding if you can prove how long it's actually been sitting there: that means comparing its file date against a trustworthy "now."

ACCESS AUDIT REPORTlegacy-notify.sh: age ?✗ Without this check:mtime: 2026-10-20 09:02:11legacy-notify.sh mtime: 10-20← no "now" to compare against✓ Fixed by:date→ Tue Oct 27 14:13:20 PDT 2026legacy-notify.sh mtime: 10-20← now: 2026-10-27 (7 days old)

Q6: Sanity-Check a File's Age

You need to know how old legacy-notify.sh's leftover credential really is. What shows "now" to compare?

$ date Tue Oct 27 14:13:20 PDT 2026 # compare this to the file's mtime

Answer: date

  • Shows the current time
  • Compare to stat's mtime
  • Confirms the real age
$ date +%F_%T 2026-10-27_14:13:20

Q7: A Stale Hardware Clock?

  • VM sat suspended a week
  • Hardware clock may be
  • stale too, not just drift

A VM that sat suspended for a week could resume with a hardware clock still showing last week's date: any file timestamp checked before chrony catches up would be auditing against a clock that hasn't caught up yet either.

ACCESS AUDIT REPORTVM suspended 7 days✗ Without this check:assumed: 2026-10-27 (unverified)hwclock reads 2026-10-20← assumed current (it's wrong)✓ Fixed by:hwclock→ 2026-10-20 09:02:11 (stale)hwclock reads 2026-10-20← confirmed stale, 7 days off

Q7: Rule Out a Stale Hardware Clock

This VM sat suspended for a week. What command checks whether the hardware clock itself is stale?

$ hwclock 2026-10-20 09:02:11.000001-07:00

Answer: hwclock

  • Reads the hardware clock
  • Compare it to date's output
  • A big gap means stale
$ hwclock --verbose | grep "Hw clock" Hw clock time : 2026-10-20 09:02:11

Q8: Sign Off the Audit

  • Every check now passes
  • One final summary left
  • Confirm, then sign off

An auditor signing off needs one final, re-run confirmation that zone, sync, and NTP state all still hold, not just a memory of having checked each one separately earlier in the audit.

ACCESS AUDIT REPORTall checks passed (unconfirmed)✗ Without this check:NTP service: inactiveaudit summary: pending sign-off← relying on memory of checks✓ Fixed by:timedatectl→ NTP service: activeaudit summary: all checks green← one final check, confirmed

Q8: Final Re-Verification

Every clock check has now passed. What single command gives the final summary to sign off the audit?

$ timedatectl Local time: 2026-10-27 14:13:20 PDT Time zone: America/Los_Angeles NTP service: active

Answer: timedatectl

  • Zone: America/Los_Angeles
  • NTP service: active
  • Audit timestamps now trusted
$ timedatectl show -p \ NTPSynchronized --value yes

Q9: UTC or GMT?

  • Audit needs one fixed clock
  • GMT shifts with UK summer
  • DST ends this weekend

An audit report dated in GMT would quietly shift by an hour for seven months of the year as the UK moves to British Summer Time: UTC is the one label that never moves, so the audit's own record stays fixed.

ACCESS AUDIT REPORTaudit report dated: GMT✗ Without this check:Time zone: GMT (BST +1 active)report dated: GMT← silently +1h during BST✓ Fixed by:timedatectl set-timezone UTC→ Time zone: UTCreport dated: UTC← UTC: never shifts

Q9: UTC or GMT?

This weekend (Nov 1), US clocks "fall back" for the end of Daylight Saving Time, so 1:30 AM happens twice in local time. For the audit's own timestamps, would you recommend UTC or GMT, and why?

$ sudo timedatectl set-timezone UTC # UTC never shifts, GMT often does

Answer: UTC, Not GMT

  • GMT ~ UK winter clock only
  • BST (UTC+1) runs Mar-Oct
  • UTC is the audit's one anchor
$ timedatectl show -p Timezone --value UTC # confirms it stuck: never GMT $ timedatectl | grep "Time zone" Time zone: UTC

Q10: Trusting a Backup's Timing

  • Cron job backs up nightly
  • Audit trusts clock first
  • Then trusts the schedule

A cron line only means something once the clock it runs against is trusted: now that the audit has verified the clock, the next claim to check is whether the backup job actually fires on the schedule it claims, not just assume the line is real.

ACCESS AUDIT REPORTbackup.sh: schedule unverified✗ Without this check:crontab: not reviewedbackup.sh: assumed @ 2 AM← claim never confirmed✓ Fixed by:crontab -l→ 0 2 * * * backup.shconfirmed: runs daily 02:00← schedule now verified

Q10: Confirm the Backup Schedule

An auditor is told a backup job runs nightly at 2 AM. What command shows the real cron schedule, to confirm this claim?

$ crontab -l 0 2 * * * /opt/hospital-vm/backup.sh

Answer: crontab -l

  • 5 fields: min hr day mo wk
  • 0 2 * * * = 2 AM daily
  • Backup time now confirmed
$ crontab -l 0 2 * * * /opt/hospital-vm/backup.sh # min hr day month weekday

Q11: Did the Timer Fire on Time?

  • Timer logs LAST and NEXT
  • Compare to the interval
  • Drift reveals a problem

A systemd timer whose last run has drifted from its own interval can mean a missed run, or that this VM's clock was wrong the last time it fired: the audit needs to see that run time directly, not assume the timer is healthy.

ACCESS AUDIT REPORTbackup.timer: last run unverified✗ Without this check:backup.timer: assumed healthyLAST/NEXT run never reviewed← drift could go unnoticed✓ Fixed by:systemctl list-timers→ NEXT: 02:00 (9h58m left)backup.timer: on schedule← interval confirmed

Q11: Check the Timer's Run Time

The backup should fire at 2 AM daily. What command shows every systemd timer's next (and last) run time?

$ systemctl list-timers NEXT LEFT UNIT 02:00 9h58m backup.timer

Answer: systemctl list-timers

  • LAST: when it last fired
  • NEXT: next scheduled run
  • Matches cron's own time
$ systemctl list-timers NEXT LEFT UNIT 02:00 9h58m backup.timer # LAST column (trimmed) shows # the previous actual run

Q12: Scanning the Log for Sync

  • Clock and backup both good
  • Check log for sync errors
  • Clean now isn't forever

A clean chronyc tracking and crontab -l only describe this moment: a past drift event may already be recorded earlier in the system log, so the audit's last step reads that log, filtered to sync warnings, before signing off.

ACCESS AUDIT REPORTsystem log: sync check pending✗ Without this check:chrony: synced right nowlog never searched for warn← past drift could be hidden✓ Fixed by:journalctl -p warning→ found: clock step 09-30chronyd: clock wrong by 4s← past drift now visible

Q12: Search the Log for Drift

chronyc tracking looks clean right now. What command shows the system log, filtered to warnings and errors, to check for a past sync problem?

$ sudo journalctl -p warning \ --since "2026-10-01" # then pipe to: grep -i sync

Answer: journalctl -p warning

  • -p filters by priority
  • --since sets time window
  • Oldest entries show first
$ journalctl -p warning \ --since "2026-10-01" | \ grep -i sync Sep 30 03:14 chronyd[812]: +4s jump # oldest entry shown first

Deliverable

  • Zone set correctly
  • chrony installed & synced
  • hwclock confirmed sane
  • Backup & log checks done
  • Audit timestamps trusted
$ timedatectl | grep "NTP service" NTP service: active

Questions?

Module 11

Automation Scripting

VM + 👤 VM + 🤖 VM: clindata-vm 👤 typing it Human factor: typos, fatigue VM: clindata-vm 🤖 clindata-backup.sh cron runs it for you
OCTOBER 2026: THE PHP2SHELL EMERGENCY CVE-2026-109618 & CVE-2026-109619: unauthenticated RCE, CVSS 9.2 BEFORE: PATCH BY HAND 👤 Admin, Oct 21 web01: patching now web02: offline 🔒 web03: offline 🔒 web04: offline 🔒 One host at a time: hours pass while exposure continues NSA: take the system offline until it can be fully mitigated AFTER: ONE SCRIPT, WHOLE FLEET 🤖 patch-php.sh web01: patched ✓ web02: patched ✓ web03: patched ✓ web04: patched ✓ The whole fleet patches together: minutes, not hours Same fix, same way, every host

The php2shell emergency, October 2026 (Source: Tenable)

All Commands: Module 11

Why Automate?

Why Automate?

  • You still repeat it, every time
  • A script never skips a step
  • You stay for judgment, not typing
👤 type it, every iteration Same commands,by hand, over and over Before: you ARE the loop 🤖 clindata-backup.sh 👤 watch, decide, fix Error? You decide. After: the script loops, you supervise Human-in-the-loop: you stop doing it, you don't stop watching it
MORE REASONS TO AUTOMATE🕐Runs 24/7No breaks, no sleep📈Scales EasilyOne script, many servers🎓Anyone Can Read ItEven a brand-new intern🤖Frees the AdminTime for non-automatable work

Why This Matters

  • Shells got control flow early
  • Bash became the GNU default
  • Scripts replace repetition
1971Unix v1 Thompson shell: thefirst real scripting shell 1977Bourne shell (Stephen Bourne,Bell Labs): real control flow 1989Bash 1.0 (Brian Fox, GNU):today's default Linux shell 2012ShellCheck released: staticanalysis for shell scripts TodayA script replaces every manual,repeated command sequence
EVERY MODULE SO FAR, ONE SCRIPTRepeating the Same Commandsby hand, every single timeTypos Happena script never mistypes a flagcron Runs It for YouModule 6: already scheduledEvery command this course has taught can be chained into one script.This module is the glue: variables, conditions, loops, and functions.

Check: Not Just History?

Every command run so far is already saved in bash history. Why write a separate script instead of just re-running history?

History is a record of what you typed, not a reusable tool: a script takes arguments, branches, and runs unattended.

Your First Script

Why Shell, Not C/C++/Java?

  • No compile step, just run it
  • Calls OS commands directly
  • Built to glue tools together
C / C++ / JAVA SHELL SCRIPT Write code Compile Link Run Write script Run No build step: a script calls the OS commands that already exist

What Is a Script?

  • A plain list of commands
  • Runs top to bottom, by itself
  • Same commands you already type
1 echo "Starting backup..."✓2 cp -r /srv/clinical-data /backups/✓3 echo "Done."✓

The Shebang Line

  • Must be the very first line
  • Tells the OS which interpreter
  • Without it, the default varies
#!/bin/bashecho "Hello, clinic ops"

Make It Executable

  • chmod +x grants run permission
  • ./ runs a script in this dir
$ chmod +x clinic-check.sh $ ./clinic-check.sh Hello, clinic ops

Make It Executable

# clinic-check.sh already has #!/bin/bash as line 1 $ chmod +x clinic-check.sh # Without +x, this fails: Permission denied $ ./clinic-check.sh Hello, clinic ops

Check: Why Not bash?

bash clinic-check.sh also runs the script, no chmod needed. Why does this module teach chmod +x instead?

bash clinic-check.sh forces one interpreter; ./clinic-check.sh trusts the shebang line, which matters once scripts call each other.

Variables & Arguments

Declaring a Variable

  • No spaces around the equals
  • Reads it back with $name
#!/bin/bash name="clindata-backup.sh" echo "Running $name"

Declaring a Variable

#!/bin/bash name="clindata-backup.sh" # No spaces: name = "x" would fail echo "Running $name"

Arguments: $1, $2, $#

  • $1 is the first argument
  • $# is the argument count
#!/bin/bash echo "Backing up $1" echo "Got $# argument(s)" $ ./clindata-backup.sh /srv/clinical-data

Arguments: $1, $2, $#

#!/bin/bash echo "Backing up $1" # $# counts how many were given echo "Got $# argument(s)" # $1 = /srv/clinical-data, the first argument $ ./clindata-backup.sh /srv/clinical-data

read: Ask the User

  • Pauses, waits for typed input
  • Stores it in a named variable
#!/bin/bash read -p "Target dir: " target echo "You chose $target"

Docs: GNU Bash Manual: read

read: Ask the User

#!/bin/bash read -p "Target dir: " target # -p shows a prompt before reading echo "You chose $target"

Check: Quoting $1

echo "Backing up $1" uses quotes around the variable. Why does that matter if the path has a space in it?

Without quotes, a space in $1 splits it into two separate words; quoting keeps the whole path as one value.

Project 2: Monitor Read

  • Don't hardcode the subnet
  • $1 makes the scan reusable
  • Same script, any team's subnet
#!/bin/bash # scan_net.sh <subnet> nmap -sV "$1" # run: ./scan_net.sh 10.0.0.0/24

Conditionals in Bash

if, Spaces Matter

  • [[ ... ]] needs spaces inside
  • -d tests "is a directory"
  • then/fi, not curly braces
if [[ -d "$1" ]]echo "Found it"echo "No such dir"YESNO

Testing a Path

  • -d: is a directory
  • -f: is a regular file
#!/bin/bash if [[ -d "$1" ]]; then echo "Found it" else echo "No such directory" fi

Testing a Path

#!/bin/bash if [[ -d "$1" ]]; then # -d tests: does this path exist as a dir? echo "Found it" else echo "No such directory" fi

Check: [[ vs [ ]

Older scripts use a single [ ] instead of [[ ]]. Why does this course teach [[ ]] instead?

[[ ]] is a bash keyword: safer with unquoted variables and supports && / || directly, unlike the older [ ] form.

Loops in Bash

for: Loop Over a List

  • Walks each item one at a time
  • A glob, a list, or a range
  • do/done, not curly braces
for f in *.log; dovitals.logRotating vitals.logintake.logRotating intake.logpharmacy.logRotating pharmacy.log

for Over Real Files

  • *.log expands to every match
  • $f holds the current filename
  • scp sends it to another VM
#!/bin/bash for f in *.log; do echo "Rotating $f" scp "$f" clindata-vm:/backups/ done

for Over Real Files

#!/bin/bash for f in *.log; do # *.log expands before the loop starts echo "Rotating $f" # scp copies $f to clindata-vm's /backups/ scp "$f" clindata-vm:/backups/ done

while: Loop on a Condition

  • Repeats as long as it's true
  • read inside the loop, per line
#!/bin/bash while read -r line; do echo "Line: $line" done < clindata-hosts.txt

while: Loop on a Condition

#!/bin/bash while read -r line; do # Reads one line per loop pass echo "Line: $line" done < clindata-hosts.txt

Check: for vs. while Here

Both loops could process a list of servers. When would while read be the better choice over for?

for splits on whitespace from a glob/list; while read handles one line at a time, safer for filenames with spaces.

Project Part 2: Attacker

  • Check several ports, not one
  • for loops over a real list
  • Same shape as rotating logs
#!/bin/bash # probe_ports.sh for port in 22 80 443 5432; do nc -zv clindata-vm "$port" done

Questions?

Pipelines & Failure

Pipelines & Failure

  • | chains commands together
  • One stage can fail unseen
  • Abort loudly, not silently
grep ERROR grep ERROR ✗ permission denied sort uniq -c exit code: 0 Every stage runs. Every stage succeeds. But grep just failed. Nobody noticed. Bash only reports the LAST stage's exit code, by default

Why This Matters

  • Pipes predate most of Unix
  • Failure handling came later
  • Safety is still opt-in today
1973Unix pipe: Thompson buildsMcIlroy's | into the shell1977AWK (Aho, Weinberger,Kernighan): a filter language1998ksh93 introduces pipefail:catch any stage's failure2004Bash 3.0 adds its ownset -o pipefailTodaypipefail + trap: standardfor any real script

What Is a Pipe?

  • | sends stdout to stdin
  • sort groups the duplicates
  • uniq -c counts each one
#!/bin/bash grep ERROR vitals.log | sort | uniq -c

Docs: sort(1) man page

What Is a Pipe?

#!/bin/bash grep ERROR vitals.log | sort | uniq -c # sort must run before uniq -c: it only counts ADJACENT dupes

awk: Pull Out a Field

  • Splits each line on whitespace
  • $1, $2... are column numbers
  • Prints just the field you want
#!/bin/bash grep ERROR vitals.log | awk '{print $1, $2}'

Docs: GNU Awk User's Guide

awk: Pull Out a Field

#!/bin/bash grep ERROR vitals.log | awk '{print $1, $2}' # $1 = date, $2 = time: awk numbers columns from 1

xargs: Feed Output as Args

  • Turns lines into arguments
  • Runs the next command per line
  • Acts on a whole file list
#!/bin/bash grep -l ERROR *.log | xargs tail -n 3

Docs: xargs(1) man page

xargs: Feed Output as Args

#!/bin/bash grep -l ERROR *.log | xargs tail -n 3 # -l lists FILENAMES only; xargs tails each one found

The Silent Failure

  • $? is only the LAST stage
  • An earlier failure hides
  • False confidence in a script
#!/bin/bash false | echo "still looks fine" echo "$?"

The Silent Failure

#!/bin/bash false | echo "still looks fine" # false always exits 1 -- but echo is the LAST stage echo "$?" # prints 0: echo succeeded, so the pipeline "succeeded"

pipefail: See Every Stage

  • Off by default in bash
  • Exit code = worst stage's code
  • Put it first, before the pipe
#!/bin/bash set -o pipefail false | echo "still prints" echo "$?"

Docs: GNU Bash Manual: The Set Builtin

pipefail: See Every Stage

#!/bin/bash set -o pipefail false | echo "still prints" # echo itself still runs and still prints echo "$?" # now 1: pipefail reports the worst stage, not the last

set -e: Abort on Any Error

  • Stops the script right there
  • No need to check $? by hand
  • Pair it with pipefail
#!/bin/bash set -euo pipefail rsync -az clindata-vm:/srv/clinical-data/ ./backup/ echo "Backup verified"

set -e: Abort on Any Error

#!/bin/bash set -euo pipefail # -e: stop on error -u: undefined var is an error -o pipefail: above rsync -az clindata-vm:/srv/clinical-data/ ./backup/ # if rsync fails, "Backup verified" never prints echo "Backup verified"

trap: Run Code on Exit

  • Fires on error, not just exit
  • Good for cleanup or alerts
  • ERR fires before the exit
#!/bin/bash set -euo pipefail trap 'echo "Backup FAILED" >&2' ERR rsync -az clindata-vm:/srv/clinical-data/ ./backup/

Docs: GNU Bash Manual: trap

trap: Run Code on Exit

#!/bin/bash set -euo pipefail trap 'echo "Backup FAILED" >&2' ERR # runs this line automatically if anything below fails rsync -az clindata-vm:/srv/clinical-data/ ./backup/

PIPESTATUS: Per-Stage Code

  • One exit code per pipe stage
  • Index 0 is the first command
  • Diagnose WHICH stage broke
#!/bin/bash grep ERROR vitals.log | sort | uniq -c echo "${PIPESTATUS[@]}"

PIPESTATUS: Per-Stage Code

#!/bin/bash grep ERROR vitals.log | sort | uniq -c echo "${PIPESTATUS[@]}" # e.g. "0 0 0": grep, sort, and uniq each succeeded

Use Case: Error Audit

  • grep finds the raw matches
  • sort groups duplicates
  • uniq -c turns them into counts
SITUATIONNeed every ERROR line, dedupedTOOLgrep ERROR vitals.log | sort | uniq -cRESULTInstant count, no manual scanning

Use Case: Safer Backup

  • pipefail catches a hidden fail
  • set -e stops the script there
  • trap sends the alert for you
SITUATIONBackup must abort loudly if rsync failsTOOLset -euo pipefail; trap ... ERRRESULTA silent failure becomes a loud one

Project 2: Safer Backups

  • Same backup_clinical_data()
  • pipefail + set -e + trap added
  • Now it can't fail silently
#!/bin/bash set -euo pipefail trap 'echo "Backup FAILED" >&2' ERR backup_clinical_data() { rsync -az clindata-vm:/srv/clinical-data/ ./backup/ } backup_clinical_data

Questions?

Functions & Exit Codes

A Function Groups Steps

  • Defined once, called by name
  • Keeps a script's parts named
  • No special keyword required
backup_dir /srv/clinical-databackup_dir() {cp -r "$1" /backups/Main script resumescallreturn

Defining and Calling It

  • Define before first use
  • Call it like any command
#!/bin/bash backup_dir() { cp -r "$1" /backups/ } backup_dir /srv/clinical-data

Defining and Calling It

#!/bin/bash backup_dir() { # $1 inside a function is its own argument cp -r "$1" /backups/ } backup_dir /srv/clinical-data

exit Codes: 0 Means OK

  • 0 means success, else failed
  • $? holds the last exit code
#!/bin/bash backup_dir() { cp -r "$1" /backups/ } backup_dir /srv/clinical-data if [[ $? -ne 0 ]]; then echo "Backup failed" fi

exit Codes: 0 Means OK

#!/bin/bash backup_dir() { cp -r "$1" /backups/ } backup_dir /srv/clinical-data # $? is the PREVIOUS command's exit code if [[ $? -ne 0 ]]; then echo "Backup failed" fi

shellcheck: Catch Mistakes

  • A linter for real scripts
  • Flags unquoted vars, typos
$ sudo apt install -y shellcheck $ shellcheck clindata-backup.sh

Docs: ShellCheck Wiki

shellcheck: Catch Mistakes

$ sudo apt install -y shellcheck # Not installed by default $ shellcheck clindata-backup.sh # Warns about real, common mistakes

Check: What $? Really Means

The script runs TWO commands before checking $? once at the end. Which command's exit code does $? report?

Only the most recent one: $? is overwritten after every command, so it never reports anything further back.

Project 2: Monitor Write

  • Function + exit code, together
  • This is your real backup job
  • Same shape, Practice Lab next
#!/bin/bash backup_clinical_data() { rsync -az clindata-vm:/srv/clinical-data/ ./backup/ } backup_clinical_data if [[ $? -ne 0 ]]; then echo "Backup failed, check the log" fi

Practice Lab

Scenario: Your First Script

  • One echo line, nothing fancy
  • Edit it, run it, trust it
  • Then back up real log files
YOUR FIRST SCRIPT, START TO FINISH 💻 Edit in Windows 🔄 Run + test in WSL 📤 scp to clindata-vm Start: one echo lineecho "Backup script running"Edit it, save it, run it again Grow it: find + copyfind ... -mtime -1 | scp ...Only logs changed in the last 24h

Step 1: Find VM in Windows

  • Kali/Ubuntu run inside WSL2
  • Explorer browses straight in
  • No separate VM disk needed
$ pwd /home/kali $ explorer.exe . # Opens THIS folder in Windows Explorer

Step 1: Find VM in Windows

$ pwd # Confirms where you are inside the VM /home/kali $ explorer.exe . # Same folder, now in a real Explorer window # Address bar: \\wsl.localhost\kali-linux\home\kali

⚠️ The path starts with \\wsl.localhost\, not a drive letter — typing it directly into Explorer's address bar works too.

Step 2: Create backup.sh

  • touch makes an empty file
  • chmod now, before any content
  • Double-click it to edit
$ touch backup.sh $ chmod +x backup.sh # Ready to run the moment it has content

Step 2: Create backup.sh

$ touch backup.sh # Empty file, right permissions can come first $ chmod +x backup.sh # Now right-click backup.sh in Explorer # Open with Notepad or VS Code, NOT nano/vim

Step 3: Start Simple

  • Shebang, then one echo
  • Save in the Windows editor
  • Run it from the WSL terminal
#!/bin/bash echo "Backup script running"

Step 3: Start Simple

#!/bin/bash echo "Backup script running" (saved from Notepad, nothing else yet) $ ./backup.sh Backup script running

Step 4: Edit & Retest

  • Change just the echo text
  • Save, switch back to WSL
  • Rerun, confirm the change
#!/bin/bash echo "Backup script v2 is alive"

Step 4: Edit & Retest

#!/bin/bash echo "Backup script v2 is alive" (same file, one line changed) $ ./backup.sh Backup script v2 is alive # Small edit, immediate proof it took

Step 5: Find Logs, Last 24h

  • find already filters for us
  • -mtime -1 means changed in 24h
  • Skip files nothing touched
#!/bin/bash echo "Checking for changed logs..." find /var/log/clindata -name "*.log" -mtime -1

Step 5: Find Logs, Last 24h

#!/bin/bash echo "Checking for changed logs..." find /var/log/clindata -name "*.log" -mtime -1 # -mtime -1: modified less than 1 day ago

Step 6: Loop and Copy

  • for walks the matching files
  • scp ships each one over SSH
  • Echo before, so you can watch
#!/bin/bash for f in $(find /var/log/clindata -name "*.log" -mtime -1); do echo "Sending $f to clindata-vm" scp "$f" clindata-vm:/backups/ done

Step 6: Loop and Copy

#!/bin/bash for f in $(find ... -mtime -1); do # One pass per changed log file echo "Sending $f to clindata-vm" scp "$f" clindata-vm:/backups/ # Quoted "$f": safe even with spaces done

Step 7: Confirm via SSH

  • scp succeeding isn't proof
  • ssh in and actually look
  • From Kali, straight to Ubuntu
$ ssh clindata-vm "ls -la /backups/" # Lists what actually arrived

Step 7: Confirm via SSH

$ ssh clindata-vm "ls -la /backups/" # One ssh call, one remote command -rw-r--r-- 1 kali kali 842 vitals.log # If it's listed, the scp really landed

Step 8: The Full Script

  • Every step so far, combined
  • Verbose: an echo per stage
  • Still only 10 lines total
#!/bin/bash echo "Starting log backup..." LOGS=$(find /var/log/clindata -name "*.log" -mtime -1) echo "Found: $LOGS" for f in $LOGS; do echo "Sending $f to clindata-vm" scp "$f" clindata-vm:/backups/ done echo "Backup complete." ssh clindata-vm "ls -la /backups/"

Step 8: The Full Script

#!/bin/bash echo "Starting log backup..." LOGS=$(find /var/log/clindata -name "*.log" -mtime -1) echo "Found: $LOGS" for f in $LOGS; do echo "Sending $f to clindata-vm" scp "$f" clindata-vm:/backups/ done echo "Backup complete." ssh clindata-vm "ls -la /backups/"

Check: Why -mtime -1?

Why not just scp every log file, every single night, and skip the find step entirely?

Resending every file every night wastes bandwidth and time; -mtime -1 only ships what actually changed.

Project 2: Verify First

  • scp alone isn't proof enough
  • diff -r compares two trees
  • Monitor Write runs this, too
$ diff -r /backups/ /var/log/clindata/ # No output at all means: identical # Any line printed means something differs

man7.org: diff(1)

Deliverable

  • backup.sh, built up in stages
  • Tested after every change
  • Confirmed live via ssh
echo "Backup complete."

Questions?

Practice Lab Part 2

Scenario: Nightly Backup

  • Nightly clinical-data backup
  • Skip it if the folder's gone
  • Scheduled via cron (Module 6)
clindata-backup.sh: check, copy, logchmod +x, test it by handcrontab -e: run it nightly

Step 1: Write the Script

  • Shebang, then the check
  • Exits early if missing
#!/bin/bash if [[ ! -d /srv/clinical-data ]]; then echo "Source missing, exiting" exit 1 fi

Step 1: Write the Script

#!/bin/bash if [[ ! -d /srv/clinical-data ]]; then # ! negates the test: true if NOT a dir echo "Source missing, exiting" exit 1 fi

Step 2: Copy and Log It

  • cp runs the real backup
  • date stamps the log line
cp -r /srv/clinical-data /backups/ echo "Backed up on $(date)" >> clindata-backup.log

Step 2: Copy and Log It

cp -r /srv/clinical-data /backups/ # $(date) runs date, inserts its output echo "Backed up on $(date)" >> clindata-backup.log

Step 3: Make It Executable

  • Grant run permission
  • Test it once by hand first
$ chmod +x clindata-backup.sh $ ./clindata-backup.sh

Step 3: Make It Executable

$ chmod +x clindata-backup.sh # Always test by hand before scheduling $ ./clindata-backup.sh

Step 4: Schedule with cron

  • Reuses Module 6's own crontab
  • Runs every night at 2 AM
$ crontab -e 0 2 * * * /home/user/clindata-backup.sh

Step 4: Schedule with cron

$ crontab -e # minute hour day month weekday, then the path 0 2 * * * /home/user/clindata-backup.sh

Check: Test by Hand First?

Step 3 runs ./clindata-backup.sh manually before Step 4 schedules it. Why not go straight to crontab?

cron runs silently in the background; a manual run surfaces errors immediately, before they fail unseen overnight.

Deliverable

  • A working, executable script
  • One manual test run, confirmed
  • A real crontab entry for it
echo "Backed up on Fri Oct 16 02:00:01" >> clindata-backup.log

Questions?

Module 12

Firewalls & Network Security

ufw (Module 2): the simple layeriptables: the real rulesnftables: the modern engine

All Commands: Module 12

Why a Firewall?

WHY A FIREWALL AT ALL?A host with no filtering accepts every packet that arrivesWITHOUT A FIREWALLAny port, any sourcereaches every open serviceScanner finds it in secondsno firewallEvery exposed service is reachable from anywhereA single misconfigured service is now internet-facingWITH A FIREWALLAny port, any sourcemeets a rule firstBlocked before it arrivesFIREWALLlistens to every packetThe firewall is a service listening to all incoming trafficIt intercepts every packet before any app ever sees itThe rule set still decides what gets through

Filtering Since ipfwadm

  • Filtering since ipfwadm
  • ufw simplifies iptables
  • Old engine still runs beneath
1993ipfwadm: Linux's first realkernel packet filter1998iptables (Rusty Russell):today's classic Linux firewall2009ufw released: a simplefront end over iptables2014nftables replaces iptablesas the kernel's own engineTodayufw still calls iptables underthe hood on most installs

ufw Is a Front End

  • Hides the real rule engine
  • Great for the common cases
  • Can't express everything
ufw allow 22/tcp (Module 2)Generates a real iptables ruleThe kernel enforces that rule

Check: Why Go Deeper?

DOES ufw COVER EVERYTHING?ufw allow 22/tcprate limits? NAT?ufw handles simple allow/deny wellufw already handles allow/deny in one command. Why go further, into iptablesitself?ufw cannot express rate-limiting, specific interfaces, or NAT;iptables is the full tool underneath it.

Use Case: SSH Lockdown

  • Server only needs port 22
  • Everything else is risk
  • ufw: one line, done
New Ubuntu server, SSH onlysudo ufw allow 22/tcp &&ufw enableAll other ports blocked by default

Use Case: Web Exposure

  • Web app on 8080, internal only
  • ufw lacks fine-grained match
  • iptables adds the exact rule
App listens on 8080, LAN-onlyiptables -A INPUT -s 10.0.0.0/8-p tcp --dport 8080 -j ACCEPTOnly the LAN subnet can reach it

Check ufw's Real Rules

  • verbose shows numbered rules
  • Each line maps to iptables
$ sudo ufw status verbose Status: active To Action From 22/tcp ALLOW IN Anywhere

Check ufw's Real Rules

$ sudo ufw status verbose Status: active To Action From 22/tcp ALLOW IN Anywhere # verbose: numbered rules plus the default policy # This is what iptables -L would also show # Project Part 2: capture this as defense evidence

ufw: Which Distros?

  • Ships by default on Ubuntu
  • Available on Debian via apt
  • Fedora/RHEL use firewalld
  • Arch: no firewall by default
Ubuntu: ships ufw by defaultDebian: available via aptFedora/RHEL: firewalld defaultArch: no firewall enabled

ufw: Useful Flags

  • numbered: shows rule index
  • allow from: scope by source
  • delete removes by number
$ sudo ufw status numbered Status: active To Action From [ 1] 22/tcp ALLOW IN Anywhere

ufw: Useful Flags

$ sudo ufw status numbered Status: active To Action From [ 1] 22/tcp ALLOW IN Anywhere # numbered: shows a [n] index for each rule # allow from 10.0.0.0/8 to any port 22: scope by source # delete 1: remove the rule at that index # logging on: turn on ufw's own log entries # Project Part 2: numbered output speeds up your demo

ufw: Official Docs

  • Full flag reference: man ufw
  • Project source: Launchpad
  • Community guide: Ubuntu wiki
man ufwFull flag and command referenceIncludes status, allow, logging

ufw(8) manual page (Source: manpages.ubuntu.com)

Chain Default Policy

  • No match = fall to default
  • DROP by default is safer
  • ACCEPT by default: risky
Policy DROP: nothing unless allowedPolicy ACCEPT: nothing unless blocked

Word Origin: Firewall

  • From building construction
  • Stops fire from spreading

Firewall originally meant a fire-resistant wall built to stop fire from spreading between sections of a building; 1980s networking borrowed it for a barrier stopping unwanted traffic (Source: etymonline.com)

Questions?

Chains & Packet Filtering

WHAT'S INSIDE A PACKET?This is the real content a firewall evaluatesSRC IP10.0.0.5DST IP10.0.0.1PROTOTCP (6)SRC PORT51342DST PORT22PAYLOAD(app data)Rules match on IP address, port, and protocolPayload data itself is not inspected by packet filtering
WHERE DOES A PACKET GET CHECKED?Every packet passes through one of three chainsARRIVING FOR THIS HOSTincoming packetINPUT chainTraffic addressed to this machine checks INPUTPASSING THROUGH THIS HOSTfrom elsewhereFORWARD chainto elsewhereRouted traffic through this host checks FORWARD

Three Built-In Chains

  • INPUT: traffic to this machine
  • OUTPUT: traffic leaving it
  • FORWARD: passing through it
INPUT: incoming to this hostOUTPUT: outgoing from this hostFORWARD: routed through it

Stateful: Remembers Flows

  • ESTABLISHED: a known flow
  • NEW: the first packet
  • Replies skip needing own rule
You send a request (NEW)Firewall remembers itReply allowed (ESTABLISHED)

Word Origin: Chain

  • Rules in order, like links
  • Borrowed from chain-link logic

The term "chain" for an ordered rule list predates Linux netfilter, from early packet-filter firewalls like BSD's ipfw (Source: iptables(8), man7.org)

Check: Why Track State?

A REPLY, WITH NO MEMORYyou: requestserver: replyA stateless firewall checks every packet aloneA stateless firewall has no memory of your request. What problem does thatcreate for the reply?Every reply would need its own explicit allow rule; statefultracking lets a reply through automatically.

Use Case: Blocking Scans

  • Repeated port probes, no state
  • INPUT chain sees each as NEW
  • Rate-limit NEW on that port
Scanner hits port 22 repeatedlyiptables -A INPUT -p tcp --dport22 -m state --state NEW -m limit--limit 3/min -j ACCEPTOnly 3 new connections per minuteallowed

Use Case: DNS Replies

  • UDP has no handshake
  • Reply looks like new traffic
  • ESTABLISHED lets it through
DNS query sent out on UDP/53iptables -A INPUT -p udp --sport53 -m state --state ESTABLISHED-j ACCEPTThe DNS reply is acceptedautomatically

Viewing Tracked Connections

  • Not installed by default
  • Shows every active flow
  • ESTABLISHED, NEW, or closing
$ sudo apt install -y conntrack $ sudo conntrack -L tcp 6 431999 ESTABLISHED src=10.0.0.5 dst=10.0.0.1 sport=51342 dport=22

Viewing Tracked Connections

$ sudo apt install -y conntrack $ sudo conntrack -L tcp 6 431999 ESTABLISHED src=10.0.0.5 dst=10.0.0.1 sport=51342 dport=22 # -y: auto-confirm the install prompt # conntrack package provides this command # -L: list every tracked connection # 431999: seconds left before this entry expires # Project Part 2: watch for Attacker team scans

OUTPUT: Leaving Traffic

  • This host as the sender
  • Blocks a bad outbound call
  • Rare, but real use case
A process tries to connect outOUTPUT chain checks itBlocked: no exfiltration

Questions?

iptables: Rules

READING AN iptables RULEMatch conditions, then a target actionA RULE HAS TWO PARTS-p tcp --dport 8080the match: what to look for-j ACCEPTthe target: what to do with itEvery rule reads as: if this matches, do thisRULE ORDER DECIDES THE WINNERrule 1: dport 8080 ACCEPTrule 2: dport 8080 DROPiptables checks top to bottom, stops at the first matchRule 1 wins here: the packet is accepted, rule 2 never runs

Viewing the Current Rules

  • -L lists rules in each chain
  • -v shows packet/byte counts
$ sudo iptables -L -v Chain INPUT (policy ACCEPT) ACCEPT tcp -- anywhere anywhere tcp dpt:ssh

Viewing the Current Rules

$ sudo iptables -L -v Chain INPUT (policy ACCEPT) ACCEPT tcp -- anywhere anywhere tcp dpt:ssh # iptables ships with ufw (Module 2), no install needed # -L: list every rule in this chain # -v adds packet and byte counters # -L -n: same listing, skips slow DNS lookups # Project Part 2: screenshot every rule change

Adding a Rule

  • -A appends to the end
  • -p, --dport: protocol, port
$ sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

Adding a Rule

$ sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT # -A INPUT: append this rule to the INPUT chain # -p tcp: match only TCP packets # --dport 8080: match destination port 8080 # -j ACCEPT: the target action for a match # Project Part 2: open only the port your role needs

Not Saved by Default

  • A reboot wipes them
  • Not installed by default
  • iptables-persistent saves them
$ sudo apt install -y iptables-persistent

Not Saved by Default

$ sudo apt install -y iptables-persistent # -y: auto-confirm the install prompt # Prompts to save current rules on install # Project Part 2: keep rules after a VM reboot

Check: Rule Order Matters

TWO RULES, SAME PORT1: dport 8080 ACCEPT2: dport 8080 DROPTwo rules both match port 8080: one ACCEPTs, one DROPs, in that order. Whichone wins?The first match wins: iptables checks rules top to bottom and stopsat the first one that matches.

Use Case: DB Lockdown

  • MySQL on 3306, app server only
  • Exact source IP, exact port
  • One explicit ACCEPT rule
Only app-01 should reach MySQLiptables -A INPUT -s 10.0.0.5 -ptcp --dport 3306 -j ACCEPTEvery other source is unaffected(default policy applies)

Use Case: Log Then Drop

  • Want to see what's blocked
  • LOG doesn't stop the traffic
  • A DROP rule must follow it
Need visibility into dropped trafficiptables -A INPUT -p tcp --dport23 -j LOG --log-prefix"TELNET-BLOCK: "Matching packets get logged, thenstill fall through to the DROP rule

Flushing a Chain

  • -F wipes rules in a chain
  • Fast way to start clean
$ sudo iptables -F INPUT

Flushing a Chain

$ sudo iptables -F INPUT # -F: flush (delete) every rule in a chain # INPUT: flush only this chain, not all three # Only INPUT is cleared; policy stays set # Project Part 2: don't flush rules before demo day

Default Policy on a Chain

  • -P sets the chain's fallback
  • Used when no rule matches
iptables -P INPUT DROPNo rule ever matches a packetFallback policy DROP decides it

Questions?

nftables: The Replacement

ONE TOOL FOR IPv4 AND IPv6iptables needed a separate tool for each protocol familyBEFORE: TWO SEPARATE TOOLSiptables (IPv4 only)ip6tables (IPv6 only)Every rule had to be written and maintained twiceAFTER: ONE UNIFIED ENGINEnft (table inet: both families)One rule set covers IPv4 and IPv6 togetherUbuntu now ships nftables as the kernel's default engine

One Tool, Both Families

  • Replaces iptables itself
  • Handles IPv4 and IPv6 together
  • Ubuntu ships it by default now
iptables: separate v4/v6 toolsnftables: one unified tool

Listing nftables Rules

  • Not installed by default
  • Uses tables and chains
  • Its own, newer syntax
$ sudo apt install -y nftables $ sudo nft list ruleset table inet filter { chain input { ... } }

Listing nftables Rules

$ sudo apt install -y nftables $ sudo nft list ruleset table inet filter { chain input { ... } } # -y: auto-confirm the install prompt # nftables package provides the nft command # list ruleset: show every table and chain # inet: one table covers IPv4 and IPv6 # Project Part 2: document which tool you used

Word Origin: nftables

  • nf = netfilter kernel layer
  • Replaces 4 older tools

nftables takes its name from netfilter, the Linux kernel subsystem it configures, and was built to unify iptables, ip6tables, arptables and ebtables into one engine (Source: nftables Wiki)

Check: Teach Both Tools?

OLDER TOOL, STILL EVERYWHEREexisting servers: iptables rulesnew installs: nftables by defaultnftables is the modern replacement for iptables. Why does this module stillteach the older tool too?Most existing servers and documentation still use iptables; readingit is still a real, common sysadmin skill.

Use Case: Migrate Rules

  • Old server still runs iptables
  • Rules translate, don't rewrite
  • nft keeps both readable
Server has years of iptables rulessudo iptables-restore-translate-f /etc/iptables/rules.v4Equivalent nftables syntax generated

Use Case: Dual-Stack Site

  • Site serves IPv4 and IPv6
  • One nft table, not two
  • Half the rules to maintain
New server must support IPv6nft add rule inet filter inputtcp dport 443 acceptRule applies to both IPv4 and IPv6traffic

Adding an nftables Rule

  • add rule: appends to a chain
  • Reads almost like English
$ sudo nft add rule inet filter input \ tcp dport 8080 accept

Adding an nftables Rule

$ sudo nft add rule inet filter input \ tcp dport 8080 accept # add rule: appends to the named chain # inet filter input: table, then chain # tcp dport 8080 accept: match, then target # Project Part 2: match your own ufw rules here too

Origin: netfilter Project

  • Started 1998, Rusty Russell
  • Now governs iptables and nft

The netfilter project began in 1998 to give Linux a hookable packet filtering framework in the kernel; both iptables and nftables are front ends to it (Source: netfilter.org)

Comparing the Firewall Tools

Propertyufwiptablesnftablesfirewalld
Released2009199820142011
Kernel engineiptables beneath itnetfilter (ip_tables)netfilter (nf_tables)nftables (since 2018)
Distro defaultUbuntuOlder/Debian legacyDebian 11+, ArchFedora, RHEL/CentOS
Syntax stylePlain English-likeFlags: -A, -p, -jStructured rule languageZones + rich rules
Stateful by defaultYesNo (-m state needed)YesYes
Learning curveLowHighMediumMedium
Persists on rebootYesNo (needs extra pkg)YesYes (daemon-managed)
Zone/profile conceptNoNoNoYes (public, home, dmz)
NAT supportLimitedYes (full)Yes (full)Yes (rich rules)
Still the kernel's defaultFront end onlyLegacy mode nowYes, current standardYes (via nftables)

Properties drawn from each tool's own man page/docs (Source: ufw(8), iptables(8), nftables Wiki, firewalld.org)

Questions?

Network Zones & NAT

WHERE DOES THE PUBLIC SERVER LIVE?A breach of an exposed service shouldn't reach everything elseNO DMZ: ONE FLAT NETWORKInternetWeb server + internal data, togetherA compromised web server reaches internal data directlyWITH A DMZ: SEPARATEDInternetDMZ: web serverInternal: protectedA breach in the DMZ stays contained, away from internal data

DMZ: A Buffer Zone

  • Public servers, isolated
  • Internal net stays protected
  • A breach there stays contained
Internet: untrustedDMZ: web server, exposedInternal network: protected

NAT: One Public Address

  • Many internal IPs share one
  • Outside sees only the router
  • Hides internal addressing
Internal host: 10.0.0.5Router rewrites the source IPInternet sees only 203.0.113.9

Word Origin: DMZ

  • Borrowed from military use
  • A buffer, not a neutral space

DMZ stands for demilitarized zone, borrowed from the term for a buffer area between opposing forces; networking adopted it for a buffer segment between the internet and a trusted internal network (Source: Cloudflare)

Check: Not Inside?

WHY NOT PUT IT INTERNALLY?Internal network: firewalledWeb server: public targetThe internal network is already firewalled from the internet. Why not just putthe web server there directly?A public-facing server is the most likely to be attacked; a DMZkeeps that risk out of the trusted internal network.

Use Case: Mail Relay

  • Must face the internet
  • Risk kept out of internal LAN
  • DMZ placement, limited rules
Mail relay needs internet accessiptables -A FORWARD -i dmz0 -olan0 -j DROPDMZ traffic cannot initiate into theLAN

Use Case: Home Router NAT

  • Several devices, one public IP
  • ISP sees one address
  • Router tracks each connection
Laptop and phone share one IPRouter performs NAT on outboundtrafficReplies routed back to the rightdevice automatically

Viewing NAT Rules

  • -t nat selects the NAT table
  • Separate from the filter table
$ sudo iptables -t nat -L -v Chain POSTROUTING (policy ACCEPT) MASQUERADE all -- any eth0 anywhere anywhere

Viewing NAT Rules

$ sudo iptables -t nat -L -v Chain POSTROUTING (policy ACCEPT) MASQUERADE all -- any eth0 anywhere anywhere # -t nat: operate on the NAT table, not filter # -L: list the rules in that table # -v: show packet and byte counters # POSTROUTING: applied just before a packet leaves # MASQUERADE: rewrite source to this host's IP # Project Part 2: bridged VMs don't need NAT

Port Forwarding: DNAT

  • Public port maps inside
  • Lets a server sit behind NAT
Internet hits router's port 8443DNAT rewrites the destinationForwarded to 10.0.0.20:443 inside

Word Origin: NAT

  • Coined in RFC 1631, 1994
  • Meant as a short-term fix

Network Address Translation was formally defined in RFC 1631 (1994) as a short-term fix for IPv4 address exhaustion that became a permanent fixture of networking (Source: RFC 1631)

Questions?

Crypto & Defense in Depth

A FIREWALL IS ONE LAYER, NOT THE ONLY ONEFiltering traffic says nothing about the crypto behind itFIREWALL ALONEPort 443 allowedIs the crypto inside it sound?Allowing a port says nothing about what secures itDEFENSE IN DEPTHFirewallTLS / key sizesPatchingMonitoringEach layer catches what the one before it missed

AI Speeds Up Cryptanalysis

  • AI agents found RSA-1024 flaws
  • 2048-bit keys still unaffected
  • Firewalls don't cover crypto
DEEPMIND, NOV 2026RSA-1024weakenedRSA-2048unaffected1,600× faster attack on a legacy keyA firewall rule never checks key lengthSource: shiftdelete.net, Nov 6 2026

Tech Update: RSA-1024

  • Human-supervised AI agents
  • Found 2 real RSA-1024 flaws
  • Not peer-reviewed yet
TWO WEAKNESSES FOUNDSignature paddingweak if attacker controls halfthe signed data blockBatch factorization30× cheaper per extra keywhen many 1024-bit keys existForged a signature withoutrecovering the private key

DeepMind vs. RSA-1024 (Source: shiftdelete.net)

Checking a Key's Size

  • Reports the RSA modulus bits
  • 1024 is the weakened size
$ openssl rsa -in key.pem -text -noout | grep bit Private-Key: (1024 bit, 2 primes)

Checking a Key's Size

$ openssl rsa -in key.pem -text -noout | grep bit Private-Key: (1024 bit, 2 primes) # openssl ships with the OS; no install needed # -in key.pem: read this key file # -text: print the key's details as text # -noout: skip printing the encoded key itself # | grep bit: filter to just the key-size line # (4096 bit) or (2048 bit) is the safer reading # Project Part 2: avoid old key sizes on your web VM

Use Case: Retire Old Key

  • Still signs with RSA-1024
  • Firewall rules unaffected
  • Upgrade to 2048-bit or higher
Audit finds an RSA-1024 TLS certopenssl req -new -newkey rsa:4096-nodes -keyout new.key -outnew.csrNew cert issued at a key sizeoutside the AI attack's scope

Use Case: Fleet Key Scan

  • Servers, key sizes unknown
  • Script checks every cert
  • Flags anything under 2048-bit
100 servers, ages of certs unknownopenssl x509 -in cert.pem -noout-text | grep 'Public-Key'Any RSA-1024 cert gets flagged forrenewal

Origin: Defense in Depth

  • A military strategy term
  • Layers, not one single wall

Defense in depth comes from military strategy: slowing an attacker through successive defensive lines rather than one single barrier; information security adopted the phrase for layered controls (Source: CISA)

Check: Firewall Enough?

FIREWALL RULE: PORT 443 ALLOWEDiptables: 443 ACCEPTRSA-1024 cert, insideweakened by AI cryptanalysisYour firewall correctly allows port 443. Does that mean the connection itselfis secure?No: the firewall only controls reachability. The DeepMind findingsshow the crypto behind an allowed port can still be weak.

Questions?

Practice Lab

BLOCK, VERIFY, THEN UNDOProve a firewall change works, then leave the system cleanPHASE 1: ALLOW, THEN BLOCKnmap: 8080 openiptables: DROP 8080Confirm the baseline before you ever block anythingPHASE 2: FIX ORDER, CLEAN UPnmap: 8080 filterediptables -D: rule removedVerify from the attacker's side, then restore the clean state

Scenario: Block and Verify

  • Allow with ufw, confirm open
  • A block that silently fails
  • Fix the order, clean up both
iptables: DROP port 8080nmap from Kali: port filterediptables: remove the rule

Step 1: Check ufw's Status

See what's already allowed, before changing anything

KALI

$ # nothing to run yet -- just checking Ubuntu

UBUNTU

$ sudo ufw status Status: active # nothing allows 8080 yet

Step 2: Allow the Port in ufw

ufw's default blocks new ports until you allow one

KALI

$ # nothing to run yet -- Ubuntu is allowing it

UBUNTU

$ sudo ufw allow 8080/tcp Rule added Rule added (v6)

Step 3: Confirm the Rule Exists

Always check your own change actually landed

KALI

$ # still nothing -- confirming on Ubuntu first

UBUNTU

$ sudo ufw status Status: active 8080/tcp ALLOW Anywhere # the rule from Step 2 is really there

Step 4: See It in iptables Too

ufw is a friendly front end for real iptables rules

KALI

$ # still nothing yet -- watching Ubuntu's rules

UBUNTU

$ sudo iptables -L INPUT -n \ --line-numbers | grep 8080 1 ACCEPT tcp dpt:8080 # ufw's "allow" became a real ACCEPT rule

Step 5: Start the Listener

Something has to actually answer on port 8080

KALI

$ # nothing to run yet -- Ubuntu starts it

UBUNTU

$ python3 -m http.server 8080 & [1] 4821 # &: runs the listener in the background

Step 6: Find This VM's Address

Kali needs Ubuntu's real address to scan it

KALI

$ # copy the address Ubuntu is about to show

UBUNTU

$ hostname -I 10.0.2.15

Step 7: Confirm It's Open

Baseline check, before any blocking at all

KALI

$ VM_IP=10.0.2.15 # paste the address Ubuntu just showed $ nmap -p 8080 $VM_IP PORT STATE SERVICE 8080/tcp open # open: ufw allows it, listener answers

UBUNTU

$ # listener running, ufw already allowing it

Before You Block: Rule Order Matters

  • iptables checks rules top to bottom
  • The FIRST match wins, every time
  • -A appends to the END of the list
#1 ACCEPT 8080 (ufw)#2 DROP 8080 (new, -A)Packet matches #1 first#2 never even gets checked

Step 8: Append a DROP Rule

-A adds this to the bottom of the chain

KALI

$ # nothing to run yet -- Ubuntu adds the rule

UBUNTU

$ sudo iptables -A INPUT -p tcp \ --dport 8080 -j DROP # -A: appends to the END of the chain

Step 9: Wait... Still Open?

A rule that got added but has no effect yet

KALI

$ nmap -p 8080 $VM_IP PORT STATE SERVICE 8080/tcp open # open?! the DROP rule did nothing

UBUNTU

$ # rule was added... so why no effect?

Step 10: Diagnose the Order

List the chain and see which rule sits first

KALI

$ # still nothing -- reading Ubuntu's chain

UBUNTU

$ sudo iptables -L INPUT -n \ --line-numbers 1 ACCEPT tcp dpt:8080 (ufw) 2 DROP tcp dpt:8080 (new) # #1 ACCEPT wins; #2 never runs

Step 11: The Fix -- Insert at the Top

-I puts a rule at a specific position instead

KALI

$ # nothing yet -- Ubuntu reorders the rule

UBUNTU

$ sudo iptables -I INPUT 1 -p tcp \ --dport 8080 -j DROP # -I INPUT 1: inserts at position 1 # now DROP is checked before ACCEPT

Step 12: Verify It's Really Blocked

Same scan, now genuinely filtered

KALI

$ nmap -p 8080 $VM_IP # $VM_IP: set back in Step 7 PORT STATE SERVICE 8080/tcp filtered # filtered: the reordered DROP now wins

UBUNTU

$ # rule already applied -- just watching now

Step 13: Remove Your DROP Rule

-D deletes by rule content, not position

KALI

$ # waiting to re-scan once it's removed

UBUNTU

$ sudo iptables -D INPUT -p tcp \ --dport 8080 -j DROP # matches the rule, wherever it now sits

Step 14: ufw's Own Rule Still Stands

Removing your rule didn't touch ufw's rule

KALI

$ nmap -p 8080 $VM_IP PORT STATE SERVICE 8080/tcp open # your DROP is gone; ufw's ALLOW remains

UBUNTU

$ # two separate rules, two separate cleanups

Step 15: Revoke the ufw Rule Too

Leave the system exactly as you found it

KALI

$ # nothing to run yet -- Ubuntu revokes it

UBUNTU

$ sudo ufw delete allow 8080/tcp Rule deleted Rule deleted (v6)

Step 16: Close the Port

Ubuntu stops the listener; Kali confirms it's gone

KALI

$ nmap -p 8080 $VM_IP # $VM_IP: still the value from Step 7 PORT STATE SERVICE 8080/tcp closed # closed: port refused, nothing listening now

UBUNTU

$ kill %1 # %1: the background job started in Step 5

Check: open vs. filtered

SAME SCAN, TWO DIFFERENT RESULTSStep 7: 8080 openStep 12: 8080 filteredStep 7 showed "open", Step 12 showed "filtered" once the DROP rule was reordered. What does"filtered" actually tell nmap?nmap got no response at all and can't tell if the port is open orclosed, only that something is blocking it.

Deliverable

  • ufw allow, confirmed open
  • A DROP rule that first failed
  • Reordered, verified, fully cleaned up
8080/tcp filtered

Questions?

Module 13

Containerization

VIRTUALIZATION VS. CONTAINERIZATIONVIRTUAL MACHINEAppGuest OS (full OS)HypervisorHost OS + HardwareCONTAINERApp (only this)(no Guest OS)skippedContainer EngineHost OS + HardwareA container packages only the app and its dependencies.A VM also packages a full guest operating system.
MODULE 13: THE JOURNEY1Why Containers?2Containers vs. VMs3Images & Dockerfile4Running Containers5Building an Image6Practice LabSTARTFINISHFrom why containers exist to actually building and running one.
Dockerfile: the recipedocker build: makes an imagedocker run: starts a container

All Commands: Module 13

Why Containers?

Why This Matters

  • Isolation started with chroot
  • Docker made it mainstream
  • Now the default way to ship
1979chroot (Unix v7): the firstprocess-isolation idea 2008LXC: real Linux containers,using kernel cgroups/namespaces 2013Docker (Solomon Hykes)makes containers mainstream 2015OCI standard forms: imagesand runtimes become portable TodayContainers are the default waymost new apps are shipped
TWO ERAS, ONE UNDERLYING REASONWHY VIRTUALIZE?WHY CONTAINERIZE?Run several OSes on one machineConsolidate many old serversReuse a legacy OS environmentStrong, hardware-backed isolationFix "works on my machine"Start fast, scale out quicklyShip many small microservicesKeep dev/test/prod identicalBOTH SOLVE THE SAME CORE PROBLEMIsolate several workloads safely on one machineand get more use out of the same hardwareVirtualization came first: one physical box, several full machines, strict isolation.Containers followed: much lighter, but built to solve the same packaging and isolation problem.
WHY THIS MATTERS: SAME VERSIONSmyapp:1.4 imagePython 3.11.4 + Flask 3.0LaptopPy 3.11.4CI PipelinePy 3.11.4ProductionPy 3.11.4Pinned versions, every host -- dev, CI, and production all run identically.No dependency drift, no "it worked on my machine."
EXAMPLE: DEPENDENCY HELL, SOLVEDContainer APython 2.7 (legacy)Container BPython 3.12 (new)One Host OSshared kernel underneathTeam A needs Python 2.7, Team B needs Python 3.12 -- same machine, zero conflict.Each container carries its own exact runtime.
EXAMPLE: ONE IMAGE, ANY CLOUDmyapp:1.4 imageone OCI image, one tagLaptopruns unchangedCloud VMruns unchangedOn-Premruns unchangedSame image, laptop to cloud -- no per-host reinstall.The image carries its own world with it, wherever it runs.

Use Case: Consistent Envs

  • QA can't reproduce a prod bug
  • Same image, QA and prod
  • Bug reproduces, fixed fast
"Can't reproducethis bug..."QA"Try the exactimage from prod"Devmyapp:1.4Bug reproduces, fixed fast

Use Case: Scale Out Fast

  • Traffic spikes during finals
  • Spin up more of the same image
  • Load balancer spreads traffic
"Traffic isspiking!"Ops"Spin up 3 morereplicas, same image"SREmyapp:1.4 x NLoad balancer spreads the traffic

Use Case: Fast Rollback

  • New version breaks in prod
  • Old image is still right there
  • Back online in under a minute
"New releasebroke prod!"Dev"Just redeploythe old tag"Opsmyapp:1.3Back online in under a minute
SCALING FROM ONE STANDARD IMAGEmyapp:1.4Load risesAppreplica 1Appreplica 2Appreplica 3Appreplica 4Appreplica 5Incoming trafficEvery replica is the exact same image: no setup drift, no snowflakes.Scale out when busy, back down when quiet.
WHAT DOCKER ACTUALLY ISdocker CLIDocker EngineDocker Hub (docker.io)commandspulls / pushes imagesMarch 2013 · Solomon Hykes · dotCloud · PyCon demoDocker Engine runs in the background and manages containers; the CLI just talks to it.The real isolation comes from the Linux kernel -- Docker only makes it easy to use.

Check: What Does Docker Do?

Is Docker itself what isolates containers, or is it just a tool using something else?

Just a tool: the isolation comes from the Linux kernel (namespaces, cgroups). Docker's Engine and CLI make that mechanism easy to use.
WHY DOCKER? OTHER OPTIONS EXISTDockertaught in this coursedaemonless, rootlesslower-level runtimeolder, OS-level containersrktdeprecated (CoreOS)Docker is the most-used container tool among professional developers (59%).Most alternatives use the same OCI image format underneath -- the skills transfer.

Source: Stack Overflow 2024 Developer Survey, Most Popular Technologies

Check: What Problem Fixed?

"It works on my machine" is a classic developer complaint. What does a container actually fix about that?

A container packages the app with its exact dependencies, so the same image runs identically anywhere it's run.

Questions?

Containers vs. VMs

WHY VMS ARE BIG AND SLOWKernel (tens of MB)FULL OS INSTALL (THE REST OF A VM)Drivers & ServicesBoot ProcessVirtual DiskReserved RAM, held whether used or notThe kernel itself is small; the full OS install and reserved RAM make a VM big.A container skips booting an OS entirely: it starts a process on an already-running kernel.
SHARED KERNEL = WEAKER ISOLATIONHost Kernel (shared)!Container AContainer BContainer CEvery container on a host shares the one kernel; a kernel bug can affect all of them.A VM's own guest kernel stays separated from others by the hypervisor instead.
WHY A CONTAINER STARTS IN ~1 SECONDVIRTUAL MACHINEBoot full guest OSseveral seconds to bootCONTAINERStart a processabout a secondStarting a container is like starting a program on a kernel that's already running.A VM has to boot a whole guest OS first -- no OS boot means no multi-second wait.

Check: Has Its Own Kernel?

True or false: each container runs its own kernel, the same way a VM runs its own guest OS.

False. A container shares and borrows the host's kernel. "Guest" describes a VM's OS, not a container's.

Word Origin: "Container"

contain
  • Latin: to hold together
intermodal container
  • 1956: McLean standardizes cargo

Docker's own 2013 keynote framed software containers around the standardized shipping container that transformed global trade.

Source: Wikipedia: Intermodal container

Check: Why So Fast?

Why does a container start in about a second while a VM can take much longer?

A container just starts a process on a kernel that's already running; a VM has to boot an entire guest OS first.

No Guest OS, No Hypervisor

  • Module 1: VM has guest OS
  • A container shares host kernel
  • Lighter, faster to start
VM: Hardware+Hypervisor+GuestOSContainer: Hardware+HostOS kernelIsolation: from the kernel itself

Check: Why Faster to Start?

A container starts in under a second; a VM takes much longer to boot. What's the real reason for the gap?

A VM boots an entire guest OS kernel; a container just starts a process, reusing the host kernel already running.

Use Case: CI Build Agents

  • Each build needs a clean env
  • VMs: too slow to spin up
  • Containers: ready in ~1 sec
New commit pushedpipeline needs a test envStart a containernot a whole VMTests run in secondsnot minutes

Use Case: Packing More Onto One Host

  • Host has 32GB RAM
  • VMs: ~8 fit (RAM reserved)
  • Containers: 100+ fit easily
32GB RAM, one hosthow many services fit?No guest OS per appno RAM reserved upfrontDozens more containersthan VMs would allow

Questions?

Images & the Dockerfile

WHAT'S INSIDE A CONTAINER IMAGEIMAGE USERLAND (SHIPPED)LibrariesShellPkg ManagerApp FilesNO KERNEL -- borrowed from the host!An image usually ships a full userland: libraries, a shell, a package manager, and files.It never includes a kernel -- a container always borrows the host's kernel.
DOCKER DESKTOP'S HIDDEN LINUX VMmacOSWindowsTiny Linux VM (hidden)Your Linux containerA Linux container needs a Linux kernel -- macOS and Windows don't ship one.Docker Desktop quietly runs a small Linux VM underneath to provide it.
RECIPE VS. DISH: ONE IMAGE, MANY CONTAINERSImage (the recipe)Container 1Container 2Container 3The image never changes; each container is a separate running instance made from it.Cook the same recipe as many times as you like -- nothing about it is used up.

Check: Recipe Stays Same?

If you start five containers from the same image, does the image itself change?

No. The image stays exactly as it was; only new, separate containers get created from it.
INSIDE A CONTAINER: AN ISOLATED VIEWCONTAINER'S OWN VIEWPID 1: your appOwn filesystem viewOwn network viewCPU / memory limitsBy default a container sees only its own processes -- its main app runs as PID 1.Everything else happening on the host stays invisible from inside it.
ONE SERVICE PER CONTAINERApp containerDB containertalk over a networktied together by Docker ComposeConvention: one main service per container, not a bundled mini-system.A full system (app + database) uses several containers, not one giant one.
IMAGE SECURITY: REBUILD ON PATCHmy-app:1.0 (old base)!my-app:1.0 (rebuilt)FROM base gets patchedyour own app code never changedAn image carries its userland's vulnerabilities too, not just your own code.Rebuild it whenever the base image is patched, even if nothing in your code changed.

A Dockerfile Is a Recipe

  • FROM: the base image to use
  • COPY: add your own files in
  • CMD: what runs when it starts
FROM ubuntu:24.04COPY app.py /app/CMD ["python3","/app/app.py"]

Check: Image vs. Container

This module keeps saying both "image" and "container". Are they the same thing?

No: an image is the packaged recipe/template; a container is a running instance actually started from that image.
A DOCKER IMAGE: MANDATORY, OPTIONAL, AND WHERE IT LIVESMANDATORYFROM: base imageA way to start (CMD or ENTRYPOINT)OPTIONALCOPY / ADD: bring files inENV: environment variablesEXPOSE: document a portRUN: build-time commandsWORKDIR, USER, LABEL, ARGEXISTING STORES (REGISTRIES)Docker HubGitHub Container RegistryAmazon ECRQuay.ioEvery image needs a base and a way to start; everything else is optional.Built images are pushed to a registry so any host can pull and run them.

Use Case: Onboarding a New Hire

  • New dev needs the full stack
  • Manual setup: hours, drifts
  • docker pull: minutes, exact
New developer joinsneeds the team's exact stackdocker pull team-imagesame image everyone usesRunning in minutesidentical to everyone else's

Use Case: One Patched Base Image

  • Security team patches base
  • Every team's FROM: same base
  • One rebuild fixes them all
CVE found in base imagemany apps built FROM itPatch the one base imagesecurity team rebuilds itEvery team rebuildsone shared fix, many apps

Questions?

Running Containers

PULLING IMAGES LIKE A PACKAGE MANAGERdocker run nginxImage cachedlocally?Docker Hubnginx imagenoyesstarts containerdocker run checks locally first; if missing, it downloads the image, then starts it.Different from a package manager: Docker also runs what it just downloaded.
TAGS ARE LIKE VERSION NUMBERSnginx:1.24nginx:1.27nginx:latest!a moving target, not a fixed versionA tag such as nginx:1.27 works like a version number for the image.Prefer a specific version tag over latest for anything you actually depend on.
DOCKER HUB: OFFICIAL VS. ANYONE'SDOCKER HUB (MILLIONS OF REPOSITORIES)Official Imagesnginx, postgres, ubuntucurated, verifiedAnyone's uploadsverify before trustingDocker Hub works like a package repository -- but anyone can publish to it.Prefer Official or Verified images; check before pulling an image you don't know.
A CONTAINER'S LIFE CYCLEMain process startsRunning containerprocess finishesprocess crashesContainer exitsdocker logs: see whyA container lives only as long as its main process keeps running.If that process finishes or crashes, the container exits -- docker logs shows why.
DELETE A CONTAINER, LOSE ITS DATA... UNLESSContainerdata written insidedocker rmdeleted -- data inside is goneVolume (outside it)mounted volumeDeleting a container deletes any data stored inside it; the image itself is unaffected.Use volumes to store data outside the container so it survives deletion.
ESSENTIAL COMMANDS CHEAT SHEETdocker runcreate a NEW container from an image and start itdocker startrestart an EXISTING stopped containerdocker ps / ps -alist running containers / also show stopped onesdocker stopstop a running container cleanlydocker rmdelete a stopped containerdocker rmidelete an imagedocker logsshow a container's outputdocker exec -it bashopen an interactive shell inside a running containerNamed after Linux ps: docker ps lists what's alive right now.run makes something new; start brings an existing one back.

Word Origin: "Docker"

docker (occupation)
  • a dock worker loading ships
Docker, Inc.
  • 2013: dotCloud renamed itself

The name keeps the shipping metaphor: a docker loads cargo onto ships, the way Docker loads apps into containers.

Source: Wikipedia: Docker (software)

Check: Image Source?

docker run asks for an image you don't have locally. Where does Docker get it from?

From a registry -- by default, Docker Hub (docker.io).

Check: Data After Delete

You write a file inside a running container, then delete that container. What happens to the file?

It's lost, unless that data was stored in a volume mounted outside the container.

Check: run vs. start

What's the difference between docker run and docker start?

run creates a brand-new container from an image; start restarts an existing, already-created but stopped container.

Check: Listing Containers

Which command lists every currently running container?

docker ps (add -a to also see stopped ones; docker container ls also works).

Check: Stop, Then Delete

You want to remove a container for good. What two commands do you run, in order?

docker stop <name>, then docker rm <name> -- stop it cleanly, then delete it.

Check: Exiting Right Away

A container exits seconds after you start it. What's the most likely cause?

Its main process already finished or crashed -- check docker logs to see why.

Check: A Shell Inside One

How do you get an interactive shell inside a running container?

docker exec -it <name> bash (or sh, if the image has no bash).

docker run: Start One

  • -d: detached, background run
  • -p: map a host port to it
  • Not found locally? Auto-pulls
$ sudo docker run -d -p 8080:80 nginx Unable to find image 'nginx:latest' locally

docker run: Start One

$ sudo docker run -d -p 8080:80 nginx # Host port 8080 forwards to container port 80 Unable to find image 'nginx:latest' locally # No nginx image cached: docker auto-pulls it latest: Pulling from library/nginx # Same as running `docker pull nginx` first # (layers omitted, see Step 7) c89be4fef9df # The new container's ID, now running in the background

docker ps: What's Running

  • Lists containers and ports
  • -a also shows stopped ones
$ sudo docker ps CONTAINER ID IMAGE PORTS a1b2c3d4e5f6 nginx 0.0.0.0:8080->80/tcp

docker ps: What's Running

$ sudo docker ps # Shows every currently-running container CONTAINER ID IMAGE PORTS a1b2c3d4e5f6 nginx 0.0.0.0:8080->80/tcp

docker exec & stop

  • exec: run a command inside it
  • stop: shut it down cleanly
$ sudo docker exec -it a1b2c3d4 bash $ sudo docker stop a1b2c3d4

docker exec & stop

$ sudo docker exec -it a1b2c3d4 bash # -it: interactive, with a real terminal $ sudo docker stop a1b2c3d4

Use Case: docker ps Before Restart

  • Shared host, several services
  • Check what's actually running
  • Avoid colliding with others
About to restart a serviceis something else using it?docker pslist what's really runningConfirmed clearrestart without a collision

Use Case: docker exec to Debug

  • App behaves oddly in prod
  • No SSH access to the host
  • Shell inside the container
App returns bad dataneed to inspect it livedocker exec -it basha shell inside the containerFound the stale configwithout touching the host

Questions?

Check: ID Shortcuts

The container ID is a1b2c3d4e5f6, but Step 3 typed only a1b2c3d4. Why does that still work?

Docker accepts any unique prefix of the full ID, so a few characters are usually enough to identify it.

Building an Image

docker build: Make an Image

  • -t names (tags) the image
  • . means build from this dir
$ sudo docker build -t myapp:1.0 .

docker build: Make an Image

$ sudo docker build -t myapp:1.0 . # Reads ./Dockerfile; -t sets name and version

docker images: What Exists

  • Lists every image on this host
$ sudo docker images REPOSITORY TAG IMAGE ID myapp 1.0 7f8e9d0c1b2a

docker images: What Exists

$ sudo docker images # Confirms the build actually produced an image REPOSITORY TAG IMAGE ID myapp 1.0 7f8e9d0c1b2a

Check: Rebuild on Change?

app.py changes, but the Dockerfile itself doesn't. Does the image update automatically?

No: an image is a fixed snapshot; docker build must run again to bake the new code into a new image.

Use Case: docker build in CI/CD

  • Every push triggers a build
  • Image tagged with commit hash
  • Pushed to registry to deploy
Developer pushes codepipeline picks it updocker build -t app:shatagged with the commitPushed to the registryready to deploy

Use Case: docker images Cleanup

  • Host is low on disk space
  • List images taking up room
  • Remove the old, unused ones
Disk almost fullwhat's actually on this host?docker imageslist every stored imageOld builds removeddisk space reclaimed

Questions?

Practice Lab

Scenario: Containerize It

  • A small Python app (Module 11)
  • Write a Dockerfile for it
  • Build, run, confirm it works
Dockerfile: FROM, COPY, CMDdocker build: makes the imagedocker run: starts a container
WHAT apt update DOESYOUR UBUNTU VMUbuntu VM③ Index, now refreshedUBUNTU PACKAGE REPOSarchive.ubuntu.com① asks: what's available?② sends the current listThe VM only learns what versions exist -- nothing is downloaded or installed yet.

Step 1: Update Packages

  • Refresh apt's package index
$ sudo apt update

Step 1: Update Packages

$ sudo apt update # Re-syncs the package index from repos
WHAT apt install docker.io DOESYOUR UBUNTU VMUbuntu VM③ docker.io, now installedUBUNTU PACKAGE REPOSdocker.io.deb① request: docker.io② sends the .deb fileThe actual docker.io package is downloaded from the repo and installed on disk.

Step 2: Install Docker

  • Not installed by default
$ sudo apt install -y docker.io

Step 2: Install Docker

$ sudo apt install -y docker.io # docker.io: the package name on Ubuntu
WHAT systemctl enable --now docker DOESdocker.io (on disk)systemddockerd① systemd starts it② dockerd runs③ enable: also starts on every bootdocker.io sits unused on disk until systemd actually launches the dockerd process.

Step 3: Enable Docker

  • Run now, and on every boot
$ sudo systemctl enable --now docker

Step 3: Enable Docker

$ sudo systemctl enable --now docker # enable: on boot. --now: start it today
HOW docker TALKS TO dockerddocker CLI/var/run/docker.sockdockerd① is this socket alive?② yes, I'm heresystemctl checks the service; docker --version checks the CLI can reach it over that socket.

Step 4: Verify Docker Runs

  • Confirm service, then CLI
$ sudo systemctl is-active docker active $ docker --version Docker version 24.0.7, build afdd53b

Step 4: Verify Docker Runs

$ sudo systemctl is-active docker # active means the daemon is up active $ docker --version # Confirms the CLI can reach it Docker version 24.0.7, build afdd53b
WHERE THE LAB FILES COME FROMGITHUBSE4CPS/2026-COMP-175YOUR UBUNTU VMDockerfileapp.pypractice-lab/① git clone② real files land on your VMDockerfile and app.py are real files from the course repo, not retyped by hand.

Step 5: Clone the Project

  • Real files, not retyped
  • Already cloned? git pull
$ git clone \ https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/modules/module-13/practice-lab Already cloned it before? Instead: $ cd 2026-COMP-175 && git pull

Step 5: Clone the Project

$ git clone https://github.com/SE4CPS/2026-COMP-175.git # Pulls the real Dockerfile and app.py $ cd 2026-COMP-175/modules/module-13/practice-lab # This folder has both files already # Already cloned it before? Do this instead: $ cd 2026-COMP-175 && git pull # Pulls any updates, keeps your clone current
LAYERS IN A DOCKERFILEapp.pyprint("Hello...")FROM python:3.12-slimbase layer1COPY app.py /app.pyapp layer2CMD ["python3","/app.py"]entrypoint layer3copied inEach instruction stacks one more layer on top of the last, building the final image.

Step 6: The Dockerfile

  • app.py's own print() line
  • Base image, copy the script in
$ cat app.py print("Hello from inside a container") FROM python:3.12-slim COPY app.py /app.py CMD ["python3", "/app.py"]

Step 6: The Dockerfile

$ cat app.py # This exact line is the cloned app.py print("Hello from inside a container") FROM python:3.12-slim # slim: a smaller, minimal base image COPY app.py /app.py # Copies that same file into the image CMD ["python3", "/app.py"] # Runs it, which prints the line above
WHAT docker build DOESDockerfileapp.pydocker buildmy-script:1.0/var/lib/containerd/① reads both files② produces the imageThe image is built and tagged locally, but nothing is running from it yet.Exact location varies by storage driver -- use `docker images`, not ls, to find it.

Step 7: Build It

  • Tag it with a real name
$ sudo docker build -t my-script:1.0 .

Step 7: Build It

$ sudo docker build -t my-script:1.0 . # Reads the Dockerfile in this directory # Real output continues on the next slides

Step 7: Build It (Warnings)

sudo: unable to resolve host vm-ubuntu # Harmless: hostname isn't in /etc/hosts DEPRECATED: legacy builder will be removed later # A warning only -- this build still works (suggests installing buildx/BuildKit instead) # Optional modern builder, not needed here

Step 7: Build It (Pulling the Base Image)

Sending build context to Docker daemon 4.096kB # Your Dockerfile + app.py sent to the daemon Step 1/3 : FROM python:3.12-slim # Step 1 of 3: start from the slim Python image 3.12-slim: Pulling from library/python # Downloads that base image from Docker Hub

Step 7: Build It (Layers Downloaded)

05e0eee5572e: Pull complete 68bced9e0afa: Pull complete 2dc99d2d0a39: Pull complete 37fb86c2a767: Pull complete # Each hash is one layer of the base image # "Pull complete" means that layer finished Digest: sha256:5e2bdb1b0d54... # A checksum confirming the exact image pulled Status: Downloaded newer image for python:3.12-slim # Confirms a fresh image was fetched, not cached

Step 7: Build It (Copy, Run, Done)

Step 2/3 : COPY app.py /app.py # Step 2: copies your script into the image Step 3/3 : CMD ["python3", "/app.py"] # Step 3: sets what runs when it starts # (container-bookkeeping lines omitted here) Successfully built dd7679866e74 # The final image ID -- build finished Successfully tagged my-script:1.0 # That image is now named my-script:1.0

Where's My Image, Really?

  • Missing image/overlay2 dirs
  • Likely the containerd store
  • Ask docker, not ls, to check
$ sudo ls /var/lib/docker/ buildkit containers engine-id network plugins rootfs runtimes swarm tmp volumes

Where's My Image, Really?

$ sudo ls /var/lib/docker/ # No image/ or overlay2/ listed here at all buildkit containers engine-id network plugins # These are daemon bookkeeping, not your image rootfs runtimes swarm tmp volumes # Newer Docker stores layers via containerd $ docker info | grep -i "storage driver" # The real, authoritative way to check
WHAT docker run DOESmy-script:1.0docker runrunning container"Hello from inside a container"① starts from the image② runs CMD, prints, exitsA container is a temporary running process started from the image -- it exits when the command finishes.

Step 8: Run and Verify

  • Name set in Step 7's -t flag
  • Output is app.py's print()
  • Confirm it actually ran
$ sudo docker run my-script:1.0 sudo: unable to resolve host vm-ubuntu Hello from inside a container

Step 8: Run and Verify

$ sudo docker run my-script:1.0 # my-script:1.0 is the -t name set in Step 7's build # No -d here: runs in the foreground, prints output sudo: unable to resolve host vm-ubuntu # Harmless: hostname missing from /etc/hosts # Fix: echo "127.0.1.1 $(hostname)" | sudo tee -a /etc/hosts Hello from inside a container # That's app.py's own print(), from Step 6

Check: Why the Slim Image?

The Dockerfile could have used a full ubuntu:24.04 base instead. Why reach for a slim Python image here?

A smaller base means a smaller, faster-to-build image, and it already includes exactly what a Python app needs.

Deliverable

  • A working Dockerfile
  • An image built and tagged
  • A running, verified container
Hello from inside a container

Questions?

Practice Quiz

Practice Quiz: Match the Command

Drag an answer from the outside onto the question it matches — one answer per question.

docker ps
docker build
docker pull
docker run
Image
-d flag
-p flag
Registry
Deletes an image
Maps host↔container port
Lists running containers
A read-only template
Shell into a container
Starts a new container
Stores and shares images
Shows container output
Build instructions file
Deletes a container
Downloads an image
Runs in the background
A running image
Builds an image
Lists local images
Stops a container
docker stop
docker rm
docker rmi
docker logs
docker images
docker exec
Dockerfile
Container

Questions?

Module 14

Deployment & Network Segmentation

Subnets: carve up the address spaceVLANs: separate without new wiringDeploy: dev → staging → prod

All Commands: Module 14

Why Segment a Network?

Why This Matters

  • CIDR replaced rigid classes
  • VLANs separate traffic
  • Staging limits blast radius
1981RFC 791 defines classful IPaddressing (A/B/C networks) 1993CIDR (RFC 1519) replaces it:flexible subnet sizes 1998IEEE 802.1Q standardizesVLAN tagging 2000sdev/staging/prod becomesstandard deployment practice TodaySegmentation and stageddeploys both limit blast radius
ONE FLAT NETWORK, ONE BIG RISKEvery Host Sees Every Hostno boundaries at allOne Breach, Full AccessModule 12: firewalls alone are not enoughA Bad Deploy Hits Everyoneno staging to catch it firstSegmentation limits how far a breach spreads.Staged deployment limits how far a bad change spreads.

Check: Firewall Not Enough?

Module 12 taught firewall rules on one host. Why isn't that alone enough to protect a whole network?

A firewall protects one host's own traffic; segmentation limits what an already-compromised host can even reach.

Subnetting & CIDR

CIDR: A Slash and a Number

  • 192.168.1.0/24: mask is /24
  • More masked bits: fewer hosts
  • Already in Module 7's netplan
/24: 256 addresses, 254 usable/28: 16 addresses, 14 usable/32: exactly one single host

ipcalc: Do the Math For You

  • Shows the network, host range
  • Faster and safer than by hand
$ ipcalc 192.168.1.0/24 Network: 192.168.1.0/24 HostMin: 192.168.1.1 HostMax: 192.168.1.254

ipcalc: Do the Math For You

$ ipcalc 192.168.1.0/24 # Network: the subnet's own base address Network: 192.168.1.0/24 # HostMin/HostMax: the usable address range HostMin: 192.168.1.1 HostMax: 192.168.1.254

Check: Why Not Always /24?

A /24 gives 254 usable hosts. Why would a network ever use a smaller subnet, like a /28?

A smaller subnet limits broadcast traffic and blast radius per segment, even when far fewer than 254 hosts exist.

VLANs

Separate Without New Wiring

  • A tag on each Ethernet frame
  • One switch, many logical nets
  • Devices on different VLANs
VLAN 10: Registrar devicesVLAN 20: Guest Wi-FiSame switch, kept fully apart

Check: VLAN vs. Subnet

This module teaches both subnets and VLANs. Are they two names for the same idea, or different layers?

Different layers: a VLAN separates traffic at layer 2 (the switch); a subnet is a layer-3 IP addressing boundary.

Deployment Environments

Three Stages of Trust

  • dev: your own machine
  • staging: a real copy, checked
  • production: real users
dev: broken is expected herestaging: catches it before users doproduction: the real, live system

Check: Deploy to Prod?

A change already works on dev. Why add a staging step before it reaches production at all?

dev often differs from the real environment; staging catches integration issues before real users are affected.

A Real Deploy Script

Reusing What You Learned

  • git clone/pull: Module 2
  • rsync: Module 5
  • Wrapped in a script: Module 11
git pull: get the latest codersync: copy it to the serverScript ties both together

deploy.sh: Pull, Then Sync

  • cd into the repo, pull first
  • rsync to the staging server
#!/bin/bash cd /home/user/app && git pull rsync -avz /home/user/app/ staging:/srv/app/

deploy.sh: Pull, Then Sync

#!/bin/bash # Always pull the latest before syncing cd /home/user/app && git pull # -avz: archive mode, verbose, compressed rsync -avz /home/user/app/ staging:/srv/app/

Check: Why pull First?

The script runs git pull before rsync, not the other way around. Why does the order matter here?

rsync copies whatever is currently on disk; pulling first ensures that copy actually includes the latest code.

Practice Lab

Scenario: Plan, Then Deploy

  • Calculate a subnet with ipcalc
  • Write and run a deploy script
  • Verify the files arrived
ipcalc: plan the registrar subnetdeploy.sh: pull and rsyncls on the target: confirm it

Step 1: Plan the Subnet

  • A /28 for the registrar team
$ ipcalc 10.0.5.0/28

Step 1: Plan the Subnet

$ ipcalc 10.0.5.0/28 # Confirms 14 usable addresses fit the team

Step 2: Write deploy.sh

  • Reuses Module 11's own pattern
#!/bin/bash cd ~/app && git pull rsync -avz ~/app/ staging:/srv/app/

Step 2: Write deploy.sh

#!/bin/bash # Same pull-then-sync order as before cd ~/app && git pull rsync -avz ~/app/ staging:/srv/app/

Step 3: Run and Verify

  • chmod +x, run it, then confirm
$ chmod +x deploy.sh $ ./deploy.sh $ ssh staging ls /srv/app/

Step 3: Run and Verify

$ chmod +x deploy.sh $ ./deploy.sh # ssh + ls confirms the files really arrived $ ssh staging ls /srv/app/

Check: Proving It Worked

Step 3's final ls runs on the staging server, not the local machine. Why check there instead of locally?

rsync could have silently failed; checking the remote side is the only real proof the deploy actually worked.

Deliverable

  • A subnet planned with ipcalc
  • A working, executable script
  • Files confirmed on the remote
app.py config.yml requirements.txt

Questions?

Module 15

Final Preparation & Course Wrap-up

inventory.ini: which hostsplaybook.yml: desired stateansible-playbook: make it so

All Commands: Module 15

Why Infrastructure as Code?

Why This Matters

  • Config management isn't new
  • Ansible needs only SSH
  • Config lives in git now
1993CFEngine: the first realconfig management tool 2005Puppet: declarative config,widely adopted 2012Ansible (Michael DeHaan):agentless, just needs SSH 2014Terraform: IaC for wholecloud infrastructure, not just config TodayConfig lives in version control,same as application code

Check: What "As Code" Adds

The phrase is "infrastructure AS code," not just "infrastructure automation." What does that distinction add?

The config itself is a tracked file: version-controlled, reviewable, and reusable, not just a one-off script run.

Declarative vs. Imperative

Say What, Not How

  • Imperative: a script, steps
  • Declarative: end state wanted
  • Playbooks are declarative
Imperative: apt install, then startDeclarative: nginx presentThe tool figures out the steps

Check: Was Module 11 This?

Module 11's backup.sh gave exact steps: cp, then echo. Is that imperative or declarative?

Imperative: it is a literal sequence of commands to run, not a description of the end state that is wanted.

Ansible: Inventory & Playbooks

inventory.ini: Which Hosts

  • Lists the real hosts to manage
  • Groups can organize them
[webservers] 192.168.1.10 192.168.1.11

inventory.ini: Which Hosts

[webservers] # A group name in brackets 192.168.1.10 192.168.1.11

playbook.yml: Desired State

  • YAML: structured, readable
  • Each task is one outcome
- hosts: webservers tasks: - name: Ensure nginx is installed apt: name: nginx state: present

playbook.yml: Desired State

- hosts: webservers tasks: # Each task has a name and a module - name: Ensure nginx is installed apt: name: nginx state: present

Check: Why YAML, Not Bash?

A playbook could have just been a bash script instead. Why does Ansible use YAML to describe tasks?

YAML describes the desired end state in structured data; a shell script would describe imperative steps instead.

Running a Playbook

ansible-playbook: Run It

  • -i points at the inventory
  • Connects via SSH, applies it
$ ansible-playbook -i inventory.ini playbook.yml TASK [Ensure nginx is installed] changed: [192.168.1.10]

ansible-playbook: Run It

$ ansible-playbook -i inventory.ini playbook.yml # Reuses Module 5/8's own SSH connection TASK [Ensure nginx is installed] changed: [192.168.1.10]

Check: "changed"?

The task output says "changed", not "ok". What does that specific word tell you?

It means this run actually DID something (installed nginx); "ok" would mean it was already in that state.

Idempotency

Run It Twice, Same Result

  • First run: installs it
  • Second run: matches, no-op
  • Safe to run it again
Run 1: nginx missing, installs itRun 2: nginx present, does nothingResult: always the same end state

Check: Why This Matters

A bash script run twice in a row could install nginx twice, or error the second time. Why doesn't a playbook have that problem?

Each Ansible task checks the current state first and only acts if it needs to, instead of blindly re-running steps.

Practice Lab

Scenario: Automate Setup

  • Install nginx via playbook
  • Run it twice, confirm no-op
  • Verify against live service
inventory.ini: the Ubuntu VMplaybook.yml: nginx present, runningRun twice: changed, then ok

Step 1: Install Ansible

  • Runs from Kali, targets Ubuntu
$ sudo apt install -y ansible

Step 1: Install Ansible

$ sudo apt install -y ansible # Installed on the controller (Kali), not the target

Step 2: Write the Inventory

  • Point it at the real VM
# <VM-IP>: hostname -I on the target # <your-user>: whoami on the target [target] <VM-IP> ansible_user=<your-user>

Step 2: Write the Inventory

# <VM-IP>: hostname -I on the target # <your-user>: whoami on the target [target] <VM-IP> ansible_user=<your-user>

Step 3: Write the Playbook

  • One task: nginx present
- hosts: target become: yes tasks: - name: Install and start nginx apt: name=nginx state=present

Step 3: Write the Playbook

- hosts: target # become: yes, same idea as sudo become: yes tasks: - name: Install and start nginx apt: name=nginx state=present

Step 4: Run It Twice

  • Confirm the second run: no-op
$ ansible-playbook -i inventory.ini playbook.yml $ ansible-playbook -i inventory.ini playbook.yml

Step 4: Run It Twice

$ ansible-playbook -i inventory.ini playbook.yml # First run: changed=1 $ ansible-playbook -i inventory.ini playbook.yml # Second run: changed=0, already matches

Check: Proving Idempotency

The second run reports changed=0. What does that actually prove about the playbook?

It proves the playbook is idempotent: re-running it is safe and doesn't redo work already in the desired state.

Deliverable

  • A working inventory, playbook
  • nginx installed and running
  • Second run proving idempotency
changed=0 unreachable=0 failed=0

Questions?

Reminder

Who is interested in attending the Fall Showcase on Fri, Dec. 4, 2–3:15 PM, Makerspace?

Assignment

  1. Homework 1 & Lab 1
  2. Homework 2 & Lab 2
  3. Homework 3 & Lab 3
  4. Homework 4 & Lab 4
  5. Homework 5 & Lab 5
  6. Homework 6 & Lab 6
  7. Homework 7 & Lab 7
  8. Project Part 1: Overview, Review, Verify, Reflections
  9. Project Part 2: Overview, Teams, Week 1, Use Case, Rhythm, GitHub
  10. Midterm

Midterm: Modules 1-6

  • Date: Oct 15
  • 20 questions, 5 pts each
  • 18 MC, 1 diagram, 1 written
  • On paper: bring a pen
  • Closed book, 1 note page OK
  • Modules 1-6, ~3 Qs each
  • Full class: 8:25-9:45

Midterm: Answer Key

Q1

In a Type 2 setup such as VirtualBox on a Windows laptop, which one is the host?

A. The Linux guest OS running inside the VM
B. The hypervisor program itself, VirtualBox
C. The Windows PC that VirtualBox runs on
D. The virtual network switch for the VMs

Answer: C

The Windows PC is the host; VirtualBox is the hypervisor running on it, one layer above the guest.

  • Other Type 2 hypervisors:
  • VMware Workstation
  • Parallels Desktop

Q2

What does sudo apt-get update do?

A. Installs every pending package upgrade
B. Refreshes the package lists from repos
C. Removes any package no longer used
D. Upgrades the kernel to a newer version

Answer: B

update only re-syncs the local package index. Installing is a separate command.

  • apt-get upgrade: installs them
  • apt-get install pkg: adds one
  • apt-get remove pkg: removes it

Q3

What does nmap -p 22 host do?

A. Logs in to host over SSH as root user
B. Blocks port 22 on the host's own firewall
C. Prints the full routing table of the host
D. Checks if port 22 is open on the host

Answer: D

-p 22 scopes the scan to one port; nmap only probes and reports state.

  • nmap -p 80 host: just port 80
  • nmap -p 1-1000 host: a range
  • nmap -sV host: version detect

Q4

After chmod 640 notes.txt, what does ls -l show for its permissions?

A. rw-r-----
B. rwxr-----
C. rw-rw-r--
D. r--r--r--

Answer: A

640 = 6 (owner: rw-), 4 (group: r--), 0 (other: ---); no execute bit for anyone.

  • chmod 755: rwxr-xr-x
  • chmod 600: rw-------
  • chmod 644: rw-r--r--

Q5

What does sudo ufw allow 22/tcp do?

A. Shuts port 22 in the firewall
B. Opens port 22 in the firewall
C. Moves SSH onto port 22 now
D. Lists every firewall rule in use

Answer: B

allow adds a rule permitting that port/protocol; it never touches sshd's own config.

  • ufw deny 23/tcp: blocks telnet
  • ufw allow 80/tcp: opens HTTP
  • ufw status: lists the rules

Q6

What makes a file hidden from a plain ls?

A. Its name has no file extension
B. Its owner is the root user now
C. Its name starts with a dot (.)
D. Its permission mode is set 000

Answer: C

A leading dot is purely a naming convention; ls -a still lists it.

  • Hidden by convention:
  • .bashrc
  • .ssh/
  • .gitignore

Q7

Which of these is NOT stored in a file's inode?

A. The owner and group IDs of the file
B. The permission mode bits of the file
C. The name shown for the file in ls -l
D. The time the file was last modified

Answer: C

A filename lives only in a directory entry; the inode never stores it.

  • What an inode DOES store:
  • uid/gid, mode bits
  • size, timestamps, data blocks

Q8

What does id do?

A. Shows your uid, gid, and groups
B. Shows this machine's IP address
C. Changes the numeric user ID now
D. Lists every account on a system

Answer: A

id reports the identity the current shell is running as.

  • Example output:
  • uid=1000(alex) gid=1000(alex)
  • groups=1000(alex),27(sudo)

Q9

According to the FHS, where do system log files belong?

A. /etc/log
B. /usr/log
C. /tmp/log
D. /var/log

Answer: D

/var holds data that changes at runtime; /etc is only for static config.

  • /var/log/syslog
  • /var/log/auth.log
  • /var/log/apt/history.log

Q10

After chmod 2770 /srv/registrar, what does the leading 2 (setgid) do?

A. Only root may remove files inside it
B. Any new file inside inherits its group
C. Every file inside is marked executable
D. The folder gets hidden from a plain ls

Answer: B

setgid on a directory makes every new file inherit the directory's own group.

  • A file made by any user shows:
  • shows group: registrar

Q11

What does sudo -u www-data whoami do?

A. Runs whoami as www-data, prints that
B. Runs whoami as root, and prints root
C. Switches your shell over to www-data
D. Creates a new account named www-data

Answer: A

-u names the target user for this one command only; the shell's own identity never changes.

  • sudo -u postgres psql
  • sudo -u backup tar -czf ...

Q12

What does inotifywatch -e create,modify /srv/registrar do?

A. Streams every event, with no summary
B. Deletes every new file as it appears
C. Changes the folder's permission bits
D. Prints a summary table of the events

Answer: D

inotifywatch is the summary tool in inotify-tools, unlike inotifywait's live stream.

  • Example summary row:
  • 3 CREATE, 1 MODIFY report.txt

Q13

Which best defines a process?

A. A file saved on disk, waiting to be run
B. A program that is running, with a PID
C. A user account that owns some files
D. A network port that a service listens on

Answer: B

A program is the file on disk; a process is that program running, with its own PID.

  • /usr/sbin/sshd: the program
  • PID 842: sshd now running

Q14

Why run top instead of ps aux?

A. top shows just the root user's processes
B. top prints the full command line of each one
C. top keeps refreshing the process list live
D. top also lists processes on other hosts

Answer: C

ps aux is one static snapshot; top redraws continuously in real time.

  • top's live columns:
  • %CPU, %MEM, refreshed live

Q15

What does ssh-keygen -t ed25519 do?

A. Makes a brand-new SSH key pair
B. Copies your public key to a server
C. Deletes your existing SSH key pair
D. Opens an SSH session to a host

Answer: A

ssh-keygen generates a new key pair; -t picks the algorithm. Copying is ssh-copy-id's job.

  • Files it creates:
  • id_ed25519 (private)
  • id_ed25519.pub (public)

Q16

Which order matches: a file on disk, that file running with a PID, a process managed by systemd?

A. Process, program, service
B. Service, process, program
C. Program, service, process
D. Program, process, service

Answer: D

Program (on disk) becomes a process (running, PID), which systemd manages as a service.

  • /usr/sbin/sshd: the program
  • PID 842: the process
  • ssh.service: the service

Q17

What does sudo systemctl restart cron do?

A. Stops and then starts cron right now
B. Makes cron start up at each future boot
C. Shows if cron is currently running
D. Deletes the unit file that runs cron

Answer: A

restart stops then starts the service now; it changes nothing about boot-time behavior.

  • systemctl enable: on at boot
  • systemctl reload: re-reads cfg

Q18

In a crontab, what does 0 6 * * 1-5 mean?

A. Every 6 minutes, around the clock
B. 6:00 AM, Monday through Friday
C. 6:00 PM, every day of every week
D. Midnight, every day of every week

Answer: B

Fields are minute hour day month weekday: 6:00 AM, Mon-Fri only.

  • */15 * * * *: every 15 min
  • 0 0 1 * *: midnight, month 1

Q19

A file /srv/library/catalog.txt has one hard link named /srv/library/backup.txt and one symlink named /srv/library/latest.txt pointing at it. Draw and label a diagram showing how the directory entries, the inode(s), the data blocks, and the symlink relate.

catalog.txtdirectory entrybackup.txtdirectory entry (hard link)inodelink count: 2data blockslatest.txtdirectory entry (symlink)stores: "catalog.txt"a path string, no inodecatalog.txt and backup.txt share one inode; latest.txt only stores a path.

Q20

The registrar's Ubuntu server runs a nightly backup script, but last night it did not run, and a colleague says the server "was slow all evening." From your Kali VM you can SSH in. Write the steps you would take, naming the command for each and why.

ssh user@serverconnect to the Ubuntu serversystemctl list-timers | grep backupdid the timer actually run?top (or ps aux)find the process using the most CPUkill <PID>stop only that one processnohup ./backup.sh &re-run, survives logging out

Q1: Role of a Sysadmin

  • Explain the sysadmin role
  • Name one history milestone
  • Include its year
  • Manages systems and servers
  • Handles accounts and security
  • 1950s: Computer Operators
  • ran mainframes by hand

Source: Module 1 slides (The Sysadmin Role timeline)

Q2: Linux vs. Unix

  • Compare Linux and Unix
  • Give 2 similarities
  • Give 1 legal difference
  • Both: hierarchical file trees
  • Both: multi-user, multitask
  • UNIX = registered trademark
  • Linux = free, GPL-licensed

Source: class slides (Unix vs. Linux comparison)

Q3: What Is Virtualization?

  • Define virtualization
  • Explain why it's "virtual"
  • One host runs many guests
  • CPU/RAM/disk get divided up
  • Not physical, but still real
  • From Latin "virtus" (power)

Source: virtualbox.org/manual, Introduction

Q4: VirtualBox vs. WSL2

  • List 5 differences
  • install, VM window,
  • resources, hypervisor type
  • Install: package vs. wsl cmd
  • GUI manager vs. CLI only
  • Fixed vs. dynamic resources
  • Type 2 vs. Type 1 hypervisor
  • Separate disk vs. shared files

Source: Module 1 slides, learn.microsoft.com/windows/wsl, virtualbox.org/manual

Q5: Virtual Hardware

  • Explain vCPU, vRAM,
  • vDisk, and vNIC
  • Why needed on the host?
  • vCPU: sliced host CPU time
  • vRAM: reserved host memory
  • vDisk: a file acting as disk
  • vNIC: a virtual network link
  • Shares real hardware safely

Source: Module 1 slides, virtualbox.org/manual

Q6: Snapshots

  • Define a snapshot
  • Give a University example
  • Saves a VM's exact state
  • Disk, settings, sometimes RAM
  • Example: registration server,
  • snapshot before a big update
  • Restore fast if it breaks

Source: virtualbox.org/manual, vboxmanage snapshot

Q7: Kernel, GNU & Distro

  • Define kernel, GNU,
  • and distro
  • Kernel: manages hardware
  • GNU: free tools + Linux
  • Distro: kernel + GNU + tools

Source: kernel.org, class slides (Word Origin: GNU)

Q7: Ubuntu, Debian & Fedora

  • Compare 3 distros:
  • package manager, cycle,
  • and typical use case
DistroPackageCycleUse Case
UbuntuAPT6mo / 2yr LTSBeginners, servers
DebianAPT~2yr, stableReliable servers
FedoraDNF~6moDevelopers, new tech

Source: distrowatch.com, major distributions

Q8: Host OS vs. Guest OS

  • Define host vs. guest OS
  • Name one security risk
  • Host: runs on real hardware
  • Guest: runs inside a VM
  • Risk: 1 breach hits all guests
  • Exposes all VMs' student data

Source: virtualbox.org/manual, Guest OS Support

Q9: Types of OS Users

  • Describe 3 user types
  • Give a University example
  • Human: a student on Canvas
  • Device: a campus printer
  • Virtual: a load-test script
  • Simulates 1000s of students

Source: Module 1 class slides

Q10: Server & Naming

  • Pick a VM for a library
  • server; a naming convention
  • Ubuntu Server LTS
  • Long support, stable cycle
  • Matches campus IT standards
  • Name: campus-env-role-num
  • Example: MAIN-PROD-LIB-01

Q10: Usernames & Passwords

  • Username policy?
  • Password policy? (FERPA)
  • Username: first+last+number
  • Unique, no sensitive info
  • Disabled after unenrollment
  • Password: 14+ chars, MFA
  • Block weak, reused passwords

Source: class discussion, University domain scenario

Q11: Project 1 & 2 Structure

  • How are Project 1 and 2
  • structured for this course?
  • Project 1: individual work
  • Project 2: team-based work

Lab 1, Q1: Host Specs

  • Record the physical machine's
  • OS, version, CPU, and RAM
# Deliverable: screenshot of # host OS, version, CPU, RAM
Terminal showing host OS name, version, CPU, and total RAM

Lab 1, Q2: Downloads

  • Download VirtualBox and the
  • pre-built Ubuntu VM image
# Deliverable: downloads folder # showing both files
Downloads folder showing the Kali Linux ISO and VirtualBox installer

Lab 1, Q3: Import the VM

  • Install VirtualBox, import
  • the .ova (2 vCPU, 2GB, 20GB)
# Deliverable: VirtualBox Manager # showing the VM + its specs
VirtualBox Manager showing the imported Ubuntu VM

Lab 1, Q4: hostname/whoami

  • Right after login, run:
$ hostname $ whoami
Terminal showing hostname and whoami output

Lab 1, Q5: Add User jdoe

  • Deliverable: screenshot
  • showing id jdoe
$ sudo adduser jdoe
Terminal showing sudo adduser jdoe completing successfully

Lab 1, Q6: Add User dsmith

  • Deliverable: screenshot
  • showing id dsmith
$ sudo adduser dsmith
Terminal showing sudo adduser dsmith completing successfully

Lab 1, Q7: Create the Group

  • Deliverable: screenshot of
  • groups jdoe, getent group
$ sudo groupadd cs175-students $ sudo usermod -aG cs175-students jdoe
Terminal showing groups jdoe and getent group cs175-students

Lab 1, Q8: Project Folder

  • Deliverable: ls -ld showing
  • owner, group, and 770
$ sudo mkdir /srv/cs175-project $ sudo chown dsmith:cs175-students /srv/cs175-project $ sudo chmod 770 /srv/cs175-project
Terminal showing ls -ld /srv/cs175-project with owner, group, and permissions

Lab 1, Q9: jdoe Can Write

  • Deliverable: command succeeds,
  • then ls -l on the new file
$ su - jdoe $ touch /srv/cs175-project/notes.txt
Terminal showing jdoe successfully creating notes.txt

Lab 1, Q10: Outsider Denied

  • Deliverable: screenshot of
  • the Permission denied error
$ su - someoutsideuser $ touch /srv/cs175-project/notes2.txt
Terminal showing an outside user denied access

Homework 2, Q1: What Is a CLI?

  • Define what a CLI is.
  • Why prefer it on servers?

Source: class slides (History of the Command Line)

❓Your Answer

Homework 2, Q2: Command Syntax

  • Name a command's 3 parts.
  • Why does order matter?

Source: class slides (Command Syntax & Navigation)

❓Your Answer

Homework 2, Q3: Why /home Is Optional

  • Why is /home optional?
  • Why not assume a fixed path?

Read: page 10 (Section 3.8.1), FHS 3.0

❓Your Answer

Homework 2, Q4: What /tmp Guarantees

  • Can /tmp files persist?
  • Why does FHS require this?

Read: page 17 (Section 3.18.1), FHS 3.0

❓Your Answer

Homework 2, Q5: What Lives in /dev

  • What lives in /dev?
  • Name the 3 required devices.
  • What role does each play?

Read: page 7 (3.6.1) & page 39 (6.1.3), FHS 3.0

❓Your Answer

Homework 2, Q6: What Is /srv For?

  • What is /srv for?
  • Name an admin-context case.

Read: page 16 (Section 3.17.1), FHS 3.0

❓Your Answer

Homework 2, Q7: /usr Is Read-Only

  • What does read-only mean?
  • Why is /var split from /usr?

Read: page 18 (4.1) & page 30 (5.1), FHS 3.0

❓Your Answer

Homework 2, Q8: /usr vs. /usr/local

  • How do they differ?
  • Why must software go local?

Read: page 18 (4.2) & page 21 (4.9.1), FHS 3.0

❓Your Answer

Homework 2, Q9: What /boot Stores

  • What does /boot store?
  • Why ready before the kernel?

Read: page 7 (Section 3.5.1), FHS 3.0

❓Your Answer

Homework 2, Q10: /tmp vs. /var/tmp

  • What's the real difference?
  • When use each one?

Read: page 17 (3.18.1) & page 38 (5.15.1), FHS 3.0

❓Your Answer

Lab 2: Library Admin -- Setup

  • Kali = your workstation
  • Ubuntu VM = library server
  • Accts: athomas/pchen/rgarcia
  • Groups: circulation/cataloging
🏦Library Server

⚠️ Apple Silicon Macs: Kali's VirtualBox image is amd64-only and won't run there -- use a CTC 214 lab machine or UTM instead.

Recommended: VirtualBox with a Host-only adapter (so Kali and Ubuntu each get their own IP), not WSL2. Source: VirtualBox manual, Virtual Networking

Lab 2, Q1: Import the Kali VM

  • Download the Kali VM image.
  • Import it into VirtualBox.
# Deliverable: VirtualBox Manager # showing both Kali and Ubuntu
No screenshot submitted yet

Lab 2, Q2: Create the 3 Accounts

  • Create athomas.
  • Create pchen.
  • Create rgarcia.
$ sudo adduser athomas $ sudo adduser pchen $ sudo adduser rgarcia
No screenshot submitted yet

Lab 2, Q3: Create the 2 Groups

  • Create circulation-staff.
  • Create cataloging-staff.
$ sudo groupadd circulation-staff $ sudo groupadd cataloging-staff
No screenshot submitted yet

Lab 2, Q4: Assign Staff to Groups

  • Add athomas to circulation.
  • Add pchen to cataloging.
  • Add rgarcia to cataloging.
$ sudo usermod -aG circulation-staff athomas $ sudo usermod -aG cataloging-staff pchen $ sudo usermod -aG cataloging-staff rgarcia
No screenshot submitted yet

Lab 2, Q5: Give rgarcia Sudo

  • rgarcia leads Cataloging.
  • They need admin rights.
$ sudo usermod -aG sudo rgarcia $ groups rgarcia
No screenshot submitted yet

Lab 2, Q6: Secure Circulation

  • Create /srv/circulation.
  • Restrict it to the group.
$ sudo mkdir /srv/circulation $ sudo chgrp circulation-staff /srv/circulation $ sudo chmod 770 /srv/circulation $ ls -ld /srv/circulation
No screenshot submitted yet

Lab 2, Q7: Secure Cataloging

  • Create /srv/cataloging.
  • Owned by rgarcia's group.
$ sudo mkdir /srv/cataloging $ sudo chown rgarcia:cataloging-staff /srv/cataloging $ sudo chmod 770 /srv/cataloging $ ls -ld /srv/cataloging
No screenshot submitted yet

Lab 2, Q8: Clone Catalog Scripts

  • Clone the scripts repo.
  • Place it in Cataloging.
$ sudo apt install -y git $ cd /srv/cataloging $ git clone https://github.com/SE4CPS/2026-COMP-175.git
No screenshot submitted yet

Lab 2, Q9: pchen Searches Scripts

  • pchen finds the .py files.
  • Then greps them for isbn.
$ sudo apt install -y findutils grep $ su - pchen $ find /srv/cataloging -name "*.py" $ grep -ri "isbn" /srv/cataloging/2026-COMP-175/modules/module-3/catalog-scripts/*.py
No screenshot submitted yet

Lab 2, Q10: Enable SSH on Ubuntu

  • Install the SSH server.
  • Then start the service.
$ sudo apt install -y openssh-server $ sudo systemctl enable --now ssh
No screenshot submitted yet

Lab 2, Q11: Connect From Kali

  • athomas logs in remotely.
  • Then confirms their identity.
$ ssh athomas@<ubuntu-vm-IP> $ whoami $ groups
No screenshot submitted yet

Homework 3: AI Policy

  • Use AI to learn, not to answer
  • Write each answer yourself
  • Say if you used AI on it
  • Submitting: you understand all
End every answer with one line: AI used: No AI used: Yes, asked how -mtime counts days; wrote the answer myself

Modules 3 and 4: 10 questions each, 5 conceptual and 5 practical

Homework 3, Q1: What Is an Inode?

  • What does an inode store?
  • What does it not store?
  • Why can data outlive a name?

Source: class slides (Module 3)

Answer
Stores metadata (owner, perms, size, timestamps, block locations), not the filename. The name lives in a directory entry. Data survives if a hard link or open handle still references the inode.

Homework 3, Q2: Symlink vs. Hard Link

  • Compare the two link types.
  • The original file is deleted.
  • What happens to each link?

Source: class slides (Module 3)

Answer
Hard link: another name for the same inode; still works after the original name is deleted. Symlink: a stored path to the original; becomes broken once the original is deleted.

Homework 3, Q3: Everything Is a File

  • What does the phrase mean?
  • Give 2 non-document examples
  • Why does it help an admin?

Source: class slides (Module 3)

Answer
/dev/null (a device) and /proc/cpuinfo (kernel info) are both accessed as files. This lets an admin use the same commands and permissions model to manage very different system resources.

Homework 3, Q4: x on Directory vs. File

  • What does x mean on a folder?
  • What does x mean on a file?
  • How do the two differ?

Source: class slides (Module 3)

Answer
On a directory: x lets you traverse/enter it (access a known item by name), but not by itself list its contents. On a file: x lets you execute it as a program or script.

Homework 3, Q5: setgid and Sticky Bit

  • Folders set to 2770 and 3770
  • What does setgid add?
  • What does sticky add?
  • Why do both help sharing?

Source: class slides (Module 3)

Answer
Both give owner+group rwx, others none. setgid (2770): new files inherit the folder's group. Sticky (added in 3770): only the owner or root can delete/rename another member's files.

Homework 3, Q6: Find Old Files

  • Look in /srv/library
  • Regular files only
  • Not modified in 6 months
  • Explain the number you used

Source: class slides (Module 3)

Answer
find /srv/library -type f -mtime +180. -type f selects regular files; 180 approximates 6 months in days.

Homework 3, Q7: Create a Team Folder

  • Create /srv/team
  • Only group team gets access
  • Group can read, write, enter
  • New files inherit the group

Source: class slides (Module 3)

Answer
sudo mkdir -p /srv/team; sudo chown root:team /srv/team; sudo chmod 2770 /srv/team. Owner+group rwx, others none, setgid for group inheritance.

Homework 3, Q8: Disk Usage

  • Which disk holds /srv?
  • How full is that disk?
  • Use human-readable sizes

Source: class slides (Module 3)

Answer
df -h /srv

Homework 3, Q9: Links to report.txt

  • Make one symbolic link
  • Make one hard link
  • Show proof of shared inode

Source: class slides (Module 3)

Answer
ln -s report.txt report-symbolic.txt; ln report.txt report-hard.txt; ls -li report.txt report-hard.txt. Matching inode numbers prove the hard link shares the inode.

Homework 3, Q10: Add a User to a Group

  • Add dana to group library
  • Keep her other groups
  • Then verify her group list

Source: class slides (Module 3)

Answer
sudo usermod -aG library dana; id -nG dana. -aG appends without removing her existing groups.

Homework 3, Q11: DAC, RBAC and MAC

  • Define each in one sentence
  • Which one is chmod?
  • Why can root be denied?

Source: class slides (Module 4)

Answer
DAC: owner decides access. RBAC: access depends on assigned role. MAC: a system-wide policy controls access. chmod = DAC. Root can still be denied under MAC since it's enforced independent of DAC ownership.

Homework 3, Q12: Least Privilege

  • What is least privilege?
  • One sudoers script vs. ALL
  • Why is one script safer?

Source: class slides (Module 4)

Answer
Grant only the access needed for the job. One script in sudoers limits what can run as root; ALL lets any command run as root, so a mistake or compromise can affect the whole system.

Homework 3, Q13: AAA in Practice

  • Authentication, authorization
  • and accounting: real examples
  • If one is absent, what's lost?

Source: class slides (Module 4)

Answer
Authentication: an SSH login, in /var/log/auth.log. Authorization: a sudoers rule. Accounting: the sudo log entry. Missing one leaves no record of who connected, what was allowed, or what was done.

Homework 3, Q14: inotifywait Log Lines

  • What can a log line tell you?
  • What can it not tell you?
  • Give 2 limits that matter

Source: class slides (Module 4)

Answer
Shows the watched path, event type, and (if configured) a timestamp. It does NOT show who or which process caused it, and can miss events from unwatched paths, downtime, or queue overflow.

Homework 3, Q15: The ACL Mask

  • What is the ACL mask?
  • How can it cancel a grant?

Source: class slides (Module 4)

Answer
Caps the effective permissions for named users/groups and the owning group (not the owner or other). A setfacl grant can be silently reduced by the mask; getfacl shows the actual effective permission.

Homework 3, Q16: Read-Only ACL

  • morgan gets read-only access
  • to /srv/registrar/grades.csv
  • Owner, group, mode unchanged
  • Then show the confirming cmd

Source: class slides (Module 4)

Answer
sudo setfacl -n -m u:morgan:r-- /srv/registrar/grades.csv; getfacl /srv/registrar/grades.csv

Homework 3, Q17: Limited sudo

  • Group registrar runs one cmd
  • Only /usr/local/bin/backup.sh
  • Write the sudoers line
  • Name the safe way to edit it
  • Explain each part of the line

Source: class slides (Module 4)

Answer
%registrar ALL=(root) /usr/local/bin/backup.sh "", edited with sudo visudo. Group; any host; run as root; this script only; no arguments allowed.

Homework 3, Q18: Watch and Log

  • Watch /srv/registrar
  • Events: create, modify, delete
  • Log: /tmp/registrar-watch.log
  • Keep running after logout
  • List only grades.csv events

Source: class slides (Module 4)

Answer
nohup inotifywait -m -r -e create,modify,delete --format '%T %e %w%f' /srv/registrar > /tmp/registrar-watch.log 2>&1 < /dev/null &
then: grep grades.csv /tmp/registrar-watch.log

Homework 3, Q19: Logins and sudo Rights

  • (a) Who is logged in now,
  • and what are they running?
  • (b) What can dana run as sudo?

Source: class slides (Module 4)

Answer
(a) w (b) sudo -l -U dana

Homework 3, Q20: Remove an ACL Entry

  • Remove morgan's ACL entry
  • From /srv/registrar/grades.csv
  • Show a command proving it

Source: class slides (Module 4)

Answer
sudo setfacl -x u:morgan /srv/registrar/grades.csv; getfacl /srv/registrar/grades.csv to confirm it's gone.

Lab 3: Registrar Server Setup

  • Kali = admin workstation
  • Ubuntu VM = registrar server
  • Roles: CLERK, LEAD, AUDITOR
  • Groups: registrars/auditors
  • No CLI editor: use cat to edit
  • Show your prompt in each shot
  • State AI use on each answer
Kali admin ssh Ubuntu: /srv/registrar grades.csv archive/ reports/ shared/ dropbox/ public/

Lab 3, Q1: Get the Lab Setup

  • Clone or pull the course repo
  • Run lab3/setup.sh with sudo
  • Find CLERK, LEAD, AUDITOR
$ sudo apt install -y git $ git clone \ https://github.com/SE4CPS/2026-COMP-175.git \ ~/2026-COMP-175 $ git -C ~/2026-COMP-175 pull $ sudo bash \ ~/2026-COMP-175/modules/module-5/lab3/setup.sh # it asks for a password: answer it, then run the rest $ getent group registrars auditors $ ls -l /srv/registrar

Evidence

  • SETUP OK line and Ubuntu IP
  • getent group: the 3 accounts
  • ls -l /srv/registrar

Screenshot from: Ubuntu VM

Lab 3, Q2: Find Stale Files

  • Find files older than 180 days
  • Regular files, all subfolders
  • Save list, count, add sizes
$ sudo find /srv/registrar/archive \ -type f -mtime +180 \ -printf '%s %TY-%Tm-%Td %p\n' \ > ~/stale.txt $ cat ~/stale.txt $ wc -l < ~/stale.txt $ awk '{s+=$1} END {print s}' ~/stale.txt

Evidence

  • stale.txt: size, date, path
  • The file count
  • Total bytes of those files
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q3: Links and Inodes

  • Symlink + hard link as CLERK
  • Compare inodes and link counts
  • Delete original, cat both
$ cd /srv/registrar/reports $ sudo -u CLERK ln -s summary.txt summary-sym.txt $ sudo -u CLERK ln summary.txt summary-hard.txt $ ls -li $ sudo -u CLERK rm summary.txt $ ls -li $ cat summary-hard.txt summary-sym.txt

Evidence

  • ls -li before the delete
  • ls -li and cat after
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q4: Shared and Drop Folders

  • shared/: test, then set 2770
  • dropbox/: sticky bit, 1777
  • CLERK can't rm LEAD's file
$ sudo -u CLERK touch /srv/registrar/shared/before.txt $ sudo chmod 2770 /srv/registrar/shared $ sudo -u CLERK touch /srv/registrar/shared/after.txt $ sudo ls -l /srv/registrar/shared $ sudo chmod 1777 /srv/registrar/dropbox $ sudo -u LEAD touch /srv/registrar/dropbox/lead.txt $ sudo -u CLERK rm /srv/registrar/dropbox/lead.txt $ ls -ld /srv/registrar/shared /srv/registrar/dropbox

Evidence

  • Group before and after 2770
  • The rm error message
  • ls -ld on both folders
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q5: ACL and the Mask

  • AUDITOR denied, then granted
  • Owner, group, mode unchanged
  • Mask --- cancels the grant
$ sudo -u AUDITOR cat /srv/registrar/grades.csv $ sudo setfacl -m u:AUDITOR:r-- \ /srv/registrar/grades.csv $ sudo -u AUDITOR cat /srv/registrar/grades.csv $ getfacl /srv/registrar/grades.csv $ ls -l /srv/registrar/grades.csv $ sudo setfacl -m m::--- /srv/registrar/grades.csv $ getfacl /srv/registrar/grades.csv $ sudo -u AUDITOR cat /srv/registrar/grades.csv $ sudo setfacl -m m::r-- /srv/registrar/grades.csv $ sudo -u AUDITOR cat /srv/registrar/grades.csv

Evidence

  • cat result at each step
  • getfacl with #effective
  • ls -l showing the +
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q6: One-Script sudo

  • Group registrars: one script
  • Write with cat, check, install
  • CLERK: script ok, cat denied
$ sudo rm -f /tmp/90-registrar-backup $ cat > /tmp/90-registrar-backup <<'EOF' %registrars ALL=(root) /usr/local/bin/backup-grades.sh EOF $ cat /tmp/90-registrar-backup $ sudo visudo -cf /tmp/90-registrar-backup $ sudo install -m 0440 \ /tmp/90-registrar-backup \ /etc/sudoers.d/90-registrar-backup $ sudo cat /etc/sudoers.d/90-registrar-backup $ sudo visudo -c # su asks for a password: run the rest one line at a time $ su - CLERK $ sudo -l $ sudo /usr/local/bin/backup-grades.sh $ sudo cat /etc/shadow $ exit

Evidence

  • The sudoers.d file contents
  • visudo -c says parsed OK
  • sudo -l, run, and the denial
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q7: Watch and Log

  • Watch the tree, log with time
  • Keep it running after logout
  • Cause 3 events as 2 users
$ sudo nohup inotifywait -m -r \ -e create,modify,delete \ --timefmt '%F %T' \ --format '%T %w%f %e' \ /srv/registrar \ >> /tmp/registrar-watch.log 2>&1 & $ sudo -u LEAD sh -c \ 'cat >> /srv/registrar/grades.csv' \ <<'EOF' 1006,COMP-175,A EOF $ sudo -u CLERK touch /srv/registrar/reports/tmp.txt $ sudo -u CLERK rm /srv/registrar/reports/tmp.txt $ cat /tmp/registrar-watch.log $ pgrep -a inotifywait

Evidence

  • Log lines with time stamps
  • CREATE, MODIFY, DELETE shown
  • pgrep shows the watcher
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q8: Runaway Process

  • CLERK runs the report job
  • Find it, renice it to 19
  • AUDITOR can't kill; CLERK can
$ sudo -u CLERK nohup \ /opt/registrar/report-job.sh \ > /dev/null 2>&1 & $ ps -o pid,ni,pcpu,user,cmd -u CLERK $ sudo renice -n 19 -p PID $ ps -o pid,ni,pcpu,user,cmd -p PID $ sudo -u AUDITOR kill PID $ sudo -u CLERK kill PID $ pgrep -af report-job.sh

Evidence

  • ps before and after renice
  • The kill denied message
  • pgrep shows it is gone
  • A # comment explaining it

Screenshot from: Ubuntu VM

Lab 3, Q9: SSH Keys From Kali

  • Kali: key, copy, log in
  • Ubuntu: passwords off
  • Kali: password login fails
# Kali $ ssh-keygen -t ed25519 $ ssh-copy-id LEAD@UBUNTU_IP $ eval "$(ssh-agent -s)" $ ssh-add $ ssh LEAD@UBUNTU_IP 'hostname; whoami' # Ubuntu (keep a 2nd session open) $ cat > /tmp/10-lab.conf <<'EOF' PasswordAuthentication no PermitRootLogin no EOF $ sudo install -m 0644 /tmp/10-lab.conf \ /etc/ssh/sshd_config.d/10-lab.conf $ sudo sshd -t $ sudo systemctl reload ssh $ sudo sshd -T | grep -Ei '^(password|permitroot)' # Kali again $ ssh -o PubkeyAuthentication=no \ LEAD@UBUNTU_IP

Evidence

  • Kali: key login, hostname
  • Kali: Permission denied line
  • Ubuntu: sshd -T settings
  • A # comment explaining it

Screenshot from: Kali and Ubuntu

Lab 3, Q10: Tunnel to a Local Page

  • Ubuntu: serve public/ on 8000
  • Kali: direct curl must fail
  • Kali: tunnel, then curl 9000
# Ubuntu $ python3 -m http.server 8000 \ --bind 127.0.0.1 \ --directory /srv/registrar/public & $ sudo ss -tlnp | grep 8000 # Kali $ curl -m 5 http://UBUNTU_IP:8000 $ ssh -N -L 9000:localhost:8000 \ LEAD@UBUNTU_IP # a 2nd Kali terminal $ curl http://localhost:9000

Evidence

  • Ubuntu: ss shows 127.0.0.1
  • Kali: failed direct curl
  • Kali: page text via tunnel
  • A # comment explaining it

Screenshot from: Kali and Ubuntu

Homework 4: AI Policy

  • Use AI to learn, not to answer
  • Write each answer yourself
  • Say if you used AI on it
  • Submitting: you understand all
End every answer with one line: AI used: No AI used: Yes, asked how -mtime counts days; wrote the answer myself

Modules 5 and 6: 5 conceptual questions each, no code required

Homework 4, Q1: Process vs. Program

  • What is a program, on disk?
  • What is a process, once run?
  • Use a car diagnostic scan as the example

Source: class slides (Module 5)

❓Your Answer

Homework 4, Q2: One-Time vs. Live View

  • Compare ps and top.
  • ps: a snapshot. top: live.
  • When use top during a test?

Source: class slides (Module 5)

❓Your Answer

Homework 4, Q3: Foreground vs. Background

  • What can a bg job let you do?
  • Why background the logger?
  • What does jobs show you?

Source: class slides (Module 5)

❓Your Answer

Homework 4, Q4: Why Lower a Job’s Priority?

  • What does nice change?
  • Why lower its priority
  • during a real-time dyno test?

Source: class slides (Module 5)

❓Your Answer

Homework 4, Q5: Why Keys Beat Passwords

  • Why is key-based SSH stronger?
  • What is the public key for?
  • What is the private key for?

Source: class slides (Module 5)

❓Your Answer

Homework 4, Q6: Starting vs. Enabling

  • What does starting it do?
  • What does enabling it add?
  • Why enable it too?

Source: class slides (Module 6)

❓Your Answer

Homework 4, Q7: Timer or Plain Cron?

  • What can a systemd timer do
  • that plain cron cannot?
  • When would a shop prefer each?

Source: class slides (Module 6)

❓Your Answer

Homework 4, Q8: Why Restart=on-failure?

  • What does this setting do?
  • It watches a sensor
  • that can disconnect sometimes

Source: class slides (Module 6)

❓Your Answer

Homework 4, Q9: Five Fields, One Real Job

  • Name cron’s five time fields
  • Check tires every 15 min
  • Write the full crontab line

Source: class slides (Module 6)

❓Your Answer

Homework 4, Q10: Why Cron Needs Full Paths

  • Why does cron need full paths?
  • Using a relative path instead
  • What mistake could that cause?

Source: class slides (Module 6)

❓Your Answer

Lab 4: Shop Diagnostics Server

  • Kali = admin workstation
  • Ubuntu VM = diagnostics server
  • All of Q2–Q10 run over SSH
  • Show your prompt in each shot
  • State AI use on each answer
Kali admin ssh Ubuntu: diagnostics engine-scan.sh telemetry-logger.sh dyno-test.sh dyno-monitor.sh oil-check.sh engine-samples.csv

Lab 4, Q1: SSH In & Get the Files

  • SSH from Kali into Ubuntu
  • Rest of lab runs on Ubuntu
  • Clone repo, chmod the scripts
# from Kali $ ssh USER@UBUNTU_IP # now on Ubuntu: $ git clone \ https://github.com/SE4CPS/2026-COMP-175.git $ cd 2026-COMP-175/modules/homework-4 $ chmod +x *.sh $ ls

Evidence

  • Kali prompt, then ssh
  • The Ubuntu prompt after login
  • ls showing .sh files, csv

Screenshot from: Kali and Ubuntu

Lab 4, Q2: Run and Identify a Process

  • Run engine-scan.sh (fg)
  • In a 2nd shell, find its PID
  • Use pgrep, not ps | grep
$ ./engine-scan.sh # in a second ssh session to Ubuntu: $ pgrep -f engine-scan.sh

Evidence

  • The scan’s RPM/temp output
  • pgrep showing a real PID

Screenshot from: Kali and Ubuntu

Lab 4, Q3: Background, Confirm, Foreground

  • Start the logger in the bg
  • Confirm it’s running with jobs
  • Bring to fg, then stop it
$ ./telemetry-logger.sh & $ jobs $ fg # Ctrl+C to stop it

Evidence

  • jobs shows the logger
  • Prompt after fg, then Ctrl+C

Screenshot from: Kali and Ubuntu

Lab 4, Q4: Stop a Running Job

  • Start dyno-test.sh in the bg
  • Find its PID, send it SIGTERM
  • Confirm the process is gone
$ ./dyno-test.sh & $ pgrep -f dyno-test.sh $ kill PID $ pgrep -f dyno-test.sh # no output: it is gone

Evidence

  • pgrep finding the PID
  • pgrep again: no output now

Screenshot from: Kali and Ubuntu

Lab 4, Q5: A Lower-Priority Background Job

  • Start the logger with nice
  • Use nice -n 10
  • Confirm the NI column with ps
$ nice -n 10 ./telemetry-logger.sh & $ pgrep -f telemetry-logger.sh $ ps -o pid,ni -p PID

Evidence

  • The nice command you ran
  • ps showing NI = 10

Screenshot from: Kali and Ubuntu

Lab 4, Q6: Write and Start a Service

  • Write dyno-monitor.service
  • ExecStart runs dyno-monitor.sh
  • daemon-reload, enable --now
$ sudo tee /etc/systemd/system/dyno-monitor.service \ > /dev/null << 'EOF' [Unit] Description=Dyno sensor monitor [Service] ExecStart=/home/USER/2026-COMP-175/modules/homework-4/dyno-monitor.sh Restart=on-failure [Install] WantedBy=multi-user.target EOF $ sudo systemctl daemon-reload $ sudo systemctl enable --now dyno-monitor

Evidence

  • systemctl status dyno-monitor
  • active (running) and enabled

Screenshot from: Kali and Ubuntu

Lab 4, Q7: Kill It, Watch It Return

  • Find the service’s Main PID
  • Kill it with -s KILL
  • Show NRestarts went up
$ systemctl status dyno-monitor | head -4 $ sudo systemctl kill -s KILL dyno-monitor $ systemctl show dyno-monitor -p NRestarts

Evidence

  • The Main PID before the kill
  • NRestarts=1 (or higher) after

Screenshot from: Kali and Ubuntu

Lab 4, Q8: Schedule the Oil Check

  • Add a crontab line for it
  • Every 2 min: checkable now
  • Real shop: 0 6 * * * instead
$ crontab -e # add this line, then save: */2 * * * * /home/USER/2026-COMP-175/\ modules/homework-4/oil-check.sh $ crontab -l # wait 2+ minutes, then: $ cat /tmp/oil-check.log

Evidence

  • crontab -l showing the line
  • Log with 2+ timestamped rows

Screenshot from: Kali and Ubuntu

Lab 4, Q9: Read the Service Log

  • Use journalctl on dyno-monitor
  • Show only the last 5 lines
  • Name the flags you used
$ journalctl -u dyno-monitor -n 5

Evidence

  • The last 5 journal lines

Screenshot from: Kali and Ubuntu

Lab 4, Q10: Clean Up

  • Disable and stop the service
  • Remove the unit file, reload
  • Remove the crontab line
$ sudo systemctl disable --now dyno-monitor $ sudo rm /etc/systemd/system/dyno-monitor.service $ sudo systemctl daemon-reload $ crontab -r

Evidence

  • is-enabled now fails (gone)
  • crontab -l: no crontab for you

Screenshot from: Kali and Ubuntu

Deliverable

  • 10 screenshots, one per Q
  • Show your prompt in each shot
  • One sentence: enable vs. start
  • State AI use on each answer

Questions?

Homework 5: AI Policy

  • Use AI to learn, not to answer
  • Write each answer yourself
  • Say if you used AI on it
  • Submitting: you understand all
End every answer with one line: AI used: No AI used: Yes, asked how -mtime counts days; wrote the answer myself

Modules 7 and 8: 5 conceptual questions each, no code required

Homework 5, Q1: Static vs. DHCP

  • Static vs. DHCP, in short?
  • Does it survive a reboot?
  • Why pick static for a server?

Source: class slides (Module 7)

❓Your Answer

Homework 5, Q2: ip addr vs. ip route

  • What does ip addr show?
  • What does ip route add on top?
  • Which one names the gateway?

Source: class slides (Module 7)

❓Your Answer

Homework 5, Q3: Reading traceroute

  • Why multiple hops, not one?
  • What does a hop represent?
  • Why might a hop show stars?

Source: class slides (Module 7)

❓Your Answer

Homework 5, Q4: TCP vs. UDP

  • Name one real difference.
  • Which one guarantees delivery?
  • Why would DNS still use UDP?

Source: class slides (Module 7)

❓Your Answer

Homework 5, Q5: What DNS Translates

  • A name becomes what, exactly?
  • Why not just use IPs directly?
  • Where is that mapping stored?

Source: class slides (Module 8)

❓Your Answer

Homework 5, Q6: A Record vs. CNAME

  • What does an A record point to
  • What does a CNAME point to?
  • Why use a CNAME at all?

Source: class slides (Module 8)

❓Your Answer

Homework 5, Q7: The TLS Handshake

  • What gets agreed on first?
  • Why exchange a cert at all?
  • What happens after success?

Source: class slides (Module 8)

❓Your Answer

Homework 5, Q8: Why Verify the Chain

  • What is a certificate chain?
  • Why not just trust any cert?
  • What breaks if chain is bad?

Source: class slides (Module 8)

❓Your Answer

Homework 5, Q9: curl -v vs. plain curl

  • What extra does -v reveal?
  • Why would that matter here?
  • When would you skip -v?

Source: class slides (Module 8)

❓Your Answer

Homework 5, Q10: Why a Certificate at All

  • Encryption alone proves what?
  • What does the cert add on top?
  • Who signs a real certificate?

Source: class slides (Module 8)

❓Your Answer

Lab 5: Network & Secure Transport Audit

  • Kali = admin workstation
  • Ubuntu VM = web server
  • Q2–Q10 all run over SSH
  • Show your prompt in each shot
  • State AI use on each answer
Kali admin ssh Ubuntu: web server netplan config self-signed cert nginx :443

Lab 5, Q1: SSH In

  • SSH from Kali into Ubuntu
  • Rest of lab runs on Ubuntu
  • No repo to clone, commands only
# from Kali $ ssh USER@UBUNTU_IP # now on Ubuntu, continue below

Evidence

  • Kali prompt, then ssh
  • The Ubuntu prompt after login

Screenshot from: Kali and Ubuntu

Lab 5, Q2: Confirm the Current IP

  • Run ip addr on the VM
  • Find the real interface name
  • Note the current IPv4 address
$ ip addr

Evidence

  • Full ip addr output
  • The interface and IPv4 circled

Screenshot from: Ubuntu

Lab 5, Q3: Find the Default Gateway

  • Run ip route
  • Identify the default line
  • Note the gateway address
$ ip route

Evidence

  • Full ip route output
  • default line visible

Screenshot from: Ubuntu

Lab 5, Q4: Trace the Path Out

  • Run traceroute to a real host
  • Count the hops shown
$ traceroute 8.8.8.8

Evidence

  • Full traceroute output
  • Hop count visible

Screenshot from: Ubuntu

Lab 5, Q5: Look Up an A Record

  • Use dig for a real domain
  • Find the A record in ANSWER
$ dig pacific.edu

Evidence

  • Full dig output
  • ANSWER section circled

Screenshot from: Ubuntu

Lab 5, Q6: Look Up a CNAME

  • Pick a domain with a CNAME
  • Compare it to Q5's A record
$ dig www.github.com

Evidence

  • CNAME record visible
  • Compare to the A record

Screenshot from: Ubuntu

Lab 5, Q7: Start a Test HTTPS Service

  • Install and start nginx
  • Confirm it's listening on 443
$ sudo apt install -y nginx $ ss -tlnp | grep 443

Evidence

  • nginx install output
  • ss showing port 443 open

Screenshot from: Ubuntu

Lab 5, Q8: Inspect the Certificate

  • Use openssl s_client
  • Find the cert subject line
$ openssl s_client -connect localhost:443

Evidence

  • Full openssl output
  • Certificate subject circled

Screenshot from: Ubuntu

Lab 5, Q9: Verify with curl -v

  • Use curl -v against localhost
  • Find the TLS handshake lines
$ curl -vk https://localhost

Evidence

  • Full curl -v output
  • TLS handshake lines circled

Screenshot from: Ubuntu

Lab 5, Q10: Summarize the Audit

  • One command, one combined file
  • Confirms IP, route, and cert
$ { ip addr; ip route; } > audit.txt $ cat audit.txt

Evidence

  • Full audit.txt contents
  • All three sections present

Screenshot from: Ubuntu

Homework 6: AI Policy

  • Use AI to learn, not to answer
  • Write each answer yourself
  • Say if you used AI on it
  • Submitting: you understand all
End every answer with one line: AI used: No AI used: Yes, asked how -mtime counts days; wrote the answer myself

Modules 9 and 10: 5 conceptual questions each, no code required

Homework 6, Q1: Why Rotate Logs?

  • What if logs never rotate?
  • What does logrotate -d show?
  • Why -d before a real run?

Source: class slides (Module 9)

❓Your Answer

Homework 6, Q2: What fail2ban Does

  • What does it actually watch?
  • What action does it take?
  • Why ban, not just log it?

Source: class slides (Module 9)

❓Your Answer

Homework 6, Q3: Why Check auth.log?

  • What does auth.log record?
  • Why grep it, not read it all?
  • What pattern signals attack?

Source: class slides (Module 9)

❓Your Answer

Homework 6, Q4: Install, Then Verify

  • Why check status post-install?
  • What does active mean here?
  • What if it failed silently?

Source: class slides (Module 9)

❓Your Answer

Homework 6, Q5: fail2ban-client status

  • What does status alone show?
  • What does status sshd add?
  • Why check a specific jail?

Source: class slides (Module 9)

❓Your Answer

Homework 6, Q6: date vs. timedatectl

  • What does date alone show?
  • What does timedatectl add?
  • When would you need both?

Source: class slides (Module 10)

❓Your Answer

Homework 6, Q7: Why chrony Matters

  • What if the clock drifts?
  • How does chrony fix it?
  • Why does this matter for logs?

Source: class slides (Module 10)

❓Your Answer

Homework 6, Q8: NTP Stratum, Briefly

  • What is stratum 0?
  • Why is your VM not stratum 0?
  • Why does the chain exist?

Source: class slides (Module 10)

❓Your Answer

Homework 6, Q9: Compare Logs Across Hosts

  • Why sync time, then compare?
  • What goes wrong if you don't?
  • Which command confirms sync?

Source: class slides (Module 10)

❓Your Answer

Homework 6, Q10: A Cert Checked at the Wrong Time

  • What does a cert check need?
  • What if the clock is wrong?
  • Which module explains why?

Source: class slides (Module 10)

❓Your Answer

Homework 7: AI Policy

  • Use AI to learn, not to answer
  • Write each answer yourself
  • Say if you used AI on it
  • Submitting: you understand all
End every answer with one line: AI used: No AI used: Yes, asked how $? differs from $1; wrote the answer myself

Modules 11 and 12: 5 conceptual questions each, no code required

Homework 7, Q1: The Shebang Line

  • What does #!/bin/bash do?
  • Why must it be the first line?
  • What happens without it?

Source: class slides (Module 11)

❓Your Answer

Homework 7, Q2: Make It Executable

  • What does chmod +x grant?
  • Why won't ./script.sh run?
  • What error appears instead?

Source: class slides (Module 11)

❓Your Answer

Homework 7, Q3: read: Ask the User

  • What does read -p do?
  • Where does the input go?
  • Why pause for input at all?

Source: class slides (Module 11)

❓Your Answer

Homework 7, Q4: for vs. while

  • When does for fit better?
  • When does while read fit?
  • What's the key difference?

Source: class slides (Module 11)

❓Your Answer

Homework 7, Q5: shellcheck: Catch Mistakes

  • What does shellcheck check?
  • Why run it before scheduling?
  • Is it installed by default?

Source: class slides (Module 11)

❓Your Answer

Homework 7, Q6: Three Built-In Chains

  • What does INPUT chain cover?
  • What does FORWARD chain cover?
  • Which chain covers replies?

Source: class slides (Module 12)

❓Your Answer

Homework 7, Q7: Stateful: Remembers Flows

  • What does ESTABLISHED mean?
  • What does NEW mean?
  • Why track state at all?

Source: class slides (Module 12)

❓Your Answer

Homework 7, Q8: Not Saved by Default

  • What happens on reboot?
  • What package saves them?
  • Why does this trip people up?

Source: class slides (Module 12)

❓Your Answer

Homework 7, Q9: iptables vs. nftables

  • What replaced iptables?
  • Why still teach iptables too?
  • What does nftables unify?

Source: class slides (Module 12)

❓Your Answer

Homework 7, Q10: DMZ: A Buffer Zone

  • What sits inside a DMZ?
  • Why isolate it from internal?
  • What if the DMZ is breached?

Source: class slides (Module 12)

❓Your Answer

Lab 6: Automated Monitoring Setup

  • Reuses Lab 5's Ubuntu VM
  • Adds logging and time sync
  • Q2–Q10 all run over SSH
  • Show your prompt in each shot
  • State AI use on each answer
Kali admin ssh Ubuntu: monitored /var/log/auth.log fail2ban jail: sshd chrony: synced

Lab 6, Q1: SSH In, Confirm the Server

  • Reuses Lab 5's Ubuntu VM
  • No new setup needed here
# from Kali $ ssh USER@UBUNTU_IP $ hostnamectl

Evidence

  • Kali prompt, then ssh
  • hostnamectl output

Screenshot from: Kali and Ubuntu

Lab 6, Q2: Install fail2ban

  • Not installed by default
  • Confirm the package landed
$ sudo apt install -y fail2ban $ dpkg -l | grep fail2ban

Evidence

  • Install output
  • dpkg confirming it's present

Screenshot from: Ubuntu

Lab 6, Q3: Check the sshd Jail

  • Confirm the service is active
  • Then check the sshd jail
$ sudo systemctl status fail2ban $ sudo fail2ban-client status sshd

Evidence

  • systemctl: active (running)
  • Jail status output

Screenshot from: Ubuntu

Lab 6, Q4: Preview Log Rotation

  • -d: preview, not a real run
$ sudo logrotate -d /etc/logrotate.conf

Evidence

  • Full preview output

Screenshot from: Ubuntu

Lab 6, Q5: Search auth.log

  • grep for failed logins
$ sudo grep "Failed password" /var/log/auth.log

Evidence

  • Matching lines, or none found

Screenshot from: Ubuntu

Lab 6, Q6: Check the Current Time

  • Plain date first
  • Then the full timedatectl view
$ date $ timedatectl

Evidence

  • date output
  • timedatectl full output

Screenshot from: Ubuntu

Lab 6, Q7: Confirm chrony Is Synced

  • Install if missing, then check
$ sudo apt install -y chrony $ chronyc tracking

Evidence

  • chronyc tracking output
  • System time offset visible

Screenshot from: Ubuntu

Lab 6, Q8: Check the Trusted Source

  • Look for the * marker
$ chronyc sources

Evidence

  • sources output
  • * on the trusted line

Screenshot from: Ubuntu

Lab 6, Q9: Read the Hardware Clock

  • Compare it to the system clock
$ sudo hwclock --show

Evidence

  • hwclock output

Screenshot from: Ubuntu

Lab 6, Q10: Write the Summary Report

  • One file, all four checks
$ { date; chronyc tracking; \ sudo fail2ban-client status sshd; } \ > monitor-report.txt $ cat monitor-report.txt

Evidence

  • Full report.txt contents

Screenshot from: Ubuntu

Lab 7: Script It, Then Firewall It

  • Reuses Lab 6's Ubuntu VM
  • Write, test, run a script
  • Q6–Q10 all run over SSH
  • Show your prompt in each shot
  • State AI use on each answer
Kali admin ssh Ubuntu: target backup.sh crontab: nightly iptables: port 8080

Lab 7, Q1: SSH In, Confirm the Server

  • Reuses Lab 6's Ubuntu VM
  • No new setup needed here
# from Kali $ ssh USER@UBUNTU_IP $ hostnamectl

Evidence

  • Kali prompt, then ssh
  • hostnamectl output

Screenshot from: Kali and Ubuntu

Lab 7, Q2: Write the Backup Script

  • Shebang, then exits if missing
  • No editor: cat with a heredoc
$ cat > backup.sh <<'EOF' #!/bin/bash if [[ ! -d /srv/registrar ]]; then echo "Source missing, exiting" exit 1 fi cp -r /srv/registrar /backups/ echo "Backed up on $(date)" >> backup.log EOF $ cat backup.sh

Evidence

  • The heredoc command
  • cat showing the saved file

Screenshot from: Ubuntu

Lab 7, Q3: Make It Executable & Test

  • Grant run permission
  • Test it once by hand first
$ chmod +x backup.sh $ ./backup.sh $ cat backup.log

Evidence

  • chmod and the run
  • backup.log's new line

Screenshot from: Ubuntu

Lab 7, Q4: Schedule With cron

  • Reuses Module 6's own crontab
  • Runs every night at 2 AM
$ crontab -l $ (crontab -l; echo "0 2 * * * $(pwd)/backup.sh") | crontab - $ crontab -l

Evidence

  • crontab -l before and after
  • Your new line, in the list

Screenshot from: Ubuntu

Lab 7, Q5: Lint It With shellcheck

  • Not installed by default
  • Confirm it runs clean
$ sudo apt install -y shellcheck $ shellcheck backup.sh

Evidence

  • Install output
  • shellcheck's real result

Screenshot from: Ubuntu

Lab 7, Q6: View Current iptables Rules

  • -L lists rules per chain
  • -v adds packet/byte counts
$ sudo iptables -L -v

Evidence

  • Full -L -v output

Screenshot from: Ubuntu

Lab 7, Q7: Add a Rule for Port 8080

  • -A appends to the chain
  • -j ACCEPT is the action
$ sudo iptables -A INPUT -p tcp \ --dport 8080 -j ACCEPT $ sudo iptables -L -v

Evidence

  • The new rule, in the list

Screenshot from: Ubuntu

Lab 7, Q8: Make Rules Survive Reboot

  • A reboot wipes them otherwise
  • This package saves them
$ sudo apt install -y iptables-persistent

Evidence

  • Install and save prompt

Screenshot from: Ubuntu

Lab 7, Q9: List the Same Rules via nftables

  • nftables now holds the engine
  • Confirm the 8080 rule shows up
$ sudo nft list ruleset

Evidence

  • Full ruleset output

Screenshot from: Ubuntu

Lab 7, Q10: Write the Summary Report

  • One file, both checks
$ { cat backup.log; \ sudo iptables -L -v; } \ > lab7-report.txt $ cat lab7-report.txt

Evidence

  • Full lab7-report.txt contents

Screenshot from: Ubuntu

Project Part 1

  • Individual project
  • 4 weeks, 100 points
  • Due Oct 22 (Pacific)
  • Covers Modules 1-6
admin-ws(Kali)SSHhospital-records(Ubuntu)

What You'll Do

  • Harden the Ubuntu server
  • Onboard & offboard users
  • Attack it from Kali
  • Free AI tool assists you
  • Fix what you find
AdministerModules 2-4AttackKali + free AI toolFix & ReportModules 2-4, again

Deliverables & Bounty

  • Slide deck (with evidence)
  • 2-3 page PDF report
  • AI use disclosure needed
  • Bonus: find the bounty flag

Full instructions: Canvas

AI tool: ai.ecs.stk.pacific.edu

🚩The Bounty

Project Part 1: Review

Q1: VMs & Network

What did you build: which two VMs, and how are they networked?

I used two personal VirtualBox VMs: admin-ws (Kali) as the admin workstation, and hospital-records (Ubuntu) as the server. They communicate on an isolated host-only network, never bridged, with no real patient data.

Q2: Records Permissions

What permission changes did you make on the records directory and files, and why?

Permission changes applied:

sudo chown root:hospital \ /srv/hospital-records # sets owner=root, group=hospital sudo chmod 750 /srv/hospital-records # rwx owner, r-x group, none else sudo chmod 640 \ /srv/hospital-records/*.csv # rw- owner, r-- group, none else

Why: so only the hospital group can read the records, and no one else has any access.

Q3: Accounts & Roles

Which accounts exist on the server now, and what is each one allowed to do?

admin-intern: read-only access to service status and logs. staff-intern: hospital group, read-only on records, no admin rights. patient: non-interactive shell, time-bound. contractor: locked and expired.

Q4: Disabling Contractor

How did you disable the contractor's account, and how did you confirm it actually stopped working?

Commands used to disable the account:

sudo passwd -l contractor # -l: locks password login entirely sudo usermod -e 1970-01-01 \ contractor # -e: expires the account, forcing # an immediate lockout sudo gpasswd -d contractor \ svc-backup # -d: drops contractor from the # group, revoking script access sudo rm -f \ /etc/sudoers.d/hospital-backup # -f: deletes the sudoers file that # granted root on the script sudo chage -l contractor # -l: confirms expiration took # effect, no password reset needed Account expires: Jan 01, 1970

Confirmed with chage -l (shows expired) and a rejected SSH attempt.

Q5: Access-Control Scheme

What access-control scheme did you design for the records directory: who can read, who can write, who has no access at all?

The hospital group gets read-only access; only staff-intern is a member. The backup group can run the backup/sync scripts; no human accounts belong to it, only the dedicated service account.

Q6: SSH Hardening

How did you harden SSH?

Key steps to harden SSH:

echo 'PasswordAuthentication no' | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf # writes a config disabling # password-based SSH login sudo sshd -t # -t: checks syntax first so a bad # config can't lock everyone out sudo systemctl restart ssh # reloads sshd with the new rule password login: Permission denied (publickey)

Q7: Services & Timers

What services and timers are running on the server, and did you find or fix anything running with more privilege than it needed?

Audit and fix commands:

systemctl list-units --type=service \ --state=running # lists only services active now systemctl list-timers --all # --all: includes timers that # aren't currently scheduled sudo chown root:root \ /opt/hospital/sync.sh # removes group ownership sudo chmod 750 /opt/hospital/sync.sh # rwx owner, r-x group, none else

Q8: Finding: What & Where

What is it, and where did you find it: in the downloaded data, or in a configuration choice you made?

The backup script was owned root:group but group-writable (mode 775), and a sudoers file gave the contractor account NOPASSWD sudo to run it as root.

Q9: Finding: Discovery

How did you discover it? What did you check, or what did the AI suggest, that led you to it?

Checks that led to the finding:

sudo -l # -l: lists sudo rights without # running anything (root) NOPASSWD: backup.sh ls -la /opt/hospital/backup.sh # -l: long form, -a: show hidden, # reveals the script's real perms -rwxrwxr-x root svc-backup

Q10: Finding: The Exploit

How did you exploit it? What commands did you run, in what order?

The exploit pattern (illustrative):

echo 'id' >> /opt/hospital/backup.sh # appends the id command to the script's end sudo /opt/hospital/backup.sh # runs it as root: the NOPASSWD sudo rule # found in Q9 needs no password uid=0(root) gid=0(root) # proves the injected id ran as root, # not as the contractor account

Q11: Finding: Attacker Impact

What could an attacker actually do with this, once exploited?

Any member of that group with this sudo grant could escalate straight to root: read every patient record, modify system files, or erase the evidence of having done so.

Q12: Finding: The Fix

How did you fix it? What command(s) closed it?

Commands that closed it:

sudo rm -f \ /etc/sudoers.d/hospital-backup # -f: deletes the file granting # contractor root on the script sudo chown root:root \ /opt/hospital/backup.sh # removes svc-backup group owner sudo chmod 750 /opt/hospital/backup.sh # rwx owner, r-x group, none else

Q13: Finding: Confirm the Fix

How did you confirm the fix worked: did you re-test the exploit and see it fail?

The retest, and its result:

sudo -u contractor test -w \ /opt/hospital/backup.sh \ && echo "Still writable" \ || echo "Write denied: fix confirmed" # -u: runs the check as contractor, # -w: tests write access directly Write denied: fix confirmed

Verification Practice

Verify: Contractor Key

Fix applied:

sudo passwd -l contractor sudo usermod -e 1970-01-01 contractor sudo gpasswd -d contractor svc-backup

Which commands prove contractor's sudo rights and account are both gone?

(click to reveal)

Verification:

sudo -l -U contractor # -U: checks rights for a specific user User contractor is not allowed to run sudo chage -l contractor # -l: lists the account's expiration Account expires: Jan 01, 1970

Verify: Intern Account

Fix applied:

sudo passwd -l intern sudo usermod -e 1970-01-01 intern sudo usermod -s /usr/sbin/nologin intern

Which commands prove the intern account can no longer log in?

(click to reveal)

Verification:

getent passwd intern # confirms the shell is now nologin intern:x:1011:1018::/home/intern: /usr/sbin/nologin # <IP>: hostname -I on this VM ssh intern@<IP> # tries logging in with the old key Permission denied (publickey)

Verify: SSH Password Auth

Fix applied:

echo 'PasswordAuthentication no' | \ sudo tee \ /etc/ssh/sshd_config.d/10-lab.conf sudo systemctl restart ssh

Which commands prove password login is actually disabled?

(click to reveal)

Verification:

sudo sshd -T | grep passwordauth # -T: dumps the real effective config passwordauthentication no # <IP>: hostname -I on this VM ssh -o PreferredAuthentications=password \ -o PubkeyAuthentication=no osboxes@<IP> # forces a password-only login attempt Permission denied (publickey)

Verify: Readable Backups

Fix applied:

sudo chmod 700 /var/backups/hospital sudo chmod 600 \ /var/backups/hospital/*.tar.gz

Which commands prove only root can read the backups?

(click to reveal)

Verification:

ls -ld /var/backups/hospital # -d: shows the directory's own perms drwx------ root root sudo -u contractor cat \ /var/backups/hospital/*.tar.gz # -u: runs the read attempt as contractor Permission denied

Verify: Backup Script

Fix applied:

sudo chown root:root \ /opt/hospital/backup.sh sudo chmod 750 /opt/hospital/backup.sh sudo rm -f \ /etc/sudoers.d/hospital-backup

Which commands prove contractor can't run backup.sh as root anymore?

(click to reveal)

Verification:

sudo -u contractor test -w \ /opt/hospital/backup.sh \ && echo "Still writable" \ || echo "Write denied" # -u: run as contractor, -w: check write Write denied sudo -l -U contractor # -U: confirms the NOPASSWD grant is gone User contractor is not allowed to run sudo

Verify: Sync Script

Fix applied:

sudo chown root:root \ /opt/hospital/sync.sh sudo chmod 750 /opt/hospital/sync.sh

Which commands prove svc-backup can't edit sync.sh anymore?

(click to reveal)

Verification:

sudo -u svc-backup test -w \ /opt/hospital/sync.sh \ && echo "Still writable" \ || echo "Write denied" # -u: run as svc-backup, -w: check write Write denied systemctl cat hospital-sync.service \ | grep User # confirms the dedicated service account User=svc-sync

Student Reflections (Anonymized)

What Went Well

  • Snapshot isolation made exploit tests reversible, and testing from Kali confirmed the real network path.
  • Group and file access management went smoothly once the work actually got going.
  • Dedicated service accounts and ACLs gave clear, repeatable evidence for every retest.
  • SSH key-based auth felt like the clearest, most effective fix to make.

What They'd Do Differently

  • Start earlier and pace the work evenly, instead of one late sprint at the end.
  • Keep a command transcript and take screenshots before and after every change.
  • Verify a snapshot restore (chage -l, groups, sudo -l) right away, before moving on.
  • Audit /etc/sudoers.d and group memberships early, not after re-testing finds it.

Project Part 2

  • Team-based: continues Part 1
  • 5 teams, 1 team per laptop
  • Assigned: Week 9 (Oct 20)
  • Demo: Week 14 (Tue, Nov 24)

Full instructions and rubric: Canvas

What You'll Do

  • Build and defend your VM pair
  • Join a 5-team shared network
  • Monitor, attack, secure, build
  • Weekly status, then integrate

Five Laptops, One Shared Network

Monitor ReadUbuntuclinical dataKalidashboardMonitor WriteUbuntuclinical dataKalidashboardAttackerUbuntuclinical dataKalidashboardClinical DataUbuntuclinical dataKalidashboardWeb InterfaceUbuntuclinical dataKalidashboardNetwork Switch (5 ports)Every Ubuntu VM starts identical: same seeded clinical data, same 4 persona accounts

Physical lab: Ethernet cables through a real switch. Remote: one virtual network, same effect.

The 5 Teams at a Glance

Monitor Readread-onlyMonitor Writewrite-capableAttackerprobe-only, by agreementClinical Data & Access Controlwrite-capable, most privilegedClinical Web Interfacewrite-capable, scoped

Full role breakdown on the next slides.

WHO WORKS AT WHICH LAYERL7 · ApplicationDashboards & app accessMonitors build it, Med Units gate it, Attackers target itL6 · PresentationNot this project's focus—L5 · SessionNot this project's focus—L4 · TransportFirewall rules, portsMed Units defend (ufw/iptables); Attackers scanL3 · NetworkIP addressing, nmapEvery team; Attackers recon the whole subnetL2 · Data LinkShared virtual switchInfrastructure, not one team's jobL1 · PhysicalShared virtual switchInfrastructure, not one team's job

Orange = a team actively builds or attacks here. Gray = shared infrastructure.

Top-Down: Attacker's View

1. L7 AppWhat is it supposed to do?2. L4 TransportIs the port even open?3. L3 NetworkIs the IP reachable?4. L1/L2 LinkLast resort: cable, link

Bottom-Up: Defender's View

1. L1/L2 LinkIs the cable/link up first?2. L3 NetworkDoes it have a valid IP?3. L4 TransportIs the right port open?4. L7 AppLast: is the app itself OK?

⚠️ Starting at the wrong end wastes time: an attacker checking cables first, or a defender guessing at the app before confirming the link is up, both burn time on the wrong layer.

Who Can Write?

Monitor ReadRead-onlyMonitor WriteWrite-capableAttackerProbe-only (by agreement)Clinical Data & Access ControlWrite-capableClinical Web InterfaceWrite-capable (scoped)

Monitor Read's account is technically restricted to read-only commands: enforced, not just agreed to.

Network Setup

  • Decided in advance, not live
  • Bridged mode on every VM
  • NAT can't reach other laptops
  • Shared /etc/hosts file early

Static IPs, pre-assigned: 10.0.0.1x = Laptop 1 (.10 Ubuntu, .11 Kali), 10.0.0.2x = Laptop 2, and so on. The switch and cabling are shared infrastructure: each team just plugs in and configures its own.

Teams & VM Assignment

  • Each team: 1 Ubuntu + 1 Kali
  • Sign-up posted on Canvas
  • Each team builds + hardens own
  • Whole class shares the network
Sign up for a team roleBuild Ubuntu + Kali, harden itJoin the shared network

Role: Monitor Read

  • Watch the whole network
  • Owns IP scheme + hosts file
  • Runs physical check each test
  • Assembles the project poster
# scan the whole network nmap -sV 10.0.0.0/24 # tail logs, read-only account ssh clindata-vm "tail -f /var/log/auth.log"

Monitor Read: Deliverable

  • A live page, not a report
  • Triggers real commands
  • Proves the work, not just talk
nmap scan: who is upLog tail: what happenedDashboard: shows it live

Role: Monitor Write

  • Back up Clinical Data on time
  • Verify restores actually work
  • Remediates what Read/Atk flag
# scheduled backup pull rsync -az clindata-vm:/srv/clinical-data/ ./backup/ # verify a restore diff -r ./backup/ /srv/clinical-data/

Monitor Write: Deliverable

  • A live page, not a report
  • Triggers real commands
  • Proves the work, not just talk
rsync pull: backup nowRestore + diff: verifyDashboard: shows it live

Role: Attacker

  • Find a real vuln in Clin. Data
  • Only attack this class network
  • Build a simple web dashboard
  • Signed agreement required
# recon first, always nmap -sV -p- clindata-vm-ip # only authorized targets on # this class network, nothing else

Attacker: Deliverable

  • A live page, not a report
  • Triggers real commands
  • Proves the work, not just talk
Scan: find a real weaknessAttempt: try, log resultDashboard: shows it live

Role: Clinical Data Admin

  • Secure the shared Ubuntu seed
  • RBAC: groups set the rules
  • Most privileged, real target
# from Kali, configure your own Ubuntu ssh clindata-vm "sudo groupadd physicians" ssh clindata-vm "sudo chgrp -R physicians /srv/clinical-data" ssh clindata-vm "sudo chmod -R 2770 /srv/clinical-data"

Clinical Data: Deliverable

  • A live page, not a report
  • Triggers real commands
  • Proves the work, not just talk
Configure: real RBAC rulesAccess log: who tried whatDashboard: shows it live

Role: Web Interface

  • Log-in-as-persona web app
  • Reads Clinical Data's rules
  • No write access to records
# deploy and watch the persona-login app ssh webapp-vm "sudo systemctl restart persona-app" ssh webapp-vm "journalctl -u persona-app -f"

Web Interface: Deliverable

  • A live page, not a report
  • Triggers real commands
  • Proves the work, not just talk
Deploy: persona-login appReads: real permissions liveDashboard: shows it live

Phase 1: Component Testing

  • Not on the shared network yet
  • Verify your own Ubuntu+Kali
  • Proves your config is right
  • Not that anyone can reach you

Each team tests its own pair in isolation. This catches configuration mistakes cheaply, before the switch is ever connected.

Phase 2: Integration Testing

  • Physical check: links up first
  • Test 1: reachability
  • Test 2: functional
  • Final: dress rehearsal

Test 1 (Week 10, Tue) is pure reachability. Test 2 (Week 12, Tue) is functional: real attacks, backups, monitoring, logs. Final Integration (Week 13, Thu) is a full dress rehearsal before the demo.

Demo: Week 14

  • Tuesday, Nov 24 only
  • Thu Nov 26 is Thanksgiving
  • Monitor Read runs first sweep
  • Then Dec 4 Project Showcase

Week 14 has only one class day. Monitor Read runs the physical check and the first nmap sweep at the start of every integration test.

Weekly Status Updates

  • Every team, every week
  • Weeks 10 through 13 (4 total)
  • What's done, blocked, next

Keeps problems visible early instead of surfacing for the first time at an integration test.

GitHub Submission

  • team1: Monitor Read
  • team2: Monitor Write
  • team3: Attacker
  • team4: Clinical Data Admin
  • team5: Web Interface

Submit to your own team folder: code, your presentation slides (.pptx), and every other artifact. If it's part of your deliverable, it belongs in your folder, not just attached to Canvas.

Push to: github.com/SE4CPS/2026-COMP-175/project/part-2

Discord

  • Join the class server
  • Use your own team channel
  • Questions, blockers, drafts

Join: discord.gg/2wuVZu6Fm

Logistics

  • 5 laptops, 5-port switch
  • 6th laptop could add Auditor
  • Synthetic clinical data only
  • No real patient information

A second switch or a 6th laptop could re-add a dropped role (e.g. a dedicated Auditor) later: not required for the current 5-team plan.

Deliverables

  • Working VM pair, demo-ready
  • Weekly status, Weeks 10-13
  • Short per-team write-up
  • Week 14 demo + Dec 4 Showcase

Full rubric and point values: Canvas

What a Good Write-up Shows

  • What your role did
  • One real problem you hit
  • How you fixed it
  • A screenshot of it working

AI use is allowed: clearly state which parts used AI and which parts you did without it.

Week 1: Kickoff

  • ✅ Teams created (5 teams)
  • Not on the shared network yet
  • Just your own VM pair, for now
  • Phase 1: component testing

One core task this week, the same for every team: clone the shared repo, run setup.sh on your own Ubuntu VM, and confirm the 4 persona accounts and clinical data match the shared baseline. That's Phase 1: proving your own pair works, not yet that anyone else can reach you.

Get the Hospital Use Case

  • Clone the shared repo
  • Run setup.sh on your Ubuntu
  • Check for SETUP OK
  • Starts world-readable on purpose
sudo apt install -y git # make sure git is available git clone \ https://github.com/SE4CPS/2026-COMP-175.git cd 2026-COMP-175/project/part-2/Hospital-VM chmod +x setup.sh # makes the script runnable ./setup.sh SETUP OK

Repo: github.com/SE4CPS/2026-COMP-175/project/part-2/Hospital-VM

Weekly Rhythm

  • Tuesday: team work time
  • Thursday: team presentation
  • Build toward the demo
  • Status + progress, not final

Between Tuesday and Thursday, build your slides for the Thursday update and upload them to the shared Drive folder before class.

Slides: Google Drive (name file team-N)

Timeline: Task per Team

TeamOct 20
Team Formation
Oct 27
Component Setup
Nov 3
Join Network
Nov 10
Integration Test 2
Nov 17-19
Final Integration
Nov 24
Due / Demo
Monitor ReadTeams formedIP scheme, hosts file, first sweepConfirm reach; full network sweepLive dashboard: sweep + log tailAssemble the project posterDemo
Monitor WriteTeams formedTest rsync backup & restoreConfirm backup target is reachableReal backup/restore buttons wiredFull dress-rehearsal backup cycleDemo
AttackerTeams formedSign ethics agreement; nmap own VMConfirm reach to Clinical DataReal exploit attempt, loggedFinalize findings write-upDemo
Clinical Data & Access ControlTeams formedsetup.sh; start real RBACJoin network; verify reachHarden RBAC; close gaps foundFinal hardening passDemo
Clinical Web InterfaceTeams formedScaffold the persona-login appConfirm app reachable on netWire login to real permissionsPolish dashboard, fix bugsDemo

Questions?

Module 16

Final Preparation & Course Wrap-up

Project Showcase: Dec 4Final Exam: Dec 8Sixteen modules, one semester

Final Project Showcase

When & Where

  • Friday, Dec. 4, 2-3:15 PM
  • Location: the Makerspace
  • Teams present their full build
Fri, Dec. 4, 2-3:15 PMLocation: MakerspaceEvery team presents

What to Bring

  • The working system, demo-ready
  • A short walkthrough of design
  • Be ready for real questions

Reuses every module this course taught: virtualization, networking, access control, logging, automation, containers, and IaC, all working together in one real system.

Final Exam Logistics

When & Where

  • Tue, Dec. 8, 8:25–09:45 AM
  • Location: CTC 214
  • Covers Modules 1 through 15
Tue, Dec. 8, 8:25-09:45 AMLocation: CTC 214Cumulative, all 15 modules

How to Prepare

  • Review each module's commands
  • Re-run the hardest labs
  • Check the Schedule page links

Every module's own command-reference table (the "All Commands" slide) is the fastest way to jog your memory on real syntax before the exam.

Course Wrap-up

From One VM to a Full Build

  • Started: one VM, one terminal
  • Ended: networked, automated
  • Every module built on the last
Modules 1-4: one machine, securedModules 5-9: networked, monitoredModules 10-15: automated, deployed

Thank You

  • Real sysadmin work, covered
  • The project tied it together
  • Keep building on it
🎉