PAM ยท LDAP ยท Kerberos ยท Firewalls ยท SELinux ยท AppArmor ยท Cryptography ยท OS Hardening
Security in Linux is built in layers โ no single control is sufficient. The standard stack:
DAC (Discretionary Access Control) โ Standard Linux rwx permissions. The file owner controls access. Users can grant or restrict access at their discretion.
MAC (Mandatory Access Control) โ SELinux and AppArmor. Policy-controlled by the system/administrator, not by individual owners. Even root is constrained by MAC policy labels and profiles.
No single security control is sufficient. The principle of Defense in Depth requires layering multiple independent controls:
If one layer fails, others contain the damage.
Version 8 (XK0-006) significantly expanded the security domain. Key additions and expansions:
PAM provides a flexible framework for authentication on Linux. Configuration files live in /etc/pam.d/ (one file per service, e.g., /etc/pam.d/sshd).
Four module types:
Control flags determine how module success/failure affects the stack:
pam_pwquality โ Password complexity (min length, complexity rules)pam_faillock โ Account lockout after N failed attemptspam_unix โ Standard Unix auth (shadow passwords)pam_google_authenticator โ TOTP-based MFApam_u2f โ Hardware token (YubiKey) authpam_ldap โ LDAP authenticationpam_krb5 โ Kerberos authenticationTOTP (Time-based One-Time Password) โ generates 6-digit codes that expire every 30 seconds.
pam_google_authenticator module/etc/pam.d/sshdChallengeResponseAuthentication yes in sshd_configpam_u2f โ hardware tokens (YubiKey, FIDO2)LDAP provides centralized user authentication across multiple Linux systems. Instead of local /etc/passwd accounts, users authenticate against a central directory server.
ldap:// โ unencrypted (port 389)ldaps:// โ encrypted TLS (port 636)/etc/ldap.conf or via SSSDSSSD is the modern way to connect Linux to LDAP (and Kerberos/AD). It provides caching for offline authentication.
/etc/sssd/sssd.confgetent passwd usernamesystemctl restart sssdTicket-based authentication โ passwords are never sent over the network after initial login. Uses symmetric key cryptography.
kinit/etc/krb5.confkinit username โ authenticate and obtain TGTklist โ display current tickets and expiry timeskdestroy โ remove all tickets (logout)klist -l โ list credential cacheskinit -r 7d username โ renewable ticket for 7 daysTicket flow: kinit โ KDC issues TGT โ present TGT to get service ticket โ access service. No password re-entry needed during ticket lifetime.
| Tool | Type | Use Case | Key Commands |
|---|---|---|---|
| iptables | Legacy (kernel netfilter) | RHEL 7 and earlier, scripting | iptables -L, iptables -A INPUT -p tcp --dport 22 -j ACCEPT |
| nftables | Modern replacement for iptables | RHEL 8+, Debian 10+, new deployments | nft list ruleset, nft add rule ip filter input tcp dport 22 accept |
| UFW | iptables frontend (simple) | Ubuntu/Debian, simpler syntax | ufw allow 22/tcp, ufw enable, ufw status |
| firewalld | Dynamic zones, iptables/nftables backend | RHEL/CentOS/Fedora default | firewall-cmd --zone=public --add-port=80/tcp --permanent |
| Zone | Behavior |
|---|---|
| trusted | All connections accepted โ fully trusted network |
| home / work / internal | Selected connections accepted โ semi-trusted |
| public | Default zone โ only explicitly selected services accepted |
| dmz | Limited inbound accepted โ demilitarized zone |
| block | Inbound connections rejected (ICMP reply sent) |
| drop | Inbound dropped without response โ stealth mode |
Check: getenforce
Temp change: setenforce 0 (permissive) or setenforce 1 (enforcing)
Permanent: edit /etc/selinux/config โ SELINUX=enforcing (requires reboot)
Every file, process, and port has a security context label.
ls -Z /file โ show file contextps -eZ โ show process contextuser:role:type:levelhttpd_sys_content_t for web contentchcon -t httpd_sys_content_t /var/www/myapp/ โ temporary context change (overridden by relabeling)restorecon -Rv /var/www/ โ restore to policy default; use after mv/cpsemanage fcontext -a -t httpd_sys_content_t '/custom(/.*)?' โ create permanent policy rulesemanage fcontext, always run restorecon to applyausearch -m avc -ts recent โ find recent AVC denial messagesaudit2allow -a โ analyze audit log and suggest policy rulessealert โ human-readable explanations of denials/var/log/audit/audit.logavc: denied entries to identify blocked actionsaa-status โ show all loaded profiles and modesaa-enforce /path/to/profile โ set profile to enforcing modeaa-complain /path/to/profile โ log-only / permissive modeaa-disable profile โ disable profile/etc/apparmor.d/apparmor_parser -r /etc/apparmor.d/profileConfig file: /etc/ssh/sshd_config
PermitRootLogin no โ block direct root SSHPasswordAuthentication no โ key-based auth onlyAllowUsers alice bob โ whitelist specific usersPort 2222 โ non-default portClientAliveInterval 300 โ disconnect idle sessionsMaxAuthTries 3 โ limit auth attemptsProtocol 2 โ SSHv2 onlyApply changes: systemctl reload sshd
NOPASSWD โ allow specific commands without passwordCmnd_Alias โ group related commands!command โ explicitly deny specific commandExample sudoers rule (restrict to one command):
alice ALL=(ALL) /usr/bin/systemctl restart nginx
Edit safely with visudo โ validates syntax before saving.
chage -M 90 alice โ max days before password expireschage -m 7 alice โ min days before password can changechage -W 14 alice โ warn days before expirychage -l alice โ list current settingsSystem-wide defaults in /etc/login.defs:
PASS_MAX_DAYS, PASS_MIN_DAYS, PASS_WARN_AGE
usermod -s /sbin/nologin alice โ prevent interactive login; used for service accountsusermod -s /bin/false alice โ same effect (no shell)/etc/shells โ lists valid login shellspasswd -l), nologin still allows PAM/sudogpg --gen-key โ generate key pairgpg --export -a "alice" > alice.pub โ export public keygpg --import alice.pub โ import a public keygpg --encrypt -r alice file โ encrypt for alicegpg --decrypt file.gpg โ decryptgpg --sign file โ sign a filegpg --verify file.sig โ verify signaturegpg --list-keys โ list keyringsha256sum file โ generate SHA-256 hashsha256sum -c checksums.txt โ verify from checksum filemd5sum โ legacy; avoid for security purposesFile integrity baseline workflow:
sha256sum /bin/bash > hash.txt (save baseline)
sha256sum -c hash.txt (verify later โ "OK" = no tampering)
openssl genrsa -out key.pem 2048 โ generate RSA keyopenssl req -new -key key.pem -out csr.pem โ generate CSRopenssl x509 -req -in csr.pem -signkey key.pem -out cert.pem โ self-signopenssl s_client -connect host:443 โ test TLS connectionopenssl x509 -in cert.pem -text โ inspect certificate detailsgpg --symmetric file โ symmetric encryption with passphrase โ file.gpgopenssl enc -aes-256-cbc -in file -out file.enc โ encrypt with AES-256openssl enc -d -aes-256-cbc -in file.enc -out file โ decryptGPG asymmetric = encrypt with recipient's public key, decrypt with their private key. Symmetric = same passphrase to encrypt and decrypt.
Linux auditing daemon for tracking system activity and file access.
/etc/audit/audit.rulesauditctl -w /etc/passwd -p wa -k passwd_changes โ watch file for write/attribute changesausearch -k passwd_changes โ search logs by keyaureport --summary โ summary report/var/log/audit/audit.logFile integrity monitoring tool. Detects unauthorized file changes.
aide --init โ create initial database baselineaide --check โ compare current system to database/etc/aide.conflynis audit systemrkhunter --checkQ1. SELinux is blocking a web server from serving files from a new custom directory /srv/webapp. The audit log shows AVC denials. Which command FIRST restores the correct SELinux context based on the current policy?
Q2. An admin wants to ensure that new firewall rules on a firewalld system survive a reboot. Which flag must be added to firewall-cmd commands?
Q3. In PAM configuration, which control flag causes immediate failure if the module fails, without executing any subsequent modules in the stack?
Q4. An admin needs to prevent the root account from logging in directly via SSH. Which line in /etc/ssh/sshd_config achieves this?
Q5. A sysadmin wants to verify the SHA-256 hash of a downloaded ISO file against a provided checksum. Which command performs this verification?
Q6. Which command temporarily switches SELinux from enforcing to permissive mode WITHOUT requiring a system reboot?
Q7. An AppArmor profile for nginx needs to be loaded in log-only mode (complain mode) for testing without blocking any actions. Which command achieves this?
Q8. In Kerberos authentication, what is the purpose of the TGT (Ticket Granting Ticket)?
Q9. A service account svc_backup should be able to log in and run processes but should not be able to open an interactive login shell. Which command configures this correctly?
Q10. Which tool creates an initial baseline of file checksums and system state for Linux intrusion detection, and can later compare the current system against that baseline?
Enforcing: denies AND logs violations (production). Permissive: only logs, no blocking (safe testing). Disabled: completely off. Check mode: getenforce. Temp change: setenforce 0 (permissive) or setenforce 1. Permanent: /etc/selinux/config (reboot required).
UFW: simple syntax, Ubuntu/Debian default. firewalld: dynamic zones, RHEL/Fedora default. iptables: legacy, still functional. nftables: modern replacement for iptables on RHEL 8+. Critical: always use --permanent with firewall-cmd then --reload.
kinit authenticates to KDC and obtains a TGT. Present TGT to get service-specific tickets. No password sent after initial kinit. klist displays all current tickets and their expiry. kdestroy removes all tickets (logout equivalent).
PermitRootLogin no. PasswordAuthentication no. AllowUsers alice bob. Port 2222. All settings live in /etc/ssh/sshd_config. Always run systemctl reload sshd after changes โ reload, not restart (keeps existing connections alive).
restorecon -Rv /dir restores context to what the SELinux policy says it SHOULD be. chcon -t type /file manually sets context โ overridden by relabeling or restorecon. For permanent rules: use semanage fcontext to define the rule, then restorecon to apply it.
auditctl -w /etc/passwd -p wa -k passwd_watch. -p flags: r=read, w=write, x=execute, a=attribute change. Search by key: ausearch -k passwd_watch. Summary view: aureport --summary. Logs in /var/log/audit/audit.log.
setenforce 0 (permissive) or setenforce 1 (enforcing) โ survives until reboot./etc/selinux/config โ SELINUX=enforcing / permissive / disabled โ requires reboot.
firewall-cmd --zone=public --add-port=443/tcp --permanentfirewall-cmd --reload--permanent: rule is lost on reload or reboot.firewall-cmd --list-allfirewall-cmd --zone=public --remove-port=443/tcp --permanent
auth (who are you?), account (are you allowed?), password (change password), session (setup/teardown).required โ fail counts, stack continuesrequisite โ fail = immediate stopsufficient โ success = skip restoptional โ result mostly ignored
gpg --encrypt -r alice@example.com file.txt โ file.txt.gpggpg --decrypt file.txt.gpg > file.txtgpg --sign file.txtgpg --verify file.txt.siggpg --import alice.pubgpg --list-keys
semanage fcontext -a -t httpd_sys_content_t '/srv/webapp(/.*)?' โ add permanent policy rule.restorecon -Rv /srv/webapp โ apply the rule.ls -Z /srv/webappchcon is temporary โ lost on relabeling. restorecon alone only works if policy rule already exists.
PermitRootLogin no โ no direct root SSHPasswordAuthentication no โ key-based auth onlyAllowUsers alice bob โ whitelist specific usersPort 2222 โ non-default portMaxAuthTries 3 โ limit auth attemptssystemctl reload sshd (reload, not restart โ keeps existing connections alive)
nft list ruleset โ show all rulesnft add rule ip filter input tcp dport 22 acceptaide --initcp /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gzaide --check โ compare to baselinegetenforce, setenforce). Learn SSH hardening โ specifically PermitRootLogin no and PasswordAuthentication no. Understand the difference between iptables, UFW, and firewalld at a high level before diving into syntax.
required vs requisite. Learn firewalld zones and the critical --permanent flag requirement. Understand the difference between restorecon and chcon for SELinux contexts, and when each is appropriate.
klist, kdestroy), GPG encryption and signing workflows, auditd watch rules (-w -p -k syntax), AIDE baseline creation and verification, and semanage fcontext for creating permanent SELinux context rules followed by restorecon.
setenforce 0=permissive; restorecon=restore to policy default; firewall-cmd --permanent is required for persistence; PAM requisite=immediate fail; SSH PermitRootLogin no; nftables=modern iptables replacement (RHEL 8+); /sbin/nologin=no interactive shell for service accounts.
setenforce 0; restorecon -Rv=restore context; chcon=temp.--permanent + --reload.ufw allow 22/tcp + ufw enable.PermitRootLogin no / PasswordAuthentication no.--encrypt -r / --decrypt.-w -p -k syntax; ausearch -k.--init then --check.kinit / klist / kdestroy.