OS Security
Linux Security Hardening
Section titled “Linux Security Hardening”SSH Hardening
Section titled “SSH Hardening”SSH is the primary remote administration protocol on Linux. Default configurations are permissive And must be hardened.
Key-based authentication:
ssh-keygen -t ed25519 -C "admin@server" -f ~/.ssh/id_ed25519ssh-copy-id -i ~/.ssh/id_ed25519.pub user@serverEd25519 is preferred over RSA and ECDSA. It is faster, more secure, and has smaller keys. RSA keys Should be at least 4096 bits if used.
sshd_config hardening:
PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesAuthorizedKeysFile .ssh/authorized_keysPermitEmptyPasswords noChallengeResponseAuthentication noUsePAM yesX11Forwarding noMaxAuthTries 3ClientAliveInterval 300ClientAliveCountMax 2AllowUsers admin deployProtocol 2LogLevel VERBOSEKey directives:
- PermitRootLogin no: Prevent direct root login over SSH. Administrators should log in as an unprivileged user and escalate with
sudo. - PasswordAuthentication no: Disable password-based authentication. Require key-based authentication. This eliminates brute-force attacks against passwords.
- MaxAuthTries 3: Limit authentication attempts. Combined with fail2ban, this provides effective brute-force mitigation.
- AllowUsers: Restrict login to specific users. All other users are denied, even if they have valid keys.
- ClientAliveInterval 300 / ClientAliveCountMax 2: Terminate idle sessions after 600 seconds (300 x 2). This prevents abandoned sessions from being hijacked.
Fail2ban
Section titled “Fail2ban”Fail2ban monitors log files for repeated authentication failures and temporarily bans the offending IP addresses using firewall rules (iptables, nftables, or firewalld).
[sshd]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.logmaxretry = 3findtime = 600bantime = 3600- maxretry: Number of failures before banning (3).
- findtime: Time window in seconds (600 = 10 minutes).
- bantime: Duration of the ban in seconds (3600 = 1 hour).
For production servers, consider more aggressive settings: maxretry = 2``bantime = 86400.
File Permissions
Section titled “File Permissions”Linux file permissions control access to files and directories. Every file has three permission Classes: owner (u), group (g), and others (o). Each class has three permissions: read (r), write (w), and execute (x).
| Permission | Octal | File | Directory |
|---|---|---|---|
| r | 4 | Read file contents | List directory entries |
| w | 2 | Modify file | Create/delete/rename entries |
| x | 1 | Execute file | Enter directory (access files by name) |
Common permissions:
- 644: Owner rw, group r, others r (typical for files)
- 755: Owner rwx, group rx, others rx (typical for directories and executables)
- 600: Owner rw, group nothing, others nothing (SSH keys, sensitive config)
- 700: Owner rwx, group nothing, others nothing (private directories)
chmod, chown, umask
Section titled “chmod, chown, umask”chmod 600 /etc/ssh/sshd_configchown root:root /etc/ssh/sshd_configumask 027umask sets the default permissions for newly created files. The umask value is subtracted from the Maximum permissions (666 for files, 777 for directories).
With umask 027:
- New file: (owner rw, group r, others nothing)
- New directory: (owner rwx, group rx, others nothing)
SUID, SGID, and Sticky Bit
Section titled “SUID, SGID, and Sticky Bit”SUID (Set User ID): When set on an executable file, the process runs with the permissions of the File”s owner, not the user who executed it. This is how passwd can modify /etc/shadow — the passwd binary has SUID root.
chmod u+s /path/to/binarychmod 4755 /path/to/binarySUID binaries are a common privilege escalation vector. Every SUID binary on the system should be Audited:
find / -perm -4000 -type f 2>/dev/nullSGID (Set Group ID): When set on a directory, new files inherit the directory’s group rather Than the creator’s primary group. This is used for shared directories.
chmod g+s /path/to/shared-directorySticky bit: When set on a directory, only the file owner, directory owner, or root can delete or Rename files within it. This is used for world-writable directories like /tmp.
chmod +t /tmpchmod 1777 /tmpUser Management
Section titled “User Management”/etc/passwd
Section titled “/etc/passwd”root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinadmin:x:1000:1000:Admin User:/home/admin:/bin/bashFields: username:x:UID:GID:comment:home_dir:shell
The x in the password field means the password hash is stored in /etc/shadow. If the password Field contains anything other than xThe account has a password stored directly in /etc/passwd Which is a security issue (passwd is world-readable).
/etc/shadow
Section titled “/etc/shadow”root:$6$rounds=656000$salt$hash:19000:0:99999:7:::admin:$6$rounds=656000$salt$hash:19000:0:99999:7:::nobody:*:19000:0:99999:7:::Fields: username:hash:last_change:min:max:warn:inactive:expire
- Hash algorithm:
$6$= SHA-512,$5$= SHA-256,$1$= MD5 (insecure),$y$= yescrypt - min: Minimum days between password changes
- max: Maximum days before password must be changed
- warn: Days before expiration to warn the user
- inactive: Days after expiration before account is disabled
- expire: Account expiration date (days since epoch)
Only root can read /etc/shadow. Permissions should be 640.
PAM (Pluggable Authentication Modules)
Section titled “PAM (Pluggable Authentication Modules)”PAM provides a flexible framework for authentication. Configuration files are in /etc/pam.d/.
Key modules:
- pam_unix.so: Standard Unix authentication using
/etc/shadow. - pam_faillock.so: Account lockout after failed authentication attempts.
- pam_faildelay.so: Introduce delay after failed authentication.
- pam_deny.so: Always deny access (used as a fallback).
- pam_permit.so: Always allow access (used for non-authenticated modules).
Account lockout configuration (/etc/security/faillock.conf):
deny = 3unlock_time = 900fail_interval = 900root_unlock_time = 60Service Hardening
Section titled “Service Hardening”Disable unnecessary services to reduce the attack surface:
systemctl disable --now avahi-daemonsystemctl disable --now cupssystemctl disable --now bluetoothsystemctl mask --now rpcbindsystemctl mask prevents the service from being started manually or by another service, even by Root (until unmasked).
Review all enabled services:
systemctl list-unit-files --state=enabledsystemctl list-units --type=service --state=runningSELinux and AppArmor
Section titled “SELinux and AppArmor”Mandatory Access Control (MAC)
Section titled “Mandatory Access Control (MAC)”Discretionary Access Control (DAC) — standard Linux permissions (chmod, chown) — allows the file Owner to set permissions. MAC overrides DAC with system-wide policies that the user cannot modify.
MAC is enforced by the kernel. Even root is subject to MAC policies (unless the policy specifically Exempts root, which it does not).
SELinux
Section titled “SELinux”SELinux (Security-Enhanced Linux) was developed by the NSA and uses a policy-based MAC system. It Assigns a security context (label) to every process, file, port, and other system object. Access is Granted only if the policy explicitly allows the source context to access the target context’s class With the specified permission.
Security context format: user:role:type:level
Example: system_u:system_r:httpd_t:s0
- user: SELinux user identity (system_u, unconfined_u, staff_u, etc.)
- role: Role (system_r, object_r, staff_r, etc.)
- type: Type (the primary identifier for access decisions)
- level: MLS/MCS level (optional, for multi-level security)
Common types:
httpd_t: Apache/Nginx process typehttpd_sys_content_t: Web content filessshd_t: SSH daemon process typevar_log_t: Log filesuser_home_t: User home directory files
SELinux Modes
Section titled “SELinux Modes”| Mode | Behavior |
|---|---|
| Enforcing | Policy is enforced. Violations are blocked and logged. |
| Permissive | Policy is not enforced. Violations are logged but not blocked. Used for testing. |
| Disabled | SELinux is completely disabled. No policy loaded, no logging. |
Check and set mode:
getenforcesestatussetenforce 1setenforce 0Permanent setting in /etc/selinux/config:
SELINUX=enforcingSELINUXTYPE=targetedSELinux Troubleshooting
Section titled “SELinux Troubleshooting”When SELinux blocks an action, it generates an AVC (Access Vector Cache) denial:
ausearch -m avc -ts recentsealert -a /var/log/audit/audit.logCommon remediation strategies:
Relabel the file:
Terminal window restorecon -v /path/to/fileSet the correct context permanently:
Terminal window semanage fcontext -a -t httpd_sys_content_t "/var/www/custom(/.*)?"restorecon -v /var/www/customAllow a specific action with a boolean:
Terminal window setsebool -P httpd_can_network_connect_db 1Write a custom policy module:
Terminal window audit2allow -M my_custom_policysemodule -i my_custom_policy.pp
AppArmor
Section titled “AppArmor”AppArmor is an alternative MAC system used by default on Ubuntu, SUSE, and some other distributions. Unlike SELinux, AppArmor uses path-based policies rather than label-based policies.
Profile example (/etc/apparmor.d/usr.sbin.nginx):
#include <tunables/global>
/usr/sbin/nginx { #include <abstractions/base> #include <abstractions/nameservice>
capability dac_override, capability setuid, capability setgid,
/etc/nginx/** r, /usr/share/nginx/** r, /var/log/nginx/** rw, /var/www/** r,
network inet tcp,}Commands:
aa-statusaa-enforce /etc/apparmor.d/usr.sbin.nginxaa-complain /etc/apparmor.d/usr.sbin.nginxaa-logprofapparmor_parser -r /etc/apparmor.d/usr.sbin.nginxKernel Security
Section titled “Kernel Security”Kernel Modules
Section titled “Kernel Modules”Kernel modules extend kernel functionality at runtime. They run in kernel mode with full privileges. Unauthorized or malicious kernel modules can completely compromise the system.
Hardening:
echo "install usb-storage /bin/true" >> /etc/modprobe.d/disable-usb.confecho "install cramfs /bin/true" >> /etc/modprobe.d/disable-filesystems.conflsmodecho "blacklist floppy" >> /etc/modprobe.d/blacklist.confsysctl Parameters
Section titled “sysctl Parameters”Sysctl configures kernel parameters at runtime. Security-relevant parameters:
net.ipv4.ip_forward = 0net.ipv4.tcp_syncookies = 1net.ipv4.conf.all.accept_source_route = 0net.ipv4.conf.default.accept_source_route = 0net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv6.conf.all.accept_redirects = 0net.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1kernel.dmesg_restrict = 1kernel.kptr_restrict = 2fs.suid_dumpable = 0kernel.unprivileged_bpf_disabled = 1kernel.perf_event_paranoid = 3Persistent configuration in /etc/sysctl.d/99-security.conf:
net.ipv4.ip_forward = 0net.ipv4.tcp_syncookies = 1kernel.dmesg_restrict = 1kernel.kptr_restrict = 2kernel.unprivileged_bpf_disabled = 1Apply with sysctl --system.
Kernel Hardening Boot Parameters
Section titled “Kernel Hardening Boot Parameters”Add to /etc/default/grub (GRUB_CMDLINE_LINUX_DEFAULT):
slab_nomergeinit_on_alloc=1init_on_free=1page_poison=1page_alloc.shuffle=1nosmtUpdate GRUB after modification:
grub-mkconfig -o /boot/grub/grub.cfgPrivilege Escalation
Section titled “Privilege Escalation”Understanding privilege escalation techniques is essential for both attackers and defenders. This Section covers common techniques and their defenses.
SUID Binaries
Section titled “SUID Binaries”If a SUID root binary has a known vulnerability or can be manipulated, an unprivileged user can gain Root access.
Enumeration:
find / -perm -4000 -type f 2>/dev/nullClassic examples:
- find:
find . -exec /bin/sh -p \;(iffindis SUID root) - vim:
:!/bin/sh(if vim is SUID root) - nmap:
nmap --interactivethen!sh(older versions with SUID) - less/more:
!/bin/sh(if less is SUID root)
Defense: Audit all SUID binaries. Remove SUID from binaries that do not require it. Use chmod u-s to remove the SUID bit. Replace SUID binaries with capabilities where possible (e.g., setcap cap_net_raw+ep /usr/bin/ping instead of SUID root on ping).
Misconfigured sudo
Section titled “Misconfigured sudo”Sudo allows users to run commands as root (or another user). Misconfigured sudoers rules are a Common escalation path.
sudo -lDangerous misconfigurations:
sudo vim /etc/shadow— The user can run:!/bin/shfrom vim to get a root shell.sudo less /var/log/auth.log— The user can run!/bin/shfrom less.sudo awk '{print $1}' /etc/shadow— Directly reads the shadow file.sudo envfollowed by manipulation of PATH or LD_PRELOAD.sudo (root) NOPASSWD: /usr/bin/find— Can execute arbitrary commands via find’s -exec.sudo (root) NOPASSWD: ALL— Full root access.
Defense:
- Grant specific commands, not editors or interpreters.
- Use
sudoeditinstead ofsudo vimfor editing files. - Disable command escaping in editors:
Defaults use_pty. - Remove NOPASSWD from all rules unless operationally required.
- Regularly audit sudoers:
visudo -cand review the output.
Cron Jobs
Section titled “Cron Jobs”Cron jobs run on a schedule with the privileges of the owning user. If a cron job executes a script That an unprivileged user can modify, the user can inject arbitrary commands that run with the cron Job’s privileges.
Enumeration:
crontab -lcat /etc/crontabls -la /etc/cron.d/ls -la /var/spool/cron/crontabs/Common issues:
- Writable cron scripts: If
/opt/backup.shis owned by root but group-writable, any group member can modify it and execute code as root. - Wildcards in cron commands:
tar czf /backup/archive.tar.gz *can be exploited with filename trickery (e.g., a file named--checkpoint=1or--use-compress-program=/bin/sh). - PATH hijacking: If the cron job does not use absolute paths and the PATH includes a user-writable directory, an attacker can place a malicious binary in that directory.
Defense:
- Set
chmod 700on all cron scripts. Ensure root-owned scripts are not group- or world-writable. - Use absolute paths for all commands in cron jobs.
- Set
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binin the crontab. - Avoid wildcards or use
--to terminate option parsing.
Kernel Exploits
Section titled “Kernel Exploits”Kernel vulnerabilities allow an unprivileged user to escalate to root by exploiting bugs in the Kernel itself. These are the most dangerous escalation vectors because they bypass all application- Level controls.
Common kernel vulnerability classes:
- Use-after-free: A memory page is freed but a pointer to it remains. An attacker can reallocate the page and control its contents.
- Stack overflow: Buffer overflow on the kernel stack. Modern kernels have stack canaries (
CONFIG_STACKPROTECTOR), but some paths may be unprotected. - Race conditions: Exploiting TOCTOU (Time of Check, Time of Use) between two kernel operations.
- Null pointer dereference: Mapping page 0 and exploiting a kernel null pointer dereference.
- Heap overflow: Overflowing kernel heap allocations (slab/SLUB allocator).
Defense:
- Keep the kernel updated. Apply security patches promptly.
- Enable kernel address space layout randomization (KASLR):
CONFIG_RANDOMIZE_BASE=y. - Enable kernel stack protector:
CONFIG_STACKPROTECTOR=y. - Restrict kernel module loading.
- Use
kernel.unprivileged_bpf_disabled = 1to prevent unprivileged eBPF. - Use
kernel.perf_event_paranoid = 3to restrict perf events.
Path Hijacking
Section titled “Path Hijacking”If a directory in the PATH is writable by the current user, an attacker can place a malicious binary With the same name as a commonly used command in that directory. When the command is executed, the Malicious binary runs instead.
echo $PATHDefense: Ensure system PATH directories (/usr/bin``/bin``/usr/sbin``/sbin) are owned by Root and not writable by non-root users. Never put . (current directory) in PATH.
Shared Library Injection (LD_PRELOAD)
Section titled “Shared Library Injection (LD_PRELOAD)”The LD_PRELOAD environment variable allows a user to load a shared library before all others. A Malicious library can hook function calls and execute arbitrary code with the privileges of the Target process.
# Attacker creates /tmp/evil.c#include <stdio.h>#include <sys/types.h>#include <stdlib.h>
void _init() { if (geteuid() == 0) { system("/bin/bash -p"); }}
# Compile: gcc -fPIC -shared -o /tmp/evil.so /tmp/evil.c -nostartfiles# Use: LD_PRELOAD=/tmp/evil.so sudo some_commandThis only works if sudo preserves the LD_PRELOAD environment variable (it does not by default in Modern sudo versions).
Defense:
- Ensure
env_resetis set in sudoers (default in most distributions). - Ensure
env_keepdoes not includeLD_PRELOAD``LD_LIBRARY_PATHOr similar. - Use
Defaults secure_pathin sudoers to set a fixed PATH.
Logging and Auditing
Section titled “Logging and Auditing”syslog / rsyslog
Section titled “syslog / rsyslog”Syslog is the standard logging daemon on Linux. Rsyslog is the default implementation on most modern Distributions. It receives log messages from applications and the kernel and routes them to files, Remote servers, or other destinations.
Configuration in /etc/rsyslog.conf or /etc/rsyslog.d/:
auth,authpriv.* /var/log/auth.logkern.* /var/log/kern.log*.emerg :omusrmsg:**.*;auth,authpriv.none -/var/log/syslogLog severity levels (from lowest to highest):
| Level | Keyword | Description |
|---|---|---|
| 0 | emerg | System is unusable |
| 1 | alert | Immediate action required |
| 2 | crit | Critical condition |
| 3 | err | Error condition |
| 4 | warning | Warning condition |
| 5 | notice | Normal but significant |
| 6 | info | Informational |
| 7 | debug | Debug messages |
journald
Section titled “journald”Systemd-journald is the log manager for systemd-based systems. It stores logs in a binary format (journal files) and provides structured log entries with metadata.
journalctl -u ssh # Logs for sshd servicejournalctl -f # Follow logs (like tail -f)journalctl --since "1 hour ago"journalctl -p err # Error-level messages onlyjournalctl --disk-usage # Show disk usageJournald can forward to syslog for integration with existing log management infrastructure.
auditd
Section titled “auditd”Auditd provides kernel-level auditing for security events. It goes beyond application logging by Intercepting system calls and recording security-relevant events.
Configuration in /etc/audit/audit.rules:
## Audit file access-w /etc/passwd -p wa -k identity-w /etc/shadow -p wa -k identity-w /etc/sudoers -p wa -k identity-w /etc/ssh/sshd_config -p wa -k ssh_config
## Audit system calls-a always,exit -F arch=b64 -S execve -F auid>=1000 -F auid!=4294967295 -k exec
## Monitor network configuration changes-w /etc/network/ -p wa -k network_changes- -p wa: Watch for writes and attribute changes.
- -k key: Assign a key for filtering.
- -S execve: Watch the execve system call.
View audit logs:
ausearch -k identityaureport -xauditctl -lLog Rotation
Section titled “Log Rotation”Unmanaged log files grow without bound and can fill the disk, causing service outages. Logrotate Manages log rotation, compression, and retention.
Configuration in /etc/logrotate.d/:
/var/log/auth.log { daily missingok rotate 90 compress delaycompress notifempty create 640 root adm postrotate /usr/lib/rsyslog/rsyslog-rotate endscript}Centralized Logging
Section titled “Centralized Logging”In production environments, logs should be forwarded to a centralized log management system:
- ELK Stack: Elasticsearch, Logstash, Kibana
- Splunk: Commercial SIEM with log collection
- Graylog: Open-source log management
- Fluentd / Fluent Bit: Log forwarder and processor
- Vector: High-performance log pipeline by Datadog
Centralized logging provides:
- Correlation of events across multiple systems
- Longer retention than local storage allows
- Real-time alerting on security events
- Protection against log tampering (an attacker who compromises a system cannot erase centralized logs)
Patch Management
Section titled “Patch Management”Update Strategies
Section titled “Update Strategies”| Strategy | Description | Risk | Best For |
|---|---|---|---|
| Rolling updates | Update one node at a time | Lowest | Stateful services, databases |
| Blue-green | Maintain two identical environments | Low | Stateless services |
| Canary | Update a small subset first | Low | Large deployments |
| Big bang | Update everything at once | Highest | Homogeneous, small environments |
Automated Patching
Section titled “Automated Patching”# Debian/Ubuntuapt update && apt upgrade -yapt install unattended-upgradesdpkg-reconfigure -plow unattended-upgrades
# RHEL/CentOSdnf update -ydnf install dnf-automaticsystemctl enable --now dnf-automatic-install.timerUnattended-upgrades configuration (/etc/apt/apt.conf.d/50unattended-upgrades):
Unattended-Upgrade::Allowed-Origins { "${distro_id}:${distro_codename}-security";};Unattended-Upgrade::AutoFixInterruptedDpkg "true";Unattended-Upgrade::Remove-Unused-Dependencies "true";Unattended-Upgrade::Automatic-Reboot "false";Vulnerability Scanning
Section titled “Vulnerability Scanning”Tools that scan systems for known vulnerabilities:
- OpenSCAP: SCAP-based compliance and vulnerability scanning.
- Vuls: Agentless vulnerability scanner for Linux.
- Lynis: Security auditing tool (not a vulnerability scanner per se, but detects misconfigurations).
- Trivy: Container image and filesystem scanner.
File Integrity Monitoring
Section titled “File Integrity Monitoring”AIDE (Advanced Intrusion Detection Environment)
Section titled “AIDE (Advanced Intrusion Detection Environment)”AIDE creates a database of file hashes, permissions, and metadata. It periodically compares the Current state against the database and reports changes.
Configuration (/etc/aide/aide.conf):
/var/log p+im/etc/passwd p+im/etc/shadow p+im/etc/ssh/sshd_config p+im/bin p+im/usr/bin p+imFlags: p (permissions), i (inode), m (mtime), s (size), sha256 (SHA-256 hash), sha512 (SHA-512 hash).
aideinit # Initialize databaseaide --update # Update databaseaide --check # Check for changesaide --compare # Compare with last known stateTripwire
Section titled “Tripwire”Tripwire is a commercial file integrity monitoring tool with similar functionality to AIDE. It uses Two databases: a baseline database (read-only, ideally stored offline or on immutable storage) and a Current database that is updated on each scan.
OSSEC / Wazuh
Section titled “OSSEC / Wazuh”OSSEC (now maintained as Wazuh) provides file integrity monitoring alongside log analysis, rootkit Detection, and active response. It is more feature-rich than AIDE alone and includes a centralized Management architecture.
Process Isolation
Section titled “Process Isolation”Namespaces
Section titled “Namespaces”Linux namespaces provide isolation for system resources. Each namespace type isolates a different Aspect:
| Namespace | Isolates |
|---|---|
| Mount | Filesystem mount points |
| PID | Process IDs |
| Network | Network interfaces, routing, iptables |
| UTS | Hostname and domain name |
| IPC | System V IPC, POSIX message queues |
| User | User and group IDs |
| Cgroup | Cgroup root directory |
Namespaces are the fundamental building block of containers. Docker and Kubernetes use namespaces to Provide process isolation.
cgroups
Section titled “cgroups”Control groups (cgroups) limit and account for resource usage (CPU, memory, I/O, network) for a set Of processes. Cgroups v2 is the current standard.
# Create a cgroup and limit memory to 512 MBmkdir /sys/fs/cgroup/memory/limitedecho 536870912 > /sys/fs/cgroup/memory/limited/memory.max
# Limit CPU to 1 coreecho 100000 > /sys/fs/cgroup/cpu/limited/cpu.maxseccomp
Section titled “seccomp”Seccomp (Secure Computing Mode) restricts the system calls a process can make. There are two modes:
- Strict mode: Allows only
read``write``_exitAndsigreturn. Too restrictive for most applications. - Filter mode (BPF): Allows specifying a whitelist of permitted system calls using BPF programs.
Docker uses a default seccomp profile that blocks about 44 system calls (out of ~330). Custom Profiles can be created for specific applications.
Containers as Isolation
Section titled “Containers as Isolation”Containers provide process isolation through namespaces, cgroups, and seccomp. However, they are not A security boundary. The kernel is shared between all containers on a host, and container escape is Possible.
Container isolation vs VM isolation:
| Property | Containers | VMs |
|---|---|---|
| Kernel | Shared | Separate |
| Isolation | Process-level | Hardware-level |
| Escape difficulty | Moderate (depends on config) | Very difficult |
| Overhead | Low | High |
| Startup time | Seconds | Minutes |
Secure Boot Chain
Section titled “Secure Boot Chain”UEFI Secure Boot
Section titled “UEFI Secure Boot”UEFI Secure Boot ensures that only cryptographically signed bootloaders and kernels can be executed During the boot process. The firmware verifies the signature of each component before executing it:
- UEFI firmware verifies the bootloader (e.g., GRUB, shim)
- The bootloader verifies the kernel
- The kernel verifies loaded modules (if module signing is enabled)
Keys:
- Platform Key (PK): The top-level key. Replaces all other keys if changed.
- Key Exchange Keys (KEK): Used to update the Signature Database and forbid list.
- Signature Database (db): Contains keys and hashes of trusted bootloaders and applications.
- Forbidden Database (dbx): Contains keys and hashes of revoked bootloaders.
Measured Boot
Section titled “Measured Boot”Measured Boot extends Secure Boot by recording (measuring) each component loaded during the boot Process into a Platform Configuration Register (PCR) in the TPM. Unlike Secure Boot, which blocks Unauthorized components, Measured Boot records what was loaded and allows a remote attestation Service to verify that the boot process was clean.
TPM (Trusted Platform Module)
Section titled “TPM (Trusted Platform Module)”The TPM is a hardware chip on the motherboard that provides:
- Secure key storage: Keys stored in the TPM never leave the chip. Operations are performed inside the TPM.
- Platform measurement: PCR values record the state of the system at boot.
- Remote attestation: A remote party can verify the PCR values to confirm the system is in a known-good state.
- Sealing: Data can be encrypted to a specific PCR state. The data is only decryptable if the system boots with the expected components.
# Check TPM statustpm2_getcap properties-fixed
# Seal a secret to the current PCR stateecho "my-secret" | tpm2_encryptdecrypt -c key.ctx -o sealed.dat
# Unseal (only works if PCR values match)tpm2_encryptdecrypt -c key.ctx -i sealed.datWindows Hardening Basics
Section titled “Windows Hardening Basics”Group Policy
Section titled “Group Policy”Group Policy (GPO) is the primary mechanism for managing Windows security settings centrally.
Key security policies:
- Password policy: Minimum length (14+ characters), complexity requirements, maximum age, lockout threshold.
- Account lockout: Lock accounts after 5 failed attempts for 15 minutes.
- User Rights Assignment: Define who can log on locally, who can shut down the system, who can take ownership of files.
- Audit policy: Enable audit for logon events, object access, policy change, privilege use.
- Windows Defender settings: Configure real-time protection, scheduled scans, exclusions.
BitLocker
Section titled “BitLocker”BitLocker provides full-disk encryption for Windows systems. It encrypts the entire volume and uses The TPM to protect the encryption key.
- TPM-only mode: The key is released automatically if the boot measurements are correct.
- TPM + PIN: Requires a PIN in addition to TPM. Protects against physical attacks on a powered- off system.
- TPM + USB key: Requires a USB flash drive in addition to TPM.
Windows Defender
Section titled “Windows Defender”Windows Defender is the built-in antivirus and anti-malware solution. Key features:
- Real-time protection: Monitors files, processes, and network activity for malware.
- Attack Surface Reduction (ASR): Blocks behaviors commonly used by malware (executing from email client, creating processes from Office documents, etc.).
- Exploit Protection: Mitigations against memory corruption vulnerabilities (DEP, ASLR, CFG).
- Network protection: Blocks outbound connections to known malicious domains.
UAC (User Account Control)
Section titled “UAC (User Account Control)”UAC prompts for consent when an administrative action is attempted. Even administrators run with Standard user privileges by default. UAC elevates privileges only when explicitly approved.
UAC settings (from most to least secure):
- Always notify: Prompt for every elevation, including built-in admin accounts.
- Notify only for app changes: Suppress prompts for Windows operations.
- Notify only for app changes (secure desktop disabled): Same as above without dimming the screen.
- Never notify: Effectively disables UAC. Never use this setting.
Common Pitfalls
Section titled “Common Pitfalls”Disabling SELinux
Section titled “Disabling SELinux”Many administrators disable SELinux because “it breaks things.” This removes a critical defense Layer. The correct approach is to run SELinux in permissive mode, diagnose the AVC denials, and Write appropriate policy or fix the file contexts. Most issues are resolved with restorecon or a Boolean.
Root SSH Access
Section titled “Root SSH Access”Allowing direct root login over SSH means that if the root password is compromised (brute force, Credential stuffing, password reuse), the attacker has full system access immediately. Always use Key-based authentication with an unprivileged user and sudo.
Not Monitoring Logs
Section titled “Not Monitoring Logs”Logs are useless if nobody reads them. Centralized logging with automated alerting on high-severity Events (failed logins, privilege escalation, file integrity changes) is essential. A breach Discovered months after the fact from forensic analysis is far more costly than one caught in real Time.
Ignoring Kernel Updates
Section titled “Ignoring Kernel Updates”Kernel vulnerabilities are among the most severe because they bypass all application-level controls. Automated patching with a reboot window is the minimum. For critical systems, use live patching (e.g., Canonical Livepatch, KernelCare) to apply security fixes without rebooting.
Shared Library Path Issues
Section titled “Shared Library Path Issues”Leaving LD_LIBRARY_PATH or LD_PRELOAD in sudoers env_keep allows privilege escalation through Shared library injection. Modern sudo defaults to env_resetBut always verify.
Practice Problems
Section titled “Practice Problems”Problem 1: File Permission Calculation
Section titled “Problem 1: File Permission Calculation”A file has permissions rwxr-xr--. An administrator runs chmod 750 on the file. What are the new Permissions, and which octal value represents the original permissions?
Answer
Original permissions rwxr-xr--:
- Owner: rwx = 4 + 2 + 1 = 7
- Group: r-x = 4 + 0 + 1 = 5
- Others: r— = 4 + 0 + 0 = 4
Original octal: 754
After chmod 750:
- Owner: rwx = 7
- Group: r-x = 5
- Others: --- = 0
New permissions: 750 (rwxr-x---)
The change removes read permission from others.
Problem 2: umask Calculation
Section titled “Problem 2: umask Calculation”A system has umask 077. What are the default permissions for:
A) A newly created file b) A newly created directory
Answer
A) File: — but this is wrong because execute bits are never set by default on File creation. The correct calculation masks off execute bits:
(rw-------)
B) Directory: (rwx------)
Both give owner-only access. This is a paranoid but secure default for multi-user systems.
Problem 3: SELinux Troubleshooting
Section titled “Problem 3: SELinux Troubleshooting”An Apache web server returns 403 Forbidden for files in /var/www/html/app/. The file permissions Are correct (644, owned by apache:apache). ls -Z shows:
-rw-r--r--. apache apache unconfined_u:object_r:default_t:s0 index.htmlWhat is the problem, and how do you fix it?
Answer
The SELinux context is default_tWhich Apache (running as httpd_t) is not allowed to read. Web Content should have the httpd_sys_content_t context.
Fix:
semanage fcontext -a -t httpd_sys_content_t "/var/www/html/app(/.*)?"restorecon -Rv /var/www/html/app/After the fix, ls -Z should show:
-rw-r--r--. apache apache unconfined_u:object_r:httpd_sys_content_t:s0 index.htmlIf the application needs to write to the directory, you may also need:
setsebool -P httpd_unified onOr give the directory the httpd_sys_rw_content_t context.
Problem 4: Privilege Escalation Analysis
Section titled “Problem 4: Privilege Escalation Analysis”An attacker has access to a low-privilege shell. They run sudo -l and see:
User deploy may run the following commands on webserver: (root) NOPASSWD: /usr/bin/tarHow can the attacker escalate to root?
Answer
The attacker can exploit the tar command with filename trickery. They create files with names that tar interprets as options:
# Create a malicious file in /tmpcd /tmpecho "/bin/bash -p" > shell.shchmod +x shell.shtouch -- "--use-compress-program=shell.sh"touch archive.tar
# Create a tar archive that triggers the exploitsudo tar cf archive.tar --use-compress-program=shell.sh *When tar processes the filename --use-compress-program=shell.shIt treats it as an option and Executes shell.sh as the compression program, which runs /bin/bash -p as root.
Defense: Never allow sudo access to tar``cp``find``vim``less``awkOr any Interactive/editor command. If archiving is needed, create a wrapper script that validates inputs And only allows operations on specific paths.
Problem 5: Audit Rule Interpretation
Section titled “Problem 5: Audit Rule Interpretation”An auditd rule is configured as:
-a always,exit -F arch=b64 -S open,openat -F dir=/etc -F auid>=1000 -F auid!=4294967295 -k etc_accessWhat does this rule do? Why is auid!=4294967295 included?
Answer
This rule audits the open and openat system calls on 64-bit systems when the target path is Under /etc and the triggering user has a UID of 1000 or higher (regular users, not system Accounts). The key etc_access allows filtering audit logs for this specific rule.
auid!=4294967295 excludes the “unset” login UID (4294967295 = Which is the value of -1 as an unsigned 32-bit integer). When a process is started by the system (not through a user Login), its audit UID is unset. Excluding this prevents the rule from triggering for system Processes that happen to access files in /etcReducing noise in the audit logs.
Problem 6: Kernel Parameter Verification
Section titled “Problem 6: Kernel Parameter Verification”A server has the following sysctl settings:
net.ipv4.ip_forward = 1net.ipv4.conf.all.accept_redirects = 1net.ipv4.conf.all.rp_filter = 0kernel.dmesg_restrict = 0Identify the security issues and provide the corrected values.
Answer
net.ipv4.ip_forward = 1: IP forwarding is enabled. If this server is not a router, this allows it to forward packets between interfaces, potentially creating a routing path for attackers. Fix:net.ipv4.ip_forward = 0(unless the server is intentionally a router).net.ipv4.conf.all.accept_redirects = 1: The server accepts ICMP redirects, which can be spoofed to redirect traffic through an attacker’s machine (MITM). Fix:net.ipv4.conf.all.accept_redirects = 0.net.ipv4.conf.all.rp_filter = 0: Reverse path filtering is disabled. This allows spoofed source IP addresses in incoming packets, facilitating DDoS reflection attacks. Fix:net.ipv4.conf.all.rp_filter = 1.kernel.dmesg_restrict = 0: Any user can read the kernel ring buffer viadmesgWhich may contain sensitive information (kernel addresses, module loading, error messages). Fix:kernel.dmesg_restrict = 1.
Summary
Section titled “Summary”This topic covers the essential concepts and techniques related to os security, including key principles and practical applications.
Key concepts include:
- core concepts and definitions
- key principles and frameworks
- practical applications
- common techniques and methods
- evaluation and critical analysis
A thorough understanding of these concepts, combined with regular practice and review, is essential for mastery of this topic.
Worked Examples
Section titled “Worked Examples”Worked examples demonstrating the application of key concepts are covered in the detailed sub-pages linked above.