Linux cheat sheet
Part 1 · Basics
Find your way (lesson 1)
| Task | Command |
|---|---|
| Show where you are | pwd |
| Make a folder and its parents | mkdir -p ~/krlab/linux-basics |
| Go up, go back | cd .., cd - |
| List with hidden entries | ls -la |
| List with readable sizes | ls -lh |
| Sort by size, by time, reversed | ls -S, ls -t, ls -tr |
| Rename a file | mv old new |
| Delete a folder and contents | rm -r cases/2026 |
| Delete a folder only if it is empty | rmdir empty |
Edit and repeat commands (lesson 2)
| Task | Command |
|---|---|
| Start or end of the line | Ctrl+A, Ctrl+E |
| Delete a word, to the start, to the end | Ctrl+W, Ctrl+U, Ctrl+K |
| Clear the screen | Ctrl+L |
| Stop, suspend, end of input | Ctrl+C, Ctrl+Z, Ctrl+D |
| Wake a suspended program | fg |
| Help for a command, the manual page | ls --help, man ls (/word, q) |
| Find a command by its job, say what a name is | man -k WORD, whatis ls, type -a ls |
| Search the history | Ctrl+R |
| List history, repeat the last line, repeat line 40 | history, !!, !40 |
| Complete a name | Tab (twice for the choices) |
Variables, scripts and aliases (lesson 3)
| Task | Command |
|---|---|
| Set and read a variable | name=Ada, echo "$name" |
| Run a script by its own name | chmod +x hello.sh, ./hello.sh Ada |
| Make, list, remove an alias | alias lh='ls -lh', alias, unalias lh |
| Quote: variables work, or stay as typed | echo "hi $name", echo 'hi $name' |
| Wildcards: any text, one character | ls *.txt, ls ?.log |
| Keep an alias, remove it again | echo "alias lh='ls -lh'" >> ~/.bashrc, sed -i '/^alias lh=/d' ~/.bashrc |
Read and search text (lesson 4)
| Task | Command |
|---|---|
| Make an empty file | touch notes.txt |
| Show first or last lines | head -n 2 auth.log, tail -n 1 auth.log |
| Follow a log by name (Field note) | tail -F auth.log |
| Count lines, words, bytes | wc -l, wc -w, wc -c |
| Read a big file | less numbers.txt |
| Count matching lines | grep -c "Failed password" auth.log |
| Match either word | grep -cE "root|admin" auth.log |
| Search a fixed text (Field note) | grep -F TEXT auth.log |
| Search folders, list names | grep -rl "invalid user" . |
| Keep columns | cut -d' ' -f2, cut -c1-15 |
| Rank sources by count | grep -oE "from [0-9.]+" auth.log | cut -d' ' -f2 | sort | uniq -c | sort -rn |
Fields and sums with awk (lesson 5)
| Task | Command |
|---|---|
| Print a field, the last field | awk '{print $1}' f, awk '{print $NF}' f |
| Select lines by a field | awk '$2 == 443 {print $1}' f |
| Skip the header line | awk 'NR > 1 && $3 > 3000' f |
| Add up a column | awk 'NR > 1 {s += $3} END {print s}' f |
| Change the separator | awk -F: '$3 == 0 {print $1}' /etc/passwd |
Pipes, redirects and tee (lesson 6)
| Task | Command |
|---|---|
| Output to a file, add to a file | cmd > out.txt, cmd >> out.txt |
| Errors to a file | cmd 2> err.txt |
| Output and errors to one file | cmd > all.txt 2>&1 |
| Throw the errors away | cmd 2> /dev/null |
| Read a file as input | wc -l < file |
| Run the next command only on success, on failure | cmd && next, cmd || next |
| Screen and file at once | cmd | tee out.txt |
| Add to a file and the screen | cmd | tee -a out.txt |
| Write several files | cmd | tee a.txt b.txt |
| Save in the middle of a pipe | grep fail jobs.txt | tee fails.txt | wc -l |
Edit files (lesson 7)
| Task | Command |
|---|---|
| Open, save, leave nano | nano file, Ctrl+O then Enter, Ctrl+X |
| Search, cut a line, paste, undo in nano | Ctrl+W, Ctrl+K, Ctrl+U, Alt+U |
| Insert, back to Normal mode in vim | i or o, Esc |
| Search, delete a line, undo in vim | /word Enter, dd, u |
| Save and quit, quit without saving | :wq, :q! |
| Two-panel file manager | mc (F5 copy, F6 move, F8 delete, F10 quit) |
Find files and read details (lesson 8)
| Task | Command |
|---|---|
| Find by name | find . -name "*.conf" |
| Find by type, size, age | find . -type f -size +5k -mtime +30 |
| Find broken symbolic links | find . -xtype l |
| Find by name in the name database | locate -i name (after sudo updatedb) |
| Show the facts of a file | stat file, stat -c '%n %s' file |
| Say what kind of data a file holds | file name |
| Hard link, symbolic link | ln old new, ln -s target new |
| Show where a link points | readlink link |
Archives with tar (lesson 9)
| Task | Command |
|---|---|
| Pack a folder | tar -czf project.tar.gz project |
| List an archive | tar -tf project.tar.gz, tar -tvf |
| Extract into another folder | tar -xzf project.tar.gz -C restore |
| Extract one member | tar -xzf project.tar.gz -C one project/readme.txt |
| Leave things out | tar -czf s.tar.gz --exclude=cache project |
| Drop the top folder | tar -xzf project.tar.gz --strip-components=1 -C flat |
| Use xz | -J |
| Write and check a fingerprint | sha256sum a.tar.gz > a.sha256, sha256sum -c a.sha256 |
Permissions (lesson 10)
| Task | Command |
|---|---|
| Show who you are | id |
| Set owner read and write only | chmod 600 notes.txt |
| Set bits in symbolic form | chmod u=rw,go= notes.txt |
| Show the default mode mask | umask |
| Find SUID files | find /usr/bin /usr/sbin -perm -4000 -type f 2>/dev/null |
| Find open directories without sticky bit | find lab -type d -perm -0002 ! -perm -1000 |
| List what sudo allows you | sudo -l |
Build a log triage script (lesson 11)
| Task | Command |
|---|---|
| Count the failed logins | grep -c "Failed password" "$1" |
| Rank the addresses of the failures | grep "Failed password" "$1" | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn |
| List accepted logins, user and address | grep "Accepted" "$1" | awk '{print $9, $11}' |
| Show the report and save it | ./triage.sh auth.log | tee report.txt |
Safety habits
- Run
lson a path beforerm -r. There is no undo. - Check the file name before you use
>. It replaces the file without a question. - Never use
chmod 777. Give the one user or group the bit it needs. - List an archive with
tar -tfbefore you extract it, and extract into an empty folder. - Check a download with its checksum before you open it.
- Do not type a secret in a command line. The history keeps it.
- Run
findwith-printfirst, and read the list, before you use-execor-delete. - Run single commands with
sudo. Edit sudo rules only withvisudo.
Part 2 · System administration
Set up (lesson 0)
| Task | Command |
|---|---|
Your user and groups, a fresh sudo entry | id, sudo -v |
| Check the lab | bash labcheck.sh |
Identify the system (lesson 1)
| Task | Command |
|---|---|
| Distribution and version | cat /etc/os-release, lsb_release -d |
| Read the fields as variables | . /etc/os-release; echo "$VERSION_ID" |
| Host name, system, kernel, machine type | hostnamectl |
| Kernel release, all kernel facts | uname -r, uname -a |
| Kernel build text | cat /proc/version |
| Processors, logical CPUs | lscpu, nproc |
| Raw processor and memory data | /proc/cpuinfo, /proc/meminfo |
| Disks and partitions | lsblk |
| All hardware, one line each | sudo lshw -short |
| Real machine, virtual machine or container | systemd-detect-virt |
| Time and time zone | date, date -u, timedatectl, journalctl --utc |
Measure the load (lesson 2)
| Task | Command |
|---|---|
| Load average (1, 5, 15 minutes) | uptime, compare with nproc |
| Memory and swap | free -h, read available |
| One line each second | vmstat 1 5 (r, si, so, wa) |
| Disk traffic, busy disk | iostat -d DEVICE 1 2, iostat -dx (r_await, w_await, %util) |
| Live process list | top (P, M, 1, q), top -b -n 1 |
| Network card counters | ip -s link show eth0 |
| Count of sockets | ss -s |
Check and free disk space (lesson 3)
| Task | Command |
|---|---|
| Space of the file systems, with type | df -h, df -hT / |
| Inodes | df -i |
| Size of a folder | du -sh FOLDER |
| Sub-folders, one level | du -h --max-depth=1 FOLDER |
| Biggest first | du -h --max-depth=1 . | sort -rh | head |
| Size of the content, not the blocks | du --apparent-size |
| Stay on one file system | du -x |
| Folder with the most files | find . -type f | cut -d/ -f2 | sort | uniq -c | sort -rn |
| Find a deleted file that is still open | ls -l /proc/PID/fd |
| Empty the package cache, trim the journal | sudo apt-get clean, sudo journalctl --vacuum-size=200M |
Partitions, file systems and mounting (lesson 4)
| Task | Command |
|---|---|
| Devices, file systems, mounts | lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS, findmnt, sudo blkid |
| Disk image in a file | truncate -s 64M disk.img |
| Write a GPT table from a script | printf 'label: gpt\n,16M,L\n,,L\n' | sfdisk disk.img |
| Read a partition table | fdisk -l disk.img |
| Make an ext4 file system | mkfs.ext4 -L label /dev/sdb1 |
| Read its facts | dumpe2fs -h part.img, blkid part.img |
| Practise a mount without a disk | sudo mount -t tmpfs -o size=4m tmpfs /mnt/kr, findmnt -n -o FSTYPE /mnt/kr |
| Attach an image as a loop device, detach it | L=$(sudo losetup --find --show part.img), sudo losetup -d "$L" |
| Mount an image, a real partition | sudo mount -o loop part.img /mnt/kr, sudo mount /dev/sdb1 /data |
| Check the mount, unmount | findmnt /data, sudo umount /data |
| Check an fstab file | findmnt --verify, sudo mount -a |
| Make swap from a file, use it, stop it | sudo fallocate -l 64M /swapfile, sudo chmod 600 /swapfile, sudo mkswap /swapfile, sudo swapon /swapfile, swapon --show, sudo swapoff /swapfile |
| LVM layers (Field note) | pvcreate, vgcreate, lvcreate, lvextend, resize2fs |
Watch and control processes (lesson 5)
| Task | Command |
|---|---|
| List all processes, as a tree | ps -ef, ps -ef --forest |
| Choose columns, one process | ps -o pid,ppid,stat,ni,cmd -p PID |
| Biggest memory users | ps -eo pid,%mem,comm --sort=-%mem | head |
| Find by name | pgrep -a NAME |
| Polite stop, forced stop | kill PID, kill -9 PID |
| Pause, continue | kill -STOP PID, kill -CONT PID |
| List signals | kill -l |
| Background jobs | cmd &, jobs, fg %1, bg %1, nohup cmd & |
| Start nicer, change a running one | nice -n 5 cmd, renice -n 12 -p PID |
| What a process really runs | ls -l /proc/PID/exe /proc/PID/cwd |
| Zombie state | Z in STAT: end its parent |
Users and groups (lesson 6)
| Task | Command |
|---|---|
| Read an account | getent passwd NAME, id NAME, groups NAME |
| Add a group, an account | sudo groupadd -g 2100 GROUP, sudo useradd -m -u 2001 -g GROUP -s /bin/bash NAME |
| Set a password | sudo passwd NAME, passwd |
| Add a user to a group | sudo usermod -aG GROUP NAME |
| Lock, unlock, status | sudo passwd -l NAME, sudo passwd -u NAME, sudo passwd -S NAME |
| Close a login fully | sudo chage -E 0 NAME, sudo usermod -s /usr/sbin/nologin NAME |
| Password ageing | sudo chage -M 90 -m 1 -W 7 NAME, sudo chage -l NAME, sudo chage -d 0 NAME |
| Remove an account, with its home | sudo userdel NAME, sudo userdel -r NAME |
Sudo rules and ACLs (lesson 7)
| Task | Command |
|---|---|
| Run as another user | sudo -u NAME cmd, su - NAME |
| Check a sudo rule, install it | visudo -cf rule.sudo, sudo install -m 440 -o root -g root rule.sudo /etc/sudoers.d/NAME |
| A sudo rule for a group | %GROUP ALL=(root) NOPASSWD: /full/path/cmd |
| List what a user may run | sudo -l -U NAME |
| Show, add, remove an ACL entry | getfacl FILE, setfacl -m u:NAME:r FILE, setfacl -x u:NAME FILE, setfacl -b FILE |
Services (lesson 8)
| Task | Command |
|---|---|
| List running, failed services | systemctl list-units --type=service --state=running, systemctl --failed |
| State of one service | systemctl status NAME, systemctl is-active NAME, systemctl is-enabled NAME |
| Start, stop, restart | sudo systemctl start NAME, stop, restart |
| Start at boot, stop starting | sudo systemctl enable NAME, sudo systemctl disable NAME, enable --now |
| Read a unit file | systemctl cat NAME |
| Read the unit files again | sudo systemctl daemon-reload |
| Log of one service | sudo journalctl -u NAME -n 20, -o cat |
| Check a unit file | systemd-analyze verify FILE |
| Clear a failed mark | sudo systemctl reset-failed NAME |
| Replace text in a file, in place | sed -i 's/OLD/NEW/' FILE |
Software (lesson 9)
| Task | apt and dpkg | dnf and rpm | pacman |
|---|---|---|---|
| Refresh the list | sudo apt update | dnf check-update | not covered |
| See what can be upgraded | apt list --upgradable | dnf check-update | not covered |
| Upgrade | sudo apt upgrade | sudo dnf upgrade | sudo pacman -Syu |
| Install, remove | sudo apt install NAME, sudo apt remove NAME | dnf install, dnf remove | pacman -S, pacman -R |
| Search, details | apt search WORD, apt show NAME | dnf search, dnf info | pacman -Ss, pacman -Si |
| Owner of a file | dpkg -S FILE | rpm -qf FILE | pacman -Qo FILE |
| Files of a package | dpkg -L NAME | rpm -ql NAME | pacman -Ql NAME |
| Verify the files of a package (Field note) | sudo dpkg --verify NAME | rpm -V NAME | not covered |
| Task | Command |
|---|---|
| Write and check a fingerprint | sha256sum FILE > SUMS, sha256sum -c SUMS |
Build from source and control the path (lesson 10)
| Task | Command |
|---|---|
| Compile one C file | cc -o hello hello.c |
| Build, show the rule without running it, install into your folder | make, make -n install, make install PREFIX=$HOME/krlab/linux-admin/local |
| Show the search path | echo "$PATH" | tr ':' '\n' |
| Show every program of a name, the one the shell runs | type -a NAME, command -v NAME |
| Give a variable to child programs, remove it | export NAME=value, unset NAME |
Write a script (lesson 11)
| Task | Command |
|---|---|
| Stop on errors, unset variables, pipe failures | set -euo pipefail |
| Default for an argument | ${1:-default} |
| Choose | if [[ -r $f ]]; then ...; else ...; fi |
| Repeat | for x in a b c; do ...; done, while [[ $n -lt 4 ]]; do ...; done |
| Calculate, test a number | n=$((n + 1)), (( n )) |
Tests of [[ ]] | -z empty, -n not empty, -r readable, -ge -gt -lt -eq number compare, ! not |
| Fail on an empty variable | "${dir:?dir is not set}" |
| Check the syntax only | bash -n script.sh |
| Read the exit code | echo $? |
Run a script on a schedule (lesson 12)
| Task | Command |
|---|---|
| Save, install, show your crontab | crontab -l > crontab.backup, crontab FILE (replaces every job), crontab -l |
| Put it back, or remove it | crontab crontab.backup, crontab -r |
| Five cron fields | minute hour day-of-month month day-of-week |
| Run once later | echo "cmd" | at now + 1 minute, atq, atrm N |
| Check a timer schedule | systemd-analyze calendar "Mon..Fri 06:30" |
| List timers | systemctl list-timers |
Audit a machine (lesson 13)
| Task | Command |
|---|---|
| SUID files | find DIR -xdev -type f -perm -4000 |
| Directories that anybody may write to, without the sticky bit | find DIR -xdev -type d -perm -0002 ! -perm -1000 |
| Listening TCP ports with their processes | ss -tlnp |
| Members of the admin group | getent group sudo wheel |
| File systems above 80 per cent | df -P | awk 'NR > 1 && $5 + 0 > 80' |
| Failed services | systemctl --failed --no-legend --no-pager |
| Choose the report file and the log | AUDIT_OUT=FILE AUDIT_LOG=LOG ./audit.sh DIR |
Safety habits
- Practise on a system that you may break. Take a snapshot before you change disks, users or services.
- Measure before you change, and save the numbers. A change without a number before and after is a guess.
- Name the cause of a full disk before you delete anything, and delete only what the system can recreate.
- Check the device name twice before
mkfsorfdisk. Mount new disks on an empty folder, and test an fstab line withfindmnt --verifybefore the reboot. - Try
kill PIDbeforekill -9 PID. Readpgrep -a NAMEbeforepkill NAME. - Add a user to a group with
usermod -aG, never-Galone. - Write sudo rules in
/etc/sudoers.d/, check them withvisudo -cf, and allow one exact command, notALL. - Lock an account with a password lock and an expiry date, and remove its keys.
- Run
systemctl daemon-reloadafter a change to a unit file, and readstatusandjournalctl -uwhen a service fails. - Check a download with its checksum, from a second trusted route. Keep signature checks switched on.
- Quote every variable in a script, use
set -euo pipefail, and give cron jobs full paths and a log file. - Audit as a habit: run
audit.shafter each change, keep the reports and compare them.
Part 3 · Networking and hardening
Inspect the network (lesson 1)
| Task | Command |
|---|---|
| List addresses, one line each | ip -br addr |
| List interfaces with counters | ip -s link show lo |
| Show the routes | ip route |
| Ask which route an address uses | ip route get 198.51.100.7 |
List listening TCP sockets with processes (sudo for other users) | sudo ss -tlnp |
| Show one port only | ss -tln 'sport = :8000' |
| Serve a folder on the loopback only | python3 -m http.server 8000 --bind 127.0.0.1 --directory site |
| Print only the HTTP status | curl -s -o /dev/null -w "%{http_code}\n" URL |
| Resolve a name like a program | getent hosts localhost |
| Ask a DNS server | dig +short @127.0.0.53 localhost |
Addresses, routes and names (lesson 2)
| Task | Command |
|---|---|
| Make a dummy interface | sudo ip link add krdummy0 type dummy |
| Bring a link up or down | sudo ip link set krdummy0 up, sudo ip link set krdummy0 down |
| Add and remove an address | sudo ip addr add 198.51.100.10/24 dev krdummy0, sudo ip addr del 198.51.100.10/24 dev krdummy0 |
| Add a route | sudo ip route add 203.0.113.0/24 via 198.51.100.1 |
| Add a spare default route | sudo ip route add default via 198.51.100.1 dev krdummy0 metric 500 |
| Change or remove a route | sudo ip route replace ..., sudo ip route del ... |
| Add a local name | echo "198.51.100.20 files.lab files" | sudo tee -a /etc/hosts |
| Show or set a DNS server of a link | resolvectl dns, sudo resolvectl dns krdummy0 198.51.100.53 |
| Undo the link settings of resolved | sudo resolvectl revert krdummy0 |
| Show or set the host name | hostnamectl, sudo hostnamectl set-hostname krlab-net |
| Check and apply netplan | sudo netplan generate, sudo netplan apply |
| Apply netplan with a rollback | sudo netplan try |
| Delete a virtual interface | sudo ip link del krdummy0 |
Where a setting is kept permanently:
| System | File | Tool |
|---|---|---|
| Ubuntu | /etc/netplan/*.yaml | netplan apply |
| systemd-networkd | /etc/systemd/network/*.network | networkctl reload |
| Desktop Linux | NetworkManager connections | nmcli, nmtui |
| Older Debian | /etc/network/interfaces | ifup, ifdown |
| Older RHEL and CentOS | /etc/sysconfig/network-scripts/ifcfg-* | ifup, ifdown |
Firewall (lesson 3)
| Task | Command |
|---|---|
| List all rules | sudo nft list ruleset |
| Make a table | sudo nft add table inet krlab |
| Make an input chain | sudo nft add chain inet krlab input '{ type filter hook input priority 0 ; policy accept ; }' |
| Allow known connections | sudo nft add rule inet krlab input ct state established,related accept |
| Allow a port from one network | sudo nft add rule inet krlab input ip saddr 198.51.100.0/28 tcp dport 8080 accept |
| Set the policy to drop (last) | sudo nft chain inet krlab input '{ policy drop ; }' |
| Show rule handles | sudo nft -a list chain inet krlab input |
| Delete one rule | sudo nft delete rule inet krlab input handle 5 |
| Delete a table (the way back) | sudo nft delete table inet krlab |
| Check a rule file, then load it | sudo nft -c -f krlab.nft, sudo nft -f krlab.nft (the file starts with table inet krlab and delete table inet krlab, so it replaces only its own table) |
| Keep rules at boot | add iif lo accept first in the chain, copy the file to /etc/nftables.conf, sudo systemctl enable --now nftables |
| ufw: set defaults, allow SSH first | sudo ufw default deny incoming, sudo ufw allow 22/tcp |
| ufw: allow a port from a network | sudo ufw allow from 198.51.100.0/28 to any port 8080 proto tcp |
| ufw: switch on, list, delete, reset | sudo ufw --force enable, sudo ufw status numbered, sudo ufw delete 2, sudo ufw --force reset |
| Test a rule from one address | curl -s -m 2 --interface 198.51.100.10 http://198.51.100.10:8080/ |
SSH (lesson 4)
| Task | Command |
|---|---|
| Install and start the server | sudo apt install -y openssh-server, sudo systemctl enable --now ssh |
| Connect | ssh kr_ops@localhost, ssh -i lab_key kr_ops@localhost (-p PORT for another port) |
| Make a key pair | ssh-keygen -t ed25519 -f ./lab_key -C "you@krbox" |
| Install a public key | ssh-copy-id -i lab_key.pub kr_ops@localhost |
| Show the settings that sshd uses | sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication)' |
| Check the configuration | sudo sshd -t |
| Read a file without restart | sudo systemctl reload ssh |
| Listen on the loopback on Ubuntu 24.04 | ListenAddress 127.0.0.1 in a drop-in, then sudo systemctl disable --now ssh.socket, sudo systemctl restart ssh |
| Prove that the first value wins | put PermitRootLogin yes in 00-test.conf, read sudo sshd -T | grep permitrootlogin, remove the file |
| Remove a stale host key | ssh-keygen -R localhost |
| Show the host key fingerprint | ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub |
| Stop SSH | sudo systemctl disable --now ssh |
| Clean up the lab | sudo sed -i '/you@krbox/d' /root/.ssh/authorized_keys, sudo userdel -r kr_guest, sudo passwd -l kr_ops |
The options that matter in /etc/ssh/sshd_config.d/*.conf: ListenAddress ADDRESS, PermitRootLogin no, PasswordAuthentication no, KbdInteractiveAuthentication no, PubkeyAuthentication yes, AllowUsers NAME, Port N. The first value that sshd reads wins.
Copy files (lesson 5)
| Task | Command |
|---|---|
| Move the server to port 2222 | add Port 2222 to 01-krlab.conf, sudo sshd -t, sudo systemctl restart ssh |
| Upload a file | scp -P 2222 -i "$KEY" report.txt kr_ops@localhost:/tmp/report.txt |
| Download a file | scp -P 2222 -i "$KEY" kr_ops@localhost:/tmp/report.txt back.txt |
| Copy a folder | scp -r -P 2222 -i "$KEY" project kr_ops@localhost:/tmp/project |
| Keep times and modes | scp -p ... |
| Prove a copy is identical | sha256sum FILE, cmp FILE1 FILE2 |
| Copy only what changed | rsync -av -e "ssh -p 2222 -i $KEY" project/ kr_ops@localhost:/tmp/rs/ |
GnuPG (lesson 6)
| Task | Command |
|---|---|
| Use a lab keyring | mkdir -m 700 alice; export GNUPGHOME=$PWD/alice |
| Make a key pair | gpg --batch --passphrase '' --quick-generate-key "Alice Lab <alice@krbox.lab>" default default 1y |
| List public and private keys | gpg --list-keys, gpg --list-secret-keys |
| Export a public key | gpg --armor --export alice@krbox.lab > alice.pub.asc |
| Import a key | gpg --import bob.pub.asc |
| Read a fingerprint | gpg --fingerprint bob@krbox.lab |
| Certify a key for yourself | gpg --quick-lsign-key FINGERPRINT |
| Encrypt for a person | gpg --armor --encrypt --recipient bob@krbox.lab plan.txt |
| Decrypt | gpg --output plan.txt --decrypt plan.txt.asc |
| Sign a text | gpg --clearsign notice.txt |
| Make a detached signature | gpg --armor --detach-sign tool.tar.gz |
| Verify | gpg --verify notice.txt.asc, gpg --verify tool.tar.gz.asc tool.tar.gz |
| Stop the agents, forget the lab keyring | GNUPGHOME=$PWD/alice gpgconf --kill gpg-agent, unset GNUPGHOME |
chroot (lesson 7)
| Task | Command |
|---|---|
| List the libraries of a program | ldd /bin/ls |
| Copy a program with its path | cp --parents /bin/ls jail/ |
| Run a program in a jail | sudo chroot jail /bin/ls / |
| Start a shell in a jail | sudo chroot jail /bin/bash |
| Read the root of a process | sudo readlink /proc/PID/root |
| List the namespaces of a process | ls -l /proc/self/ns |
| Run a program in a new host name space | sudo unshare --uts sh -c 'hostname krjail; hostname' |
| Run a program in a new process space | sudo unshare --pid --fork --mount-proc ps -e |
Web stack (lesson 8)
| Task | Command |
|---|---|
| Install on Ubuntu | sudo apt install -y apache2 mariadb-server php libapache2-mod-php php-mysql |
| Check each part | systemctl is-active apache2 mariadb, apache2 -v, php -v, curl -sI http://127.0.0.1/ |
| Run SQL as the administrator | sudo mariadb -e "SHOW DATABASES" |
| Give the least rights | GRANT SELECT ON krshop.products TO 'kr_web'@'localhost'; |
| Find anonymous accounts | sudo mariadb -e "SELECT user,host FROM mysql.user" |
| Remove them | sudo mariadb -e "DROP USER IF EXISTS ''@'localhost'; DROP DATABASE IF EXISTS test;" |
| Keep the database on the loopback | bind-address = 127.0.0.1 in /etc/mysql/mariadb.conf.d/99-krlab.cnf |
| Hide the version, stop listing | ServerTokens Prod, ServerSignature Off, Options -Indexes |
| Enable a configuration and check it | sudo a2enconf zz-krlab, sudo apache2ctl configtest, sudo systemctl reload apache2 |
| Lock the web folder | sudo chown -R root:www-data /var/www/html, find ... -type d -exec chmod 750 {} +, find ... -type f -exec chmod 640 {} + |
| Find entries that others can write | sudo find /var/www/html -perm -o+w |
Packages on other families (not tested here): CentOS and RHEL httpd mariadb-server php php-mysqlnd, Arch apache mariadb php php-apache.
The kernel (lesson 9)
| Task | Command |
|---|---|
| Show the release | uname -r |
| Read a parameter | sysctl net.ipv4.ip_forward, cat /proc/sys/net/ipv4/ip_forward |
| Change it now | sudo sysctl -w net.ipv4.icmp_echo_ignore_all=1 |
| Keep it | a line NAME = VALUE in /etc/sysctl.d/90-krlab.conf, sudo sysctl -p FILE or sudo sysctl --system |
| List the loaded modules | lsmod |
| Read a module (licence) | modinfo -F license dummy |
| See what a load would do | sudo modprobe -n -v vxlan |
| Load or remove a module | sudo modprobe NAME, sudo modprobe -r NAME |
| Get the build tools and the source | sudo apt install -y build-essential bc flex bison libssl-dev libelf-dev libncurses-dev linux-source |
| Write a default configuration | make defconfig |
| Start from the config of the running kernel | cp /boot/config-$(uname -r) .config, scripts/config --set-str LOCALVERSION "-krlab", scripts/config --set-str SYSTEM_TRUSTED_KEYS "" --set-str SYSTEM_REVOCATION_KEYS "", scripts/config --disable DEBUG_INFO_BTF --disable DEBUG_INFO_DWARF5 --enable DEBUG_INFO_NONE |
| Change an option | scripts/config --disable ISO9660_FS, scripts/config --state ISO9660_FS |
| Fill in the rest | make olddefconfig |
| Build, install, boot loader | make -j"$(nproc)", sudo make modules_install, sudo make install, sudo update-grub |
A hardening check (lesson 10)
| Task | Command |
|---|---|
| Build a sample tree, good or weak | bash sample.sh lab good, bash sample.sh lab weak |
| Check a tree, or the real system | bash krharden-check.sh lab, sudo bash krharden-check.sh |
| Use the result in a script | exit code 0 when every check is ok, 1 when one is FAIL |
| First or last value wins | sshd: the first value. sysctl, MariaDB: the last value |
Safety habits
- Work on a practice system that the internet cannot reach, and take a snapshot before the network lessons.
- Bind lab services to
127.0.0.1, and remove lab keys and accounts when the lesson ends. - Keep a second terminal logged in while you change SSH, the firewall or an address.
- Add the allow rules first, and switch the firewall policy to drop last. Allow SSH before you switch a firewall on.
- Delete your test table and your dummy interface when you are done: that is your way back.
- Run
sshd -t,apache2ctl configtestornft -c -fbefore you reload a service. - Test a fix from the outside: the proof is a login that fails or a connection that times out.
- Never put a password on a command line, and give a private key the mode
600. - Compare a fingerprint over a second channel before you accept a host key or trust a GnuPG key.
- Do not delete a changed host-key line before you know why the key changed.
- A listener on
0.0.0.0is open to the network. Bind to127.0.0.1when only this machine needs the service. - Give an account the least rights that the job needs, and own the web files as
root. - Keep the old kernel as a way back when you install a new one.
Part 4 · Operations and troubleshooting
Follow the boot process (lesson 1)
| Task | Command |
|---|---|
| Tell UEFI from BIOS | [ -d /sys/firmware/efi ] && echo UEFI |
| Show the kernel command line, the kernel | cat /proc/cmdline, uname -r |
| List the files of the initial RAM disk | sudo lsinitramfs /boot/initrd.img |
| Show and set the default target | systemctl get-default, sudo systemctl set-default multi-user.target |
| Time of the boot, slowest units, critical chain | systemd-analyze, systemd-analyze blame, systemd-analyze critical-chain |
| List boots, read the last boot, errors only | journalctl --list-boots, journalctl -b -1, journalctl -b -p err |
| Kernel messages | journalctl -k, sudo dmesg |
| Rebuild the boot menu after a change | sudo update-grub (never edit grub.cfg by hand) |
| Read the reason of a panic | grep -B2 "Kernel panic" panic.log |
Boot to a shell (GRUB, key e) | systemd.unit=rescue.target (needs a root password), or init=/bin/bash on Ubuntu |
Containers (lessons 2 and 3)
| Task | Command |
|---|---|
| Pull an image | podman pull docker.io/library/alpine:3.20 |
| Run once and delete | podman run --rm IMAGE COMMAND |
| Run in the background with a port | podman run -d --name NAME -p 8088:80 IMAGE |
| List containers, all of them | podman ps, podman ps -a |
| Logs, a command inside, stop, remove | podman logs NAME, podman exec NAME CMD, podman stop NAME, podman rm NAME |
| Make and use a volume | podman volume create V, podman run -v V:/data IMAGE |
| Bind a folder read-only | -v "$PWD/site:/usr/share/nginx/html:ro" |
| Make a network | podman network create NET, podman run --network NET IMAGE |
| Build and list an image | podman build -t NAME:1 FOLDER, podman images |
| Read the digest of an image | podman image inspect IMAGE --format '{{.Digest}}' |
| Make a pod with a published port | podman pod create --name P -p 8090:80, podman run --pod P ... |
| Pod to YAML, YAML to pod, remove | podman kube generate P -f p.yaml, podman kube play p.yaml, podman kube down p.yaml |
Track changes with Git (lesson 4)
| Task | Command |
|---|---|
| Start a repository, set who you are | git init -b main R, git config user.name "You" |
| Status, stage, commit | git status --short, git add FILE, git commit -m "text" |
| Show changes | git diff, git diff --staged, git log --oneline --graph |
| Branch, switch, merge | git switch -c NAME, git switch main, git merge NAME |
| Finish a merge after a conflict | edit the file, git add FILE, git commit --no-edit |
| Throw away or undo a change | git restore FILE, git revert --no-edit COMMIT |
| Tag a release | git tag -a v1.0 -m "text" |
| Make and use a remote | git init --bare -b main r.git, git remote add origin PATH, git push -u origin main --tags |
| Copy a repository | git clone SOURCE FOLDER |
| Find a commit by text | git log --oneline -S TEXT |
| Remove a path from all history | git filter-repo --invert-paths --path .env --force |
| Ignore a file | echo ".env" >> .gitignore |
Describe systems as code (lesson 5)
| Task | Command |
|---|---|
| Check a JSON file | python3 -m json.tool FILE |
| Read YAML as data | python3 -c 'import yaml; print(yaml.safe_load(open("f.yaml")))' |
| Validate a description without applying it (refuses an unknown key, a missing key, a bad mode, an empty or unsafe path, a section that is not a list) | python3 converge.py desired.yaml --check |
| Apply it, and apply it again | python3 converge.py desired.yaml (the second run: changed: 0) |
| Install a pre-commit hook | cp pre-commit.sh .git/hooks/pre-commit; chmod +x .git/hooks/pre-commit |
| Skip a hook once (the server still checks) | git commit --no-verify |
Troubleshoot the network (lesson 6)
| Task | Command |
|---|---|
| Run a command in a private namespace | sudo ip netns exec NS COMMAND |
| Address, route, route for one address | ip -br addr, ip route, ip route get ADDRESS |
| Reach a neighbour | ping -c 1 -W 2 ADDRESS |
| Resolve a name the way programs do | getent hosts NAME |
| Request and read the exit code | curl -sS -m 3 URL (6 no such name, 7 refused or no route, 28 time-out: read whether the message says Resolving or Connection) |
Listening ports on the server (sudo shows other users' processes) | sudo ss -tlnp |
| Firewall rules | sudo nft list ruleset |
Troubleshoot CPU and memory (lesson 7)
| Task | Command |
|---|---|
| Busiest processes | ps -eo pid,pcpu,ni,stat,args --sort=-pcpu | head |
| One process now | top -b -n 2 -d 3 -p PID |
| Limit the CPU of a service | sudo systemd-run --unit U -p CPUQuota=20% CMD, systemctl set-property --runtime U CPUQuota=5% |
| Find zombies and their parent | ps -eo pid,ppid,stat,args | awk '$3 ~ /^Z/' |
| Limit memory, wait, read the result | sudo systemd-run --wait -p MemoryMax=50M -p MemorySwapMax=0 CMD (oom-kill) |
| Memory and its pressure | free -m, cat /proc/pressure/memory |
| Swap | swapon --show, free -m, sysctl vm.swappiness |
| Memory and swap of a unit | systemctl status U | grep Memory: |
Troubleshoot storage (lesson 8)
| Task | Command |
|---|---|
| Space, inodes | df -h PATH, df -i PATH |
| Biggest files | sudo du -ah PATH | sort -rh | head |
| Inodes by folder | sudo du --inodes -d 1 PATH |
| Deleted files that are still open | sudo lsof -nP +aL1 PATH 2>/dev/null |
| Empty an open file | : > /proc/PID/fd/N |
| Mount options | findmnt -no OPTIONS PATH |
| Remount read-write | sudo mount -o remount,rw PATH |
| Check an unmounted file system, change nothing | sudo fsck -f -n DEVICE |
| Mount an image file through a loop device | sudo mount -o loop FILE PATH |
Troubleshoot logins, permissions and services (lesson 9)
| Task | Command |
|---|---|
| Account line, password status, expiry | getent passwd NAME, passwd -S NAME, chage -l NAME |
| Change the shell, unlock | sudo usermod -s /bin/bash NAME, sudo passwd -u NAME |
| Modes of every part of a path | namei -l PATH |
| Run one command as another user | sudo -u NAME COMMAND |
| What sudo allows a user, check a rule file | sudo -l -U NAME, sudo visudo -cf FILE |
| Why a unit fails | systemctl status U, journalctl -u U, systemd-analyze verify FILE |
| Status codes | 200/CHDIR folder, 203/EXEC program, 217/USER account |
Build a troubleshooting kit (lesson 10)
| Task | Command |
|---|---|
| Collect the evidence bundle | bash kr-evidence.sh -o bundles |
| Give the bundle a fixed name | KR_STAMP=demo bash kr-evidence.sh |
| Check the seal | cd bundles/evidence-demo && sha256sum -c manifest.sha256 |
| Pack it for the ticket | tar -czf case.tar.gz -C bundles evidence-demo |
Safety habits
- Work on a practice system with a snapshot. Plant faults there and nowhere else.
- Collect evidence before you change anything. The first state is the state of the incident.
- Test from the bottom up, change one thing at a time, and write down what you saw.
- Read a file before you delete it, and move or empty it when you are not sure. Never
kill -9first. - Check a rule file before you load it:
visudo -cf,nft -c -f,systemd-analyze verify,converge.py --check. - Use the full name and a version or digest for an image. Run containers rootless, and the program inside as an ordinary user.
- Never commit a secret. If one was committed, remove it from the history and rotate it.
- A limit (
CPUQuota,MemoryMax) keeps a service alive while you search;Restart=alwaysmeans that you must stop the unit. - Prove every repair with the test that failed before.
- Keep a root shell open in a second terminal when you change sudo, SSH or the firewall.