HTB Academy - Linux Security
HTB Academy - Linux Security: Harden a Linux host quickly and safely by applying high‑impact controls: timely patching, host firewalling, MAC (SELinux/AppArmor), account & password policy, logging/time sync, and surface‑area reduction (services, SUID/SGID). This guide keeps the original intent of your notes but expands them into a repeatable checklist with copy‑paste commands. • HTB Academy • suid, sgid
🎯 Objective
Harden a Linux host quickly and safely by applying high‑impact controls: timely patching, host firewalling, MAC (SELinux/AppArmor), account & password policy, logging/time sync, and surface‑area reduction (services, SUID/SGID). This guide keeps the original intent of your notes but expands them into a repeatable checklist with copy‑paste commands.
⚡ TL;DR — High‑Impact Checklist
| Area | What to do | Why it matters |
|---|---|---|
| Patching | apt update && apt full-upgrade (Debian/Ubuntu) / dnf upgrade (RHEL/Fedora) | Fixes known vulns fast |
| Firewall | Default‑deny inbound, allow only required ports (e.g., SSH 22, HTTP/HTTPS) | Shrinks attack surface |
| MAC | Enable SELinux (Enforcing) or tune AppArmor profiles | Contain process compromise |
| Accounts | Unique users, strong passwords, aging, lockout after N failures, sudo least privilege | Limits lateral movement |
| Logging & Time | Ensure rsyslog/journald + logrotate + NTP (timesyncd/chrony) | Forensics & correlation |
| Services | Remove/disable unnecessary packages & services | Reduce exposed code |
| SUID/SGID | Audit and remove risky SUID/SGID, prefer capabilities | Kill common privilege-escalation paths |
| Integrity/Threat detect | Lynis, AIDE, rkhunter/chkrootkit, Snort/Suricata | Find misconfig & tampering |
1) Patch Management
Keeping the OS and packages updated is the #1 defensive control.
Debian/Ubuntu
sudo apt update && sudo apt full-upgrade -y # (aka dist-upgrade)
sudo apt autoremove --purge -y # clean unusedNote:
apt full-upgrade(newer) ≈apt dist-upgrade(older).
RHEL/CentOS/Alma/Rocky
sudo dnf upgrade -y
sudo dnf autoremove -ySchedule automatic security updates (Debian/Ubuntu)
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades2) Host Firewalling (nftables/ufw/firewalld/iptables)
If network firewalls aren’t strict, enforce host‑level policy.
Quick policy with UFW (Ubuntu/Debian)
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp # SSH
# sudo ufw allow 80/tcp # HTTP (if needed)
# sudo ufw allow 443/tcp # HTTPS (if needed)
sudo ufw enable
sudo ufw status verbosefirewalld (RHEL/Fedora)
sudo dnf install -y firewalld
sudo systemctl enable --now firewalld
sudo firewall-cmd --set-default-zone=public
sudo firewall-cmd --permanent --add-service=ssh
# sudo firewall-cmd --permanent --add-service=http
# sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reloadPrefer nftables where possible; iptables is legacy on many distros though still present. For raw nftables use
nft list rulesetandnft add rule ....
3) Mandatory Access Control (SELinux or AppArmor)
Kernel security modules enforce policy between labeled processes/objects.
SELinux (RHEL/Fedora/CentOS/Alma/Rocky)
- Each process, file, dir, and object has a label.
- Rules (policy) constrain which domains can access which types.
Status & Modes
getenforce # Enforcing | Permissive | Disabled
sestatusEnable Enforcing (requires reboot if changing from disabled)
# /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targetedsudo setenforce 1 # switch to enforcing at runtime (if supported)Common ops
sudo seinfo -t httpd_t -x 2>/dev/null || true # needs setools-console
# manage file contexts
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?"
sudo restorecon -Rv /srv/www
# toggle booleans (feature switches)
sudo getsebool -a | grep httpd
sudo setsebool -P httpd_can_network_connect onAppArmor (Ubuntu/Debian)
sudo aa-status
sudo aa-enforce /etc/apparmor.d/* # enforce loaded profiles
sudo aa-complain /etc/apparmor.d/abstractions/* # tune in complain modeProfiles live in /etc/apparmor.d/. Use aa-logprof to iteratively build rules.
4) Accounts, Passwords & SSH
Principles: each user has a unique account; least‑privilege sudo; strong secrets; aging; lockouts.
Ensure unique users and sane defaults
# list local users (with shells)
awk -F: '$7 ~ /(bash|zsh|fish|sh)$/ {print $1 ":" $7}' /etc/passwd
# new user example (no sudo by default)
sudo adduser alice
# grant limited admin (create a bounded sudoers drop-in if needed)
echo 'alice ALL=(ALL:ALL) /usr/bin/systemctl restart myapp' | sudo tee /etc/sudoers.d/alice-myapp
sudo visudo -cf /etc/sudoers.d/alice-myapp # validate syntaxPassword policy (PAM)
Complexity (pwquality) — Debian/Ubuntu:
sudo apt install -y libpam-pwquality
sudoedit /etc/security/pwquality.conf
# Recommended baseline
# minlen = 14
# dcredit = -1
# ucredit = -1
# lcredit = -1
# ocredit = -1
# maxrepeat = 3
# dictcheck = 1Aging & history
# default for new users
sudo sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS 365/' /etc/login.defs
sudo sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS 1/' /etc/login.defs
sudo sed -i 's/^PASS_WARN_AGE.*/PASS_WARN_AGE 14/' /etc/login.defs
# per-user example
sudo chage -M 365 -m 1 -W 14 aliceLockout after N failures (pam_faillock on modern distros)
# RHEL9+/Fedora, Debian 12+ typically have pam_faillock
sudo authselect enable-feature with-faillock 2>/dev/null || true
# Or edit /etc/pam.d/system-auth and password-auth (RHEL) or common-auth (Debian):
# auth required pam_faillock.so preauth silent deny=5 unlock_time=900
# auth [default=die] pam_faillock.so authfail deny=5 unlock_time=900
# account required pam_faillock.soSSH hardening
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F)
sudo tee -a /etc/ssh/sshd_config >/dev/null <<'EOF'
# --- Hardening ---
Protocol 2
PermitRootLogin no
PasswordAuthentication no # consider key-only if feasible
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers alice # limit if practical
EOF
sudo systemctl restart sshdConsider MFA via PAM (e.g.,
libpam-google-authenticatororpam_oath) for privileged access.
5) Logging & Time Sync
Consistent time + logs = reliable evidence.
# journald + rsyslog present on most systems
systemctl is-enabled rsyslog 2>/dev/null || echo "rsyslog not installed"
sudo journalctl --disk-usage
sudo journalctl -p warning -xn
# log rotation
sudo ls /etc/logrotate.d/
# NTP
timedatectl status
sudo timedatectl set-ntp true # systemd-timesyncd
# or install chrony for servers
# Debian/Ubuntu: sudo apt install -y chrony
# RHEL/Fedora: sudo dnf install -y chrony ; sudo systemctl enable --now chronyd6) Threat Detection & Integrity
- Lynis — config audit & best-practice checks
sudo apt install -y lynis || sudo dnf install -y lynis sudo lynis audit system - AIDE — filesystem integrity baseline
sudo apt install -y aide || sudo dnf install -y aide sudo aideinit sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz sudo aide --check - rkhunter/chkrootkit — quick malware heuristics (signal only)
sudo apt install -y rkhunter chkrootkit || true sudo rkhunter --propupd sudo rkhunter --check --sk sudo chkrootkit - Snort/Suricata — NIDS for traffic visibility (optional on endpoints).
7) Remove/Disable Unnecessary Services
# list enabled units
systemctl list-unit-files --type=service | grep enabled
# stop + disable what you do not need
sudo systemctl disable --now cups.service avahi-daemon.service || true
# enumerate listening sockets
ss -tulpen8) SUID/SGID Audit & Linux Capabilities
Unnecessary SUID/SGID binaries are frequent privilege‑escalation vectors.
# enumerate SUID/SGID
sudo find / -xdev -type f \( -perm -4000 -o -perm -2000 \) -print 2>/dev/null
# remove SUID bit when not required
sudo chmod u-s /path/to/binary
# prefer capabilities over SUID when you must grant specific privileges
sudo getcap -r / 2>/dev/null | sort
sudo setcap cap_net_bind_service=+ep /usr/sbin/mydaemon # example9) Validation — Quick Health Checks
# Patching
/usr/bin/env bash -c 'if command -v apt >/dev/null; then apt -s upgrade | grep -q "0 upgraded" || echo "Upgrades pending"; fi'
# Firewall
sudo ufw status 2>/dev/null || sudo firewall-cmd --list-all 2>/dev/null || echo "Check nftables/iptables"
# MAC
(command -v getenforce >/dev/null && getenforce) || (command -v aa-status >/dev/null && aa-status) || echo "No MAC module active?"
# Accounts
sudo awk -F: '$7 ~ /(bash|zsh|fish|sh)$/ {print $1}' /etc/passwd | wc -l
sudo grep -E "^[^#].*pam_faillock" -r /etc/pam.d/ 2>/dev/null || echo "No faillock?"
# Logging/Time
timedatectl status | sed -n '1,6p'
journalctl -p err -n 5 --no-pager10) Complementary Tools
- Snort – Network IDS/IPS: https://www.snort.org/
- chkrootkit – Rootkit indicators: http://www.chkrootkit.org/
- rkhunter – Rootkit hunter: https://packages.debian.org/sid/rkhunter
- Lynis – Security auditing: https://cisofy.com/lynis/
Appendix A — Quick Reference (What you originally listed)
- Keep OS & packages up to date:
apt update && apt dist-upgrade(orapt full-upgrade) - Use Linux firewall (ufw, firewalld, nftables) and/or
iptablesto restrict traffic. - SELinux/AppArmor for granular access control policies: labels + kernel‑enforced rules.
- Recommended security utilities: Snort, chkrootkit, rkhunter, Lynis.
- Baseline system settings:
- Remove/disable unnecessary services/software
- Remove services using unencrypted auth
- Ensure NTP enabled and syslog/journald active
- Each user must have their own account
- Enforce strong passwords & aging; restrict re‑use
- Lock accounts after repeated login failures
- Disable unwanted SUID/SGID binaries
References
- CIS Controls v8: https://www.cisecurity.org/controls/cis-controls-list
- CIS Benchmarks (Linux): https://www.cisecurity.org/benchmark/ubuntu_linux
- Red Hat SELinux Guide: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/using_selinux
- Ubuntu AppArmor: https://ubuntu.com/server/docs/security-apparmor
- Debian Security Manual: https://www.debian.org/doc/manuals/securing-debian-howto/