> ## Documentation Index
> Fetch the complete documentation index at: https://journal.daudaldi.my.id/llms.txt
> Use this file to discover all available pages before exploring further.

# Linux

# Linux Hardening

Linux is everywhere - web servers, cloud infrastructure, containers, embedded devices, developer workstations. And because it's so prevalent, it's also a top target. The good news is that Linux gives you a lot of control over your security posture. The bad news is that control only helps if you actually use it.

This page covers the practical hardening steps you should apply to any Linux system, whether it's a production server, a cloud VM, or a dev box handling sensitive work.

## Where to Start - The CIS Benchmark

Before doing anything manual, grab the **CIS Benchmark for your distribution**. CIS maintains specific benchmarks for:

* Ubuntu (LTS versions)
* Red Hat Enterprise Linux / CentOS / AlmaLinux
* Debian
* SUSE Linux Enterprise
* Amazon Linux

These are free to download at [cisecurity.org/cis-benchmarks](https://www.cisecurity.org/cis-benchmarks/). They tell you exactly what to configure and why. Use them as your checklist.

For a quick automated audit, run **Lynis**:

```bash theme={null}
# Install and run Lynis
sudo apt install lynis   # or dnf install lynis on RHEL-based
sudo lynis audit system
```

It'll give you a hardening index and a list of suggestions. A good starting target is 70+.

## User and Authentication Hardening

### Disable the Root Login (or Restrict It Heavily)

If root is accessible directly, you're one credential leak away from a full system compromise.

```bash theme={null}
# Lock the root account password (use sudo instead)
sudo passwd -l root

# In /etc/ssh/sshd_config - disable root SSH login
PermitRootLogin no
```

### Enforce Strong Password Policies

Edit `/etc/security/pwquality.conf`:

```ini theme={null}
minlen = 14
minclass = 3
maxrepeat = 2
```

And configure password aging in `/etc/login.defs`:

```ini theme={null}
PASS_MAX_DAYS   90
PASS_MIN_DAYS   7
PASS_WARN_AGE   14
```

### Audit Existing Users and Groups

```bash theme={null}
# Find users with UID 0 (should only be root)
awk -F: '$3 == 0 {print $1}' /etc/passwd

# Find accounts with empty passwords
sudo awk -F: '$2 == "" {print $1}' /etc/shadow

# List all users with login shells
grep -v 'nologin\|false' /etc/passwd
```

Remove or lock any accounts that aren't needed:

```bash theme={null}
sudo usermod -L username    # Lock account
sudo userdel username       # Remove account (add -r to also remove home dir)
```

### Configure sudo Properly

Never give blanket `ALL=(ALL) NOPASSWD: ALL` to regular accounts. Edit via `visudo`:

```
# Good - requires password
username ALL=(ALL) ALL

# Avoid this in production
username ALL=(ALL) NOPASSWD: ALL
```

## SSH Hardening

SSH is the most common remote access method - and one of the most targeted services. Lock it down.

Edit `/etc/ssh/sshd_config`:

```bash theme={null}
# Use key-based auth only - no passwords
PasswordAuthentication no
PubkeyAuthentication yes

# Disable root login
PermitRootLogin no

# Only allow specific users
AllowUsers yourusername

# Disable unused auth methods
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes

# Use a non-default port (security through obscurity, but reduces noise)
Port 2222

# Limit auth attempts
MaxAuthTries 3
LoginGraceTime 30

# Disable X11 forwarding if not needed
X11Forwarding no

# Disable agent forwarding if not needed
AllowAgentForwarding no

# Set strong crypto
Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com
MACs hmac-sha2-256,hmac-sha2-512
KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512
```

After editing:

```bash theme={null}
sudo systemctl reload sshd
```

**Always test the new config before closing your current session:**

```bash theme={null}
ssh -T -p 2222 user@host
```

## Firewall Configuration

### UFW (Ubuntu / Debian)

```bash theme={null}
# Enable UFW
sudo ufw enable

# Default: deny all incoming, allow all outgoing
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow only what you need
sudo ufw allow 22/tcp      # or your custom SSH port
sudo ufw allow 443/tcp     # HTTPS if it's a web server
sudo ufw allow from 10.0.0.0/8 to any port 8080  # Restrict by source IP

# Check status
sudo ufw status verbose
```

### firewalld (RHEL / CentOS / Fedora)

```bash theme={null}
# Check active zones
sudo firewall-cmd --get-active-zones

# Remove a service from the public zone
sudo firewall-cmd --zone=public --remove-service=dhcpv6-client --permanent

# Add only what's needed
sudo firewall-cmd --zone=public --add-service=https --permanent

sudo firewall-cmd --reload
```

## File System and Permissions

### Set noexec, nodev, nosuid on Appropriate Partitions

Edit `/etc/fstab` to add mount options:

```
/tmp        tmpfs   defaults,noexec,nosuid,nodev   0 0
/var/tmp    tmpfs   defaults,noexec,nosuid,nodev   0 0
/dev/shm    tmpfs   defaults,noexec,nosuid,nodev   0 0
```

### Find World-Writable Files and SUID/SGID Binaries

```bash theme={null}
# World-writable files (potential for tampering)
sudo find / -xdev -type f -perm -002 2>/dev/null

# SUID binaries (can be privilege escalation vectors)
sudo find / -xdev -perm /4000 -type f 2>/dev/null

# SGID binaries
sudo find / -xdev -perm /2000 -type f 2>/dev/null
```

Review the results - remove SUID bits from binaries that don't need them:

```bash theme={null}
sudo chmod u-s /path/to/binary
```

### Restrict /etc/cron.\* Access

```bash theme={null}
sudo chown root:root /etc/crontab
sudo chmod 600 /etc/crontab
sudo chmod 700 /etc/cron.d /etc/cron.daily /etc/cron.weekly /etc/cron.monthly
```

## Kernel Hardening (sysctl)

Kernel parameters significantly impact security posture. Edit `/etc/sysctl.conf` or drop files in `/etc/sysctl.d/`:

```ini theme={null}
# Disable IP source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0

# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0

# Enable reverse path filtering (helps prevent IP spoofing)
net.ipv4.conf.all.rp_filter = 1

# Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Protect against SYN flood attacks
net.ipv4.tcp_syncookies = 1

# Disable IPv6 if not needed
net.ipv6.conf.all.disable_ipv6 = 1

# Restrict kernel pointer exposure
kernel.kptr_restrict = 2

# Restrict dmesg access to root
kernel.dmesg_restrict = 1

# Disable core dumps for SUID programs
fs.suid_dumpable = 0

# Enable ASLR
kernel.randomize_va_space = 2
```

Apply changes:

```bash theme={null}
sudo sysctl -p
```

## Audit Logging (auditd)

`auditd` is the Linux kernel's audit framework - essential for monitoring and forensics.

```bash theme={null}
# Install
sudo apt install auditd   # or: sudo dnf install audit

# Enable and start
sudo systemctl enable auditd
sudo systemctl start auditd
```

Add audit rules to `/etc/audit/audit.rules`:

```bash theme={null}
# Log all authentication events
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudo_rules

# Log sudo usage
-a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -k setuid

# Log SSH config changes
-w /etc/ssh/sshd_config -p wa -k sshd_config

# Log privileged command execution
-a always,exit -F arch=b64 -S execve -F euid=0 -k root_commands
```

## Services - Disable What You Don't Need

```bash theme={null}
# List all running services
systemctl list-units --type=service --state=running

# Disable a service you don't need
sudo systemctl stop servicename
sudo systemctl disable servicename
sudo systemctl mask servicename   # Prevents it from being started at all
```

Common services to consider disabling if not in use:

* `avahi-daemon` (mDNS/zeroconf - usually not needed on servers)
* `cups` (printing - almost never needed on servers)
* `bluetooth`
* `rpcbind` (only needed for NFS)
* `nfs` (unless you're using NFS)
* `telnet` / `rsh` / `rlogin` (never use these)

## Package Management Security

```bash theme={null}
# Remove packages you don't need
sudo apt remove --purge package-name

# Enable automatic security updates (Ubuntu/Debian)
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

# RHEL/CentOS equivalent
sudo dnf install dnf-automatic
sudo systemctl enable dnf-automatic.timer
```

## AppArmor and SELinux

These are Mandatory Access Control (MAC) systems that restrict what programs can do, even if they're compromised.

* **AppArmor** - Default on Ubuntu/Debian. Usually easier to work with.
* **SELinux** - Default on RHEL/CentOS/Fedora. More powerful, steeper learning curve.

```bash theme={null}
# AppArmor - check status and profiles
sudo aa-status

# SELinux - check status
sestatus

# Never set SELinux to permissive/disabled in production unless you know what you're doing
# Most "just disable SELinux" advice on StackOverflow is lazy - learn to fix the policy instead
```

## Useful Tools for Linux Hardening

| Tool           | What it's for                                              |
| -------------- | ---------------------------------------------------------- |
| **Lynis**      | System audit and hardening recommendations                 |
| **OpenSCAP**   | Compliance scanning against CIS/STIG benchmarks            |
| **AIDE**       | File integrity monitoring - detects unauthorized changes   |
| **Fail2ban**   | Automatically bans IPs with too many failed login attempts |
| **rkhunter**   | Rootkit hunter and system integrity checker                |
| **chkrootkit** | Another rootkit detection tool                             |
| **auditd**     | Kernel-level audit framework for logging                   |
| **Ansible**    | Automate hardening configs across many systems             |

## Quick Wins - Things to Do First

If you're hardening a Linux server and don't know where to start, do these first:

1. Update all packages
2. Disable root SSH login
3. Switch to key-based SSH authentication
4. Enable and configure UFW or firewalld
5. Disable unused services
6. Enable auditd
7. Run Lynis and address the top findings

These alone will dramatically improve your posture relative to a default install.

## Reference

* [CIS Ubuntu Linux Benchmark](https://www.cisecurity.org/benchmark/ubuntu_linux)
* [Lynis](https://cisofy.com/lynis/) - Quick security audit for any Linux system
* [DISA STIG for Red Hat](https://public.cyber.mil/stigs/downloads/) - Government-grade hardening
* [Linux Audit Documentation](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/security_hardening/) - RHEL security hardening guide

***

*There's no such thing as a fully hardened system - only systems that are harder to attack than others. The goal is to make exploitation as difficult and noisy as possible.*
