Linux Hour 6: Security Hardening and Kernel Mechanism
- Draw the checks that an access request goes through in the kernel: seccomp (system call entry) → DAC (owner/group/others) + ACL) → capabilities (privilege coverage) → LSM (SELinux/AppArmor), and can determine which layer was rejected based on the error code and log (
EACCES/EPERM,type=AVC,apparmor="DENIED",type=SECCOMP). - Use CIS style baselines (Ubuntu's
usg, RHEL's OpenSCAPoscap) to auditlinuxlab/rhellab, understanding "baseline = auditable configuration list", not a one-time script. - Understand SELinux context, Boolean values and AVC on
rhellab, useaudit2whyto locate and correct fix the port and label rejection of myapp; useaa-genprofonlinuxlabto generate AppArmor configuration file for myapp and switch from complain to enforce. - Use nftables / firewalld / ufw three ways to implement the same policy: Only let 22 and 5000 inbound, and know that they all end up in the kernel nf_tables.
- Understand the control flags of the PAM stack, write the sudoers policy with minimum permissions, and build an SSH Certificate Authority (CA) to issue short-term user certificates and host certificates.
- Use auditd rules to record key files and privileged commands, and use
ausearch/aureport/journalctlto do a small forensics. - Use sysctl to harden kernel parameters and distinguish the scope of
limits.conf(PAM login session) and systemdLimitNOFILE=(service); usesystemd-analyze securityto reduce the exposure score of myapp.service from above 9 points to the 2–4 range. - Use
unshare/nsenter/systemd-runto create a "container" yourself and understand where the isolation and resource limitations of Docker/Kubernetes come from.
1-hour time allocation table
| # | Time | Module | Core content | Animation/Interaction | Experiment (linuxlab / rhellab) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: Reinforce the lab VM | Snapshot, check myapp.service, optionally create rhellab and deploy myapp | Self-assessment of hardening readiness (10 items) | Two machines curl :5000/healthz Normal |
| 1 | 00–06 | Security model and CIS baseline | DAC / capabilities /LSM/seccomp Layering, Attack Surface, CIS Level 1/2, usg, OpenSCAP, systemd sandbox | Core Animation: Access requests pass through four gates | usg/oscap audit + systemd-analyze security myapp.service |
| 2 | 06–13 | SELinux and AppArmor | Type enforcement, context, mode, boolean, port type, audit2why; AppArmor profile, complain/enforce, aa-genprof | SELinux Decision Simulator (mode × boolean × label) | Fix labels and port denials for myapp; generate AppArmor configuration for myapp |
| 3 | 13–21 | Firewall | netfilter hook, nftables table/chain/rule/set, firewalld area, ufw; only release 22 and 5000 | Rule matching of data packets passing through the input chain | Three front-ends implement the same policy and verify |
| 4 | 21–28 | Authentication: PAM · sudo · SSH certificate | PAM four-type stack and control flags, faillock/pwquality, sudoers minimum privileges (sudo-rs difference), SSH user/host certificate, KRL revocation | PAM stack evaluation simulator | Build an SSH CA and issue an 8-hour certificate to log in |
| 5 | 28–35 | Audit and forensics | kauditd → auditd, rule syntax, auid, immutable rules, ausearch/aureport, journald persistence and FSS | A system call becomes a pipeline of audit records | "Who changed myapp.env?" Forensic drill |
| 6 | 35–42 | Kernel parameters and resource limits | sysctl hardening list, sysctl.d priority, ulimit and pam_limits, systemd Limit*=, cgroup resource attributes | "Where does the limit for this process come from?" emulator | Hardening sysctl + fix Too many open files |
| 7 | 42–50 | namespaces and cgroups v2 | 8 Namespaces, unshare/nsenter/lsns, cgroup v2 unified hierarchy, controller files, systemd-run resource restrictions | Step by step "hand-made containers" | unshare + systemd-run limit memory/CPU, observe OOM |
| 8 | 50–60 | Comprehensive hardening architecture review | Defense layering in depth, threat modeling, exception management, review checklist, continuous compliance | Reinforcement scorer + "Permission denied which level?" Troubleshooting tree | Do a complete review of myapp host |
| — | After class | Cheat sheet · Comprehensive experiment | Reinforce the myapp host to an online baseline | Final test (12 questions) | Comprehensive experiment |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Experiments |
|---|---|---|---|---|---|---|---|---|---|---|
| Determine which layer the rejection comes from | ✓ | ✓ | · | · | ✓ | · | · | ✓ | ausearch -m AVC,SECCOMP, getpcaps | M1 animation / M8 troubleshooting tree |
| Baseline Audit and Compliance Scan | ✓ | · | · | · | · | · | · | ✓ | usg audit, oscap xccdf eval | M1 Experiment |
| Service Sandbox (systemd) | ✓ | · | · | · | · | ✓ | ✓ | ✓ | systemd-analyze security | myapp hardened drop-in |
| Mandatory Access Control (MAC) | ✓ | ✓ | · | · | ✓ | · | · | ✓ | semanage, restorecon, aa-genprof | M2 Experiment |
| Host Firewall | · | · | ✓ | · | · | · | · | ✓ | nft, firewall-cmd, ufw | Pass only 22/5000 |
| Authentication and privilege management | · | · | · | ✓ | ✓ | · | · | ✓ | pam-auth-update, authselect, visudo, ssh-keygen -s | SSH CA |
| Audit and forensics | · | ✓ | · | ✓ | ✓ | · | · | ✓ | auditctl, ausearch, aureport | Who changed the configuration |
| Kernel parameters and resource limits | · | · | ✓ | · | · | ✓ | ✓ | ✓ | sysctl --system, prlimit | M6 experiment |
| Container underlying mechanism | ✓ | · | · | · | · | ✓ | ✓ | · | unshare, nsenter, systemd-run | Hand-made container |
Excluded content from this course (and where to learn)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| File permissions, ACL, special permission bits, sudo basics | Has been taught in Lesson 1, and will be used directly in this lesson | Hour 1 |
| SSH key login, sshd basic reinforcement, journald basics | Lesson 2 has been taught, this lesson will add SSH certificate and audit on top of it | Hour 2 |
| Docker image security, container seccomp/capabilities default value, rootless container | Belong to the container layer; this lesson only talks about kernel primitives | Docker 8-hour course |
| Batch implementation baseline (such as CIS role) with Ansible | Configuration management topic | Ansible 8-hour course |
| Security Alert and Indicator Dashboard | Monitoring Topic | Prometheus & Grafana course |
| strace/perf/eBPF in-depth analysis, startup failure | Troubleshooting and Performance Topics | Hour 7 |
| Full Disk Encryption (LUKS/TPM), Secure Boot and IMA/EVM, SELinux Policy module development | Exceeds 1 hour, requires specialized environment | Ubuntu Security Documentation · RHEL 10 Security hardening |
How to use this courseware
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Test · Voice · Video. It is recommended to read the "Principle" and "Animation" first, and then do the "Experiment".
Reinforcement operations (firewall, PAM, sshd, SELinux) are the easiest to lock yourself out. Take a VM snapshot before each experiment, and always keep a logged-in root sessionAlways maintain a logged-in root session, or confirm that you can log in using the console.
Quiz score ≥ 70% or click "Mark this module completed" to count the progress (save in this browser). The "Voice" tab uses the browser Web Speech API to read Chinese explanations.
sudo-rs and rust-coreutils), RHEL system uses it in contrast Rocky Linux / AlmaLinux 10.2(released on 2026-05, kernel 6.12). Two points require special attention: ① As of 2026-11-17, the CIS configuration files listed in Ubuntu's official USG documentation only cover 20.04 / 22.04 / 24.04 (24.04 corresponds to CIS v1.0.0), and 26.04 is not listed26.04 not listed, the usg experiment in this lesson therefore gives the 24.04 approach and explains the alternatives on 26.04; ② Please refer to the actual output of oscap info for the CIS configuration files available in the SCAP content of RHEL 10. When learning with 24.04, sudo is traditional sudo.ws, and the other commands are the same. Module 0 · Preparation: Reinforced lab VM (Ubuntu + RHEL department)
- CompletedLesson 1 and Lesson 2: Experimental machine
linuxlab(Ubuntu Server 26.04 LTS, administratorlabadmin), myapp runs as system usermyapp/opt/myapp(virtual environment/opt/myapp/venv), configuration/etc/myapp/myapp.env, systemd unitmyapp.service, listener 5000, health check/healthz, Redis fromredis-serverpackage. - Working directory
~/linuxlab; the files created in this lesson are placed in~/linuxlab/hour6. - Optional: Second virtual machine
rhellab(Rocky Linux 10.2 or AlmaLinux 10.2, minimal installation, 2 vCPU / 2–4 GB RAM), also withlabadminadministrator. Without rhellab, the SELinux/firewalld/OpenSCAP section can just read "expected output". - Cost: Local virtual machine, no cloud charges. Permissions: sudo for both machines. Risk: Correcting errors in firewall, PAM, and sshd will result in inability to log in - take a snapshot first and retain a root session.
Step 1: Take a snapshot of linuxlab and confirm that myapp is normal
# Multipass: Stop first and then take a snapshot (the snapshot requires the instance to be stopped) multipass stop linuxlab multipass snapshot linuxlab --name before-hour6 multipass start linuxlab multipass shell linuxlab
mkdir -p ~/linuxlab/hour6 && cd ~/linuxlab/hour6 lsb_release -ds; uname -r; systemctl --version | head -1 systemctl is-active myapp.service redis-server.service curl -fsS http://127.0.0.1:5000/healthz; echo systemctl cat myapp.service | grep -E '^(User|ExecStart|EnvironmentFile|WorkingDirectory|SyslogIdentifier)='
Ubuntu 26.04 LTS
7.0.0-15-generic
systemd 259 (259.5-1ubuntu1)
active
active
{"status":"ok"}
User=myapp
WorkingDirectory=/opt/myapp/app
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 2 app:app
SyslogIdentifier=myapp
Myapp's log identifier is myapp (SyslogIdentifier=myapp), so it is displayed as myapp[PID] in journald, and journalctl can be used -u myapp or journalctl -t myapp query. The specific ExecStart is based on the units in your previous lessons.
dnf with sudo apt install -y python3-venv redis-server). All reinforcements in this lesson have passed drop-in(/etc/systemd/system/myapp.service.d/*.conf) superposition, there is no need to modify the original unit file, so there are no requirements for the ExecStart you wrote in Lesson 2. A basic reinforcement drop-in has been added to myapp in Lesson 2; the drop-in in this lesson uses the number after 60- (60-sandbox.conf, 61-limits.conf), and is loaded after the file name in order. The instructions with the same name are loaded later (SystemCallFilter= and other list-type instructions will be accumulated). The layout of myapp: code /opt/myapp/app/app.py(WorkingDirectory=/opt/myapp/app), virtual environment /opt/myapp/venv, configuration /etc/myapp/myapp.env(root:myapp 0640), Type=exec. Hyper-V/VirtualBox users please use the corresponding "checkpoint/snapshot" function. The WSL2 default kernel does not enable SELinux/AppArmor enforcement, and does not have independent firewall and auditd behaviors.Not suitable for this lesson. Step 2 (optional): Prepare rhellab and deploy minimal myapp
RHEL 10 does not provide the redis package (replaced by Valkey). To focus on SELinux, rhellab Deploy a minimal myapp that does not rely on Redis and only provides / and /healthz. The path, user, and port are exactly the same as linuxlab.
sudo dnf -y install python3 python3-pip policycoreutils-python-utils setroubleshoot-server \
audit nginx openscap-scanner scap-security-guide
sudo useradd --system --home-dir /opt/myapp --shell /usr/sbin/nologin myapp
sudo install -d -o myapp -g myapp /opt/myapp
sudo install -d -m 0750 -o root -g myapp /etc/myapp
echo 'APP_ENV=lab' | sudo tee /etc/myapp/myapp.env >/dev/null
sudo chown root:myapp /etc/myapp/myapp.env && sudo chmod 0640 /etc/myapp/myapp.env
sudo -u myapp python3 -m venv /opt/myapp/venv
sudo -u myapp /opt/myapp/venv/bin/pip install --quiet flask gunicorn
sudo install -d -o myapp -g myapp /opt/myapp/app && sudo tee /opt/myapp/app/app.py >/dev/null <<'EOF'
from flask import Flask, jsonify
app = Flask(__name__)
@app.get("/")
def index():
return "hello from myapp on rhellab\n"
@app.get("/healthz")
def healthz():
return jsonify(status="ok")
EOF
sudo tee /etc/systemd/system/myapp.service >/dev/null <<'EOF'
[Unit]
Description=myapp (Flask + gunicorn)
After=network-online.target
Wants=network-online.target
[Service]
Type=exec
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp/app
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 2 app:app
Restart=on-failure
SyslogIdentifier=myapp
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload && sudo systemctl enable --now myapp.service
curl -fsS http://127.0.0.1:5000/healthz; echo
getenforce
Created symlink '/etc/systemd/system/multi-user.target.wants/myapp.service' → '/etc/systemd/system/myapp.service'.
{"status":"ok"}
Enforcing
/opt (type usr_t/bin_t) and without a dedicated policy will run in the unconfined_service_t domain - SELinux does not "constrain" it. Module 2 will demonstrate two real-world rejection scenarios: Files with incorrect tags (from home directory mv Come here) and restricted domain (nginx's httpd_t) to connect to port 5000. Warm-up: answer from memory (30 seconds)
Ordinary users execute cat /etc/shadow and get Permission denied. Which layer rejects it?
DAC: The mode of /etc/shadow is 640 root:shadow (Ubuntu) or 000 (RHEL system). Ordinary users are neither the owner nor the group. On the RHEL system, the mode is 000, and root can still read, because root has CAP_DAC_OVERRIDE (on Ubuntu, root itself is the owner, with r bit) - capability coverage is the third level of module 1.
ping is not a setuid program. Why can ordinary users use it?
Modern distributions allow ICMP sockets with the file capability (cap_net_raw) or net.ipv4.ping_group_range, both of which have a much smaller permission surface than setuid root. Available with getcap /usr/bin/ping and sysctl net.ipv4.ping_group_range.
Self-assessment of reinforcement readiness (10 items)
Check the projects that linuxlab has currently accomplished (the results are saved in this browser). Come back and check it again after finishing this lesson and completing the comprehensive experiment.
Module 1 · Linux Security Model and Hardening Baseline (CIS)
- Name the location and order of the four types of access control mechanisms in the Linux kernel: seccomp At the system call entry; DAC and capabilities are in the permission check of VFS/subsystem; the LSM hook performs mandatory access control after the DAC.
- Judge the source of rejection based on error codes and logs: DAC →
EACCESand default do not write logs; SELinux →type=AVC; AppArmor →apparmor="DENIED"; seccomp →EPERM/SIGSYSandtype=SECCOMP. - Understand the Level 1/Level 2 and Server/Workstation configuration files of CIS Benchmark, be able to use
usgoroscapto generate audit reports, and use customization (tailoring) to manage exceptions. - Use the systemd sandbox command to add a layer of "service-level minimum permissions" to myapp.service, and use
systemd-analyze securityto quantify the effect.
What: What layers does the Linux security model consist of
| Layer | Mechanism | Questions answered | Who will configure | When rejected | |
|---|---|---|---|---|---|
| seccomp | The BPF filter that comes with the process is executed in the system call entry | What system calls is allowed to be called by this process? | The program itself, systemd SystemCallFilter=, and the container runtime | Return EPERM (or custom errno), or kill directly SIGSYS; audit type SECCOMP | |
| DAC Discretionary Access Control | Owner/group/other rwx + POSIX ACL | Can this UID/GID read/write/execute this object? | CAP_DAC_OVERRIDE, CAP_NET_BIND_SERVICE) | Owner of the object (chmod/chown/setfacl) | EACCES (Permission denied), default does not generate logs |
| capabilities | Split root privileges into about 40 (such as CAP_DAC_OVERRIDE, CAP_NET_BIND_SERVICE) | Can this process bypass a DAC rule or perform a privileged operation? | File capability (setcap), systemd CapabilityBoundingSet=/AmbientCapabilities= | EPERM or EACCES; SELinux will also check the capability itself again ({ dac_override }AVC) | |
| LSM(SELinux / AppArmor / Landlock / Yama…) | Security hooks throughout the kernel (security_file_open, security_socket_connect...) | Does the policy allow this subject to do this operation on this object, no matter who the UID is? | System policy (administrator/distribution), the process itself cannot be relaxed | SELinux: type=AVC … denied; AppArmor: apparmor="DENIED" | |
| namespaces / cgroups | Isolate "what can be seen" and "how much can be used" | Which set of PID, mount and network does the process see? How much memory/CPU can be used at most? | systemd, container runtime | Not "rejected" but "cannot be seen/limited/OOM" (module 7) |
Real execution sequence (take openat() as an example): user mode initiates system call → kernel entry runs first seccomp filter → path lookup with may_open() → DAC in inode_permission() (generic_permission: mode bits and ACL) → check if DAC is not satisfied capabilities (CAP_DAC_OVERRIDE/CAP_DAC_READ_SEARCH, this check itself will also go through LSM's capable hook) → LSM's security_inode_permission/security_file_open hook → successfully returns the file descriptor. Many materials draw these layers as concentric circles of "DAC → capabilities → LSM → seccomp", which are arranged conceptually from the inside to the outside. When actually executed, seccomp runs first, and it does not look at the file path at all, but only the system call number and parameters.
Key rules: LSM is "can only be tightened, not relaxed" (restrictive): SELinux will not release what DAC has rejected; SELinux can still reject what DAC allows. Root is also subject to SELinux/AppArmor/seccomp - this is the value of MAC: even if the attacker gets the root-level UID, he cannot get out of the scope of the policy.
Why: Why layering (defense in depth)
- DAC is "the owner has the final say": a compromised myapp process can read and write everything that the myapp user can read and write, including other people's files in
/tmpand keys in the home directory. - Capabilities allow programs that "require a little privilege" (binding port 80, changing the system time) to not have to run as full root.
- MAC (SELinux/AppArmor) writes "what this program should do" as a policy, and deviations from the expected behavior (the Web process reads
/etc/shadow, connects to the SSH port) will be rejected and leave a log. - seccomp reduces the kernel attack surface: Most kernel privilege escalation vulnerabilities require calling unpopular system calls (such as
keyctl,bpf,userfaultfd), and the services are disabled when they are not used at all.
How: Baseline (Benchmark) turns experience into a checklist
CIS Benchmarks are formulated by the Center for Internet Security community consensus and released by release version (such as "CIS Ubuntu Linux 24.04 LTS Benchmark v1.0.0"). Each version has four configuration files: Level 1 Server / Level 1 Workstation / Level 2 Server / Level 2 Workstation. Level 1 is a project that "has little impact on the business and should basically be done"; Level 2 is defense in depth and may affect functions (such as forcing all AppArmor enforces, stricter audit rules, separate partitions). Each rule has two sections: "Audit" and "Remediation", which can be automated.
| Tools | Distribution | Audit | Fix | Instructions (verified on 2026-11-17) |
|---|---|---|---|---|
| USG(Ubuntu Security Guide) | Ubuntu LTS (requires Ubuntu Pro, free subscription available for individuals) | usg audit cis_level1_server, reported in /var/lib/usg/ (HTML + XML) | usg fix <profile> | Official documentation lists 20.04 (CIS v1.0.0), 22.04 (v2.0.0), 24.04 (v1.0.0), not listed 26.04; for customization usg generate-tailoring |
| OpenSCAP + SCAP Security Guide(ComplianceAsCode) | RHEL/Rocky/Alma (also has Ubuntu content) | oscap xccdf eval --profile … --report report.html ds.xml | --remediate or generate a Bash/Ansible repair script | RHEL 10 content files are ssg-rhel10-ds.xml; CIS/STIG/PCI-DSS and other configuration files are subject to the output of oscap info; RHEL 9 content cannot be used to scan RHEL 10 |
| Lynis | General | lynis audit system | Only suggestions | It is not an official implementation of CIS and is suitable for general hardening checks on 26.04 |
When: when to do it and to what level
- When the image is built (Packer golden image in Lesson 5), Level 1 is applied. After going online, the same configuration file is used for regular auditing, and deviations are reported as alarms.
- Level 2 is only enabled for highly sensitive systems (payment, identity, springboard), and will be run in the pre-release environment for a week before business return.
- Any "not applicable" rules are written into the tailoring file (with reasons and approvers), rather than being ignored manually - what the auditor wants to see is "whether the exception is controlled."
Comparison with similar technologies
| DAC | capabilities | SELinux | AppArmor | seccomp | |
|---|---|---|---|---|---|
| How to identify objects | Inode's UID/GID/mode | Bitmap in process credentials | Tag (extended attributes security.selinux) | Path name | System call number and parameters |
| Default release | All | All | RHEL / Rocky / Alma / Fedora | Ubuntu / Debian / SUSE | All (enabled by process) |
| Can it be relaxed by the process itself | The owner can chmod | Can only give up but not obtain (except exec file capability) | No | No | No (only stricter filters can be added) |
| Reject logs | None (auditd rules required) | None (capability AVC is available under SELinux) | AVC | apparmor="DENIED" | SECCOMP (default record of kill action) |
chattr +i can all deny root. ② "Turn off SELinux to solve the problem" - that is equivalent to removing an entire layer of defense. The correct approach is to read AVC, change labels or Boolean values (Module 2). ③ "After running usg fix , you will be compliant" - the baseline is a continuous state, not a one-time action; and the fix may change the configuration that the business depends on (such as disabling USB, changing SSH settings), you must first audit, review, tailoring, and then fix. ④ "CIS score 100% = security" - the baseline only covers configuration items and does not cover application vulnerabilities, credential leaks and patch timeliness. Architecture diagram: Layered defense panorama
Flowchart: openat() check sequence in the kernel
Core animation: An access request passes through seccomp → DAC → capabilities → LSM
Select a real scenario and click "Play" or "Next". Each level shows the actual judgments made by the kernel, the return values, and where and what logs will be left when rejected at this level. Note: DAC rejections are not logged; LSM and seccomp rejections produce audit records.
Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
namei -l PATH | Display the permissions of each directory on the path step by step (the first step of DAC troubleshooting) | Missing directory x permissions are the most common cause of hiding |
getpcaps PID / grep Cap /proc/PID/status | View the process's capability set | capsh --decode=000001ffffffffff Decode |
getcap -r / 2>/dev/null | List files with capabilities Program | Work with find / -perm -4000 to do privilege escalation inventory |
cat /sys/kernel/security/lsm | Currently enabled LSM list and sequence | Ubuntu includes apparmor, RHEL system includes selinux |
grep Seccomp /proc/PID/status | Process seccomp mode | 0 not enabled, 1 strict, 2 filter |
sudo usg audit cis_level1_server | Ubuntu CIS Audit | --tailoring-file; report /var/lib/usg/ |
oscap info / oscap xccdf eval | List config files/ Perform scan | --profile, --results, --report, --remediate |
systemd-analyze security [UNIT] | Evaluate service sandbox exposure (0 best – 10 worst) | List all services without unit name; --threshold= can be used with CI |
Inventory privileges: capabilities, setuid and LSM
cat /sys/kernel/security/lsm; echo getcap -r /usr/bin /usr/sbin 2>/dev/null find / -xdev -perm -4000 -type f 2>/dev/null | head PID=$(systemctl show -p MainPID --value myapp.service) grep -E '^(Uid|Cap(Inh|Prm|Eff|Bnd|Amb)|NoNewPrivs|Seccomp):' /proc/$PID/status
lockdown,capability,landlock,yama,apparmor,ima,evm /usr/bin/ping cap_net_raw=ep /usr/bin/mtr-packet cap_net_raw=ep /usr/bin/su /usr/bin/mount /usr/bin/passwd ... Uid: 998 998 998 998 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 CapBnd: 000001ffffffffff CapAmb: 0000000000000000 NoNewPrivs: 0 Seccomp: 0
Interpretation: myapp is running as non-root, and the effective capability is empty, which is good; but the boundary set (CapBnd) is still full, NoNewPrivs is 0, and there is no seccomp - if it execs a setuid program, it may still gain privileges. This is the hole that the systemd sandbox needs to fill below. Note: Ubuntu 26.04's sudo is provided by sudo-rs. The sudo path seen in find -perm -4000 may be a sudo-rs file such as /usr/lib/cargo/bin/sudo. The actual output shall prevail.
Add systemd sandbox (drop-in) to myapp.service
systemd-analyze security myapp.service | tail -n 1 sudo systemctl edit myapp.service --drop-in=60-sandbox
[Service] # —— Privileges —— NoNewPrivileges=yes CapabilityBoundingSet= AmbientCapabilities= RestrictSUIDSGID=yes # —— File system —— ProtectSystem=strict ProtectHome=yes PrivateTmp=yes PrivateDevices=yes UMask=0077 # —— Kernel and process visibility —— ProtectKernelTunables=yes ProtectKernelModules=yes ProtectKernelLogs=yes ProtectControlGroups=yes ProtectClock=yes ProtectHostname=yes ProtectProc=invisible LockPersonality=yes RestrictRealtime=yes RestrictNamespaces=yes MemoryDenyWriteExecute=yes # —— Network and system calls —— RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX SystemCallArchitectures=native SystemCallFilter=@system-service SystemCallFilter=~@privileged SystemCallErrorNumber=EPERM
sudo systemctl daemon-reload && sudo systemctl restart myapp.service systemctl is-active myapp.service && curl -fsS http://127.0.0.1:5000/healthz; echo systemd-analyze security myapp.service | grep -E '✗|Overall' | head -n 15
→ Overall exposure level for myapp.service: 9.2 UNSAFE 😨
active
{"status":"ok"}
✗ PrivateNetwork= Service has access to the host's network 0.5
✗ RootDirectory=/RootImage= Service runs within the host's root directory 0.1
✗ PrivateUsers= Service has access to other users 0.2
✗ IPAddressDeny= Service does not define an IP address allow list 0.2
✗ DeviceAllow= Service has no device ACL 0.2
→ Overall exposure level for myapp.service: 2.4 OK 🙂
How to verify: In addition to /healthz, look at journalctl -u myapp -b --no-pager | tail. There is no EPERM/Read-only file system reports an error. Common mistakes: When an application needs to write /opt/myapp/data, ProtectSystem=strict will make it read-only, use ReadWritePaths=/opt/myapp/data or better StateDirectory=myapp (automatically create /var/lib/myapp); Python extensions that rely on writable executable memory (part JIT/cffi callback), MemoryDenyWriteExecute=yes will cause a crash, so only this item is removed at this time. Production use: Incorporate drop-in into a Packer image or Ansible role; use systemd-analyze security --threshold=4 --offline=yes in CI to intercept exposure fallback (--offline requires newer systemd).
CIS Audit: Ubuntu (usg) and RHEL (OpenSCAP)
# 1. Attach Ubuntu Pro (free subscription for individuals: ubuntu.com/pro) sudo pro attach <TOKEN> sudo pro enable usg sudo apt install -y usg # 2. Audit (read-only) sudo usg audit cis_level1_server ls /var/lib/usg/ # 3. Customize exceptions, and then click Customize File Audit/Repair sudo usg generate-tailoring cis_level1_server tailor.xml sudo usg audit --tailoring-file tailor.xml # sudo usg fix --tailoring-file tailor.xml ← Try on snapshot first
sudo apt install -y lynis sudo lynis audit system --quick | tee ~/linuxlab/hour6/lynis.txt | tail -n 25 grep -E 'Hardening index|Warning' ~/linuxlab/hour6/lynis.txt
ls /usr/share/xml/scap/ssg/content/
DS=/usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml # If Rocky/Alma provides its own file name, the output of the above line shall prevail
oscap info --profiles $DS | grep -iE 'cis|stig|pci'
PROFILE=$(oscap info --profiles $DS | awk -F: '/cis_server_l1/{print $1; exit}')
sudo oscap xccdf eval --profile "$PROFILE" \
--results ~/oscap-results.xml --report ~/oscap-report.html $DS | tail -n 20
xccdf_org.ssgproject.content_profile_cis:CIS Red Hat Enterprise Linux 10 Benchmark for Level 2 - Server xccdf_org.ssgproject.content_profile_cis_server_l1:CIS Red Hat Enterprise Linux 10 Benchmark for Level 1 - Server xccdf_org.ssgproject.content_profile_cis_workstation_l1:CIS Red Hat Enterprise Linux 10 Benchmark for Level 1 - Workstation ... Title Ensure auditd Service Is Enabled Rule xccdf_org.ssgproject.content_rule_service_auditd_enabled Result pass Title Disable SSH Root Login Rule xccdf_org.ssgproject.content_rule_sshd_disable_root_login Result fail
Note: oscap's exit code 2 means "a rule failed", not a program error. --remediate will directly modify the system and execute it on the snapshot first; you can also oscap xccdf generate fix --profile "$PROFILE" --fix-type ansible --output fix.yml $DS to generate an Ansible playbook and then execute it after review (connected to Ansible course).
Experiment 1: Hierarchical inventory + baseline audit + myapp sandbox (about 8 minutes)
sudo -u myapp cat /etc/shadow; echo "exit=$?" sudo journalctl -k --since "-1min" | grep -i denied || echo "(no entries in kernel log)"
cat: /etc/shadow: Permission denied exit=1 (no entries in kernel log)
capsh From libcap2-bin)
echo "labadmin secret" > /tmp/secret.txt && chmod 600 /tmp/secret.txt # Owner is labadmin, others have no permission sudo cat /tmp/secret.txt sudo capsh --drop=cap_dac_override,cap_dac_read_search -- -c 'cat /tmp/secret.txt'; echo "exit=$?" sudo capsh --print | grep -E '^(Current|Bounding)' | cut -c1-120 rm /tmp/secret.txt
labadmin secret cat: /tmp/secret.txt: Permission denied exit=1 Current: =ep Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,...
root is not the owner of this file. The first time it can be read depends entirely on CAP_DAC_OVERRIDE; The second time the UID is still 0, but the boundary concentration removes the two capabilities that cover the DAC, so root is also blocked by the mode bit - "root's power" is essentially a set of capabilities. (Note: The owner of Ubuntu's /etc/shadow is root. Using it to do this experiment will succeed because of the r bit of the owner. If /tmp is enabled with fs.protected_regular, it will only affect opening with O_CREAT and will not affect the reading of this experiment.)
@clock The root process of the group (including clock_settime, settimeofday, adjtimex), let it try to "set the time to the current time" (no harm even if allowed)
sudo systemd-run --wait --pipe -p SystemCallFilter=~@clock \ -p SystemCallErrorNumber=EPERM date -s "@$(date +%s)"; echo "exit=$?" sudo systemd-run --wait --pipe -p SystemCallFilter=~@clock date -s "@$(date +%s)"; echo "exit=$?" sudo journalctl -k --since "-2min" -g 'type=1326' --no-pager | tail -n 1
date: cannot set date: Operation not permitted
exit=1
Running as unit: run-u123.service; invocation ID: …
Finished with result: signal
Main processes terminated with: code=killed, status=31/SYS
exit=1
audit: type=1326 audit(1763370000.123:412): auid=1000 uid=0 gid=0 ses=3 subj=unconfined pid=4242 comm="date" exe="/usr/bin/date" sig=31 arch=c000003e syscall=227 compat=0 ip=0x7f… code=0x80000000
First time: return EPERM, the process handles the error by itself, will not generate a SECCOMP record (errno) The action is not recorded by default); the second time: there is no SystemCallErrorNumber, the default action is to kill the process (SIGSYS, signal 31), the kernel writes type=1326 (ie SECCOMP) audit record, syscall=227 is x86_64's clock_settime (using ausyscall 227 translation). When Ubuntu does not install auditd by default, these audit records are printed to the kernel log by the kernel, so use journalctl -k to view them. Ubuntu 26.04's date comes from rust-coreutils, the prompt text may be slightly different.
60-sandbox.conf, restart and compare the scores before and after
systemd-analyze security myapp.service | tail -n 1 PID=$(systemctl show -p MainPID --value myapp.service) grep -E '^(CapBnd|NoNewPrivs|Seccomp):' /proc/$PID/status sudo -u myapp touch /opt/myapp/x 2>&1; sudo nsenter -t $PID -m touch /opt/myapp/x 2>&1
→ Overall exposure level for myapp.service: 2.4 OK 🙂 CapBnd: 0000000000000000 NoNewPrivs: 1 Seccomp: 2 touch: cannot touch '/opt/myapp/x': Permission denied touch: cannot touch '/opt/myapp/x': Read-only file system
The first one is DAC (myapp There is no write permission for the directory). The second entry after entering the mount namespace of the service is a read-only mount caused by ProtectSystem=strict - the same operation, different denial layers, and different error messages.
oscap ("Command" page), run on linuxlab lynis, each record 5 failed items, leaving them for the review of module 8. sudo rm /etc/systemd/system/myapp.service.d/60-sandbox.conf sudo systemctl daemon-reload && sudo systemctl restart myapp.service
Case 1: An RCE was "caged"
Problem: There is template injection in a certain Flask service. The attacker gained the ability to execute commands as a service user and tried to download the privilege escalation tool to /tmp and execute and read /home/*/.ssh. How to do it: The service has already added ProtectHome=yes, PrivateTmp=yes, NoNewPrivileges=yes, SystemCallFilter=@system-service. Attackers cannot see the home directory, setuid programs cannot escalate privileges, and calls such as ptrace/keyctl can be made directly. EPERM. A series of SECCOMP records appeared in auditd, and the alarm was triggered within 5 minutes. Configuration: is the drop-in of the "Command" page. Restrictions: The sandbox cannot prevent attackers from reading data that the service itself has access to (database credentials, Redis), so credential minimization and network egress control are equally important.
Case 2: CIS Level 1 one-click repair causes SSH interruption
Problem: The team directly executes the repair script on the production machine. The SSH rule sets AllowGroups, but the operation and maintenance account is not in this group. All servers can only be rescued through the console. Method: The process is changed to: fix in the image building phase → pre-release verification → audit only in production; all inapplicable rules are written into the tailoring file and approved by the security team. Configuration:usg generate-tailoring / OpenSCAP tailoring (autotailor; the SCAP Workbench graphical tool has been removed in RHEL 10). Limitations: The tailoring file itself requires version control and periodic review, otherwise it will become a "permanent exception".
Case 3: Auditor requires "proof" that hardening continues to be effective
Problem: Manual screenshots are taken every quarter to prove compliance, which is time-consuming and cannot cover configuration drift. Method: Run oscap xccdf eval/usg audit every night by systemd timer, archive the XML results to object storage, and push the score and number of failed rules to monitoring as indicators (see Prometheus & Grafana course). Limitations: Scans require root and read a large number of files, schedule during off-peak times and set Nice=/IOSchedulingClass=idle.
Common errors and solutions
myapp.service: Main process exited, code=exited, status=226/NAMESPACE
Cause:systemd failed when setting the mount namespace (ProtectSystem/ReadWritePaths/PrivateTmp, etc.) for the service. The most common reason is that the directory pointed to by ReadWritePaths= does not exist.
journalctl -u myapp -b -n 30 --no-pager | grep -iE 'namespace|No such file' systemctl cat myapp.service | grep -E 'ReadWritePaths|ReadOnlyPaths|InaccessiblePaths'
Fix: Create the directory first, or add - before the path (such as ReadWritePaths=-/opt/myapp/data) to ignore it if it does not exist; the writable state directory is preferred to use StateDirectory=.
myapp.service: Main process exited, code=killed, status=31/SYS
Cause:The process called SystemCallFilter= a system call that is not allowed. The default action is to kill the process with SIGSYS.
sudo ausearch -m SECCOMP -ts recent -i | tail -n 5 sudo journalctl -k -g 'type=1326' -b --no-pager | tail -n 3 ausyscall x86_64 227 # Translate syscall number into name (from auditd package), 227 = clock_settime
Fix: After confirming that the system call is indeed required, add it to the allowed list (SystemCallFilter=… append), or set SystemCallErrorNumber=EPERM to let the application receive an error code instead of being killed, and use systemd-analyze syscall-filter @system-service to view the calls contained in the group.
PermissionError: [Errno 13] Permission denied: '/opt/myapp/data/cache.db' (root operation also reports an error)
Reason:Errno 13 is EACCES, which may come from DAC, LSM other than read-only mount, or capability Removed by the boundary set.
namei -l /opt/myapp/data/cache.db sudo ausearch -m AVC -ts recent 2>/dev/null | tail -n 3 sudo journalctl -k -g 'apparmor="DENIED"' -b --no-pager | tail -n 3 grep CapBnd /proc/$(systemctl show -p MainPID --value myapp)/status
Fixed: Press "With or without logs" diversion: no logs → see namei to fix DAC; there are AVC/apparmor records → module 2; Read-only file system (EROFS) → Read-only path to ProtectSystem.
usg: command not found / This command must be run as root / Ubuntu Pro service not enabled
Cause:USG is provided via Ubuntu Pro without a subscription attached or services enabled; or the current distribution version is not on the USG support list (not listed as of verification date 26.04).
pro status lsb_release -rs
Fixed:sudo pro attach TOKEN && sudo pro enable usg && sudo apt install usg; 26.04 temporarily uses Lynis or ComplianceAsCode community content for approximate checking, and indicates "non-CIS official configuration file" in the report.
OpenSCAP: No such file or directory ... ssg-rhel9-ds.xml or “profile not found”
Reason: The path or configuration file ID of other versions is copied; RHEL 10 must use the content file of RHEL 10.
rpm -ql scap-security-guide | grep -- '-ds.xml' oscap info --profiles /usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml
Fix: Use the full profile ID listed in oscap info (starting with xccdf_org.ssgproject.content_profile_).
1. One command to view the capability boundary set, NoNewPrivs and seccomp mode of the myapp main process.
grep -E '^(CapBnd|NoNewPrivs|Seccomp):' /proc/$(systemctl show -p MainPID --value myapp.service)/status
2. List all CIS-related configuration file IDs in the SCAP content on rhellab.
oscap info --profiles /usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml | grep -i cis
The developer said: "myapp reported Permission denied when writing /opt/myapp/uploads, but the directory is clearly myapp:myapp 755, and I also failed to touch it using root." How do you determine which layer it is?
The directory owner is correct and root failed, indicating that it is not an ordinary DAC. First look at the error text: if it is Read-only file system, it is a read-only mount of systemd ProtectSystem=strict (root is also restricted in the service namespace), add ReadWritePaths=/opt/myapp/uploads; if it is Permission denied, check ausearch -m AVC/journalctl -k -g apparmor, if there is a record, it is LSM; there is no need to look at lsattr (chattr +i) and mount options. Note that if the "enter as root" operation is successful in the host namespace, it is more likely that the problem lies in the service's own sandbox.
Verified instructional video
Official document
- capabilities(7) · seccomp(2) · systemd.exec(5) · systemd-analyze(1)
- Ubuntu Security Guide (USG) · RHEL 10: Scanning the system for configuration compliance
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: A process icon issues an openat request, and there are four doors in a horizontal corridor: seccomp, DAC, capabilities, LSM.
Narration: A file access goes through four doors. The first door is at the system call entrance, called seccomp. It only depends on what system call you call.
Screen: rw-r----- root shadow is displayed on the DAC door, myapp is blocked, and no footprints are left on the ground.
Narration: The second door is traditional authority. When rejected by it, Permission denied is returned, but no log is written by default.
Screen: root takes the CAP_DAC_OVERRIDE key to bypass the DAC door, but is stopped in front of the SELinux door, and an AVC denied record pops up on the wall.
Narration: Root can bypass permission bits by relying on capability. However, mandatory access control does not recognize UIDs, only policies, and every rejection will leave an AVC record.
Screen: Inventory icon CIS Level 1, scanners usg and oscap generate red and green reports, and finally the exposure score of myapp.service dropped from 9.2 to 2.4.
Narration: The baseline writes these experiences into a list, which can be automatically audited; the systemd sandbox implements minimum permissions to each service.
Module 2 · SELinux and AppArmor
- Understand the SELinux security context
user:role:type:level, explains the type enforcement (TE) ruleallow source type target type: class permission;how to determine access. - Master three modes, single domain permissive, Boolean value, file context (
semanage fcontext+restorecon) and port type (semanage port). - Use
ausearch -m AVC→audit2why→ minimal repair process to solve myapp's label rejection and nginx → 5000's port rejection; know whyaudit2allowis the last resort. - Use
aa-status,aa-genprof,aa-logprofto generate AppArmor configuration file for myapp on Ubuntu, switch from complain to enforce.
What: Two mandatory access controls
SELinux Give each process and each object (file, port, socket, process...) a tag. The policy only looks at the tag: allow httpd_t httpd_sys_content_t:file { read open getattr };. The default is deny all. If there is no allow rule, it is denied. The label is stored in the file's extended attribute security.selinux, so the results are different when the file is moved (mv retains the original label) and copied/new (inherits the label of the target directory).
| Context field | Example | Meaning |
|---|---|---|
| user | system_u / unconfined_u | SELinux users (not Linux users), for RBAC |
| role | system_r / object_r | process role; file unification is the core of object_r |
| type | httpd_t, user_home_t, http_port_t | decision: the type of the process Called "domain" |
| level | s0 / s0:c1,c2 | MLS/MCS level; containers (container_t) are isolated from each other with different MCS categories |
AppArmor Centered on path: the configuration file is attached to the executable file path (such as /opt/myapp/venv/bin/gunicorn), specify which paths, network families, and capabilities this program can access. Programs without a configuration file are unconfined (subject only to DAC) - the opposite of SELinux's "all tagged by default".
Why: Why not turn them off
Most of the actions after exploiting web vulnerabilities (reading /etc/shadow, writing webshells to other directories, rebounding connections to arbitrary ports, reading data from other services) will be blocked by MAC and leave AVC/DENIED records. Turning off MAC only results in "reading fewer logs", but at the cost of losing an entire layer of defense. The clear advice from the RHEL system documentation is: when encountering a rejection, diagnose first, then make minimal repairs.
How: SELinux modes, switches and tools
| Concepts | Commands | Key points |
|---|---|---|
| Modes | getenforce, sestatus, setenforce 0|1 | Enforcing Deny and record; Permissive only records but does not deny; Disabled does not load the policy. setenforce will become invalid after restarting, and the persistent configuration is in /etc/selinux/config. To completely disable it from RHEL 9, you need to add selinux=0 to the kernel parameters. Disabled in the configuration file only prevents the policy from loading |
| Single domain permissive | semanage permissive -a httpd_t | Only one domain enters permissive to collect logs, which is much safer than global setenforce 0 |
| Boolean value | getsebool -a, setsebool -P name on | Switch reserved by the policy author, such as httpd_can_network_connect; -P Persistence |
| File context | semanage fcontext -a -t type 'regular' + restorecon -Rv path | Write the "rules" first, and then let restorecon label according to the rules; chcon It is only a temporary change and will be lost after relabeling |
| Port type | semanage port -l | grep -w 5000, -a / -m | When the port already has a type (5000 defaults to commplex_main_port_t) -a will report already defined, use -m |
| Diagnosis | ausearch -m AVC,USER_AVC -ts recent, audit2why, sealert -a | audit2why will tell you whether it is "missing rules", "boolean value is not enabled" or "constraint" |
| Last resort | audit2allow -M mymod + semodule -i mymod.pp | will allow everything that appears in the log, making it easy to write attack behaviors into the policy; it must be reviewed manually .te File |
Modes and Tools for AppArmor (Ubuntu)
| Mode | Behavior | Command |
|---|---|---|
| enforce | Deny and log apparmor="DENIED" | aa-enforce /etc/apparmor.d/config file |
| complain | Allow but log apparmor="ALLOWED", for learning | aa-complain … |
| unconfined / disable | Does not load | aa-disable... (Create link in /etc/apparmor.d/disable/) |
| Generate and update | Interactively generate rules based on logs | aa-genprof program, aa-logprof (tools from apparmor-utils) |
| View | Loaded configuration files and restricted processes | aa-status, ps -eZ or cat /proc/PID/attr/current |
Ubuntu 24.04 onwards is enabled by default kernel.apparmor_restrict_unprivileged_userns=1: When ordinary users create a user namespace, they will be put into a restrictive AppArmor configuration, and thus will not be able to obtain privileges in the namespace - this will affect unshare without sudo in module 7.
When: Which one to use
- Follow the distribution default: RHEL uses SELinux, Ubuntu/Debian uses AppArmor. Both are kernel "main LSMs" and are generally not enabled at the same time.
- If you need strong multi-tenant isolation (container MCS, multi-level security), choose SELinux; if you need to quickly write policies for a single third-party program, the learning curve of AppArmor is flatter.
- Container scenario: Docker/Podman/Kubernetes gives the container
container_t+ random MCS category on the SELinux host; load thedocker-defaultconfiguration by default on the AppArmor host (see Docker course for details).
Comparison with similar technologies
| SELinux | AppArmor | Landlock | |
|---|---|---|---|
| Object identification | Tag (inode xattr) | Path | Path hierarchy (declared by the process itself) |
| Default policy | System-wide labeling, targeted policy | Only restricts programs with configuration files | None, the process locks voluntarily |
| File movement/hard link | The label follows the inode (mv is reserved) | The new path may have no rules | By level |
| Log | type=AVC | type=1400 apparmor="DENIED" | Newer kernels provide audit support |
| Learning/generating tools | audit2why / audit2allow / sepolicy generate | aa-genprof / aa-logprof | Program code |
setenforce 1. ② "chcon has been changed" - next time restorecon or automatic relabel will be changed back, and rules must be written using semanage fcontext . ③ "It is not SELinux without AVC" - there are a large number of dontaudit rules in the policy that will be silently rejected. Use semodule -DB to temporarily close dontaudit and then reoccur, and the troubleshooting is completed semodule -B Restore. ④ "It is safe if deny is written in the AppArmor configuration file" - AppArmor defaults to deny unlisted access, and explicit deny means "no logs are recorded and cannot be allowed by subsequent rules". Architecture diagram: SELinux one-time access decision
Flowchart: Correct order for fixing SELinux rejects
SELinux Decision Simulator: Mode × Boolean × Label
Select an access scenario, then adjust the switches and click "Initiate Access". The simulator checks in sequence according to the real process: DAC → Find allow rules (including Boolean conditions) → Mode; and gives AVC records and audit2why output consistent with the real system format.
Core commands and parameters
| Commands | Function | Key parameters/description |
|---|---|---|
ls -Z / ps -eZ / id -Z | View the context of the file/process/current user | ss -tlnpZ You can also see the context of the listening process |
sestatus -v | Mode, policy name, key file context | The policy name should be targeted |
semanage fcontext -l | grep /opt/myapp | View file context rules | -a add, -d delete, -e source target equivalent path |
matchpathcon PATH / restorecon -nvR | Preview "What label should be" | -n Do not modify, only display |
semanage boolean -l -C | List the Boolean values that have been modified from the default value | Audit "who turned on what switch" |
sesearch -A -s httpd_t -t http_port_t -c tcp_socket | Query the allow rules in the policy | From setools-console, verify the fix is minimal |
aa-status | AppArmor loaded configuration files and modes | Require root to see all |
aa-genprof / aa-logprof | Generate/update configuration files based on logs | Requires apparmor-utils |
apparmor_parser -r FILE | Reload a single configuration file | -R uninstall; -p preprocessing view include expansion |
SELinux: View context (rhellab)
sestatus | head -n 6 ps -eZ | grep -E 'gunicorn|nginx|sshd' | head -n 5 ls -Zd /opt/myapp /opt/myapp/venv/bin/gunicorn /etc/myapp/myapp.env sudo ss -tlnpZ | grep -E ':5000|:22 ' sudo semanage port -l | grep -wE '5000|http_port_t'
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
system_u:system_r:unconfined_service_t:s0 2311 ? 00:00:01 gunicorn
system_u:system_r:sshd_t:s0-s0:c0.c1023 1022 ? 00:00:00 sshd
unconfined_u:object_r:usr_t:s0 /opt/myapp
unconfined_u:object_r:usr_t:s0 /opt/myapp/venv/bin/gunicorn
unconfined_u:object_r:etc_t:s0 /etc/myapp/myapp.env
LISTEN 0 2048 0.0.0.0:5000 0.0.0.0:* users:(("gunicorn",pid=2311,fd=5)) proc_ctx=system_u:system_r:unconfined_service_t:s0
commplex_main_port_t tcp 5000
http_port_t tcp 80, 81, 443, 488, 8008, 8009, 8443, 9000
Interpretation:myapp runs in unconfined_service_t - a service domain "started by systemd, without exclusive policies" and almost unrestricted by SELinux. If you want myapp itself to be constrained, you can use sepolicy generate --init /opt/myapp/venv/bin/gunicorn to generate a policy skeleton (requires policycoreutils-devel), which is beyond the scope of this lesson; the focus of this lesson is to understand and fix rejections.
SELinux: Diagnostic Trio
sudo ausearch -m AVC,USER_AVC -ts recent -i sudo ausearch -m AVC -ts recent | audit2why sudo sealert -a /var/log/audit/audit.log | head -n 40 # requires setroubleshoot-server
AppArmor: View and Switch Mode (linuxlab)
sudo apt install -y apparmor-utils sudo aa-status | head -n 12 cat /proc/$(systemctl show -p MainPID --value myapp.service)/attr/current sysctl kernel.apparmor_restrict_unprivileged_userns
apparmor module is loaded. 121 profiles are loaded. 48 profiles are in enforce mode. /usr/bin/man /usr/lib/snapd/snap-confine ... unconfined kernel.apparmor_restrict_unprivileged_userns = 1
How to verify:myapp is currently unconfined; after completing the experiment, myapp should be displayed here (enforce). Common mistakes: After modifying the configuration file, forget to apparmor_parser -r to reload; or the program has been running before the configuration file is loaded, and the service needs to be restarted to attach (the configuration file is attached during exec).
Experiment 2: Fix two types of SELinux rejection + generate AppArmor configuration for myapp (about 12 minutes)
mv to /opt/myapp/bin(mv will retain user_home_t tags)
cat > ~/start.sh <<'EOF' #!/bin/sh exec /opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 2 app:app EOF chmod 755 ~/start.sh sudo install -d /opt/myapp/bin && sudo mv ~/start.sh /opt/myapp/bin/start.sh sudo chown root:root /opt/myapp/bin/start.sh ls -Z /opt/myapp/bin/start.sh sudo mkdir -p /etc/systemd/system/myapp.service.d printf '[Service]\nExecStart=\nExecStart=/opt/myapp/bin/start.sh\n' | sudo tee /etc/systemd/system/myapp.service.d/62-start.conf sudo systemctl daemon-reload; sudo systemctl restart myapp.service; systemctl status myapp.service --no-pager | head -n 6
unconfined_u:object_r:user_home_t:s0 /opt/myapp/bin/start.sh
Job for myapp.service failed because the control process exited with error code.
× myapp.service - myapp (Flask + gunicorn)
Active: failed (Result: exit-code)
Process: 3120 ExecStart=/opt/myapp/bin/start.sh (code=exited, status=203/EXEC)sudo ausearch -m AVC -ts recent -i | tail -n 4 sudo ausearch -m AVC -ts recent | audit2why matchpathcon /opt/myapp/bin/start.sh
type=AVC msg=audit(11/17/2026 10:12:03.441:612) : avc: denied { execute } for pid=3120 comm=(start.sh) name=start.sh dev="dm-0" ino=1837402 scontext=system_u:system_r:init_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0
Was caused by:
Missing type enforcement (TE) allow rule.
You can use audit2allow to generate a loadable module to allow this access.
/opt/myapp/bin/start.sh system_u:object_r:usr_t:s0
Don't follow the prompts to audit2allow! matchpathcon shows that the path "should" be usr_t, indicating that the real problem is wrong label, not lack of policy rules. Allowing init_t to execute user_home_t is equivalent to allowing systemd to execute anything in the user's home directory.
sudo restorecon -Rv /opt/myapp sudo systemctl restart myapp.service && curl -fsS http://127.0.0.1:5000/healthz; echo
Relabeled /opt/myapp/bin/start.sh from unconfined_u:object_r:user_home_t:s0 to unconfined_u:object_r:usr_t:s0
{"status":"ok"}
If myapp's directory requires a non-default type (for example, the upload directory needs to be read by nginx: httpd_sys_content_t), write the rule instead of chcon: sudo semanage fcontext -a -t httpd_sys_content_t '/opt/myapp/static(/.*)?' && sudo restorecon -Rv /opt/myapp/static.
httpd_t) Reverse proxy to 5000
sudo tee /etc/nginx/conf.d/myapp.conf >/dev/null <<'EOF'
server {
listen 8080;
location / { proxy_pass http://127.0.0.1:5000; }
}
EOF
sudo nginx -t && sudo systemctl enable --now nginx
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/healthz
sudo ausearch -m AVC -ts recent -c nginx | audit2why
502
type=AVC msg=audit(1763374501.220:640): avc: denied { name_connect } for pid=3301 comm="nginx" dest=5000 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:commplex_main_port_t:s0 tclass=tcp_socket permissive=0
Was caused by:
One of the following booleans was set incorrectly.
Description:
Allow httpd to can network connect
Allow access by executing:
# setsebool -P httpd_can_network_connect 1
...
8080 is already http_cache_port_t, nginx can listen (name_bind); what is being rejected is the outbound connection to 5000. audit2why may list multiple Boolean values that can be released at the same time (such as Boolean values whose names are related to OpenStack). Select the one with semantic correct. Note: The firewall policy in this lesson only allows 22 and 5000, and 8080 is only accessible on this machine.
sudo setsebool -P httpd_can_network_connect on
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/healthz
getsebool httpd_can_network_connect
sudo semanage boolean -l -C
200 httpd_can_network_connect --> on SELinux boolean State Default Description httpd_can_network_connect (on , on) Allow httpd to can network connect
httpd_can_network_connect Allow httpd_t connectionsAny TCP port. A tighter approach is to put the backend on an already allowed port type, or use semanage port -m -t http_port_t -p tcp 5000 to change the port type, and then use sesearch -A -s httpd_t -t http_port_t -c tcp_socket -p name_connect Confirm that there is a corresponding allow in the policy (may depend on other Boolean values such as httpd_can_network_relay ), and then turn off the broad Boolean value. Changing the port type will affect all domains using port 5000. This should be stated during the review. sudo aa-genprof /opt/myapp/venv/bin/gunicorn # After the prompt "Please start the application to be profiled in another window", go to Terminal 2 to operate # Return to Terminal 1 and press S to scan the log, follow the prompts to select (A)llow / (I)nherit / (G)lob for each access, and finally press F to end
sudo systemctl restart myapp.service for p in / /healthz /healthz /; do curl -fsS http://127.0.0.1:5000$p >/dev/null; done sudo journalctl -k -g 'apparmor="ALLOWED"' --since "-5min" --no-pager | tail -n 3
audit: type=1400 audit(…): apparmor="ALLOWED" operation="open" class="file" profile="/opt/myapp/venv/bin/gunicorn" name="/opt/myapp/app/app.py" pid=5120 comm="gunicorn" requested_mask="r" denied_mask="r" fsuid=998 ouid=998 audit: type=1400 audit(…): apparmor="ALLOWED" operation="connect" class="net" profile="/opt/myapp/venv/bin/gunicorn" pid=5122 comm="gunicorn" family="inet" sock_type="stream" protocol=6 requested="connect" denied="connect" laddr=127.0.0.1 lport=46120 faddr=127.0.0.1 fport=6379
/etc/apparmor.d/opt.myapp.venv.bin.gunicorn). The reference version after review is as follows (for example, please refer to your aa-logprof results):
abi <abi/4.0>,
include <tunables/global>
profile myapp /opt/myapp/venv/bin/gunicorn flags=(complain) {
include <abstractions/base>
include <abstractions/nameservice>
include <abstractions/python>
network inet stream,
network inet6 stream,
network unix stream,
/opt/myapp/venv/bin/gunicorn r,
/usr/bin/python3* ix,
/opt/myapp/ r,
/opt/myapp/** r,
/opt/myapp/venv/** mr,
owner /tmp/** rwk,
@{PROC}/@{pid}/fd/ r,
deny /etc/shadow r,
deny @{HOME}/** rwx,
}
/etc/myapp/myapp.env does not need to appear in the configuration file: EnvironmentFile= is read by systemd (PID 1) and passed to the process as an environment variable, myapp Never open this file yourself - this is also a small advantage of "the key does not fall on the path readable by the application".
sudo sed -i 's/ flags=(complain)//' /etc/apparmor.d/opt.myapp.venv.bin.gunicorn sudo apparmor_parser -r /etc/apparmor.d/opt.myapp.venv.bin.gunicorn sudo systemctl restart myapp.service cat /proc/$(systemctl show -p MainPID --value myapp.service)/attr/current curl -fsS http://127.0.0.1:5000/healthz; echo sudo aa-status | grep -A1 myapp
myapp (enforce)
{"status":"ok"}
myapp
If a new rejection occurs later, use sudo aa-logprof to incrementally update instead of returning complain.
62-start.conf and nginx configuration on rhellab and turn off the Boolean value; linuxlab's AppArmor configuration is reserved for subsequent modules.
sudo rm /etc/systemd/system/myapp.service.d/62-start.conf /etc/nginx/conf.d/myapp.conf sudo systemctl daemon-reload && sudo systemctl restart myapp.service sudo systemctl disable --now nginx sudo setsebool -P httpd_can_network_connect off
Case 1: After the release, the service could not be started, and the classmate on duty turned off SELinux
Problem:CI scp the build product to the deployment user's home directory and then mv to /opt, systemd reported 203/EXEC; the on-duty staff executed setenforce 0 restored the service and changed /etc/selinux/config to permissive. A security scan discovered it three months later. Method: Add restorecon -R /opt/myapp at the end of the deployment script, or change it to install/cp (inherit the target directory label); monitor the getenforce result and alert when it is not Enforcing. Configuration: Ansible's ansible.posix.selinux and community.general.sefcontext module solidification status. Limitations: Files installed by RPM are automatically tagged by rpm. The problem mainly lies in manual/script deployment.
Case 2: Unable to log in after changing SSH port
Problem: After changing sshd to 2222 to "reduce scanning noise", sshd failed to start after restarting: error: Bind to port 2222 on 0.0.0.0 failed: Permission denied. Method:semanage port -a -t ssh_port_t -p tcp 2222, and release it in firewalld; the RHEL comment in the sshd configuration file itself prompts this step. Restrictions: Changing the port is not a security control, certificate authentication and MFA are (Module 4).
Case 3: Third-party agent intercepted by AppArmor on Ubuntu
Problem: After the monitoring agent is upgraded, reading /proc/*/fd fails, and apparmor="DENIED" appears in the log. Method: First collect the configuration file aa-complain for a day, use aa-logprof to review the new rules, and then aa-enforce; put the configuration file into configuration management. Restrictions: The manufacturer's own configuration files may be overwritten during package upgrades. Local supplementary rules should be written in the file with the same name under /etc/apparmor.d/local/.
Common errors and solutions
ValueError: Port tcp/5000 already defined
Cause:5000 already has a type (commplex_main_port_t) in the policy, semanage port -a can only add undefined ports.
sudo semanage port -l | grep -w 5000
Fix:Use -m to modify: sudo semanage port -m -t http_port_t -p tcp 5000; evaluate the impact on other domains.
status=203/EXEC and avc: denied { execute } ... tcontext=...user_home_t
Reason: The executable file comes from the home directory mv and retains user_home_t.
ls -Z /path/to/binary; matchpathcon /path/to/binary
Fixed:restorecon -v; when the path requires a special type, first semanage fcontext -a and then restorecon.
There is no AVC, but the problem disappears after setenforce 0
Reason: Hits the dontaudit rule, refusing to be silenced.
sudo semodule -DB # Close dontaudit and rebuild the policy # Reproduce the problem sudo ausearch -m AVC -ts recent | audit2why sudo semodule -B # Restore dontaudit
Repair: Process according to the new AVC; be sure to restore after troubleshooting, otherwise the log will be overwhelmed by noise.
apparmor="DENIED" operation="open" profile="myapp" name="/opt/myapp/uploads/a.png" requested_mask="wc"
Reason: The configuration file is only given to /opt/myapp/** r, and new functions need to write the upload directory.
sudo journalctl -k -g 'apparmor="DENIED"' -b --no-pager | tail -n 5 sudo aa-logprof
Fixed: Only add write permission to the directory (/opt/myapp/uploads/** rw,), then apparmor_parser -r; also check whether systemd's ProtectSystem=strict also requires ReadWritePaths= - both layers must be allowed.
The service failed immediately after aa-genprof ended: Failed to execute... Permission denied (apparmor="DENIED" operation="exec")
Reason: The script interpreter (venv's python points to /usr/bin/python3.x) was not allowed to execute.
Fixed: Add /usr/bin/python3* ix, to the configuration file (inherit the current configuration file execution), reload and restart the service.
1. Let /srv/myapp-static and all files under it permanently use the httpd_sys_content_t type.
sudo semanage fcontext -a -t httpd_sys_content_t '/srv/myapp-static(/.*)?' sudo restorecon -Rv /srv/myapp-static
2. Only allow httpd_t one domain to enter permissive to collect logs, and then cancel it.
sudo semanage permissive -a httpd_t # …reproduce and collect AVC… sudo semanage permissive -d httpd_t
Colleagues used audit2allow -a -M fixall && semodule -i fixall.pp to "fix" all SELinux problems with one click. How would you judge?
-a Reading all audit logs will turn all denied behaviors in history (including attack attempts and incorrect access caused by configuration errors) into allow rules. Correct approach: Read audit2why one by one, and use standard methods to fix label errors, Boolean values, and port types first. If there are any remaining missing rules, use audit2allow to generate .te and then review them line by line. Only keep necessary permissions. Module names are meaningful and included in version control. The fixall module should also be rolled back: semodule -r fixall.
Verified instructional video
Official document
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: Files and processes are labeled, nginx label httpd_t, port 5000 label complex_main_port_t.
Narration: SELinux does not recognize user names, only labels. Each access is a combination of a source type, a target type, a class and a permission.
Screen: nginx connection 5000 is blocked by the red baffle, AVC denied name_connect pops up in audit.log, audit2why points to the Boolean value.
Narration: When rejected, look at the AVC first and then submit it to audit2why. It will tell you whether the label is wrong, the Boolean value is not turned on, or there is really a lack of rules.
Screen: start.sh From home directory mv to opt, the label is still user_home_t; restorecon flashes, the label becomes usr_t, and the service turns green.
Aside: Moving files retains old tags. The correct fix is to restorecon, not to turn off SELinux.
Screen: Ubuntu terminal runs aa-genprof, the log scrolls, and the profile changes from complain to enforce.
Narration: On Ubuntu, AppArmor uses paths to write policies. First learn in complain mode, then review the rules, and finally switch to enforce.
Module 3 · Firewall: nftables, firewalld and ufw
- Name the 5 hooks of netfilter (prerouting / input / forward / output / postrouting) and conntrack The purpose of this is to know that inbound traffic to the local service only goes through the input chain.
- Read and write nftables tables, chains (type / hook / priority / policy), rules, and collections, and can atomically load and roll back rule sets.
- Use firewalld's zone (zone) and service/port to implement the same policy and distinguish between runtime and permanent.
- Use ufw to implement the same strategy on Ubuntu, and know that the ports published by Docker will bypass ufw's INPUT rules.
ip, ss, routing and DNS. Importance:★★★★★What: netfilter and nftables
netfilter is a set of hooks in the kernel network stack; nf_tables is a virtual machine that runs rules on these hooks. User-mode tools are nft. It replaces the four sets of tools iptables / ip6tables / arptables / ebtables: a table of the inet family can handle both IPv4 and IPv6. Today's iptables command is actually iptables-nft on most distributions - the syntax is still iptables, and the rules are written into nf_tables.
| Concept | Explanation | Example |
|---|---|---|
| Table table | Rule container, belonging to a family: ip, ip6, inet, arp, bridge, netdev | table inet filter |
| base chain base chain | Hang on the hook: type (filter/nat/route), hook, priority, default policy | type filter hook input priority filter; policy drop; |
| Rule rule | Match expression + statement (accept / drop / reject / jump / counter / log / limit) | tcp dport { 22, 5000 } accept |
| Collection / mapping | Efficient IP/port collection, dynamically updated, with timeout | set blocklist { type ipv4_addr; flags timeout; } |
| conntrack | Connection tracking: ct state new/established/related/invalid | The return packet relies on established release |
The same hook can be hung with multiple basic chains from different tables (such as firewalld's table and Docker's table), and they are executed according to the priority value from small to large; any chain is dropped, accept It only means "this chain is allowed", and subsequent chains will still be checked. This is why "running two firewall managers at the same time" interferes with each other.
Why: The value of the host firewall
- Cloud security group/network ACL is the first step, and the host firewall is the second step: lateral movement in the same network segment, misconfigured security groups, and temporarily opened debugging ports all rely on it.
- Redis (6379) is also running on the myapp host. Ubuntu's
redis-serveronly binds to 127.0.0.1 by default, but a configuration error (bind 0.0.0.0) may expose passwordless Redis - the default deny inbound policy can block such errors.
How: How to choose between the three front ends
| nftables(nft) | firewalld | ufw | |
|---|---|---|---|
| Default in | Debian system optional; available in all distributions | RHEL / Rocky / Alma / Fedora | Ubuntu (not enabled by default) |
| Abstraction layer | Write rule set directly | Region + service + port + rich rule | allow/deny/limit + application configuration |
| Persistence | /etc/nftables.conf + nftables.service | --permanent Write /etc/firewalld/ | /etc/ufw/, loaded after startup |
| Generated rules | Whatever you write is what you write | table inet firewalld | Generate ufw-* chain via iptables-nft |
| Suitable | Requires collection/mapping, fine control, container hosting | Multiple network cards/multi-region servers, dynamic changes (D-Bus) | Single machine, simple strategy |
firewalld zone (zone)
Zone is the "level of trust in the source". Data packets are classified into a certain area according to the source address (--add-source) or the inbound network card (--add-interface), and then the services and ports released by the zone are used. RHEL is the default zone public and allows ssh, dhcpv6-client and cockpit by default. Commonly used areas: drop (drop all), block (reject and return to ICMP), public, internal, trusted (release all, use with caution).
When: Trade-offs in production
- Follow the release version: RHEL system uses firewalld, Ubuntu uses ufw on a small scale, complex scenarios/container hosts directly maintain nftables files and include them in configuration management.
- Only one manager is used for the same machine; the Docker/Kubernetes host needs to understand that the container will insert its own rules when running (Ubuntu 26.04's docker.io 29 uses the nftables backend by default).
- Outbound is also worth controlling: the server rarely needs to access any external network, and restricting outbound can prevent rebound shells and data outgoing (this lesson will only do inbound).
Comparison with similar technologies
| Host Firewall | Cloud Security Group (NSG / Security Group) | systemd IPAddressDeny= | |
|---|---|---|---|
| Position | Native kernel netfilter | Host/virtual network layer, outside of VM | cgroup eBPF filtering for individual services |
| Granularity | Interface/Address/Port/Status | NIC / Subnet | Single systemd unit |
| Can it be modified after failure | root can be changed | Cloud API permission required | root can be changed |
-p 5000:5000 for prerouting and forwarding of nat, without going through the INPUT rules managed by ufw, and the outside can still access it (see Docker course's networking chapter). ② "It's safe if the policy is dropped. Will the return packet be thrown away?" - Yes! When you forget to write ct state established,related accept , the return packet of the connection (apt, DNS) initiated by this machine will not come in. ③ "Don't worry about IPv6 if it is not useful" - only write the rules of the ip table, and completely liberalize IPv6 inbound; use the inet family to cover it once, and MustICMPv6 (neighbor discovery) be allowed, otherwise the IPv6 network will be disconnected. ④ "After adding firewall-cmd, it will be permanent" - without --permanent just change the runtime, it will be gone after restarting or reloading. Architecture diagram: netfilter hook and native inbound path
Flow chart: three front ends fall into the same kernel
nft list ruleset Look at the actual rules in effect in the kernelData packets pass through the input chain: match rule by rule
Select an inbound packet and click "Next Rule" to match it step by step. The counter on the right simulates the changes in counter packets N in nft list ruleset; it finally displays the kernel decision (accept/drop) and the phenomenon seen by the client.
Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
nft list ruleset | View all rules in the kernel (all front-ends) | -a Display handle, -n does not resolve the name |
nft -c -f FILE | Only checks syntax and semantics, does not load | CI verification rule file |
nft -f FILE | Atomic loading rule set | The first line of the file is commonly used flush ruleset (will clear other front-end tables!) |
nft add element inet filter blocklist { 203.0.113.9 } | Dynamic update collection | The collection can bring timeout |
firewall-cmd --get-active-zones | The current effective area and its interface/source | --get-default-zone |
firewall-cmd --permanent --add-port=5000/tcp | Permanently release the port | then --reload; or runtime test first and then --runtime-to-permanent |
ufw default deny incoming / ufw allow 5000/tcp | ufw default policy and release | ufw limit 22/tcp speed limit; ufw status numbered |
ss -tlnp + external nc -zv / nmap -Pn | Verify "what is listening" and "what can be connected externally" | The combination of the two is the complete verification |
nftables: only release 22 and 5000
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state invalid counter drop
ct state { established, related } accept
iif "lo" accept
meta l4proto icmp icmp type { echo-request, destination-unreachable, time-exceeded } accept
meta l4proto ipv6-icmp accept
tcp dport { 22, 5000 } ct state new counter accept
limit rate 5/minute burst 10 packets log prefix "nft-input-drop: " level info
counter
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
# Safety net: Automatically clear the rules after 5 minutes (confirm that you are not locked out before canceling) sudo systemd-run --unit=nft-deadman --on-active=5min /usr/sbin/nft flush ruleset sudo nft -c -f /etc/nftables.conf && sudo nft -f /etc/nftables.conf sudo nft list chain inet filter input # Open a new SSH session and confirm that you can log in: sudo systemctl stop nft-deadman.timer sudo systemctl enable --now nftables.service
Running timer as unit: nft-deadman.timer
Will run service as unit: nft-deadman.service
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state invalid counter packets 0 bytes 0 drop
ct state { established, related } accept
iif "lo" accept
...
tcp dport { 22, 5000 } ct state new counter packets 3 bytes 180 accept
limit rate 5/minute burst 10 packets log prefix "nft-input-drop: " level info
counter packets 12 bytes 1248
}
}
How to verify: On the host machine, nc -zv LINUXLAB_IP 5000 is successful, nc -zv LINUXLAB_IP 6379 -w 2 times out (dropped, not refused); journalctl -k -g nft-input-drop Can see discarded packets. Common mistakes: Forgetting established,related causes apt update to get stuck; flush ruleset also clears Docker or ufw tables. Production use: Put the rule file into Git, check the changes with nft -c first, and then load it with the "dead man's switch".
firewalld: same policy (rhellab)
sudo firewall-cmd --get-default-zone sudo firewall-cmd --get-active-zones sudo firewall-cmd --zone=public --list-all sudo firewall-cmd --permanent --zone=public --remove-service=cockpit sudo firewall-cmd --permanent --zone=public --remove-service=dhcpv6-client sudo firewall-cmd --permanent --zone=public --add-port=5000/tcp sudo firewall-cmd --reload sudo firewall-cmd --zone=public --list-all sudo nft list table inet firewalld | grep -E 'dport|chain filter_IN_public_allow' | head
public
public
interfaces: enp1s0
public (default, active)
target: default
interfaces: enp1s0
services: cockpit dhcpv6-client ssh
ports:
...
success
public (default, active)
target: default
interfaces: enp1s0
services: ssh
ports: 5000/tcp
chain filter_IN_public_allow {
tcp dport 22 accept
tcp dport 5000 accept
Confirm that the host does not rely on DHCPv6 to obtain an address before removing dhcpv6-client. Only allow the management network segment to access SSH: firewall-cmd --permanent --zone=public --add-rich-rule='rule family=ipv4 source address=192.168.64.0/24 service name=ssh accept' and remove the general ssh service (make sure you are in this network segment first).
ufw: same policy (linuxlab, alternative to nftables above)
sudo systemctl disable --now nftables.service; sudo nft flush ruleset # If nftables was just enabled sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw limit 22/tcp comment 'ssh with rate limit' sudo ufw allow 5000/tcp comment 'myapp' sudo ufw --force enable sudo ufw status verbose
Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), deny (routed) New profiles: skip To Action From -- ------ ---- 22/tcp LIMIT IN Anywhere # ssh with rate limit 5000/tcp ALLOW IN Anywhere # myapp 22/tcp (v6) LIMIT IN Anywhere (v6) # ssh with rate limit 5000/tcp (v6) ALLOW IN Anywhere (v6) # myapp
ufw limit Denies 6 new connections from the same IP in 30 seconds, good for mitigating SSH brute force (the real protection is certificate authentication in module 4). ufw allows some ICMP and DHCP by default, and the rules are in /etc/ufw/before.rules.
Experiment 3: Three front-ends implement "only release 22 and 5000" and verify externally (about 10 minutes)
multipass shell Does not rely on SSH ports and is a good fallback channel). sudo ss -tlnp | awk 'NR==1||/LISTEN/' ip -br addr show | grep -v '^lo'
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 4096 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=812,fd=3),("systemd",pid=1,fd=111))
LISTEN 0 2048 0.0.0.0:5000 0.0.0.0:* users:(("gunicorn",pid=5120,fd=5))
LISTEN 0 511 127.0.0.1:6379 0.0.0.0:* users:(("redis-server",pid=701,fd=6))
LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* users:(("systemd-resolve",pid=520,fd=17))
enp0s1 UP 192.168.64.5/24 fd12:…/64
sshd is activated by the ssh.socket socket, so systemd can also be seen in the listener of port 22.
/etc/nftables.conf, load with dead switch; verify from the host
nc -zv 192.168.64.5 22 nc -zv 192.168.64.5 5000 nc -zv -w 3 192.168.64.5 6379; echo "exit=$?"
Connection to 192.168.64.5 port 22 [tcp/ssh] succeeded! Connection to 192.168.64.5 port 5000 [tcp/*] succeeded! nc: connect to 192.168.64.5 port 6379 (tcp) timed out: Operation now in progress exit=1
sudo nft list chain inet filter input | grep -E 'counter packets' | tail -n 1 sudo journalctl -k -g 'nft-input-drop' --since '-5min' --no-pager | tail -n 2
counter packets 7 bytes 420 kernel: nft-input-drop: IN=enp0s1 OUT= MAC=… SRC=192.168.64.1 DST=192.168.64.5 LEN=64 … PROTO=TCP SPT=53122 DPT=6379 … SYN
sudo nft list tables sudo ufw status numbered
table ip filter table ip6 filter [ 1] 22/tcp LIMIT IN Anywhere [ 2] 5000/tcp ALLOW IN Anywhere [ 3] 22/tcp (v6) LIMIT IN Anywhere (v6) [ 4] 5000/tcp (v6) ALLOW IN Anywhere (v6)
ufw generates rules through iptables-nft, so what you see in nft list tables are two compatibility tables: ip filter / ip6 filter.
nftables.service Disabled to avoid loading at the same time as ufw:systemctl is-enabled nftables.service ufw.service
Case 1: ufw rejected, but the container port was still scanned
Problem: Someone on the same host used Docker to run Redis of -p 6379:6379 After testing, the ufw status shows that only 22/5000 are allowed, and the external scan still finds 6379. Method: Only bind the publishing port to the local machine (-p 127.0.0.1:6379:6379); when you need to filter container traffic, write the rules in the DOCKER-USER chain (iptables backend) reserved by Docker or the corresponding nftables location; block the security group layer again. Restrictions: Docker's rules are dynamically maintained by the daemon process. flush ruleset will clear them and cause the container to be disconnected from the network.
Case 2: After changing firewall-cmd, everything was normal, but the service was unreachable after restarting
Problem: Only the runtime command was executed during the change, and the rules disappeared after the maintenance window was restarted. How to do it: Change the specification to "runtime verification first → --runtime-to-permanent", and attach the output of firewall-cmd --list-all --permanent to the change order; use the Ansible ansible.posix.firewalld module to set both permanent: true and immediate: true. Limitations:--reload discards unpersisted runtime rules.
Case 3: IPv6 exposes "closed" services
Problem: The handwritten iptables rules only cover IPv4. After the cloud host enables IPv6, the internal management port is directly accessible on IPv6. How to do it: Migrate to nftables rules of the inet family. One rule constrains IPv4/IPv6 at the same time; explicitly test IPv6 addresses during scanning. Limitations: ICMPv6 cannot be discarded entirely, otherwise neighbor discovery and path MTU discovery will fail.
Common errors and solutions
Error: Could not process rule: No such file or directory(nft add rule …)
Cause: The table or link does not exist (the name/family is written incorrectly, for example, looking for the table of inet in the ip family).
sudo nft list tables sudo nft list table inet filter
Fix: Create the table and chain first, or correct the family name; it is recommended to use file + nft -f to load the complete rule set at once.
ERROR: Couldn't determine iptables version / ufw enable The rules do not take effect
Cause: The iptables backend or kernel module does not match, or the flush ruleset of nftables.service is run at the same time to clear the ufw rules.
update-alternatives --display iptables systemctl is-enabled nftables.service ufw.service sudo nft list ruleset | head -n 20
Fix: Keep only one manager; make sure iptables points to iptables-nft; sudo ufw reload.
FirewallD is not running
Cause: The service is not started, or it conflicts with iptables-services / nftables.service and is blocked.
systemctl status firewalld --no-pager systemctl list-unit-files | grep -E 'firewalld|nftables|iptables'
Fix:sudo systemctl unmask --now firewalld and disable the conflicting service.
apt update stuck at "Connecting to archive.ubuntu.com" / DNS timeout (after adding rules)
Cause:Input chain policy drop but did not release ct state established,related, and the return packet of the outbound request was discarded.
sudo nft list chain inet filter input | grep -n 'ct state'
Fix: Add ct state { established, related } accept at the front of the chain.
The port has been released, but the external connection Connection refused
Cause:refused means that the packet has reached the host, but there is no process listening at the address (the firewall drop shows a timeout, and the reject means refused/ICMP unreachable).
sudo ss -tlnp | grep 5000 systemctl status myapp --no-pager
Fix: Check whether the service is only bound to 127.0.0.1 and whether it is running; distinguishing "timeout" and "rejection" is the first step in network troubleshooting.
1. Use an nft command to insert "Discard all packets from 203.0.113.0/24" at the beginning of the existing inet filter input chain.
sudo nft insert rule inet filter input ip saddr 203.0.113.0/24 counter drop
2. Only 192.168.64.0/24 is allowed to access port 5000 in firewalld (no longer open to everyone).
sudo firewall-cmd --permanent --zone=public --remove-port=5000/tcp sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.64.0/24" port port="5000" protocol="tcp" accept' sudo firewall-cmd --reload
After linuxlab enables ufw, your nc -zv IP 5000 times out on the host machine, but ufw status displays 5000 ALLOW. How to check?
① Confirm that no other manager's table is on the same hook drop: nft list ruleset Check whether inet filter (previous nftables.service) remains; ② Confirm that the service is listening and not only bound to 127.0.0.1: ss -tlnp; ③ In linuxlab Capture packets on tcpdump -ni any tcp port 5000 to see if SYN arrives - if it does not arrive, it is an upstream (Multipass/virtual switching, cloud security group) problem; if it does not return SYN-ACK, it is a local rule; ④ Look at the BLOCK log of journalctl -k -g UFW.
Verified teaching video
Official Documentation
- nftables wiki · nft(8)
- firewalld Documentation · RHEL 10: Configuring firewalls and packet filters
- Ubuntu Server: Firewalls
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The data packet enters from the network card, after prerouting, the routing decision is forked to input and forward.
Narration: Inbound traffic to the native service only goes through the input chain. The port published by the container is forward.
Screen: The input chain rules are highlighted line by line, packages 22 and 5000 pass in green, packages 6379 fall into the policy drop, and the log prints nft-input-drop.
Narration: Denied by default, established connections and loopbacks are allowed first, then 22 and 5000, and the rest are discarded and recorded at a rate limit.
Screen: The arrows of the three icons of nft, firewall-cmd, and ufw all converge to the kernel nf_tables.
Narration: The three tools are just different front ends, and they are all written into the same kernel in the end. When troubleshooting, use nft list ruleset to see the actual rules.
Screen: The host executes nc, 5000 success, 6379 timeout.
Narration: Verification must be done externally. Success, timeout, and rejection, the three results correspond to three different reasons.
Module 4 · Authentication: PAM, sudo policies and SSH certificates
- Explain how to evaluate the four types of PAM management groups (auth / account / password / session) and control flags (required / requisite / sufficient / optional and
[success=N default=ignore]). - Knowing that PAM's auth stack is skipped when logging in with SSH public key/certificate, but the account and session stack will still be executed; password quality (pwquality) and failure lock (faillock) will be configured.
- Write least privilege sudoers rules: only give
systemctl restart myapp.service, avoid the classic trap of "paginator/editor escapes to root shell"; understand the differences of sudo-rs in Ubuntu 26.04. - Build SSH user CA and host CA: issue short-term certificates with principals, validity period and restriction options, and revoke them with KRL.
What: PAM - pluggable authentication module
Sshd, login, sudo, su, cron and other programs do not implement "how to verify passwords" themselves, but call libpam, which is determined by the module stack in /etc/pam.d/. Format of each line: Type Control Flag Module Parameter.
| Management Group | Questions answered | Typical Modules |
|---|---|---|
| auth | Who are you? (Verify Credentials) | pam_unix, pam_faillock, pam_sss, MFA module |
| account | Is this account allowed to log in now? (expiration, time, source) | pam_unix (expired), pam_access, pam_nologin |
| password | Rules for changing passwords | pam_pwquality, pam_pwhistory, pam_unix (yescrypt hash) |
| session | Things to do before and after login | pam_limits (module 6), pam_systemd, pam_loginuid (auid of module 5) |
| Control flag | Module successful | Module failed |
|---|---|---|
required | Continue | Record as failure, but continue execution subsequent modules (not exposing which step failed) |
requisite | Continue | return failure immediately |
sufficient | If there is no required failure before, return success immediately | Ignore |
optional | It will only affect the result if it is the only module in the stack | Same as left |
[success=1 default=ignore] | Skip the next module | Ignore and continue to the next line |
Ubuntu uses pam-auth-update to generate common-* based on the configuration fragment in /usr/share/pam-configs/ File; RHEL uses authselect to generate system-auth/password-auth. Neither of them recommends manually modifying the generated files.
What: sudoers and sudo-rs in Ubuntu 26.04
Rule format: who host=(as who) command. Commands with parameters must exactly match; when only the command path is written without parameters, any parameters are allowed. Ubuntu 26.04's default sudo is provided by a Rust rewrite of sudo-rs (the original sudo can still be installed as a compatibility and fallback). Differences listed in the Ubuntu documentation include: different password prompt text ([sudo: authenticate] Password:, expect scripts that rely on matching prompt text will timeout), no support for I/O logs and sudoreplay, and no sudoers LDAP; the complete list of supported options is in man sudoers-rs and sudo --help. Complex sudoers (wildcard parameters, rare Defaults options) need to be verified one by one before upgrading to 26.04.
What: SSH certificate
OpenSSH certificate is a "public key signed by the CA private key" and comes with:key ID (written into the log for auditing), principals (which identities are allowed to log in), validity, serial number, restriction options (source-address, force-command, no-port-forwarding…). The server only needs to trust the CA public key (TrustedUserCAKeys) and no longer maintains everyone's authorized_keys; the client only needs to trust the host CA (@cert-authority), and "first connection confirmation fingerprint" will no longer appear. It's not X.509 and doesn't have a certificate chain.
Why
authorized_keysare "keys that never expire". It is difficult to confirm that they have been cleaned up when an employee leaves or the laptop is lost; a certificate valid for 8 hours will become invalid upon expiration.- The key ID and serial number of the certificate are recorded in the log, which can map a login to "which person and which time it was issued."
- Sudo rules that are too wide (
ALL=(ALL) ALLor allowvi/less/journalctlto run as root) are equivalent to giving a root shell.
How / When
- Small team: An offline/protected host saves the CA private key and issues it manually; Scale: HashiCorp Vault SSH engine, step-ca, Teleport, etc. automatically issue short-term certificates according to SSO identity.
- Principals use "role names" (such as
labadmin-admins) instead of personal usernames, and are mapped to local accounts usingAuthorizedPrincipalsFileon the server. - CA private key leaked = All servers lost: placed on HSM/Cloud KMS or offline host, host CA is separated from user CA.
Comparison with similar technologies
| authorized_keys | SSH certificate | Cloud identity login (Entra ID / EC2 Instance Connect / SSM) | |
|---|---|---|---|
| Revocation | Delete on a per-device basis | Expired + KRL | Disabled in Cloud IAM |
| Audit Identity | Public key fingerprint | key ID + serial | User in cloud audit log |
| Dependencies | None | CA private key protection | Cloud platform and agent |
| Reference | No. 2 Lesson | This module | Lesson 3 / Lesson 4 |
MaxAuthTries, PerSourcePenalties (OpenSSH 9.8+) and firewall speed limiting. ② "sudo only allows journalctl to be safe" - journalctl / systemctl status / less / vi / man can all be executed through the pager or editor !sh to get the root shell. ③ "Set the certificate validity period to one year to save trouble" - the value of the certificate lies in its "short term"; long-term certificates can only be revoked by KRL, and KRL must be distributed to each server. ④ "Post-loading settings in sshd_config.d will overwrite the main file" - On the contrary, sshd uses the value of the first occurrence of most keywords, and Include /etc/ssh/sshd_config.d/*.conf is located at the beginning of the main file, so drop-in takes precedence. Architecture diagram: components passed by an SSH certificate login
Flowchart: PAM Evaluation of control flags
PAM stack evaluation simulator
Choose a real stack (Ubuntu common-auth, RHEL authselect + faillock, a custom stack with traps), set the return value of each module, and then step through it. The emulator computes the semantics of pam.conf(5): ok / ignore / bad / die / done / jump N.
Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
pam-auth-update | Ubuntu: enable/disable PAM configuration fragment | --enable name, --package |
authselect current / enable-feature with-faillock | RHEL system: View configuration file, enable features | authselect check Check whether it has been manually modified |
faillock --user U [--reset] | View/clear failure count | Configuration /etc/security/faillock.conf |
visudo -cf FILE | Syntax check sudoers file | Always edit with visudo; file permissions 0440 |
sudo -l -U USER | List a user's sudo permissions | The first step in reviewing sudo policy |
ssh-keygen -s CA -I ID -n PRINCIPALS -V +8h KEY.pub | Issuing a user certificate | -h host certificate, -z serial number, -O option |
ssh-keygen -L -f KEY-cert.pub | View certificate content | Check principals, validity period, options |
ssh-keygen -k -f KRL -s CA.pub CERT… | Generate/update revocation list | -u append; -Q query |
sshd -T / sshd -t | Output effective configuration/check syntax | sshd -T -C user=labadmin,addr=1.2.3.4 |
PAM: view sshd Stack and password quality (linuxlab)
grep -vE '^\s*(#|$)' /etc/pam.d/sshd grep -vE '^\s*(#|$)' /etc/pam.d/common-auth sudo apt install -y libpam-pwquality grep pwquality /etc/pam.d/common-password printf 'minlen = 14\nminclass = 3\nenforce_for_root\n' | sudo tee /etc/security/pwquality.conf.d/50-lab.conf
@include common-auth account required pam_nologin.so @include common-account session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close session required pam_loginuid.so session optional pam_keyinit.so force revoke @include common-session session optional pam_motd.so motd=/run/motd.dynamic session required pam_limits.so ... auth [success=1 default=ignore] pam_unix.so nullok auth requisite pam_deny.so auth required pam_permit.so password requisite pam_pwquality.so retry=3
pam_loginuid Write the UID of the logged-in user into /proc/self/loginuid. Afterwards, no matter how many times sudo is used, the auid in the audit record will be the person who logged in initially (Module 5). If /etc/security/pwquality.conf.d/ does not exist, edit /etc/security/pwquality.conf directly.
faillock(rhellab)
authselect current sudo authselect enable-feature with-faillock printf 'deny = 5\nunlock_time = 900\neven_deny_root = false\n' | sudo tee -a /etc/security/faillock.conf grep faillock /etc/pam.d/system-auth sudo faillock --user labadmin
Profile ID: local Enabled features: None Make sure that SSSD service is configured and enabled. See SSSD documentation for more information. auth required pam_faillock.so preauth silent auth required pam_faillock.so authfail account required pam_faillock.so labadmin: When Type Source Valid
sudoers: only allow restart myapp
sudo groupadd -f myapp-ops sudo useradd -m -s /bin/bash -G myapp-ops,systemd-journal opsuser sudo tee /etc/sudoers.d/50-myapp-ops >/dev/null <<'EOF' # myapp operation and maintenance: only the service can be restarted; logs are read directly through the systemd-journal group without sudo %myapp-ops ALL=(root) /usr/bin/systemctl restart myapp.service EOF sudo chmod 0440 /etc/sudoers.d/50-myapp-ops sudo visudo -cf /etc/sudoers.d/50-myapp-ops sudo -l -U opsuser
/etc/sudoers.d/50-myapp-ops: parsed OK
User opsuser may run the following commands on linuxlab:
(root) /usr/bin/systemctl restart myapp.service
Why not give journalctl and systemctl status? When they are run as root, they will call the pager less. Enter !sh in less to get the root shell. Use the systemd-journal group to read logs; systemctl status itself does not require root. Use sudoedit to edit the configuration file (run the editor as a normal user and edit a temporary copy) - sudo-rs' support for sudoedit and other functions is subject to man sudoers-rs. If it is not supported, you can install the original sudo or use configuration management to issue configurations.
SSH user certificate (CA on your laptop or a separate host)
mkdir -p ~/ssh-ca && chmod 700 ~/ssh-ca ssh-keygen -t ed25519 -f ~/ssh-ca/user_ca -C "lab user CA" # Set a strong password ssh-keygen -t ed25519 -f ~/.ssh/id_lab -C "alice@laptop" # If you already have a key, you can skip it ssh-keygen -s ~/ssh-ca/user_ca -I "alice@laptop-$(date +%F)" -z 1001 \ -n labadmin-admins -V +8h -O source-address=192.168.64.0/24 ~/.ssh/id_lab.pub ssh-keygen -L -f ~/.ssh/id_lab-cert.pub
Signed user key /home/alice/.ssh/id_lab-cert.pub: id "alice@laptop-2026-11-17" serial 1001 for labadmin-admins valid from 2026-11-17T10:20:00 to 2026-11-17T18:21:31
/home/alice/.ssh/id_lab-cert.pub:
Type: ssh-ed25519-cert-v01@openssh.com user certificate
Public key: ED25519-CERT SHA256:Qm3…
Signing CA: ED25519 SHA256:8yT… (using ssh-ed25519)
Key ID: "alice@laptop-2026-11-17"
Serial: 1001
Valid: from 2026-11-17T10:20:00 to 2026-11-17T18:21:31
Principals:
labadmin-admins
Critical Options:
source-address 192.168.64.0/24
Extensions:
permit-X11-forwarding
permit-agent-forwarding
permit-port-forwarding
permit-pty
permit-user-rc
# Copy the contents of user_ca.pub to the server sudo tee /etc/ssh/user_ca.pub >/dev/null <<'EOF' ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...Replace with your CA public key... lab user CA EOF sudo install -d -m 755 /etc/ssh/auth_principals echo labadmin-admins | sudo tee /etc/ssh/auth_principals/labadmin sudo tee /etc/ssh/sshd_config.d/40-user-ca.conf >/dev/null <<'EOF' TrustedUserCAKeys /etc/ssh/user_ca.pub AuthorizedPrincipalsFile /etc/ssh/auth_principals/%u RevokedKeys /etc/ssh/revoked_keys EOF sudo touch /etc/ssh/revoked_keys # Create an empty file first: RevokedKeys sshd rejects all public key logins when pointing to non-existent/unreadable files sudo sshd -t && sudo systemctl reload ssh sudo sshd -T | grep -iE 'trustedusercakeys|authorizedprincipalsfile|revokedkeys'
How to verify: ssh -i ~/.ssh/id_lab labadmin@linuxlab can log in, appear in journalctl -u ssh -n 5 ED25519-CERT … ID alice@laptop-2026-11-17 (serial 1001) CA ED25519 …. Common errors: The principal is written as a personal name but the server file contains a role name; the certificate time is earlier than the server time (the clock is not synchronized); the file pointed to by RevokedKeys does not exist. Production use: The CA private key is stored in HSM/KMS or Vault, issuance is driven by SSO, and the validity period is hourly.
Lab 4: SSH CA + host certificate + revocation + minimal sudo (~12 minutes)
multipass shell security. ssh -i ~/.ssh/id_lab -o IdentitiesOnly=yes labadmin@192.168.64.5 'id; cat /proc/self/loginuid; echo' ssh labadmin@192.168.64.5 sudo journalctl -u ssh -n 3 --no-pager
uid=1000(labadmin) gid=1000(labadmin) groups=1000(labadmin),27(sudo) 1000 sshd-session[6120]: Accepted publickey for labadmin from 192.168.64.1 port 55012 ssh2: ED25519-CERT SHA256:Qm3… ID alice@laptop-2026-11-17 (serial 1001) CA ED25519 SHA256:8yT…
OpenSSH 9.8 onwards, each connection is handled by the sshd-session process, so the log label may appear as sshd-session.
ssh-keygen -t ed25519 -f ~/ssh-ca/host_ca -C "lab host CA" scp labadmin@192.168.64.5:/etc/ssh/ssh_host_ed25519_key.pub /tmp/linuxlab_host.pub ssh-keygen -s ~/ssh-ca/host_ca -I linuxlab-host -h -n linuxlab,192.168.64.5 -V +52w /tmp/linuxlab_host.pub scp /tmp/linuxlab_host-cert.pub labadmin@192.168.64.5:/tmp/ echo "@cert-authority linuxlab,192.168.64.* $(cat ~/ssh-ca/host_ca.pub)" >> ~/.ssh/known_hosts
sudo install -m 644 /tmp/linuxlab_host-cert.pub /etc/ssh/ssh_host_ed25519_key-cert.pub echo 'HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub' | sudo tee /etc/ssh/sshd_config.d/41-host-cert.conf sudo sshd -t && sudo systemctl reload ssh
ssh-keygen -R 192.168.64.5 # Delete old individual fingerprint entries ssh -v -i ~/.ssh/id_lab labadmin@192.168.64.5 true 2>&1 | grep -i 'host certificate'
debug1: Server host certificate: ssh-ed25519-cert-v01@openssh.com SHA256:… , serial 0 ID "linuxlab-host" CA ssh-ed25519 SHA256:… valid from 2026-11-17T10:30:00 to 2027-11-16T10:31:12 debug1: Host '192.168.64.5' is known and matches the ED25519-CERT host certificate.
echo "serial: 1001" > /tmp/revoke.spec ssh-keygen -k -u -f /tmp/revoked_keys -s ~/ssh-ca/user_ca.pub /tmp/revoke.spec scp /tmp/revoked_keys labadmin@192.168.64.5:/tmp/
sudo install -m 644 /tmp/revoked_keys /etc/ssh/revoked_keys ls -l /etc/ssh/revoked_keys
ssh -i ~/.ssh/id_lab -o IdentitiesOnly=yes labadmin@192.168.64.5 true; echo "exit=$?"
labadmin@192.168.64.5: Permission denied (publickey). exit=255
The server log will appear Authentication key ED25519-CERT … revoked by file /etc/ssh/revoked_keys. KRL does not require restarting sshd and is read during each authentication. Then re-issue a certificate with serial number 1002 to resume login.
sudo passwd opsuser su - opsuser -c 'sudo systemctl restart myapp.service && echo restarted; sudo systemctl stop myapp.service; journalctl -u myapp -n 2 --no-pager'
[sudo: authenticate] Password: restarted Sorry, user opsuser is not allowed to execute '/usr/bin/systemctl stop myapp.service' as root on linuxlab. Nov 17 10:41:02 linuxlab myapp[7012]: [INFO] Listening at: http://0.0.0.0:5000 (7012) Nov 17 10:41:02 linuxlab myapp[7012]: [INFO] Booting worker with pid: 7014
The specific text of the rejection message may be different between sudo-rs and sudo.ws; the key is that stop is rejected, and the log can be read without sudo.
/etc/ssh/sshd_config.d/40-user-ca.conf, 41-host-cert.conf after sudo systemctl reload ssh. Delete test users:sudo userdel -r opsuser. Case 1: The keys of resigned employees are still on 300 servers
Problem: The audit found that the public keys of employees who have resigned for half a year are still in the authorized_keys of some servers. Method: Migrate to SSH CA: The server only trusts the CA, and the certificate is automatically issued after SSO login (valid for 8 hours, principal corresponding role group); gradually clear authorized_keys and use AuthorizedKeysFile none to disable it. Configuration: 40-user-ca.conf of this module + automatic issuance service. Limitations: The CA service has become a critical dependency and requires high availability and a "broken window" emergency account (stored in a vault and alerted when used).
Case 2: Privilege escalation caused by a sudo rule
Problem: The development team was granted /usr/bin/vim /etc/nginx/*, and the penetration tester got root in vim :!bash. Method: Change to sudoedit /etc/nginx/conf.d/app.conf (or be issued by Git + configuration management), and check the escape risks of the GTFOBins class one by one for the remaining rules. Restrictions: Any rule that allows "a program that can execute arbitrary commands" to be run as root is essentially root privileges.
Case 3: Automation script stuck after upgrading to Ubuntu 26.04
Issue: An old script using expect to match [sudo] password for times out on 26.04. Method: According to Ubuntu documentation, the prompt text of sudo-rs is different; the script is changed to be interactive-free (special NOPASSWD rules only allow specific commands) or use --prompt to fix the prompt; use a 26.04 pre-release machine to run all automation before upgrading. Restrictions: Teams that rely on I/O logs (sudoreplay) for session auditing need to use auditd's execve rules or session recording tools instead.
Common errors and solutions
error: Certificate invalid: name is not a listed principal
Cause: The certificate's principals do not match the server's AuthorizedPrincipalsFile (or the login username if not configured).
ssh-keygen -L -f ~/.ssh/id_lab-cert.pub | sed -n '/Principals/,/Critical/p' sudo cat /etc/ssh/auth_principals/labadmin
Fix: Re-issue the correct principal, or add the principal to the server file (note the file permissions, which cannot be written by ordinary users).
error: Certificate invalid: expired or not yet valid
Cause: The certificate has expired, or the client/server clocks are out of sync (the issuance time is "in the future" of the server).
timedatectl; ssh-keygen -L -f ~/.ssh/id_lab-cert.pub | grep Valid
Fixed:Reissue; fix NTP (lesson 2); use -V -5m:+8h when issuing to allow for clock skew margin.
pam_faillock(sshd:auth): Consecutive login failures for user labadmin account temporarily locked
Cause: Password login failed continuously to deny.
sudo faillock --user labadmin sudo faillock --user labadmin --reset
Fix: Confirm that it is not an attack before unlocking; the server should turn off password login (PasswordAuthentication no), leaving only the certificate.
sudo: parse error in /etc/sudoers.d/50-myapp-ops near line 2 (all subsequent sudos fail)
Cause:A file with incorrect syntax was written without checking with visudo.
pkexec visudo -f /etc/sudoers.d/50-myapp-ops # If polkit is available # Or fix via console/multipass shell as root
Fixed: Always visudo -cf and then put /etc/sudoers.d/; the file name cannot contain . or end with ~, otherwise it will be ignored by sudo.ws.
Permission denied (publickey), server log: Authentication key ... revoked by file /etc/ssh/revoked_keys
Cause: The certificate or key is in the KRL; or the file pointed to by RevokedKeys does not exist/is not readable - at this time sshd All public key authentication will be rejected.
ls -l /etc/ssh/revoked_keys ssh-keygen -Q -f /etc/ssh/revoked_keys ~/.ssh/id_lab-cert.pub
Fix:Reissue certificate with new serial number; ensure KRL file exists and is readable.
1. Issue a certificate for the deploy robot that is valid for 1 hour, can only execute /usr/local/bin/deploy-myapp, and prohibits port forwarding (principal is deploy).
ssh-keygen -s ~/ssh-ca/user_ca -I "deploy-bot-$(date +%s)" -n deploy -V +1h \ -O force-command=/usr/local/bin/deploy-myapp -O no-port-forwarding -O no-pty ~/.ssh/deploy.pub
2. Check the actual authentication-related configuration of sshd for labadmin from 10.0.0.9.
sudo sshd -T -C user=labadmin,host=linuxlab,addr=10.0.0.9 | grep -iE 'authentication|trustedusercakeys|principals|maxauthtries'
The security team requires "Lock the account if SSH fails 5 times." You configured pam_faillock, but the penetration test failed to lock the account even after trying 100 times with the wrong key. Why? How should this requirement be met?
Public key/certificate authentication is completed by sshd itself, without going through PAM's auth stack. faillock only counts failures through PAM auth (password, keyboard interaction). Methods that meet the requirements: sshd side MaxAuthTries limits the number of single connection attempts, OpenSSH 9.8+'s PerSourcePenalties imposes penalties on sources that fail repeatedly; firewall layer ufw limit/nftables meter speed limit; more fundamentally, the certificate is short-lived and limits source-address, making "try the key" meaningless. At the same time, explain the applicable scope of the control items to the security team, and if necessary, rewrite the requirements as "authentication failure rate limit and alarm".
Verified instructional video
Official documentation
- pam.conf(5) · pam_faillock(8)
- ssh-keygen(1) CERTIFICATES · sshd_config(5)
- Ubuntu: sudo-rs differences explained · RHEL 10: Security hardening
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The server is full of authorized_keys keys, several of which belong to retired employees and flash red.
Narration: The public key file is a key that never expires. Employees leave, computers are lost, and it's difficult to be sure that every server has been cleaned.
Screen: The CA seal is stamped on the public key, and a certificate with key ID, principals, and eight-hour validity period is generated.
Narration: SSH certificates are signed by a CA and carry an identity, roles allowed to log in, and a validity period. The server only trusts the CA and no longer maintains everyone's public keys.
Screen: The login process enters PAM, the auth stack turns gray (skipped), the account and session stacks light up in sequence, and pam_loginuid is written into auid.
Narration: When logging in with a certificate, the PAM auth stack is skipped, but the account and session are executed as usual, and the audit identity is also determined here.
Screen: The sudoers rule has only one line restart myapp, and the attempt to stop is rejected; the red cross indicates that the journalctl pager escapes.
Narration: sudo only gives commands that are really needed. Any command that opens a pager or editor is equivalent to giving a root shell.
Module 5 · Audit: auditd and log forensics
- Draw the audit pipeline: the kernel filters according to rules at the system call exit → kauditd passes it to auditd through netlink →
/var/log/audit/audit.log→ausearch/aureport. - Write file monitoring (
-w) and system call rules (-a always,exit), understand why auid (login UID) can penetrate sudo, and-e 2immutable rules. - Use ausearch's
-k,-m,-ua,-tsand-ifor evidence collection, and use aureport to produce a summary; distinguish the evidence that auditd and journald are good at. - Configure journald persistence and capacity limits, and learn about forward security sealing (FSS) and centralized forwarding.
What: Linux Audit subsystem
Audit consists of kernel and user mode: the kernel generates records at system call entry/exit, file access, LSM decision (AVC), seccomp and other locations; the user mode daemon auditd receives and writes /var/log/audit/audit.log through netlink. Programs such as PAM, sshd, sudo, etc. will also actively send user space events (USER_LOGIN, USER_AUTH, USER_CMD...). An event consists of multiple records, sharing the same timestamp and sequence number msg=audit(1763377330.123:880).
| Record type | Meaning | Key fields |
|---|---|---|
SYSCALL | System call itself | syscall success exit auid uid euid comm exe key |
PATH / CWD | Involved files and current directory | name inode mode ouid nametype |
EXECVE / PROCTITLE | Command line arguments for execution (hex encoded, -i decoded) | argc a0 a1 … |
AVC / SECCOMP | SELinux deny/seccomp action | scontext tcontext / syscall sig |
USER_LOGIN, USER_AUTH, USER_CMD | Login, authentication, sudo commands | acct res= addr= cmd= |
auid (audit/login UID): written by pam_loginuid during login to /proc/self/loginuid, and then inherited by the child process and will not be changed by sudo/su. So uid=root auid=labadmin means "done as root through sudo after labadmin logs in". The system service has no login session and the auid is shown as unset (4294967295).
Why
- Ordinary logs are written by the application itself, and the attacker does not need to write or delete them after gaining permission; audit records are generated by the kernel, and the rules can be set to immutable (
-e 2, a restart is required to change the rules). - PCI-DSS, Class Protection, CIS, etc. all require recording of identity file changes, privileged commands, login and authentication failures, time modifications, and kernel module loading.
- SELinux's AVC and seccomp's SECCOMP records all go through the same pipeline (modules 1 and 2 have been used).
How: Rule Grammar
| Writing | Meaning |
|---|---|
-w /etc/myapp/myapp.env -p wa -k myapp-config | File monitoring: record when writing (w) or attribute change (a), hit the key myapp-config |
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root-cmd | At execve exit: record when the effective UID is root and initiated by the real login user (UID≥1000) |
-a always,exit -F arch=b64 -S openat -F exit=-EACCES -k access-denied | Record is DAC Opening of denials - this is how to leave evidence of "unlogged DAC denials" |
-b 8192, -f 1, -e 2 | Kernel queue size; handling of queue overflows (1 = printk, 2 = panic); locking rules |
Rules files placed in /etc/audit/rules.d/*.rules, controlled by augenrules Sort by file name and merge into /etc/audit/audit.rules and load. System call rules have overhead for each matching system call. Try to use -F to filter (auid, path, success or failure) to avoid unconditional recording of high-frequency calls (read/write).
When: auditd or journald?
| auditd | journald | |
|---|---|---|
| Source | Kernel audit + security related user events | Stdout/stderr, syslog, kernel logs of all services |
| Suitable for answers | Who changed a file, who executed what as root, AVC/SECCOMP | Why the service failed, application log, startup process |
| Tamper-proof | Immutable rules, remote forwarding (audisp-remote) | FSS seal (Seal=yes), remote forwarding (journal-upload / rsyslog) |
| Query | ausearch / aureport | journalctl field filtering (_SYSTEMD_UNIT=, _COMM=) |
disk_full_action improper configuration can bring the system to a halt. ④ "journald is persisted by default" - when Storage=auto, it will be persisted only if /var/log/journal exists (it exists by default in Ubuntu; RHEL systems with minimal installation may need to be created manually). Architecture diagram: Audit pipeline
Flowchart: Question chain of an evidence collection
How a system call becomes an audit event
Scenario: labadmin logs in through certificate (module 4), sudo vi /etc/myapp/myapp.env modified the configuration. Step through to see the actual record generated by the kernel and auditd at each stage, and which ausearch command was used to finally find it.
Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
auditctl -s / -l | Status (enabled, lost, backlog) / Rules loaded | enabled 2 means the rule is locked |
augenrules --load | Merge rules.d and load | --check Only check if regeneration is required |
ausearch -k KEY -i | Search by key and explain (UID → username, syscall number → name) | -ts today|recent|'11/17/2026 10:00:00', -te |
ausearch -ua 1000 --session N | Search by logged in user/session | -m USER_LOGIN,USER_CMD, -sv no(failed) |
aureport --summary / -au / -x --summary / --failed | Summary/Authentication/Executable/Failure Event | -k --summary Key statistics |
journalctl -u UNIT --since --until -o json-pretty | Service log query | _UID=, _COMM=, -p warning, -g regular |
journalctl --disk-usage / --vacuum-size= | View and clear log usage | For long-term configuration SystemMaxUse= |
journalctl --setup-keys / --verify | FSS seal key/verify integrity | The verification key should be saved offline |
Installation and rule files (linuxlab)
sudo apt install -y auditd systemctl is-active auditd sudo tee /etc/audit/rules.d/50-lab.rules >/dev/null <<'EOF' ## myapp and security-critical configuration -w /etc/myapp/myapp.env -p wa -k myapp-config -w /etc/systemd/system/myapp.service.d/ -p wa -k myapp-unit -w /etc/sudoers -p wa -k sudoers -w /etc/sudoers.d/ -p wa -k sudoers -w /etc/ssh/sshd_config.d/ -p wa -k sshd-config -w /etc/passwd -p wa -k identity -w /etc/shadow -p wa -k identity -w /etc/group -p wa -k identity ## Commands executed by the real logged-in user as root -a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root-cmd ## Rejected file opening (allowing DAC rejection to also leave evidence) -a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -k access-denied -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -k access-denied ## Kernel modules and time -a always,exit -F arch=b64 -S init_module,finit_module,delete_module -k modules -a always,exit -F arch=b64 -S clock_settime,settimeofday,adjtimex -k time-change EOF sudo augenrules --load sudo auditctl -l | head sudo auditctl -s
active -w /etc/myapp/myapp.env -p wa -k myapp-config -w /etc/systemd/system/myapp.service.d -p wa -k myapp-unit -w /etc/sudoers -p wa -k sudoers ... enabled 1 failure 1 pid 812 rate_limit 0 backlog_limit 8192 lost 0 backlog 0
How to verify:lost 0 means no events were lost due to queue overflow; when it continues to grow, increase -b and reduce the noise rule. Common mistakes: Copying system call names that only exist in x86_64 (such as open) on aarch64 causes augenrules to report an error; forgetting -F arch=b64 causes rules to behave inconsistently under the two ABIs. Production use: Use CIS/STIG's audit ruleset as a starting point (OpenSCAP content or the /usr/share/doc/auditd/rules/ example that comes with auditd), plus business-critical documents.
Lock the rules (last step before going live)
echo '-e 2' | sudo tee /etc/audit/rules.d/99-finalize.rules sudo augenrules --load; sudo auditctl -s | grep enabled
enabled 2
Any auditctl -w/-a/-D after that will fail, and a restart will be required to modify the rules - which is exactly the purpose. You don’t need to do this step during the experiment.
journald persistence and capacity
sudo mkdir -p /etc/systemd/journald.conf.d printf '[Journal]\nStorage=persistent\nSystemMaxUse=1G\nMaxRetentionSec=90day\n' | sudo tee /etc/systemd/journald.conf.d/50-lab.conf sudo systemctl restart systemd-journald journalctl --disk-usage journalctl --list-boots | tail -n 3
Lab 5: Forensic exercise - "Who changed myapp.env?" (~8 minutes)
cat /proc/self/loginuid; echo sudo sh -c 'echo "DEBUG=1" >> /etc/myapp/myapp.env' sudo systemctl restart myapp.service cat /etc/shadow 2>/dev/null; echo "(Intentional triggering of a DAC rejection)"
sudo ausearch -k myapp-config -ts recent -i
---- type=PROCTITLE msg=audit(11/17/2026 11:02:10.123:880) : proctitle=sh -c echo "DEBUG=1" >> /etc/myapp/myapp.env type=PATH msg=audit(11/17/2026 11:02:10.123:880) : item=1 name=/etc/myapp/myapp.env inode=393412 dev=fc:01 mode=file,640 ouid=root ogid=myapp nametype=NORMAL type=CWD msg=audit(11/17/2026 11:02:10.123:880) : cwd=/home/labadmin type=SYSCALL msg=audit(11/17/2026 11:02:10.123:880) : arch=x86_64 syscall=openat success=yes exit=3 a0=AT_FDCWD a1=0x5581… a2=O_WRONLY|O_CREAT|O_APPEND a3=0x1b6 items=2 ppid=7400 pid=7401 auid=labadmin uid=root gid=root euid=root suid=root fsuid=root egid=root sgid=root fsgid=root tty=pts0 ses=4 comm=sh exe=/usr/bin/dash subj=unconfined key=myapp-config
auid=labadmin uid=root ses=4: labadmin modified the file via sudo as root in the 4th login session.
sudo ausearch -m USER_LOGIN,USER_START -ua labadmin -ts today -i | tail -n 4 sudo ausearch -k root-cmd --session 4 -i | grep -E '^type=(EXECVE|SYSCALL)' | tail -n 6 sudo ausearch -k access-denied -ts recent -i | grep -E 'name=|SYSCALL' | tail -n 2
type=USER_LOGIN msg=audit(11/17/2026 10:20:41.002:701) : pid=6120 uid=root auid=labadmin ses=4 subj=unconfined msg='op=login id=labadmin exe=/usr/lib/openssh/sshd-session hostname=? addr=192.168.64.1 terminal=/dev/pts/0 res=success' type=EXECVE msg=audit(11/17/2026 11:02:10.120:879) : argc=3 a0=sh a1=-c a2=echo "DEBUG=1" >> /etc/myapp/myapp.env type=EXECVE msg=audit(11/17/2026 11:02:14.871:884) : argc=3 a0=systemctl a1=restart a2=myapp.service type=PATH msg=audit(11/17/2026 11:02:20.004:890) : item=0 name=/etc/shadow … nametype=NORMAL type=SYSCALL msg=audit(11/17/2026 11:02:20.004:890) : … syscall=openat success=no exit=EACCES(Permission denied) … auid=labadmin uid=labadmin … comm=cat key=access-denied
Certificate login can also be seen in the user event of sshd; comparing addr= with ID alice@laptop-… (serial 1001) in the module 4 log, you can trace back to "which certificate belongs to which person" from the "local account labadmin".
journalctl -u myapp.service --since "-15min" --no-pager | tail -n 4 sudo aureport -k --summary sudo aureport -au --summary -ts today
Key Summary Report =========================== total key =========================== 14 root-cmd 3 access-denied 2 myapp-config 1 sudoers
sudo sed -i '/^DEBUG=1$/d' /etc/myapp/myapp.env && sudo systemctl restart myapp; rules retained. Case 1: The production configuration was changed, but no one acknowledged it
Problem: A failure was caused by the database connection string being changed, and multiple people had sudo. Method: The audit rules include -w ... -k app-config for the configuration directory, and ausearch -k app-config -i displays auid= an engineer, source IP, and time; press ses= again to view all root commands in the same session to confirm that it is a misoperation rather than an intrusion. Restrictions: auid can only prove "which local account". Sharing accounts will invalidate the evidence - so one person must have one account + certificate key ID.
Case 2: Audit slows down the build machine
Problem: The CI build machine has unfiltered execve rules enabled, tens of thousands of records per second, lost continues to grow, and the build time increases by 30%. Method:Add -F auid>=1000 -F auid!=unset to the execve rule (only record human-initiated ones), add exclusion rules for build users (-a never,exit -F auid=builder in front), and increase -b. Restrictions: Exclusion rules must undergo security review to avoid becoming blind spots.
Case 3: The intruder cleared the local log
Problem: Later it was discovered that /var/log/audit and journal were cleared. Method: Fortunately, the audit events are forwarded to the append-only remote storage in real time through the audisp plug-in/rsyslog, and the forensics can be completed; then add -e 2, journald FSS, and configure alarms for "auditd stopped" and "log forwarding interrupted". Restrictions: Root-level attackers can always manipulate the local machine, and remote real-time forwarding is the only reliable guarantee.
Common errors and solutions
Error sending add rule data request (Operation not permitted)
Cause: The rule has been locked with -e 2, or there is no root / CAP_AUDIT_CONTROL.
sudo auditctl -s | grep enabled
Fix: enabled 2 Modify rules.d and restart the system to take effect; this is expected behavior.
audit: backlog limit exceeded / audit: kauditd hold queue overflow
Cause:The event generation speed exceeds the auditd processing speed, the queue overflows, and the events are lost (lost increases).
sudo auditctl -s | grep -E 'lost|backlog' sudo aureport -k --summary | head
Fix: Find the "noisiest" keys and add filter conditions; increase -b; check whether auditd's disk writes are limited.
Job for auditd.service failed / refusing manual stop (systemctl stop auditd was rejected)
Reason: The auditd unit has set RefuseManualStop=yes to prevent the audit from being stopped at will.
sudo service auditd restart # or sudo auditctl --signal reload (newer versions)
Fix: Use the service wrapper or auditctl signal as per release documentation; stopping auditing should itself trigger an alert.
ausearch shows but is confident that the event occurred
Cause: The rule loaded later than the event; the time parameter format was affected by the locale; or the log has been rotated.
sudo auditctl -l | grep KEY sudo ausearch -k KEY --input-logs -ts today ls -l /var/log/audit/
Fixed: Reproduce after confirming the existence of the rule; use keywords such as -ts today/recent/boot to avoid date format problems; check num_logs and rotation strategy.
1. Write a rule: record the deletion and renaming of files under /opt/myapp by any real logged-in user.
-a always,exit -F arch=b64 -S unlinkat,renameat,renameat2 -F dir=/opt/myapp -F auid>=1000 -F auid!=unset -k myapp-delete
2. List all failed authentication events today and count them by user.
sudo aureport -au --failed -ts today -i sudo aureport -au --failed --summary -ts today -i
In the audit log, I saw auid=unset uid=root comm=sh exe=/usr/bin/dash key=root-cmd... Wait, why can this be recorded? What does it say?
If the rule has -F auid!=unset, this should not appear - check if there is another rule without filtering that hits. If a root shell with auid=unset does appear, it means that this shell is not derived from the login session, but is started by a system service (without loginuid), such as an exploited web service, cron or systemd unit executing sh. This is a strong signal for intrusion troubleshooting: use ppid/pid to trace back the parent process (ausearch -p PPID), and check the corresponding service log.
Verified instructional video
Official documentation
- audit.rules(7) · ausearch(8) · aureport(8) · auditctl(8)
- journald.conf(5) · pam_loginuid(8)
- RHEL 10: Security hardening (including Auditing the system chapter)
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: labadmin logs in, the ID card says auid one thousand; after sudo, the coat becomes root, but the ID card remains unchanged.
Narration: The moment you log in, the kernel assigns auid to the session. No matter how many times you sudo after that, the audit trail will know who it was originally.
Screen: The openat system call passes through the kernel rule filter, hits the myapp-config rule, and four records are assembled.
Narration: Rules are filtered in the kernel. After a hit, the kernel assembles the system call, path, current directory, and command line into a single event.
Screen: Events flow to auditd through netlink, and then written to the audit point log, and a copy flows to the remote end.
Narration: auditd is responsible for placement and forwarding. Only the logs of the local machine exist and can be deleted by intruders; only forwarding to the remote end in real time is reliable.
Screen: The terminal runs ausearch bar k, aureport summary, and the timeline spells out the complete process.
Narration: Finally, use ausearch and aureport to answer who, when, in what capacity, and what was done.
Module 6 · Kernel Parameters: sysctl and Resource Limitations
- Understand the relationship between
/proc/sysandsysctl, and master it The loading order and coverage rules of/etc/sysctl.d/can write an annotated and auditable hardening configuration. - Know what each hardening parameter prevents (information leakage, kernel vulnerability exploitation, network spoofing), and which parameters will affect the business (IP forwarding and containers, ptrace and debugging, rp_filter and multiple network cards).
- Distinguish three "limits": rlimit (per process,
ulimit/prlimit), pam_limits (only applies to PAM login sessions), systemd'sLimitNOFILE=and cgroup attributes (services). - Fix myapp's
Too many open filesand add upper memory and task limit to it.
What: sysctl
Each file under /proc/sys is a kernel parameter, sysctl net.ipv4.ip_forward is equivalent to reading /proc/sys/net/ipv4/ip_forward. Runtime modifications take effect immediately but are lost upon restart; persistence is written in the configuration file and applied by systemd-sysctl.service at boot time (you can also manually sysctl --system).
Loading order (sysctl.d(5)): Read /etc/sysctl.d/, /run/sysctl.d/, /usr/local/lib/sysctl.d/, /usr/lib/sysctl.d/ *.conf; Files with the same name take priority in /etc (an empty file with the same name can be used or linked to /dev/null to shield the release version file); all files are applied in order in file name dictionary order, and the same parameter written later overwrites the one written first. Therefore, files with the 99- prefix will take effect last. Ubuntu's /etc/sysctl.conf participates via the /etc/sysctl.d/99-sysctl.conf link.
Reinforcement parameter list (including risk description)
| Parameters | Recommended value | What to prevent | Impact/Note |
|---|---|---|---|
kernel.kptr_restrict | 2 | Hide the kernel address in /proc/kallsyms and other places to increase the difficulty of vulnerability exploitation | Tools such as perf require root Symbols cannot be seen (temporarily adjusted back to 1 during performance analysis) |
kernel.dmesg_restrict | 1 | Ordinary users cannot read the kernel log (address, hardware information) | No obvious impact |
kernel.yama.ptrace_scope | 1 (Ubuntu default) or 2 | Prevent processes with the same user from ptrace each other to read memory (steal keys) | 2 = Only processes with CAP_SYS_PTRACE can attach, ordinary users cannot use gdb/strace to attach |
kernel.unprivileged_bpf_disabled | 1 or 2 | Disable non-privileged eBPF (entrance to multiple privilege escalation vulnerabilities) | After being set to 1, it cannot be changed back to 0 at runtime until restart |
net.core.bpf_jit_harden | 2 | JIT constant blinding, mitigating JIT spraying | Slight performance overhead |
kernel.kexec_load_disabled | 1 | Disable loading of new kernels at runtime | Irreversible; systems using kdump need to be evaluated |
fs.protected_symlinks / hardlinks | 1 | Prevent symbol/hard link attacks in /tmp | Usually turned on by default |
fs.protected_fifos / regular | 2 | Prevent the hijacking of other people's files in globally writable sticky directories | A very small number of old programs are affected |
fs.suid_dumpable | 0 | The setuid program does not generate a core that may contain sensitive data when it crashes | It is inconvenient to debug the setuid program |
kernel.randomize_va_space | 2 | Full ASLR | The default is 2, make sure it is not turned off |
net.ipv4.conf.all.rp_filter | 1 (strict) or 2 (loose) | Reverse path filtering, discarding packets with forged source addresses | Use 2 for multiple network cards/asymmetric routing; Ubuntu default 2 |
net.ipv4.conf.*.accept_redirects, send_redirects, accept_source_route | 0 | Prevent ICMP redirection and source route spoofing | Except hosts in the router role; IPv6 corresponding parameters are also set |
net.ipv4.conf.all.log_martians | 1 | Record impossible source addresses | May produce log noise |
net.ipv4.tcp_syncookies | 1 | SYN flood mitigation | On by default |
net.ipv4.ip_forward | 0 (non-router) | Prevent host from being used as a router | Docker/Kubernetes required 1, the container host should not set 0 |
What: Three layers of resource restrictions
| layer | Action objects | Configuration location | View |
|---|---|---|---|
| rlimit(setrlimit) | Single process, child process inheritance; soft ≤ hard, non-privileged process can only reduce hard | ulimit (shell built-in), prlimit | cat /proc/PID/limits |
| pam_limits | Login via PAM session (ssh, login, su, sudo, cron) | /etc/security/limits.conf, limits.d/*.conf | After login ulimit -a |
| systemd | Service (without PAM!) | Unit LimitNOFILE= etc.; global default DefaultLimitNOFILE= of /etc/systemd/system.conf; cgroup properties MemoryMax=, CPUQuota=, TasksMax= | systemctl show -p LimitNOFILE,MemoryMax UNIT |
| Full system upper limit | Whole kernel | fs.file-max, fs.nr_open (ceiling of single-process nofile), kernel.pid_max | cat /proc/sys/fs/file-nr |
systemd's default LimitNOFILE for services is soft 1024 / hard 524288: The soft limit is kept at 1024 for compatibility with programs that are still using select() (fd exceeding 1024 will error), programs that need more file descriptors should increase the soft limit themselves or set it explicitly by the unit.
Why / When
- sysctl hardening is a fixed chapter of the CIS baseline. The cost of modification is low and the benefits are clear; however, the business impact must be evaluated item by item, especially container hosting and debugging requirements.
- Resource limits are both a stability measure (preventing one service from eating up nodes) and a security measure (limiting fork bombs, memory exhaustion-like DoS).
- The resource limit of the container is essentially the cgroup attribute here (Module 7).
Comparison with similar technologies
| sysctl | Kernel startup parameters (GRUB) | systemd unit attributes | |
|---|---|---|---|
| Scope | Full system (net.* some parameters are based on network namespace) | Full system, at startup | Single service |
| Effective | Immediately | Restart | Restart the service (some cgroup properties can be modified online via set-property) |
| Example | kernel.kptr_restrict=2 | lockdown=integrity, init_on_free=1 | LimitNOFILE=65536, MemoryMax=512M |
LimitNOFILE=. ② "sysctl -p will load all configurations"——sysctl -p The default is read-only /etc/sysctl.conf, to load all sysctl.d files sysctl --system. ③ "I set it in 99-hardening.conf, and it will definitely take effect" - If a software package later installs a file with a later name (or Docker writes ip_forward when starting), your value will be overwritten. Use systemd-analyze cat-config sysctl.d to view the merged results. ④ "It's okay to set ulimit -n to 1 million" - if it exceeds fs.nr_open , it will fail, and an excessively large fd table will increase memory usage. Architecture diagram: sysctl configuration from file to kernel
Flowchart: Where does the nofile restriction of a process come from
Simulator: "Where do the limits of this process come from?"
Select the startup method of the process and adjust three configurations. The simulator calculates the final Max open files (soft/hard) along the real inheritance chain and gives what /proc/PID/limits looks like and "why".
myapp - nofile LimitNOFILE= DefaultLimitNOFILE= Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
sysctl -a / sysctl KEY | View all / single parameter | -w KEY=VAL Runtime modification |
sysctl --system | Reload all files according to sysctl.d rules | Output the application order of each file |
systemd-analyze cat-config sysctl.d | View the merged configuration (including overrides) | Troubleshooting "Why it didn't take effect" |
ulimit -Sn / -Hn | Nofile soft/hard limit of the current shell | ulimit -a All |
prlimit --pid PID --nofile=S:H | View/modify the rlimit of the running process | Emergency means, invalid after restart |
systemctl show -p LimitNOFILE,LimitNOFILESoft UNIT | Service limitations | Also see MemoryMax, TasksMax |
systemctl set-property UNIT MemoryMax=512M | Modify cgroup attributes online (and persist as drop-in) | --runtime Only takes effect temporarily |
ls /proc/PID/fd | wc -l | The number of fds currently opened by the process | Compare with limits to determine whether it is close to the upper limit |
sysctl reinforcement (linuxlab)
## Information leakage and kernel exploitation surface kernel.kptr_restrict = 2 kernel.dmesg_restrict = 1 kernel.yama.ptrace_scope = 1 kernel.unprivileged_bpf_disabled = 1 net.core.bpf_jit_harden = 2 fs.suid_dumpable = 0 fs.protected_fifos = 2 fs.protected_regular = 2 kernel.randomize_va_space = 2 ## Network (single network card server; container host should not turn off ip_forward) net.ipv4.conf.all.rp_filter = 1 net.ipv4.conf.default.rp_filter = 1 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.default.accept_redirects = 0 net.ipv6.conf.all.accept_redirects = 0 net.ipv6.conf.default.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 net.ipv4.conf.all.accept_source_route = 0 net.ipv6.conf.all.accept_source_route = 0 net.ipv4.conf.all.log_martians = 1 net.ipv4.icmp_echo_ignore_broadcasts = 1 net.ipv4.tcp_syncookies = 1
sudo sysctl --system | grep -E '^\* Applying|hardening' sysctl kernel.kptr_restrict kernel.unprivileged_bpf_disabled net.ipv4.conf.all.rp_filter systemd-analyze cat-config sysctl.d | grep -n rp_filter
* Applying /usr/lib/sysctl.d/10-apparmor.conf ... * Applying /etc/sysctl.d/10-console-messages.conf ... * Applying /etc/sysctl.d/60-hardening.conf ... * Applying /etc/sysctl.d/99-sysctl.conf ... kernel.kptr_restrict = 2 kernel.unprivileged_bpf_disabled = 1 net.ipv4.conf.all.rp_filter = 1 …:net.ipv4.conf.all.rp_filter = 2 …:net.ipv4.conf.all.rp_filter = 1
How to verify: When the same parameter appears multiple times in cat-config, the last time is the effective value; then use sysctl to read the current value to confirm that it has not been overwritten by other programs. Common mistakes: Setting ip_forward=0 on the container host causes the container to disconnect; rp_filter=1 causes packet loss in an asymmetric routing environment with multiple network cards. Production use: Include this file in image and configuration management, and the CIS scan will check these values one by one.
Repair Too many open files of myapp and add resource limit
PID=$(systemctl show -p MainPID --value myapp.service) grep -E 'Max (open files|processes)' /proc/$PID/limits sudo systemctl edit myapp.service --drop-in=61-limits
[Service] LimitNOFILE=65536 MemoryMax=512M MemoryHigh=400M TasksMax=128 CPUQuota=150%
sudo systemctl daemon-reload && sudo systemctl restart myapp.service PID=$(systemctl show -p MainPID --value myapp.service) grep 'Max open files' /proc/$PID/limits systemctl show myapp.service -p LimitNOFILE -p MemoryMax -p TasksMax -p CPUQuotaPerSecUSec
Max open files 1024 524288 files Max open files 65536 65536 files LimitNOFILE=65536 MemoryMax=536870912 TasksMax=128 CPUQuotaPerSecUSec=1.500000s
Experiment 6: Reinforce sysctl + reproduce and repair Too many open files (about 8 minutes)
LimitNOFILE= Valid. Environment: linuxlab. sudo sysctl -w kernel.kptr_restrict=0 >/dev/null; sudo head -n 2 /proc/kallsyms sudo sysctl -w kernel.kptr_restrict=2 >/dev/null; sudo head -n 2 /proc/kallsyms
ffffffff8a000000 T startup_64 ffffffff8a000040 T secondary_startup_64 0000000000000000 T startup_64 0000000000000000 T secondary_startup_64
Even root can only see all-0 addresses: an attacker cannot obtain the kernel address from here to bypass KASLR. Then press "Command" page to write 60-hardening.conf and sysctl --system.
echo 'myapp - nofile 65536' | sudo tee /etc/security/limits.d/50-myapp.conf
sudo systemd-run --unit=fdtest --wait --pipe -p User=myapp -p LimitNOFILE=256 \
python3 -c 'import os; fs=[open("/dev/null") for _ in range(1000)]; print(len(fs))'
Running as unit: fdtest.service; invocation ID: …
Traceback (most recent call last):
…
OSError: [Errno 24] Too many open files: '/dev/null'
Finished with result: exit-code
limits.d is set to 65536 for myapp, but the service is still only 256: the service does not go through PAM.
sudo systemd-run --unit=fdtest2 --wait --pipe -p User=myapp -p LimitNOFILE=4096 \
python3 -c 'import os; fs=[open("/dev/null") for _ in range(1000)]; print(len(fs))'
sudo rm /etc/security/limits.d/50-myapp.conf
1000
Finished with result: success61-limits.conf, confirm after restarting /healthz Normal,/proc/PID/limits Updated; check the cgroup file again
CG=/sys/fs/cgroup$(systemctl show -p ControlGroup --value myapp.service) cat $CG/memory.max $CG/memory.high $CG/pids.max $CG/cpu.max cat $CG/memory.current $CG/pids.current
536870912 419430400 128 150000 100000 61341696 5
60-hardening.conf and 61-limits.conf; systemctl reset-failed fdtest fdtest2 (if there is a failure record). Case 1: "accept(): Too many open files" during peak period
Problem: The gateway service reported EMFILE during peak period, and restarting the service after operation and maintenance modified /etc/security/limits.conf has no effect. How to do:cat /proc/PID/limits Confirm that it is still 1024; set LimitNOFILE=65536 in the unit drop-in, and monitor ls /proc/PID/fd | wc -l. Configuration:This module 61-limits.conf. Limitations: The continued growth of fd is usually a connection leak. Raising the upper limit can only buy time.
Case 2: Kubernetes node Pod network interruption after hardening
Problem: The sysctl baseline pushed uniformly contains net.ipv4.ip_forward=0, and Pod cross-node communication fails after the node is restarted. Practice: The baseline is divided by role (normal server / container host / router), the container host retains ip_forward=1 and records exceptions through tailoring. Limitations: The same CIS configuration file cannot be applied to all roles indiscriminately.
Case 3: A service eats up the memory of the entire machine
Problem: Background task memory leaked, triggering global OOM, and the kernel killed multiple key processes except sshd. Method: Set MemoryMax= (hard upper limit, OOM will only occur within the cgroup when exceeded) and MemoryHigh= (soft upper limit, it will be recycled after current limit is exceeded) for each service; enable systemd-oomd or rely on cgroup-level OOM. Limitations: Too low an upper limit will cause normal peaks to be killed and needs to be set based on monitoring data.
Common errors and solutions
sysctl: setting key "kernel.unprivileged_bpf_disabled": Operation not permitted
Cause: This parameter is already 1 and cannot be changed back to 0 (as designed); or executed in a container/non-root.
Fix: This is expected behavior. If you really need to change it, you need to modify the configuration and restart.
sysctl: cannot stat /proc/sys/net/ipv4/conf/docker0/rp_filter: No such file or directory
Cause:The configuration refers to a network card that does not exist at startup.
Fix: Use all/default; or add - before the parameter name to have systemd-sysctl ignore the error (sysctl.d(5)).
OSError: [Errno 24] Too many open files (service)
PID=$(systemctl show -p MainPID --value myapp.service) grep 'open files' /proc/$PID/limits; ls /proc/$PID/fd | wc -l systemctl show myapp -p LimitNOFILE
Fix: Set LimitNOFILE= in the unit; troubleshoot fd leaks (ls -l /proc/PID/fd to see the direction).
fork: retry: Resource temporarily unavailable / can't start new thread
Cause: TasksMax= (cgroup pids.max) or LimitNPROC was reached; the user session was also affected by UserTasksMax (logind).
systemctl show myapp -p TasksMax -p TasksCurrent cat /sys/fs/cgroup/system.slice/myapp.service/pids.max /sys/fs/cgroup/system.slice/myapp.service/pids.events
Fix: After confirming that it is not a thread leak, increase TasksMax=; the max count in pids.events represents the number of rejections.
1. Without restarting myapp, temporarily change the nofile soft/hard limit of its main process to 8192.
sudo prlimit --pid $(systemctl show -p MainPID --value myapp.service) --nofile=8192:8192
Note that gunicorn’s workers were forked before and will not automatically inherit new values; the long-term solution is still unit attributes.
2. View the definition and final effective value of rp_filter in all sysctl configuration files.
systemd-analyze cat-config sysctl.d | grep -n rp_filter sysctl net.ipv4.conf.all.rp_filter
The security team requires all servers to kernel.yama.ptrace_scope=3. Would you agree?
The value 3 means that ptrace attach is completely disabled, and cannot be lowered during runtime and can only be restored by restarting; it will make gdb/strace attach, some performance and security tools (and some EDR) invalid, and it will be extremely inconvenient when troubleshooting (strace in Lesson 7 relies on it). Recommendation: Use 1 for general servers, 2 for highly sensitive hosts (only administrators with CAP_SYS_PTRACE are allowed), limit 3 to a very small number of devices that do not require on-site troubleshooting, and write tailoring as the "Level 2/roleization" item in the baseline.
Verified teaching video
Official documentation
- sysctl.d(5) · Documentation for /proc/sys/kernel/ · Yama
- getrlimit(2) · limits.conf(5) · systemd.resource-control(5)
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The /proc/sys directory tree expands into a row of knobs, the kptr_restrict knob turns from 0 to 2, and the address of kallsyms becomes all zeros.
Narration: sysctl is the knob of the kernel. Set kptr_restrict to two, and even root cannot see the kernel address.
Screen: Multiple files under sysctl.d are superimposed in alphabetical order, and the same parameter is overwritten by subsequent files.
Narration: Configuration files are applied in order of name, and the ones written later overwrite those written first. Use systemd-analyze cat-config to view the merged results.
Screen: Two inheritance chains, ssh login reads the limits point conf through PAM, the myapp service directly inherits from systemd, and the limits point conf is crossed.
Narration: limits dot conf is only valid for login sessions. Service restrictions should be written in the unit file.
Screen: The three files memory.max, pids.max, and cpu.max in the cgroup directory of myapp light up.
Narration: The upper limit of memory, number of processes and CPU all fall in the cgroup file. This is exactly the basis of container resource limits.
Module 7 · namespaces and cgroups: the underlying mechanism of containers
- Lists what 8 namespaces (mnt, uts, ipc, pid, net, user, cgroup, time) isolate respectively, and the corresponding
clone()/unshare()flags. - Use
lsns,/proc/PID/ns/,nsenterto observe and enter the namespace of any process (including myapp's systemd sandbox). - Understand the unified hierarchy of cgroup v2, controllers (cpu, memory, io, pids) and core interface files (
cpu.max,memory.max,memory.events,pids.max). - Use
unshare+chroot+systemd-runto create a minimal "container" and trigger cgroup-level OOM.
What: namespaces - "What can be seen" in isolation
| Namespace | Flag | Isolated content | Performance in container |
|---|---|---|---|
| mnt | CLONE_NEWNS | Mount point list | Independent root file system, read-only mount |
| uts | CLONE_NEWUTS | Host name, NIS domain name | Container has its own hostname |
| ipc | CLONE_NEWIPC | System V IPC, POSIX message queue | Shared memory is not visible to each other |
| pid | CLONE_NEWPID | Process ID space | The first process in the container is PID 1 |
| net | CLONE_NEWNET | Network card, routing, firewall rules, ports | Independent eth0, independent nftables rules |
| user | CLONE_NEWUSER | UID/GID mapping and capabilities | The root in the container is mapped to the common UID of the host (rootless) |
| cgroup | CLONE_NEWCGROUP | The cgroup root seen by the process | In the container /sys/fs/cgroup only displays its own subtree |
| time | CLONE_NEWTIME | Monotonic clock and startup clock offset | For checkpoint recovery (CRIU) |
Each process has 8 symbolic links under /proc/PID/ns/. The same inode number in the link target means that it is in the same namespace. unshare (system call and command with the same name) allows the current process to enter a new namespace; setns() (command nsenter) joins an existing namespace. In addition to the user namespace, CAP_SYS_ADMIN is required to create namespaces.
What: cgroups v2 - limit "how much can be used"
cgroup v2 is a single-level file system (type cgroup2) mounted in /sys/fs/cgroup. Systemd 259 of Ubuntu 26.04 no longer supports the cgroup v1 level. All paths in this lesson are based on v2. Each directory is a cgroup, and the process PID written to cgroup.procs is moved into it; the cgroup.subtree_control of the parent directory determines which controllers are enabled in the subdirectory. systemd maps each service, scope, and slice to a cgroup: system.slice/myapp.service.
| File | Meaning | systemd attribute |
|---|---|---|
cpu.max | "Quota period", such as 20000 100000 = 20% single core | CPUQuota=20% |
cpu.weight | CPU Relative weight when busy (default 100) | CPUWeight= |
memory.max / memory.high | Hard upper limit (over → OOM within cgroup) / soft upper limit (over → current limit recycling) | MemoryMax= / MemoryHigh= |
memory.events | high, max, oom, oom_kill count | First-hand evidence for troubleshooting OOM |
pids.max | Maximum number of tasks (anti-fork bomb) | TasksMax= |
io.max | Block device read and write bandwidth/IOPS upper limit | IOReadBandwidthMax= etc. |
Why: Container = namespace + cgroup + ability tailoring + seccomp + LSM + root filesystem
Docker / Podman / containerd calls exactly these kernel primitives via runc (or crun): clone() with 6–7 CLONE_NEW* flags, pivot_root to the image's root filesystem, writes cgroup files, discards most capabilities, loads default seccomp Configure and apply AppArmor configuration file (docker-default) or SELinux label (container_t + MCS). Understand this and understand which layer "container escape" usually means is bypassed. See the Docker 8-hour course for complete usage of the container layer.
How / When
- When troubleshooting, use
nsenter -t PID -nto enter the container's network namespace, and usessandtcpdumpon the host (these tools are often not included in the container image). - Temporarily limit a batch task:
systemd-run --scope -p MemoryMax=… -p CPUQuota=… command, which is more reliable than hand-written cgroup directories, and systemd will automatically clean up. - Do not manually create/delete cgroup directories in the hierarchy managed by systemd (except for subtrees delegated to you,
Delegate=yes), otherwise it will conflict with systemd.
Comparison with similar technologies
| chroot | namespaces + cgroups (containers) | Virtual machines | |
|---|---|---|---|
| Isolation boundaries | File system root only | Multiple views within the same kernel | Independent kernel (hardware virtualization) |
| Can root escape | Functional (classic chroot escape) | Depends on capabilities/seccomp/LSM/userns configuration | Requires virtualization layer vulnerability |
| Resource limitations | None | cgroup | Virtual hardware |
| Startup overhead | None | Millisecond level | Second level |
kernel.apparmor_restrict_unprivileged_userns=1) is restricted by default. In this lesson, sudo is used uniformly in the experiments. Architecture diagram: What kernel primitives does a container process consist of
Flow chart: cgroup v2 level and systemd Mapping
systemd-cgls Show this tree"Step by step "hand-rolling the container"
Each step executes a real command, and its corresponding system calls and flags, as well as the difference between the host perspective and the "in-container" perspective, are shown below. The last two steps put the process into a cgroup and trigger OOM.
Core commands and parameters
| Command | Function | Key parameters/description |
|---|---|---|
lsns | List the namespaces and their processes in the system | -t net, -p PID |
ls -l /proc/PID/ns/ | View the namespace to which the process belongs inode | Comparison with /proc/1/ns/ |
unshare | Run the program in the new namespace | --fork --pid --mount-proc --mount --uts --ipc --net --user --map-root-user |
nsenter -t PID | Enter the namespace of the target process | -m -u -i -n -p or -a (all) |
ip netns add/exec | Named network namespace | Mounted in /run/netns/ |
systemd-run --scope -p … | Run in temporary scope and add resource restrictions | --unit=, --wait, -p MemoryMax= CPUQuota= TasksMax= |
systemd-cgls / systemd-cgtop | cgroup tree/real-time resource usage | -m Sort by memory (cgtop) |
cat /proc/PID/cgroup | Process location cgroup | v2 has only one line 0::/path |
Observation: myapp's sandbox is actually a namespace
stat -fc %T /sys/fs/cgroup; cat /sys/fs/cgroup/cgroup.controllers PID=$(systemctl show -p MainPID --value myapp.service) sudo ls -l /proc/1/ns/mnt /proc/$PID/ns/mnt sudo lsns -p $PID sudo nsenter -t $PID -m findmnt -no TARGET,OPTIONS /usr /tmp /home | head cat /proc/$PID/cgroup
cgroup2fs
cpuset cpu io memory hugetlb pids rdma misc dmem
lrwxrwxrwx 1 root root 0 Nov 17 11:20 /proc/1/ns/mnt -> 'mnt:[4026531841]'
lrwxrwxrwx 1 root root 0 Nov 17 11:20 /proc/7012/ns/mnt -> 'mnt:[4026532301]'
NS TYPE NPROCS PID USER COMMAND
4026532301 mnt 3 7012 myapp /opt/myapp/venv/bin/python3 /opt/myapp/venv/bin/gunicorn …
4026532302 uts 3 7012 myapp …
...
/usr ro,nosuid,nodev,relatime
/tmp rw,nosuid,nodev,relatime
/home ro,nosuid,nodev,noexec,relatime
0::/system.slice/myapp.service
Interpretation: Module 1 ProtectSystem=strict, PrivateTmp=yes, ProtectHome=yes are read-only/private mounts made by systemd in a private mount namespace; ProtectHostname=yes gives it an independent UTS namespace. The controller list is subject to the kernel (the new kernel may have more dmem, etc.). When ProtectHome=yes, /home is actually replaced with empty and inaccessible, and the options displayed by findmnt are subject to actual conditions.
Use systemd-run for resource limitation
sudo systemd-run --unit=memhog --wait -p MemoryMax=100M -p MemorySwapMax=0 \
python3 -c 'b = bytearray(300 * 1024 * 1024); print("allocated")'
systemctl status memhog --no-pager 2>/dev/null | head -n 4 || true
sudo journalctl -k --since '-2min' -g 'memory cgroup|oom' --no-pager | tail -n 2
Running as unit: memhog.service; invocation ID: …
Finished with result: oom-kill
Main processes terminated with: code=killed, status=9/KILL
kernel: Memory cgroup out of memory: Killed process 8123 (python3) total-vm:330112kB, anon-rss:101800kB, file-rss:0kB, shmem-rss:0kB, UID:0 pgtables:300kB oom_score_adj:0
How to verify: Finished with result: oom-kill and Memory cgroup out of memory in the kernel log indicate that it is a cgroup-level OOM (only affects this unit), not a global OOM. Common mistakes: When MemorySwapMax=0 is not set, the machine with swap will be swapped out first instead of being killed immediately. Production use: Add upper limits for batch processing tasks such as backup and reporting to avoid squeezing online services.
Experiment 7: Use busybox to rub a container by hand (about 10 minutes)
unshare, chroot, systemd-run Implementation: independent host name, independent PID space, independent mount, independent network, independent root file system, memory and CPU upper limit. Environment: linuxlab, sudo. Risk: Low, everything is in ~/linuxlab/hour6/box . sudo apt install -y busybox-static
mkdir -p ~/linuxlab/hour6/box/{bin,proc,sys,dev,tmp,etc} && cd ~/linuxlab/hour6/box
cp /bin/busybox bin/
sudo chroot . /bin/busybox --install -s /bin
ls bin | head -n 5; ls bin | wc -l
[ [[ acpid adjtimex ar 400
sudo systemd-run --unit=box1 --scope -p MemoryMax=64M -p MemorySwapMax=0 -p CPUQuota=20% -p TasksMax=32 \ unshare --fork --pid --mount --uts --ipc --net \ chroot ~/linuxlab/hour6/box /bin/sh
mount -t proc proc /proc hostname box1; hostname echo $$; ps ip link ls /
box1
1
PID USER TIME COMMAND
1 0 0:00 /bin/sh
5 0 0:00 ps
1: lo: <LOOPBACK> mtu 65536 qdisc noop qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
bin dev etc proc sys tmp
PID 1. There is only lo network card (and it is DOWN), and the root directory only has several directories of busybox - this is already like a "container".
systemctl status box1.scope --no-pager | head -n 8 CG=/sys/fs/cgroup/system.slice/box1.scope cat $CG/cgroup.procs # Unshare process and host PID of sh in "container" BOXSH=$(tail -n 1 $CG/cgroup.procs) sudo lsns -p $BOXSH | head cat $CG/memory.max $CG/cpu.max $CG/pids.max hostname
● box1.scope - /usr/bin/unshare --fork --pid --mount --uts --ipc --net chroot /home/labadmin/linuxlab/hour6/box /bin/sh
Loaded: loaded (/run/systemd/transient/box1.scope; transient)
Active: active (running) since …
Tasks: 3 (limit: 32)
Memory: 1.1M (max: 64M, swap max: 0B)
CPU: 18ms
67108864
20000 100000
32
linuxlab
The host name of the host machine has not changed; the scope unit name is the cgroup directory name; it can also be seen in systemd-cgls. You can also use sudo nsenter -t to enter it.
awk 'BEGIN { s = "x"; while (1) s = s s }'; echo "exit=$?"
(while :; do :; done) & sleep 5; kill %1
cat /sys/fs/cgroup/system.slice/box1.scope/memory.events grep -E 'nr_periods|nr_throttled' /sys/fs/cgroup/system.slice/box1.scope/cpu.stat
Killed exit=137 low 0 high 0 max 52 oom 1 oom_kill 1 nr_periods 50 nr_throttled 48
awk doubles the string length in each round, the memory quickly exceeds 64M, and is killed by OOM in the cgroup (exit code 137 = 128 + 9); the busy loop is blocked by cpu.max Throttling, nr_throttled is close to nr_periods. This is the underlying implementation of Docker --memory / --cpus.
unshare --user --map-root-user id unshare --user --map-root-user --mount sh -c 'mount -t tmpfs none /mnt' ; echo "exit=$?" sudo journalctl -k --since '-1min' -g 'unprivileged_userns' --no-pager | tail -n 1
uid=0(root) gid=0(root) groups=0(root),65534(nogroup) mount: /mnt: permission denied. exit=32 audit: type=1400 audit(…): apparmor="DENIED" operation="capable" class="cap" profile="unprivileged_userns" pid=9120 comm="mount" capability=21 capname="sys_admin"
The user namespace can be created and the identity mapped to "root", but Ubuntu puts this process into the unprivileged_userns AppArmor configuration, CAP_SYS_ADMIN in the namespace Denied - This is a mitigation for "unprivileged userns are a common entry point for kernel privilege escalation". Programs that require rootless containers (such as podman, browser sandboxes) are released through special AppArmor configuration provided by the distribution.
exit; the scope disappears automatically when the process exits. systemctl list-units --all 'box1*' 'memhog*' --no-pager sudo systemctl reset-failed memhog.service 2>/dev/null; rm -rf ~/linuxlab/hour6/box
Case 1: There are no tools in the container, how to troubleshoot the network?
Problem: The service connection database of the distroless mirror times out, and there is no shell or ss in the container. Method: Find the container main process PID on the host machine (docker inspect -f '{{.State.Pid}}' container or crictl inspect), execute nsenter -t PID -n ss -tanp, nsenter -t PID -n tcpdump -ni eth0 port 5432, directly use host tools to view the container network namespace. Restrictions: Requires host root; the temporary container of kubectl debug is more recommended on Kubernetes.
Case 2: Batch processing tasks bring down online services
Problem: The nightly data export script fills up the CPU and I/O, and the online API latency soars. Method: Export the service execution triggered by systemd timer, and set CPUWeight=20, IOWeight=20, MemoryMax=2G, Nice=10; online service CPUWeight=200. Limitations: Weights only take effect during contention; I/O control relies on block device and I/O scheduler support for cgroup v2.
Case 3: Review of a container escape drill
Problem: The red team mounted the host disk in a --privileged container and wrote to cron to obtain the host root. How to do it: A review found that privileged means: all capabilities, no seccomp, no AppArmor, access to all devices - all five layers of protection are turned off. Rectification: Disable privileged and replace it with specific --cap-add; enable user namespace remapping or rootless; use the restricted level of Kubernetes Pod Security Admission. Restrictions: Some infrastructure components (CNI, storage drivers) do require high permissions and should be concentrated on dedicated nodes and strictly audited.
Common errors and solutions
unshare: unshare failed: Operation not permitted
Cause: Non-root creation of namespaces other than user requires CAP_SYS_ADMIN; non-privileged userns are restricted by AppArmor on Ubuntu; or the process is under RestrictNamespaces=yes/seccomp restrictions.
sysctl kernel.apparmor_restrict_unprivileged_userns user.max_user_namespaces sudo journalctl -k -g 'unprivileged_userns|apparmor' --since '-5min' --no-pager | tail -n 3
Fix: Experimental sudo; write a dedicated AppArmor configuration (containing the userns, rule) for programs that do require userns, instead of turning off the restriction globally.
chroot: failed to run command ‘/bin/sh’: No such file or directory
Cause: There is no /bin/sh in the new root, or it is dynamically linked and the corresponding library is missing in the new root (the error message will be misleading: what is missing is actually the dynamic linker).
file ~/linuxlab/hour6/box/bin/busybox ls -l ~/linuxlab/hour6/box/bin/sh
Fix: Use busybox-static and execute --install -s to create the link.
ps: no processes found / Error, do this: mount -t proc proc /proc
Cause: The new PID namespace does not have its own /proc mounted (what you see is an empty directory or the host's proc).
Fix: mount -t proc proc /proc in the new mount namespace, or unshare --pid --fork --mount-proc when not using chroot.
Failed to start transient scope unit: Unit box1.scope already exists.
Cause: The temporary unit with the same name is still running or in a failed state.
systemctl status box1.scope --no-pager; sudo systemctl stop box1.scope; sudo systemctl reset-failed box1.scope
Fix: Stop/clean and try again, or change a --unit name.
1. Use ss on the host to view the sockets in the network namespace of the "container" (sh in box1.scope) in the experiment.
sudo nsenter -t $(tail -n 1 /sys/fs/cgroup/system.slice/box1.scope/cgroup.procs) -n ss -tanp
2. Run make -j8 in a temporary scope limited to 25% of 1 CPU and a maximum of 10 tasks.
sudo systemd-run --scope -p CPUQuota=25% -p TasksMax=10 --uid=$(id -u) --gid=$(id -g) make -j8
The developer said: "My container is set to --memory=512m, but docker stats shows that it was OOMKilled after only 300M was used." How do you analyze it?
First look at the memory.events (oom_kill count) and memory.stat of the container cgroup: The usage displayed by docker stats usually deducts part of the page cache, and the OOM determination is based on the total cgroup usage (anon + non-recyclable file/shmem + kernel memory). Common reasons: tmpfs (/dev/shm) occupies memory, a large number of dirty pages cannot be recycled in time, the instantaneous peak value (within the sampling interval) exceeds the upper limit, and kernel memory (a large number of sockets/inodes). Also exclude the host global OOM (there is no "Memory cgroup" in the kernel log). Processing: adjust the upper limit, limit the tmpfs size, fix the peak, or set memory.high (--memory-reservation type mechanism) to limit the current in advance.
Verified instructional video
Official document
- namespaces(7) · user_namespaces(7) · unshare(1) · nsenter(1)
- cgroups(7) · Control Group v2 (kernel documentation) · systemd-run(1)
- Container layer: Docker 8-hour course
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: An ordinary sh process, surrounded by four translucent covers of uts, pid, mount, and net.
Narration: Containers are not virtual machines. It is a normal process, but it is covered with layers of namespaces.
Screen: PS inside the cover displays PID 1, hostname displays box1; the host outside the cover sees it as PID 4711.
Narration: The namespace clips the view. In the container, it is process No. 1, but on the host, it is just ordinary process No. 4,711.
Screen: memory.max in the cgroup directory is written to 64M, the process consumes memory and hits the upper limit, and oom_kill in memory.events is increased by one.
Narration: cgroup limits usage. Exceeding memory.max, the kernel only performs OOM in this group, and the host is safe.
Screen: The Docker icon expands, revealing five building blocks: namespaces, cgroups, capabilities, seccomp, and AppArmor.
Narration: What Docker and Kubernetes do is to automatically put together these kernel building blocks.
Module 8 · Comprehensive Hardening Architecture Review
- For myapp The host performs a simplified threat modeling: assets, entrances, attack paths, and which layer of control blocks each path.
- Use a review checklist of "Control → Evidence Command → Expected Results" to complete the host review and output the findings and exception registration.
- Design a continuous compliance process: Apply baseline when building the image → Regular audit during runtime → Drift alarm → Exception review.
- When encountering "Permission denied / Service cannot be started", you can use the troubleshooting tree to quickly determine which layer is causing it.
What: Four questions to be answered by the review
- What are we protecting? Assets: myapp's code and configuration (keys in
/opt/myapp,/etc/myapp/myapp.env), data in Redis, the host itself (value as a springboard), logs and audit evidence. - Where does the attack come from? Entrance: Public network → port 5000 (application vulnerability); management plane → port 22 (credential theft, brute force cracking); supply chain → pip dependencies, software packages; internal → people with sudo.
- What cuts off each attack path? See table below. There must be at least two layers of independent control, and the failure of a single layer is not fatal.
- How do we know that the controls are in effect and can we find out when something goes wrong? Evidence: baseline scan report,
systemd-analyze securityscore, rule file, audit log, remote forwarding status.
Attack Path × Control Layer (myapp host)
| Attack Path | First Layer | Second Layer | Third Layer | Evidence |
|---|---|---|---|---|
Myapp reads the SSH private key in /home after RCE | systemd ProtectHome=yes | AppArmor configuration file deny @{HOME}/** | DAC (home directory 750) | systemd-analyze security, aa-status |
| Execute setuid program to elevate privileges after RCE | NoNewPrivileges=yes | CapabilityBoundingSet= | Patch in time (Lesson 4-5) | NoNewPrivs, CapBnd in /proc/PID/status |
| Exploiting kernel vulnerabilities after RCE (unpopular system calls) | SystemCallFilter=@system-service | sysctl: unprivileged_bpf_disabled, userns limit | Kernel update + Livepatch | Seccomp: 2, sysctl value |
| RCE Lateral access to internal services other than Redis 6379 | Outbound firewall (optional) / IPAddressDeny= | Network segmentation, security group | — | nft/ufw rules, security group configuration |
| Brute force/steal SSH credentials | SSH certificate (8 hours) + banned password | Firewall only allows management segment / speed limit | KRL revocation | sshd -T, certificate key ID log |
| Misoperation or malicious modification by insiders with sudo | Minimum sudoers | auditd -k myapp-config/root-cmd | Log real-time forwarding + -e 2 | sudo -l -U, ausearch |
| Resource exhaustion (memory leak, fork bomb) | MemoryMax/TasksMax | LimitNOFILE | Monitoring alarms | systemctl show, memory.events |
| Configuration drift (someone turns off SELinux and opens ports) | Regular baseline scan | Configuration management forced convergence (Ansible) | Audit rules | usg / oscap reporting trends |
Why: Why "review" is needed instead of just "hardening script"
- There are dependencies and conflicts between controls:
ip_forward=0The container network will be disconnected.ProtectSystem=strictneeds to be matched withReadWritePaths. The SSH rules of CIS may lock the operation and maintenance account - this can only be discovered through business review. - Exceptions are inevitable (legacy programs require
MemoryDenyWriteExecute=no, monitoring agents require more capabilities). The review turns the exception into a registered, justified, time-limited, and compensated control entry.
How: Review Process
- Collect evidence (script for the "Command" page of this module, read-only).
- Check the checklist item by item: pass/fail/not applicable (reason required).
- Output discovery items: risk level (high/medium/low), impact, repair suggestions, person in charge, and deadline.
- Register exception: control item, reason, compensation control, approver, due review date.
- Consolidate the repair into the image (lesson 5 Packer) and configuration management (Ansible), and add regression checking in CI (
systemd-analyze security --threshold,nft -c,visudo -c,sshd -t).
When
Before the new system goes online, after major changes (distribution upgrades, such as sudo-rs brought by 24.04 → 26.04), quarterly routine, and after security incidents.
Comparison with similar practices
| Run CIS scan only | Architecture review (this module) | Penetration testing | |
|---|---|---|---|
| Follow | Whether the configuration items comply with the list | Control whether the real attack path is covered and whether exceptions are controlled | Can it be actually broken |
| Frequency | Automatically daily/weekly | Pre-launch/quarter | Annual/major changes |
| Output | Scores and failure rules | Discovery items + exception registration + improvement route | Vulnerability report |
Reference architecture: hardened myapp host
Flowchart: Continuous Compliance Closed Loop
Reinforcement scorer + attack path deduction
Check the controls currently implemented by linuxlab (the default is the state after completing all experiments in this lesson). On the right side, the six attack paths are deduced one by one: which layer is intercepted and what evidence is left; the layered score is given on the lower left. Try to cancel certain items and observe which path changes from "interrupted" to "attack successful".
Review checklist and evidence command
| # | Control | Evidence command | Expected results | Module |
|---|---|---|---|---|
| 1 | MAC is enforced | aa-status --enabled; getenforce | Yes / Enforcing | 2 |
| 2 | myapp has AppArmor configuration and enforce | cat /proc/PID/attr/current | myapp (enforce) | 2 |
| 3 | myapp sandbox exposure | systemd-analyze security myapp.service | ≤ 4 (OK or better) | 1 |
| 4 | Inbound only 22/5000 | ufw status verbose / nft list ruleset + External scanning | Default deny, only two allow | 3 |
| 5 | SSH only certificate, root and password prohibited | sshd -T | grep -E 'permitrootlogin|passwordauthentication|trustedusercakeys' | no / no / with CA | 4 |
| 6 | sudo minimized | grep -rhv '^#' /etc/sudoers.d/; for each user sudo -l -U | No ALL, no pager/editor | 4 |
| 7 | Audit rules loaded and no loss | auditctl -s; auditctl -l | wc -l | lost 0, the number of rules is in line with the baseline | 5 |
| 8 | journald persistence | journalctl --list-boots | wc -l | > 1 (retained across restarts) | 5 |
| 9 | sysctl hardening | sysctl kernel.kptr_restrict kernel.unprivileged_bpf_disabled net.ipv4.conf.all.accept_redirects | 2 / 1 / 0 | 6 |
| 10 | Resource limit | systemctl show myapp -p MemoryMax -p TasksMax -p LimitNOFILE | None infinity | 6, 7 |
| 11 | No redundant listening ports | ss -tlnp | Only 22 and 5000 to the outside world | 3 |
| 12 | Baseline scan | lynis / usg / oscap Report | Failed items are all handled or excepted | 1 |
Read-only evidence collection script
#!/usr/bin/env bash
# Read-only: Collect linuxlab hardening review evidence. Usage: sudo bash hardening-review.sh | tee review-$(date +%F).txt
set -u
sec(){ printf '\n===== %s =====\n' "$1"; }
PID=$(systemctl show -p MainPID --value myapp.service)
sec "1 system"; . /etc/os-release; echo "$PRETTY_NAME kernel=$(uname -r)"; systemctl --version | head -n 1
sec "2 MAC"; aa-status --enabled && echo "AppArmor enabled"; command -v getenforce >/dev/null && getenforce
echo "myapp: $(cat /proc/$PID/attr/current 2>/dev/null)"
sec "3 myapp sandbox"; systemd-analyze security myapp.service --no-pager | tail -n 1
grep -E '^(CapBnd|NoNewPrivs|Seccomp):' /proc/$PID/status
sec "4 firewall"; (ufw status verbose 2>/dev/null || true); nft list ruleset 2>/dev/null | grep -cE 'accept|drop' | sed 's/^/nft rules: /'
sec "5 SSH"; sshd -T 2>/dev/null | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|trustedusercakeys|authorizedprincipalsfile|revokedkeys|maxauthtries) '
sec "6 sudo"; for f in /etc/sudoers /etc/sudoers.d/*; do echo "-- $f"; grep -vE '^\s*(#|$)' "$f"; done
sec "7 Audit"; auditctl -s 2>/dev/null | grep -E 'enabled|lost|backlog_limit'; echo "rules: $(auditctl -l 2>/dev/null | wc -l)"
sec "8 journald"; journalctl --disk-usage; echo "boots: $(journalctl --list-boots --no-pager | wc -l)"
sec "9 sysctl"; sysctl kernel.kptr_restrict kernel.dmesg_restrict kernel.yama.ptrace_scope kernel.unprivileged_bpf_disabled \
net.ipv4.conf.all.accept_redirects net.ipv4.conf.all.rp_filter net.ipv4.ip_forward kernel.apparmor_restrict_unprivileged_userns 2>/dev/null
sec "10 Resources"; systemctl show myapp.service -p LimitNOFILE -p MemoryMax -p TasksMax -p CPUQuotaPerSecUSec
sec "11 Monitoring"; ss -tlnpH | awk '{print $4, $6}'
sec "12 Privilege Escalation"; getcap -r /usr/bin /usr/sbin 2>/dev/null; find / -xdev -perm -4000 -type f 2>/dev/null | wc -l | sed 's/^/setuid files: /'
cd ~/linuxlab/hour6 && sudo bash hardening-review.sh | tee review-$(date +%F).txt | head -n 40
===== 1 system ===== Ubuntu 26.04 LTS kernel=7.0.0-15-generic systemd 259 (259.5-1ubuntu1) ===== 2 MAC ===== Yes AppArmor enabled myapp: myapp (enforce) ===== 3 myapp sandbox ===== → Overall exposure level for myapp.service: 2.4 OK 🙂 CapBnd: 0000000000000000 NoNewPrivs: 1 Seccomp: 2 ... ===== 5 SSH ===== permitrootlogin no passwordauthentication no trustedusercakeys /etc/ssh/user_ca.pub authorizedprincipalsfile /etc/ssh/auth_principals/%u revokedkeys /etc/ssh/revoked_keys
How to verify: The script is read-only and can be run on the production host (and more acceptable to the auditor). Common mistakes: Write repair actions into the review script - review and repair should be separated, and repair should go through the change process. Production use: Archive the output as a baseline comparison for the next review (diff requires two results to detect drift).
Experiment 8: Do a complete review of linuxlab (about 10 minutes)
review-.txt . nmap -Pn -p 1-10000 192.168.64.5 ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no labadmin@192.168.64.5 true; echo "exit=$?" ssh root@192.168.64.5 true; echo "exit=$?"
PORT STATE SERVICE 22/tcp open ssh 5000/tcp open upnp Nmap done: 1 IP address (1 host up) scanned in 9.02 seconds labadmin@192.168.64.5: Permission denied (publickey). exit=255 root@192.168.64.5: Permission denied (publickey). exit=255
nmap guesses 5000 as upnp just based on the service name of the port number (the same as the port type of 5000 in SELinux, a historical legacy), which is actually myapp. Filtered ports will not appear in the open list.
sudo systemd-run --wait --pipe -p User=myapp -p NoNewPrivileges=yes -p ProtectHome=yes \ -p ProtectSystem=strict -p PrivateTmp=yes -p CapabilityBoundingSet= \ -p SystemCallFilter=@system-service -p SystemCallFilter=~@privileged -p SystemCallErrorNumber=EPERM \ sh -c 'ls /home 2>&1; touch /etc/x 2>&1; sudo -n true 2>&1; cat /etc/shadow 2>&1; echo done'
ls: cannot open directory '/home': Permission denied touch: cannot touch '/etc/x': Read-only file system sudo: The "no new privileges" flag is set, which prevents sudo from running as root. cat: /etc/shadow: Permission denied done
Four attempts were intercepted by ProtectHome, ProtectSystem, NoNewPrivileges and DAC respectively. The prompt text for sudo may differ between sudo-rs and sudo.ws.
| No. | Discovery | Risk | Recommendation | Responsible Person/Term |
|---|---|---|---|---|
| F-1 | Outbound traffic is not restricted, and any external address can be connected after RCE | Medium | ufw defaults to deny outgoing + release DNS/NTP/APT mirror, or myapp unit IPAddressDeny=any + IPAddressAllow=localhost | labadmin / 2 weeks |
| F-2 | Audit rules are not locked (enabled 1) | Low | Add 99-finalize.rules before going online (-e 2) | labadmin / Before going online |
| F-3 | Ubuntu 26.04 currently has no official USG CIS configuration file | Medium | Replace it with lynis + this list. USG will do a formal audit after supporting 26.04 | Security Team / Tracking |
| Exception | Control | Reason | Compensating Control | Approval/Review |
|---|---|---|---|---|
| E-1 | CIS: Independent /var/log/audit Partition | Experimental VM single disk | Audit log real-time forwarding; space_left_action=email | Security Lead / 90 days |
| E-2 | kernel.yama.ptrace_scope=1 (not 2/3) | Preserve strace troubleshooting capabilities (Lesson 7) | Unable to ptrace without root Other user processes; audit ptrace calls | Security manager / 180 days |
review-*.txt to host archive:multipass transfer linuxlab:/home/labadmin/linuxlab/hour6/review-2026-11-17.txt . (date adjusted to actual file name). Case 1: Pre-launch review found "invisible" management port
Problem: During the review of the new service, ss -tlnp showed a debugging pprof port listening on 0.0.0.0, although the firewall blocks it, other hosts in the same network segment (same security group) can access it. Method: Change the port to only bind 127.0.0.1, add a "listening address" item to the review list; double-layer control of firewall and binding address. Limitations: The review can only discover the current status, and continuous ss baseline comparison can discover later added ports.
Case 2: Exception registration saved an audit
Problem: An external audit found that 30 hosts were non-compliant with a certain CIS item. Method: The team presented the tailoring document and exception registration (reason, compensation control, approver, review date), and the audit accepted it; the other 2 unregistered hosts were listed as findings. Restrictions: Exceptions must have an expiration date. If they are not reviewed after expiration, they will automatically become discovered items.
Case 3: Review of upgrade from 24.04 to 26.04
Issue: The upgrade plan only focuses on application compatibility. Practice: The review lists security-related changes in 26.04 as inspection items: sudo-rs (sudoers compatibility, no I/O logs), rust-coreutils (script output format differences), OpenSSH 10.2 (DSA removal, default post-quantum key exchange), whether USG already supports the new version; each item is verified in the pre-release environment before the upgrade is approved. Limitations: The default components of the release will change, and the baseline and review checklist will be updated with the release.
Interactive troubleshooting tree: Permission denied / The service cannot be started. Which layer is it at?
Start from symptoms and choose step by step. The troubleshooting tree will give diagnostic commands and repair directions.
Common errors and solutions
After hardening, myapp works normally, but the nightly report task fails: Read-only file system: '/opt/myapp/reports'
Reason:The report task runs in the environment of myapp.service (or inherits it) drop-in), ProtectSystem=strict makes /opt read-only.
Fix: Add ReadWritePaths= to the writable directory (or migrate to StateDirectory=), and update the write permission of the AppArmor configuration file; add this path to the review list.
The aa-status in the review script reports "apparmor filesystem is not mounted"
Cause: Running in an environment that does not support AppArmor such as containers or WSL, or the kernel startup parameters disable AppArmor.
cat /sys/kernel/security/lsm; cat /proc/cmdline
Fix: Review on a real VM; check for apparmor=0 or lsm= overrides in GRUB.
systemd-analyze security score improved, but the application occasionally encountered "Operation not permitted"
Cause:SystemCallErrorNumber=EPERM allows filtered system calls to silently return errors (no SECCOMP logs will be generated), which is used by a certain low-frequency path of the application.
sudo strace -f -e trace=all -p $(systemctl show -p MainPID --value myapp) 2>&1 | grep EPERM
Fixed: Temporarily change to SystemCallLog= (supported by newer systemd, only log but not reject) or remove ErrorNumber so that you can see SECCOMP records in the audit log, and add the call to the allow list after locating it.
1. Check that the exposure of a service unit file in CI does not exceed 4 (offline mode, does not need to be loaded into the system).
systemd-analyze security --offline=yes --threshold=4 ./myapp.service
Requires newer systemd (--offline and --threshold available since v250); returns a non-zero exit code when threshold is exceeded.
2. Compare the output of the two reviews to find out the configuration drift.
diff -u review-2026-08-17.txt review-2026-11-17.txt
Management asked: "We already have a cloud security group and WAF, why do we need to do host hardening?" Please answer with the attack path of myapp.
Security groups and WAF only cover the "network entrance" layer: WAF cannot identify all application vulnerabilities (0day, business logic defects, dependent library vulnerabilities). Once myapp is executed, the attack occurs inside the host and cannot be seen by the security group. Host hardening determines "how far you can go after being breached": systemd sandbox and AppArmor prevent attackers from reading data in the home directory and other services, and unable to escalate privileges; seccomp and sysctl reduce the kernel utilization surface; auditd leaves evidence and forwards it in real time; SSH certificate and minimal sudo prevent lateral movement and persistence. The value of defense in depth is that failure of any layer will not lead to total loss, and it can prove what happened afterwards.
Verified teaching video
Official document
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Screen: The myapp host is drawn as a concentric castle: firewall, identity, service sandbox, kernel, evidence.
Narration: The reviewer first asks four questions: what is protected, where does the attack come from, which layer is intercepted, and how to prove it.
Screen: A red attack path enters from port 5000, hits ProtectHome, NoNewPrivileges, seccomp in sequence, and finally stops, with an audit record popping up next to it.
Narration: A good design allows each attack path to encounter at least two independent lines of defense, and leaves evidence every time it is intercepted.
Screen: Check the review list one by one, mark one item as an exception, fill in the reason, compensation control and review date.
Narration: Exceptions are inevitable, but reasons, compensation controls and expiry dates must be registered.
Screen: Git, Packer, Ansible, and scheduled scanning form a closed-loop arrow.
Narration: Finally, write everything into code, apply during build, audit during runtime, and alert when drifting. Reinforcement is not a project, but a closed loop.
Command Cheat Sheet
Layered inventory and baseline
cat /sys/kernel/security/lsm grep -E '^(Cap(Eff|Bnd)|NoNewPrivs|Seccomp):' /proc/PID/status getcap -r /usr/bin /usr/sbin 2>/dev/null find / -xdev -perm -4000 -type f 2>/dev/null systemd-analyze security [UNIT] sudo usg audit cis_level1_server # Ubuntu Pro + usg(20.04/22.04/24.04) sudo usg generate-tailoring cis_level1_server tailor.xml oscap info --profiles /usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml sudo oscap xccdf eval --profile ID --report r.html DS.xml sudo lynis audit system
SELinux(rhellab)
getenforce; sestatus ls -Z PATH; ps -eZ; ss -tlnpZ sudo ausearch -m AVC,USER_AVC -ts recent -i sudo ausearch -m AVC -ts recent | audit2why sudo semanage fcontext -a -t TYPE '/path(/.*)?' && sudo restorecon -Rv /path sudo setsebool -P httpd_can_network_connect on sudo semanage port -l | grep -w 5000 sudo semanage port -m -t http_port_t -p tcp 5000 sudo semanage permissive -a httpd_t # Single domain permissive sudo semodule -DB / -B # Close/restore dontaudit
AppArmor(linuxlab)
sudo aa-status cat /proc/PID/attr/current sudo aa-genprof /opt/myapp/venv/bin/gunicorn sudo aa-logprof sudo aa-complain|aa-enforce /etc/apparmor.d/PROFILE sudo apparmor_parser -r /etc/apparmor.d/PROFILE sudo journalctl -k -g 'apparmor="DENIED"' -b sysctl kernel.apparmor_restrict_unprivileged_userns
Firewall
sudo nft list ruleset sudo nft -c -f /etc/nftables.conf && sudo nft -f /etc/nftables.conf sudo systemd-run --unit=nft-deadman --on-active=5min /usr/sbin/nft flush ruleset sudo firewall-cmd --get-active-zones sudo firewall-cmd --permanent --add-port=5000/tcp && sudo firewall-cmd --reload sudo firewall-cmd --zone=public --list-all sudo ufw default deny incoming; sudo ufw limit 22/tcp; sudo ufw allow 5000/tcp sudo ufw status verbose
PAM/sudo/SSH certificate
grep -vE '^\s*(#|$)' /etc/pam.d/sshd /etc/pam.d/common-auth authselect current; sudo authselect enable-feature with-faillock sudo faillock --user U [--reset] sudo visudo -cf /etc/sudoers.d/FILE; sudo -l -U USER ssh-keygen -s user_ca -I ID -z SERIAL -n PRINCIPAL -V +8h key.pub ssh-keygen -s host_ca -I HOST -h -n host,ip -V +52w ssh_host_ed25519_key.pub ssh-keygen -L -f key-cert.pub ssh-keygen -k -u -f revoked_keys -s user_ca.pub spec sudo sshd -t; sudo sshd -T | grep -i trusted
Audit and log
sudo augenrules --load; sudo auditctl -l; sudo auditctl -s -w /etc/myapp/myapp.env -p wa -k myapp-config -a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root-cmd sudo ausearch -k KEY -ts today -i sudo ausearch -m USER_LOGIN -ua labadmin -i sudo aureport --summary; sudo aureport -k --summary; sudo aureport -au --failed journalctl -u myapp --since -1h; journalctl -t myapp; journalctl -k -b journalctl --disk-usage; journalctl --verify
sysctl and resource limits
sysctl KEY; sudo sysctl -w KEY=VAL sudo sysctl --system systemd-analyze cat-config sysctl.d | grep KEY cat /proc/PID/limits; ulimit -Sn; ulimit -Hn sudo prlimit --pid PID --nofile=S:H systemctl show UNIT -p LimitNOFILE -p MemoryMax -p TasksMax sudo systemctl set-property UNIT MemoryMax=512M sudo systemctl edit UNIT --drop-in=61-limits
namespaces and cgroups
lsns; ls -l /proc/PID/ns/
sudo unshare --fork --pid --mount-proc --uts --net bash
sudo nsenter -t PID -n ss -tanp
stat -fc %T /sys/fs/cgroup; cat /proc/PID/cgroup
systemd-cgls; systemd-cgtop
sudo systemd-run --scope -p MemoryMax=100M -p CPUQuota=20% -p TasksMax=32 CMD
sudo systemd-run --unit=job --wait -p MemoryMax=100M -p MemorySwapMax=0 CMD
cat /sys/fs/cgroup/system.slice/UNIT/{memory.events,cpu.stat,pids.max}Quick troubleshooting table
| Symptoms | What to look at first | Most likely layer | Repair direction |
|---|---|---|---|
| Permission denied, no logs | namei -l PATH | DAC | Owner/Mode/ACL/Directory Add rules |
Permission denied, with type=AVC | ausearch -m AVC | audit2why | SELinux | restorecon / setsebool / semanage port |
Permission denied, with apparmor="DENIED" | journalctl -k -g apparmor | AppArmor | aa-logprof add rules |
| Read-only file system (directory is obviously writable) | systemctl cat UNIT | grep Protect | systemd sandbox | ReadWritePaths= / StateDirectory= |
| status=31/SYS or Operation not permitted | ausearch -m SECCOMP | seccomp | Adjust SystemCallFilter= |
| status=203/EXEC (RHEL system) | ls -Z Executable file | SELinux label | restorecon |
| Port timeout (not refused) | nft list ruleset, packet capture | Firewall | Release/check multiple manager conflicts |
| Too many open files (service) | cat /proc/PID/limits | rlimit | LimitNOFILE=(limits.conf is invalid) |
| Service was killed, result: oom-kill | memory.events | cgroup | Adjust MemoryMax/fix leak |
| SSH: Certificate invalid | ssh-keygen -L, server log | SSH CA | principal / validity period / KRL |
Recommended configuration fragment
[Service] NoNewPrivileges=yes CapabilityBoundingSet= ProtectSystem=strict ProtectHome=yes PrivateTmp=yes PrivateDevices=yes ProtectKernelTunables=yes ProtectKernelModules=yes ProtectControlGroups=yes RestrictNamespaces=yes RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX SystemCallArchitectures=native SystemCallFilter=@system-service SystemCallFilter=~@privileged SystemCallErrorNumber=EPERM
TrustedUserCAKeys /etc/ssh/user_ca.pub AuthorizedPrincipalsFile /etc/ssh/auth_principals/%u RevokedKeys /etc/ssh/revoked_keys PasswordAuthentication no KbdInteractiveAuthentication no PermitRootLogin no MaxAuthTries 3
Comprehensive experiment + final test
Cost: None (local VM). Risk: sshd/firewall/PAM error correction leads to loss of connection - take a snapshot first and retain the console channel.
multipass stop linuxlab && multipass snapshot linuxlab --name before-final && multipass start linuxlab multipass exec linuxlab -- sudo bash /home/labadmin/linuxlab/hour6/hardening-review.sh > review-before.txt
60-sandbox.conf and 61-limits.conf Exists and takes effect
systemctl cat myapp.service | grep -E '^# /etc|NoNewPrivileges|MemoryMax|LimitNOFILE' systemd-analyze security myapp.service | tail -n 1 curl -fsS http://127.0.0.1:5000/healthz
sudo aa-status | grep -A1 'enforce mode' | head; cat /proc/$(systemctl show -p MainPID --value myapp)/attr/current
for p in / /healthz; do curl -fsS -o /dev/null -w "%{http_code} $p\n" http://127.0.0.1:5000$p; done
sudo journalctl -k -g 'apparmor="DENIED"' --since '-10min' --no-pager | grep -c myapp
Expect: myapp (enforce), all 200, DENIED count is 0 (if any, use aa-logprof to handle).
nmap -Pn -p 1-10000 only sees 22 and 5000. printf 'PasswordAuthentication no\nKbdInteractiveAuthentication no\nPermitRootLogin no\nMaxAuthTries 3\n' | sudo tee /etc/ssh/sshd_config.d/42-auth.conf sudo sshd -t && sudo systemctl reload ssh sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin|trustedusercakeys|maxauthtries) ' sudo -l -U opsuser 2>/dev/null | tail -n 2
After successfully logging in with a certificate on another terminal, close the current session. If a drop-in (such as the 50-cloud-init.conf that comes with the cloud image) has PasswordAuthentication yes written in it, because "the first appearing value takes effect", please confirm the final result of sshd -T.
sudo auditctl -l | grep -cE 'myapp-config|root-cmd|identity|sudoers' sudo auditctl -s | grep -E 'enabled|lost' journalctl --list-boots --no-pager | wc -l sudo touch /etc/myapp/myapp.env && sudo ausearch -k myapp-config -ts recent -i | grep -c 'key=myapp-config'
sysctl kernel.kptr_restrict kernel.dmesg_restrict kernel.unprivileged_bpf_disabled \ net.ipv4.conf.all.accept_redirects net.ipv4.conf.all.send_redirects net.ipv4.tcp_syncookies
review-after.txt, diff -u review-before.txt review-after.txt, and fill in the findings and exception registration. Acceptance Checklist
Open-ended self-test (answer first, then expand the reference answers)
1. What security checks does an openat() go through in sequence in the kernel? What will be left behind when rejected by each layer?
Seccomp of system call entry (rejection: EPERM or SIGSYS, kill action record SECCOMP) → DAC in VFS permission check (EACCES, no log by default) → Check CAP_DAC_OVERRIDE/CAP_DAC_READ_SEARCH when DAC is not satisfied (EACCES if incapable; SELinux will also check the capability itself and may generate AVC) → LSM hook(SELinux: type=AVC; AppArmor: apparmor="DENIED"). DAC rejects -F exit=-EACCES rules that require auditd to leave evidence.
2. Why does the program from the home directory mv to /opt cause 203/EXEC on RHEL? What is the correct fix?
mv reserves the SELinux label user_home_t for the inode, which policy does not allow init_t to execute. matchpathcon shows that the correct type should be usr_t, use restorecon -Rv to restore; when a non-default type is required, first semanage fcontext -a. audit2allow should not be allowed, and SELinux should not be turned off.
3. ufw shows that only 22/5000 is allowed. Why is the port published by Docker still accessible from the outside?
Docker publishes the port by doing DNAT in prerouting, and the traffic then enters the container through the forward chain without going through the input rules managed by ufw. You should only bind 127.0.0.1, add rules in the filtering positions reserved by Docker (such as DOCKER-USER), and control at the security group level.
4. What problems does SSH certificate solve compared to authorized_keys? How to protect CA private key?
The short validity period automatically expires, there is no need to distribute/clean public keys on each server, the key ID and serial number are in the log for easy auditing, principals implement role-based authorization, and the host certificate eliminates the fingerprint confirmation (TOFU) of the first connection. The CA private key is the "master key to all servers" and should be taken offline or in an HSM/KMS/Vault, with the user CA separated from the host CA, issuance automated and audited.
5. limits.conf is set to nofile 65536, why is myapp still only 1024?
limits.conf is applied by pam_limits in the PAM session, which only affects login sessions; the systemd service is directly forked by PID 1, without going through PAM, and its limits come from the unit's LimitNOFILE= or DefaultLimitNOFILE= (default soft 1024).
6. What does the "container" spelled out using unshare + chroot + systemd-run lack compared to the Docker container?
Missing: capabilities pruning (we run as root and retain all capabilities), default seccomp configuration, AppArmor/SELinux container configuration, user namespace mapping, real pivot_root and read-only image layer (overlayfs), network (veth + bridge + NAT), minimal device node for /dev, image distribution and lifecycle management. This also shows that "containers" running as root and lacking these layers can easily escape.
End exam (12 questions, covering all modules)
Source and version notes
| Topic | Verification conclusion | Source (Accessed 2026-11-17) |
|---|---|---|
| Ubuntu 26.04 LTS | 2026-04-23 Released; Kernel 7.0, systemd 259, OpenSSH 10.2 (default hybrid post-quantum key exchange mlkem768x25519-sha256, remove DSA); default sudo-rs and rust-coreutils; docker.io 29 uses nftables backend; cgroup mount options add nsdelegate, memory_recursiveprot, etc. | Ubuntu 26.04 release notes · What’s new in security for Ubuntu 26.04 LTS |
| sudo-rs differences | The prompt text is different; I/O logs and sudoreplay are not supported; no sudoers LDAP; supported options are subject to man sudoers-rs, sudo --help; the original sudo can still be used for compatibility and rollback | Ubuntu Server: System utility replacements(sudo-rs) |
| Rocky / Alma | Rocky Linux 10.2 on 2026-05 Released in late (kernel 6.12); AlmaLinux 10.2 released on 2026-05-26 (based on RHEL 10.2, kernel 6.12); RHEL 10 replaces Redis with Valkey | Rocky 10.2 GA · AlmaLinux Blog (10.2 Release Announcement) · RHEL 10 Infrastructure services |
| USG / CIS | USG is available through Ubuntu Pro (pro enable usg + apt install usg); usg audit|fix cis_level1_server, reported in /var/lib/usg/; usg generate-tailoring with --tailoring-file; documentation lists 20.04 (CIS v1.0.0), 22.04 (v2.0.0), 24.04 (v1.0.0), not listed 26.04 | USG · cis-audit · cis-comply · cis-customize |
| OpenSCAP(RHEL 10) | Content file /usr/share/xml/scap/ssg/content/ssg-rhel10-ds.xml; oscap xccdf eval --profile … --report; RHEL 9 content cannot be used to scan RHEL 10; CIS configuration file ID is subject to oscap info output | RHEL 10: Scanning the system for configuration compliance |
| SELinux | Port 5000 default type commplex_main_port_t (semanage port -a reports already defined, required -m); Boolean value, fcontext, audit2why process | RHEL 10: Using SELinux · semanage(8) |
| AppArmor and userns restrictions | Introduced in Ubuntu 23.10, enabled by default from 24.04 kernel.apparmor_restrict_unprivileged_userns; Unprivileged userns process entry unprivileged_userns configuration, capabilities in the namespace are denied | Ubuntu Server: AppArmor · AppArmor wiki: unprivileged userns restriction |
| capabilities / seccomp / LSM | Capability set and DAC coverage; seccomp returns action and SIGSYS; LSM is a restrictive hook | capabilities(7) · seccomp(2) · Linux Security Module docs |
| systemd sandbox and resource control | ProtectSystem, NoNewPrivileges, SystemCallFilter, CapabilityBoundingSet, etc.; systemd-analyze security; LimitNOFILE default 1024:524288; MemoryMax/CPUQuota/TasksMax | systemd.exec(5) · systemd.resource-control(5) · systemd-analyze(1) |
| nftables / firewalld / ufw | inet family, base chain, atomic load; firewalld zone and runtime/permanent; ufw via iptables-nft | nftables wiki · firewalld · Ubuntu: Firewalls |
| PAM/SSH certificate | Control flag semantics; pam_faillock; ssh-keygen certificates and KRLs; RevokedKeys reject all public keys when unreadable; sshd keyword takes effect on first occurrence | pam.conf(5) · ssh-keygen(1) · sshd_config(5) |
| auditd / journald | Rule syntax, auid, -e 2, ausearch/aureport; journald Storage/SystemMaxUse/FSS | audit.rules(7) · ausearch(8) · journald.conf(5) |
| sysctl / namespaces / cgroups | sysctl.d loading and overwriting order; 8 namespaces; cgroup v2 interface file | sysctl.d(5) · namespaces(7) · Control Group v2 |
Video Verification Instructions
The following videos have their titles and channels verified through the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json, 2026-11-17): Red Hat Enterprise Linux "How to Achieve CIS Benchmark Compliance to Harden Linux Systems | Into the Terminal 120" (TVTQcEWMQa0), "System Compliance Testing with OpenSCAP" (KyjMBc0gfjk), "Mastering AuditD: Efficient Logging and Rule Management" (wbwqoQIj_bE), "Don’t Disable SELinux | Into the Terminal 102" (oSTsn-QhM-0), "Hardening RHEL 9 with OpenSCAP and DISA STIG" (wuHeoDcIybY); Red Hat "Stop disabling SELinux | RHEL Field Guide" (PN8lrUOyITc); Red Hat Summit "Security-Enhanced Linux for mere mortals" (_WOKRaM-HI4); CentOS "Gerlof Langeveld - Practical use of Linux" capabilities" (WYC6DHzWzFQ); All Systems Go! "The state of systemd sandboxing in Debian" (ZLTzEjcnbmE); The Linux Foundation "Overview and Recent Developments: AppArmor - John Johansen, Canonical" (3MkU_Z-fClE), "Tutorial: Firewalls with NFtables - John Hawley, VMware" (EGKhIljDPCw); BeginLinux Guru "Demystifying Ubuntu's Uncomplicated Firewall" (YV3aDbQTzrs); Akamai Developers "UFW Full Tutorial | HackerSploit Linux Security" (lt2itMlreQo); TekNeed "Understand How firewalld Zones Work In Linux (RHCSA 8, Lesson) 10B)”(8TR1wywsLvY); linux.conf.au“"Zero Trust SSH" - Jeremy Stott (LCA 2020)”(lYzklWPTbsQ); theurbanpenguin“Understanding PAM, Pluggable Authentication Modules in Linux”(CagsZdJ3ZhA); Learn Linux TV“Linux Crash Course - sudo" (07JOqKOBRnU); Richard Haines "Linux Security Hardening: Auditing/Logging (Auditd)" (m2ytY8kQmd0); SecureRandom "Managing Kernel Parameters with Sysctl" (KZMZN85zYVg); HawkStack Technologies "RHEL Tutorial: Set Kernel Parameters Persistently with sysctl" (UTSfitKo2to); GOTO Conferences "Containers From Scratch • Liz Rice • GOTO 2018" (8fi7uSYlOdc); Docker "Cgroups, namespaces, and beyond: what are containers made from?" (sK5i-N34im8); NDC Conferences "An introduction to control groups (cgroups) version 2 - Michael Kerrisk" (kcnFQgg9ToY), "Containers unplugged: Linux namespaces - Michael Kerrisk" (0kJPa-1FuoI); CIS "Effectively Harden Your Systems with CIS Benchmarks" (kN6ATyzjNGA); Haruna Adoga "Linux Server Hardening - Ep 1: Reducing the Attack Surface (CIS Benchmark)" (xQHweeFyLtQ). oEmbed can only prove that the video exists and the title/channel is consistent. Whether the content covers the new changes in Ubuntu 26.04 / RHEL 10 is subject to the text of this course. Each module comes with a storyboard script that can be generated by a video tool.
Voice explanation instructions
The "Voice" page uses the browser's Web Speech API (speechSynthesis, en-US) to read the explanation script in real time. English terms are pronounced in en-US. The effect depends on the voices installed in the operating system. This courseware generation environment cannot call the TTS service, so there is no embedded MP3; when offline audio is needed, the lecture notes can be generated by any TTS tool.
Known limitations
- All commands in this lesson are not run one by one on the real Ubuntu 26.04 / Rocky 10.2 virtual machine; the "expected output" are examples organized according to the official document and tool format. PID, inode, timestamp, hash, score and count are subject to your environment.
- As of the verification date, Ubuntu's official USG document does not list the CIS configuration file for 26.04. The usg steps in this lesson are based on 24.04, which will be replaced by Lynis and the review list on 26.04. For the CIS Benchmark version number, please refer to the latest instructions on the CIS official website and USG documents.
- The CIS configuration file ID and file name (Rocky/Alma may use its own file name) in the RHEL 10 SCAP content are not verified on the actual machine, and are obtained dynamically using
oscap infoin the command. - The specific support scope of sudo-rs (sudoedit, some Defaults, rejection prompt text) changes with the version. The sudoers example in this lesson deliberately uses only the most basic syntax, and prompts to use
man sudoers-rsto check. - The score of
systemd-analyze security, the content of the configuration file generated by AppArmor, and the field order of SELinux AVC will be slightly different between different versions; the AppArmor configuration file example needs to be adjusted according to the actual results ofaa-logprof(especially the Python version path). - The check order in "Core Animation" takes the file opening path as an example, and is displayed in the actual execution order of the kernel (seccomp is executed first at the system call entry, followed by DAC, capabilities, and LSM). It is different from the common "concentric circle" concept map order, which has been explained in the text.
- The rules, counts and scores in the animation and simulator are schematic and are used to illustrate the mechanism and do not represent all the rules of the real strategy.