> For the complete documentation index, see [llms.txt](https://mainekhacker-1.gitbook.io/mainekhacker/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mainekhacker-1.gitbook.io/mainekhacker/linux-security-and-hardening-playbook.md).

# Linux Security & Hardening Playbook:

## Linux Security & Hardening Playbook

## Linux Security & Hardening: Complete Guide for Ethical Hackers

### 1. Introduction to Linux Security

#### Linux Security Architecture

* Multi-user design: Linux inherently supports multiple users with different privilege levels
* Kernel security: The kernel enforces security policies at the lowest level
* Security layers: Defense in depth approach with multiple security mechanisms

#### Common Vulnerabilities

* Privilege escalation exploits
* Misconfigured services and permissions
* Unpatched software vulnerabilities
* Weak authentication mechanisms
* Information disclosure through logs and error messages

***

### 2. User Management and Permissions

#### User and Group Management

Creating Users:

```bash
# Add new user
sudo useradd -m -s /bin/bash username

# Add user with specific UID and GID
sudo useradd -m -u 1500 -g 1500 username

# Set password
sudo passwd username
```

Modifying Users:

```bash
# Add user to group
sudo usermod -aG groupname username

# Change user's shell
sudo usermod -s /bin/zsh username

# Lock/unlock user accounts
sudo usermod -L username  # Lock
sudo usermod -U username  # Unlock
```

Deleting Users:

```bash
# Remove user (keep home directory)
sudo userdel username

# Remove user and home directory
sudo userdel -r username
```

Group Management:

```bash
# Create group
sudo groupadd groupname

# Delete group
sudo groupdel groupname

# View user's groups
groups username
id username
```

File Permissions:

Understanding Permissions:

rwxrwxrwx

* Others (o)
* Group (g)
* Owner (u)
* File type (- = file, d = directory)

Permission values:

* Read (r) = 4
* Write (w) = 2
* Execute (x) = 1

Setting Permissions:

```bash
# Numeric mode
chmod 755 file.txt  # rwxr-xr-x
chmod 644 file.txt  # rw-r--r--
chmod 600 file.txt  # rw-------

# Symbolic mode
chmod u+x file.txt   # Add execute for owner
chmod g-w file.txt   # Remove write for group
chmod o=r file.txt   # Set others to read only

# Recursive
chmod -R 755 /path/to/directory
```

Changing Ownership:

```bash
# Change owner
sudo chown user file.txt

# Change owner and group
sudo chown user:group file.txt

# Recursive
sudo chown -R user:group /path/to/directory

# Change group only
sudo chgrp group file.txt
```

Special Permissions:

```bash
# SUID (Set User ID) - 4xxx
chmod 4755 file    # Run as file owner
chmod u+s file

# SGID (Set Group ID) - 2xxx
chmod 2755 directory   # Inherit group ownership
chmod g+s directory

# Sticky Bit - 1xxx
chmod 1777 /tmp    # Only owner can delete
chmod +t directory
```

#### Sudo Configuration

Editing sudoers:

```bash
# Always use visudo (syntax checking)
sudo visudo
```

Common sudo configurations:

```
# /etc/sudoers examples
# User with full sudo access
username ALL=(ALL:ALL) ALL

# User without password prompt
username ALL=(ALL) NOPASSWD: ALL

# User can run specific commands
username ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl

# Group sudo access
%admin ALL=(ALL) ALL

# Command aliases
Cmnd_Alias NETWORKING = /sbin/ifconfig, /sbin/route
username ALL = NETWORKING
```

Best Practices:

```
# Require password for sudo
Defaults timestamp_timeout=5

# Log sudo commands
Defaults logfile="/var/log/sudo.log"

# Require TTY (prevent background sudo)
Defaults requiretty
```

***

### 3. Secure Shell (SSH) Hardening

#### SSH Configuration

Edit SSH config:

```bash
sudo nano /etc/ssh/sshd_config
```

Essential Hardening Settings (examples):

```
# Change default port
Port 2222

# Disable root login
PermitRootLogin no

# Use SSH protocol 2 only
Protocol 2

# Limit authentication attempts
MaxAuthTries 3

# Disable password authentication (use keys only)
PasswordAuthentication no
PubkeyAuthentication yes

# Disable empty passwords
PermitEmptyPasswords no

# Limit users who can SSH
AllowUsers username1 username2
DenyUsers baduser

# Set idle timeout
ClientAliveInterval 300
ClientAliveCountMax 2

# Disable X11 forwarding (if not needed)
X11Forwarding no

# Disable host-based authentication
HostbasedAuthentication no

# Use strong ciphers
Ciphers aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512,hmac-sha2-256
```

#### SSH Key-Based Authentication

Generate SSH keys (client side):

```bash
# Generate RSA key (4096 bits)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Generate Ed25519 key (recommended)
ssh-keygen -t ed25519 -C "your_email@example.com"

# Specify key locations
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_custom
```

Copy public key to server:

```bash
# Using ssh-copy-id
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# Manual method
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Set correct permissions on server
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
```

#### Fail2Ban for Brute-Force Protection

Install Fail2Ban:

```bash
# Debian/Ubuntu
sudo apt install fail2ban

# RHEL/CentOS
sudo yum install fail2ban
```

Configure Fail2Ban:

```bash
# Create local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
```

SSH jail configuration example:

```ini
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
```

Manage Fail2Ban:

```bash
# Start
sudo systemctl start fail2ban
sudo systemctl enable fail2ban

# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Unban IP
sudo fail2ban-client set sshd unbanip 192.168.1.100
```

***

### 4. Firewall Configuration

#### iptables

Basic iptables concepts:

* Tables: filter, nat, mangle, raw
* Chains: INPUT, OUTPUT, FORWARD
* Targets: ACCEPT, DROP, REJECT

Basic iptables commands:

```bash
# View current rules
sudo iptables -L -v -n

# Save rules
sudo iptables-save > /etc/iptables/rules.v4

# Restore rules
sudo iptables-restore < /etc/iptables/rules.v4

# Flush all rules
sudo iptables -F
```

Common iptables rules:

```bash
# Set default policies
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# Allow loopback
sudo iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (custom port)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Rate limit SSH connections
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

# Block specific IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP

# Log dropped packets
sudo iptables -A INPUT -j LOG --log-prefix "iptables-dropped: "
```

#### UFW (Uncomplicated Firewall)

Basic UFW commands:

```bash
# Install UFW
sudo apt install ufw

# Enable UFW
sudo ufw enable

# Disable UFW
sudo ufw disable

# Check status
sudo ufw status verbose

# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow specific services
sudo ufw allow 2222/tcp   # SSH
sudo ufw allow 80/tcp     # HTTP
sudo ufw allow 443/tcp    # HTTPS

# Allow from specific IP
sudo ufw allow from 192.168.1.100

# Allow specific IP to specific port
sudo ufw allow from 192.168.1.100 to any port 2222

# Deny specific IP
sudo ufw deny from 192.168.1.100

# Delete rules
sudo ufw delete allow 80/tcp

# Reset UFW
sudo ufw reset
```

#### firewalld (RHEL/CentOS/Fedora)

Basic firewalld commands:

```bash
# Start and enable
sudo systemctl start firewalld
sudo systemctl enable firewalld

# Check status
sudo firewall-cmd --state

# List all zones
sudo firewall-cmd --get-zones

# List active zones
sudo firewall-cmd --get-active-zones

# Add service
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --reload

# Add port
sudo firewall-cmd --zone=public --add-port=2222/tcp --permanent

# Remove service
sudo firewall-cmd --zone=public --remove-service=http --permanent

# Block IP
sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject' --permanent
```

***

### 5. Intrusion Detection and Prevention Systems

#### Snort Installation and Configuration

Install Snort:

```bash
# Debian/Ubuntu
sudo apt install snort

# Configure network interfaces
sudo nano /etc/snort/snort.conf
```

Basic Snort configuration:

```
# Set your network
ipvar HOME_NET 192.168.1.0/24
ipvar EXTERNAL_NET !$HOME_NET

# Enable rule sets
include $RULE_PATH/local.rules
```

Create custom rules:

```
# /etc/snort/rules/local.rules

# Alert on ping
alert icmp any any -> $HOME_NET any (msg:"ICMP Ping Detected"; sid:1000001; rev:1;)

# Alert on SSH brute force
alert tcp any any -> $HOME_NET 22 (msg:"Possible SSH Brute Force"; threshold:type both, track by_src, count 5, seconds 60; sid:1000002; rev:1;)
```

Run Snort:

```bash
# Test configuration
sudo snort -T -c /etc/snort/snort.conf

# Run in console mode
sudo snort -A console -c /etc/snort/snort.conf -i eth0

# Run as daemon
sudo snort -D -c /etc/snort/snort.conf -i eth0
```

#### Suricata

Install Suricata:

```bash
sudo apt install suricata

# Update rules
sudo suricata-update

# Configure
sudo nano /etc/suricata/suricata.yaml

# Start service
sudo systemctl start suricata
sudo systemctl enable suricata

# Check logs
sudo tail -f /var/log/suricata/fast.log
sudo tail -f /var/log/suricata/eve.json
```

***

### 6. System Updates and Patch Management

#### Debian/Ubuntu (APT)

Update commands:

```bash
# Update package lists
sudo apt update

# Upgrade installed packages
sudo apt upgrade

# Full upgrade (handles dependencies)
sudo apt full-upgrade

# Remove unnecessary packages
sudo apt autoremove

# Clean package caches
sudo apt clean
```

Automated updates:

```bash
# Install unattended-upgrades
sudo apt install unattended-upgrades

# Configure
sudo dpkg-reconfigure -plow unattended-upgrades

# Edit configuration
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
```

Configuration example:

```
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
    "${distro_id}ESMApps:${distro_codename}-apps-security";
};
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
```

#### RHEL/CentOS (YUM/DNF)

Update commands:

```bash
# YUM (CentOS 7 and earlier)
sudo yum update
sudo yum upgrade

# DNF (CentOS 8+, Fedora)
sudo dnf update
sudo dnf upgrade

# Check for security updates only
sudo yum updateinfo list security
sudo dnf updateinfo list security

# Install security updates only
sudo yum update --security
sudo dnf upgrade --security
```

Automated updates:

```bash
# Install yum-cron
sudo yum install yum-cron

# Configure
sudo nano /etc/yum/yum-cron.conf
# Set apply_updates = yes for automatic installation

# Start service
sudo systemctl start yum-cron
sudo systemctl enable yum-cron
```

***

### 7. Filesystem Security

#### Secure Mount Options

Edit /etc/fstab:

```bash
sudo nano /etc/fstab
```

Secure mount examples:

```
# /tmp with security options
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0

# /var with nosuid
/dev/sda5 /var ext4 defaults,nosuid 0 2

# /home with nodev
/dev/sda6 /home ext4 defaults,nodev 0 2

# USB/removable media
/dev/sdb1 /media/usb vfat noauto,noexec,nosuid,nodev,users 0 0
```

Mount options explained:

* noexec: Prevent execution of binaries
* nosuid: Ignore SUID/SGID bits
* nodev: Prevent device files
* ro: Read-only
* noauto: Don't mount at boot

Apply changes:

```bash
# Remount without reboot
sudo mount -o remount /tmp

# Or remount all
sudo mount -a
```

#### Access Control Lists (ACLs)

Enable ACLs:

```bash
# Check if enabled
tune2fs -l /dev/sda1 | grep "Default mount options"

# Enable on ext4
sudo tune2fs -o acl /dev/sda1
```

ACL commands:

```bash
# View ACLs
getfacl file.txt

# Set ACL for user
setfacl -m u:username:rwx file.txt

# Set ACL for group
setfacl -m g:groupname:rx file.txt

# Remove specific ACL
setfacl -x u:username file.txt

# Remove all ACLs
setfacl -b file.txt

# Recursive ACL
setfacl -R -m u:username:rx /path/to/directory

# Default ACL (for new files)
setfacl -d -m u:username:rwx /path/to/directory

# Copy ACLs from one file to another
getfacl file1.txt | setfacl --set-file=- file2.txt
```

#### Disk Encryption with LUKS

Encrypt a partition:

```bash
# Install cryptsetup
sudo apt install cryptsetup

# Create encrypted partition
sudo cryptsetup luksFormat /dev/sdb1

# Open encrypted partition
sudo cryptsetup luksOpen /dev/sdb1 encrypted_drive

# Format the encrypted partition
sudo mkfs.ext4 /dev/mapper/encrypted_drive

# Mount encrypted partition
sudo mount /dev/mapper/encrypted_drive /mnt/encrypted
```

Auto-mount encrypted partition:

```bash
# Add key file
sudo dd if=/dev/urandom of=/root/keyfile bs=1024 count=4
sudo chmod 0400 /root/keyfile
sudo cryptsetup luksAddKey /dev/sdb1 /root/keyfile

# Edit /etc/crypttab
encrypted_drive /dev/sdb1 /root/keyfile luks

# Edit /etc/fstab
/dev/mapper/encrypted_drive /mnt/encrypted ext4 defaults 0 2
```

Home directory encryption:

```bash
# Install ecryptfs
sudo apt install ecryptfs-utils

# Encrypt existing home
ecryptfs-migrate-home -u username

# Setup for new users
sudo adduser --encrypt-home username
```

***

### 8. Log Management and Monitoring

#### Syslog and Rsyslog

Rsyslog configuration:

```bash
sudo nano /etc/rsyslog.conf
```

Custom logging rules:

```
# Log all kernel messages
kern.* /var/log/kern.log

# Log auth messages separately
auth,authpriv.* /var/log/auth.log

# Emergency messages to all users
*.emerg :omusrmsg:*

# Send logs to remote server
*.* @@remote-host:514
```

Restart rsyslog:

```bash
sudo systemctl restart rsyslog
```

#### Journalctl (systemd)

View logs:

```bash
# View all logs
journalctl

# Follow logs (like tail -f)
journalctl -f

# View logs since boot
journalctl -b

# View logs for specific service
journalctl -u ssh.service

# View logs with priority
journalctl -p err

# View logs for specific time
journalctl --since "2024-01-01" --until "2024-01-31"
journalctl --since "1 hour ago"

# View kernel messages
journalctl -k

# Show disk usage
journalctl --disk-usage

# Vacuum old logs
sudo journalctl --vacuum-time=2weeks
sudo journalctl --vacuum-size=500M
```

Configure journal retention:

```bash
sudo nano /etc/systemd/journald.conf
```

Example:

```ini
[Journal]
SystemMaxUse=500M
SystemMaxFileSize=50M
MaxRetentionSec=2week
```

#### Log Analysis Tools

ELK Stack setup (Elasticsearch, Logstash, Kibana) — simplified overview:

```bash
# Install Java
sudo apt install default-jdk

# Install Elasticsearch
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-7.x.list
sudo apt update
sudo apt install elasticsearch

# Start Elasticsearch
sudo systemctl start elasticsearch
sudo systemctl enable elasticsearch

# Install Logstash
sudo apt install logstash

# Install Kibana
sudo apt install kibana
sudo systemctl start kibana
sudo systemctl enable kibana
```

Simple log monitoring:

```bash
# Monitor auth log for failed logins
sudo tail -f /var/log/auth.log | grep "Failed password"

# Count failed SSH attempts
sudo grep "Failed password" /var/log/auth.log | wc -l

# Show unique IPs attempting SSH
sudo grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr
```

***

### 9. Malware and Rootkit Detection

#### ClamAV (Antivirus)

Install ClamAV:

```bash
sudo apt install clamav clamav-daemon
```

Update virus definitions:

```bash
sudo systemctl stop clamav-freshclam
sudo freshclam
sudo systemctl start clamav-freshclam
```

Scan files:

```bash
# Scan directory
clamscan -r /home

# Scan and remove infected files
clamscan -r --remove /home

# Scan and move infected files
clamscan -r --move=/quarantine /home

# Scan with detailed output
clamscan -r -v /home

# Scan entire system (excluding certain directories)
clamscan -r -v --exclude-dir="^/sys" --exclude-dir="^/dev" --exclude-dir="^/proc" /
```

#### chkrootkit

Install and run:

```bash
# Install
sudo apt install chkrootkit

# Run scan
sudo chkrootkit

# Check specific items
sudo chkrootkit -q
```

#### rkhunter (Rootkit Hunter)

Install rkhunter:

```bash
sudo apt install rkhunter
```

Update and scan:

```bash
# Update database
sudo rkhunter --update

# Update file properties
sudo rkhunter --propupd

# Run scan
sudo rkhunter --check

# Run scan (skip keypress)
sudo rkhunter --check --skip-keypress

# View log
sudo cat /var/log/rkhunter.log
```

Configure rkhunter:

```bash
sudo nano /etc/rkhunter.conf
```

Example configuration changes:

```
# Enable automatic updates
UPDATE_MIRRORS=1
MIRRORS_MODE=0

# Email on warning
MAIL-ON-WARNING=admin@example.com
MAIL_CMD=mail -s "[rkhunter] Warnings found for ${HOST_NAME}"
```

Automate rkhunter:

```bash
# Create cron job
sudo nano /etc/cron.daily/rkhunter
```

Example script (/etc/cron.daily/rkhunter):

```bash
#!/bin/sh
/usr/bin/rkhunter --update --quiet
/usr/bin/rkhunter --cronjob --report-warnings-only
```

Make executable:

```bash
sudo chmod 755 /etc/cron.daily/rkhunter
```

#### AIDE (Advanced Intrusion Detection Environment)

Install AIDE:

```bash
sudo apt install aide
```

Initialize database:

```bash
sudo aideinit
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
```

Run checks:

```bash
# Check for changes
sudo aide --check

# Update database
sudo aide --update
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
```

Configure AIDE:

```bash
sudo nano /etc/aide/aide.conf
```

***

### 10. Network Security

#### SSL/TLS Configuration

Generate self-signed certificate:

```bash
# Generate private key and certificate
sudo openssl req -x509 -nodes -days 365 -newkey rsa:4096 \
  -keyout /etc/ssl/private/server.key \
  -out /etc/ssl/certs/server.crt

# Set permissions
sudo chmod 600 /etc/ssl/private/server.key
```

Let's Encrypt (Certbot):

```bash
# Install Certbot
sudo apt install certbot python3-certbot-apache

# For Apache
sudo certbot --apache -d example.com -d www.example.com

# For Nginx
sudo apt install python3-certbot-nginx
sudo certbot --nginx -d example.com

# Auto-renewal
sudo certbot renew --dry-run
```

#### VPN Configuration (OpenVPN)

Install OpenVPN:

```bash
sudo apt install openvpn easy-rsa
```

Setup PKI:

```bash
# Copy easy-rsa
make-cadir ~/openvpn-ca
cd ~/openvpn-ca

# Initialize PKI
./easyrsa init-pki
./easyrsa build-ca nopass

# Generate server certificate
./easyrsa gen-req server nopass
./easyrsa sign-req server server

# Generate Diffie-Hellman parameters
./easyrsa gen-dh

# Generate TLS auth key
openvpn --genkey --secret ta.key
```

Basic server configuration (/etc/openvpn/server.conf example):

```
port 1194
proto udp
dev tun0
ca ca.crt
cert server.crt
key server.key
dh dh.pem
tls-auth ta.key 0
server 10.8.0.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
keepalive 10 120
cipher AES-256-CBC
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3
```

#### Network Hardening

Disable IPv6 (if not needed):

```bash
# Edit sysctl
sudo nano /etc/sysctl.conf

# Add:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

# Apply changes
sudo sysctl -p
```

Kernel hardening parameters:

```bash
sudo nano /etc/sysctl.conf

# Examples
net.ipv4.ip_forward = 0

# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

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

# Enable SYN cookies (DDoS protection)
net.ipv4.tcp_syncookies = 1

# Disable ICMP redirects
net.ipv4.conf.all.secure_redirects = 0

# Log martian packets
net.ipv4.conf.all.log_martians = 1

# Ignore ICMP ping requests
net.ipv4.icmp_echo_ignore_all = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1

# TCP/IP stack hardening
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5

# Apply all settings
sudo sysctl -p
```

***

#### Apache Hardening

Hide version information:

```bash
sudo nano /etc/apache2/conf-available/security.conf
```

Add or ensure:

```apache
ServerTokens Prod
ServerSignature Off
TraceEnable Off
```

Disable directory listing:

```apache
<Directory /var/www/html>
    Options -Indexes
</Directory>
```

Limit request size:

```apache
LimitRequestBody 10485760
```

Install and configure ModSecurity:

```bash
sudo apt install libapache2-mod-security2

# Enable module
sudo a2enmod security2

# Copy recommended config
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

# Edit config
sudo nano /etc/modsecurity/modsecurity.conf
```

Example ModSecurity settings:

```apache
SecRuleEngine On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
```

#### Nginx Hardening

Hide version and apply other settings:

```bash
sudo nano /etc/nginx/nginx.conf
```

Example:

```nginx
http {
    server_tokens off;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    # Buffer overflow protection
    client_body_buffer_size 1k;
    client_header_buffer_size 1k;
    client_max_body_size 1k;
    large_client_header_buffers 2 1k;

    # Timeouts
    client_body_timeout 10;
    client_header_timeout 10;
    keepalive_timeout 5 5;
    send_timeout 10;
}
```

SSL/TLS configuration example for a server block:

```nginx
server {
    listen 443 ssl http2;
    ssl_certificate /etc/ssl/certs/server.crt;
    ssl_certificate_key /etc/ssl/private/server.key;

    # Modern SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}
```

#### MySQL/MariaDB Hardening

Run mysql\_secure\_installation:

```bash
sudo mysql_secure_installation
```

Manual hardening:

```sql
-- Login to MySQL
sudo mysql -u root -p

-- Remove anonymous users
DELETE FROM mysql.user WHERE User='';

-- Disable remote root login
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');

-- Remove test database
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%';

-- Reload privileges
FLUSH PRIVILEGES;
```

Secure configuration:

```bash
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
```

Example:

```ini
[mysqld]
# Bind to localhost only
bind-address = 127.0.0.1

# Disable LOAD DATA LOCAL INFILE
local-infile=0

# Enable logging
log-error = /var/log/mysql/error.log
general_log_file = /var/log/mysql/mysql.log
general_log = 1
```

#### PostgreSQL Hardening

Edit postgresql.conf:

```bash
sudo nano /etc/postgresql/*/main/postgresql.conf
```

Example:

```ini
# Listen on localhost only
listen_addresses = 'localhost'

# Enable SSL
ssl = on
ssl_cert_file = '/etc/ssl/certs/server.crt'
ssl_key_file = '/etc/ssl/private/server.key'

# Logging
log_connections = on
log_disconnections = on
log_duration = on
```

Edit pg\_hba.conf:

```bash
sudo nano /etc/postgresql/*/main/pg_hba.conf
```

Example entry to require SSL and password:

```
hostssl all all 0.0.0.0/0 md5
```

***

### 11. Backup and Recovery

#### Rsync for Backups

Basic rsync backup:

```bash
# Local backup
rsync -av --delete /source/ /backup/

# Remote backup
rsync -av --delete -e ssh /source/ user@remote:/backup/

# Exclude certain files
rsync -av --delete --exclude='*.tmp' --exclude='cache/' /source/ /backup/

# Show progress
rsync -av --progress /source/ /backup/

# Dry run (test without changes)
rsync -av --dry-run /source/ /backup/
```

Incremental backup script example:

```bash
#!/bin/bash
# backup.sh
SOURCE="/home"
DEST="/backup"
DATE=$(date +%Y-%m-%d)
LATEST="$DEST/latest"
BACKUP="$DEST/$DATE"

# Create backup
rsync -av --delete --link-dest="$LATEST" "$SOURCE/" "$BACKUP/"

# Update latest symlink
rm -f "$LATEST"
ln -s "$BACKUP" "$LATEST"

# Delete backups older than 30 days
find "$DEST" -maxdepth 1 -type d -mtime +30 -exec rm -rf {} \;
```

#### Tar for Archives

Create backups:

```bash
# Create compressed archive
tar -czf backup-$(date +%Y%m%d).tar.gz /path/to/directory

# Create archive with exclusions
tar -czf backup.tar.gz --exclude='*.log' --exclude='tmp/*' /path/to/directory

# Split large archive
tar -czf - /large/directory | split -b 1G - backup.tar.gz.

# Extract archive
tar -xzf backup.tar.gz

# List contents
tar -tzf backup.tar.gz
```

#### Automated Backup with Cron

Create backup script:

```bash
sudo nano /usr/local/bin/daily-backup.sh
```

Example script:

```bash
#!/bin/bash
BACKUP_DIR="/backup/$(date +%Y-%m-%d)"
LOG_FILE="/var/log/backup.log"
echo "Starting backup at $(date)" >> $LOG_FILE

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Backup important directories
tar -czf "$BACKUP_DIR/etc.tar.gz" /etc
tar -czf "$BACKUP_DIR/home.tar.gz" /home
tar -czf "$BACKUP_DIR/var-www.tar.gz" /var/www

# Backup MySQL
mysqldump -u root -p'password' --all-databases | gzip > "$BACKUP_DIR/mysql.sql.gz"

# Delete old backups (older than 7 days)
find /backup -type d -mtime +7 -exec rm -rf {} \;

echo "Backup completed at $(date)" >> $LOG_FILE
```

Make executable:

```bash
sudo chmod +x /usr/local/bin/daily-backup.sh
```

Schedule with cron:

```bash
sudo crontab -e
```

Example cron entry (daily at 2 AM):

```
0 2 * * * /usr/local/bin/daily-backup.sh
```

***

### 12. Security Auditing and Assessment

#### Lynis System Audit

Install Lynis:

```bash
# Debian/Ubuntu
sudo apt install lynis

# Or download latest
git clone https://github.com/CISOfy/lynis
cd lynis
```

Run audit:

```bash
sudo lynis audit system

# Save report
sudo lynis audit system --report-file /var/log/lynis-report.txt

# Automated quick scan
sudo lynis audit system --quick
```

#### OpenVAS Vulnerability Scanner

Install OpenVAS (GVM):

```bash
sudo apt install openvas

# Setup
sudo gvm-setup

# Start services
sudo gvm-start
```

Access web interface:

<https://localhost:9392/>

#### Nmap for Network Scanning

Basic scans:

```bash
# Ping scan
nmap -sn 192.168.1.0/24

# TCP SYN scan
nmap -sS 192.168.1.100

# Service version detection
nmap -sV 192.168.1.100

# OS detection
nmap -O 192.168.1.100

# Comprehensive scan
nmap -A -T4 192.168.1.100

# Scan specific ports
nmap -p 22,80,443 192.168.1.100

# Scan all ports
nmap -p- 192.168.1.100

# Script scanning
nmap --script=vuln 192.168.1.100
```

#### Nikto Web Scanner

Install and use:

```bash
sudo apt install nikto

# Scan website
nikto -h http://example.com

# Scan with SSL
nikto -h https://example.com

# Output to file
nikto -h http://example.com -o report.html -Format html
```

***

### 13. SELinux and AppArmor

#### SELinux (RHEL/CentOS)

Check status:

```bash
sestatus
getenforce
```

Set modes:

```bash
# Temporary change
sudo setenforce 0  # Permissive
sudo setenforce 1  # Enforcing

# Permanent change
sudo nano /etc/selinux/config
# Example:
# SELINUX=enforcing
# SELINUXTYPE=targeted
```

Manage contexts:

```bash
# View file context
ls -Z /path/to/file

# Restore default context
restorecon -v /path/to/file

# Change context
chcon -t httpd_sys_content_t /var/www/html/file

# Make permanent
semanage fcontext -a -t httpd_sys_content_t "/var/www/html/file"
```

Boolean management:

```bash
# List all booleans
getsebool -a

# Get specific boolean
getsebool httpd_can_network_connect

# Set boolean
setsebool -P httpd_can_network_connect on
```

#### AppArmor (Ubuntu/Debian)

Check status:

```bash
sudo aa-status
```

Manage profiles:

```bash
# Enforce mode
sudo aa-enforce /etc/apparmor.d/usr.bin.firefox

# Complain mode
sudo aa-complain /etc/apparmor.d/usr.bin.firefox

# Disable profile
sudo aa-disable /etc/apparmor.d/usr.bin.firefox

# Reload all profiles
sudo systemctl reload apparmor
```

Create custom profile:

```bash
# Generate profile
sudo aa-genprof /path/to/application

# Update profile
sudo aa-logprof
```

***

### 14. Incident Response

#### Initial Response Steps

Isolate the system:

```bash
# Disconnect network
sudo ifconfig eth0 down
# Or
sudo ip link set eth0 down
```

Preserve evidence:

```bash
# Create forensic image
sudo dd if=/dev/sda of=/mnt/evidence/disk.img bs=4M status=progress

# Hash for integrity
sha256sum /mnt/evidence/disk.img > /mnt/evidence/disk.img.sha256

# Memory dump (if possible)
sudo dd if=/dev/mem of=/mnt/evidence/memory.dump
```

Collect system information:

```bash
# Running processes
ps auxf > processes.txt

# Network connections
netstat -antp > connections.txt
ss -antp > connections-ss.txt

# Open files
lsof > open-files.txt

# Logged in users
w > logged-users.txt

# Command history
cat ~/.bash_history > bash-history.txt

# System logs
journalctl -b > system-logs.txt
```

Log Analysis for Incident Response:

Search for suspicious activity:

```bash
# Failed login attempts
sudo grep "Failed password" /var/log/auth.log

# Successful logins
sudo grep "Accepted" /var/log/auth.log

# Sudo usage
sudo grep "sudo" /var/log/auth.log

# New user creations
sudo grep "useradd" /var/log/auth.log

# Unauthorized privilege escalation
sudo grep "COMMAND" /var/log/auth.log
```

Check for rootkits and backdoors:

```bash
# Check listening ports
sudo netstat -antp | grep LISTEN

# Check cron jobs
crontab -l
sudo cat /etc/crontab
ls -la /etc/cron.*

# Check startup services
systemctl list-unit-files --type=service --state=enabled

# Check for SUID files
find / -perm -4000 -type f 2>/dev/null

# Recently modified files
find /etc -type f -mtime -7
```

***

### 15. Additional Security Tools

#### Audit Daemon (auditd)

Install auditd:

```bash
sudo apt install auditd audispd-plugins
```

Basic rules (example /etc/audit/rules.d/audit.rules):

```bash
# Monitor file changes
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes

# Monitor sudo usage
-w /usr/bin/sudo -p x -k sudo_execution

# Monitor network configuration
-w /etc/network/ -p wa -k network_changes

# System calls monitoring
-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time_change
```

Search logs:

```bash
# Search for events
ausearch -k passwd_changes

# Summary report
aureport --summary

# Failed events
aureport --failed
```

#### OSSEC HIDS

Install OSSEC:

```bash
wget https://github.com/ossec/ossec-hids/archive/3.7.0.tar.gz
tar -xzf 3.7.0.tar.gz
cd ossec-hids-3.7.0
sudo ./install.sh
```

Manage OSSEC:

```bash
# Start OSSEC
sudo /var/ossec/bin/ossec-control start

# Check status
sudo /var/ossec/bin/ossec-control status

# View alerts
sudo tail -f /var/ossec/logs/alerts/alerts.log
```

***

### 16. Security Checklist

#### Daily Tasks

* [ ] Review authentication logs for failed login attempts
* [ ] Check firewall logs for suspicious traffic
* [ ] Monitor system resource usage
* [ ] Review IDS/IPS alerts

#### Weekly Tasks

* [ ] Update all software packages
* [ ] Review user accounts and permissions
* [ ] Check for rootkits with rkhunter/chkrootkit
* [ ] Analyze system logs for anomalies
* [ ] Test backup restoration

#### Monthly Tasks

* [ ] Full system security audit with Lynis
* [ ] Review and update firewall rules
* [ ] Vulnerability scan with OpenVAS
* [ ] Update security policies and documentation
* [ ] Review and rotate passwords
* [ ] Test incident response procedures

***

### 17. Quick Reference Commands

System Information:

```bash
uname -a             # Kernel version
cat /etc/os-release  # OS information
hostname             # System hostname
uptime               # System uptime
who                  # Logged in users
last                 # Login history
```

Process Management:

```bash
ps aux                # All processes
top                   # Interactive process viewer
htop                  # Better process viewer
pgrep process_name    # Find process ID
pkill process_name    # Kill process by name
kill -9 PID           # Force kill process
```

Network Commands:

```bash
ip addr show          # Show IP addresses
ip route show         # Show routing table
ss -tulpn             # Show listening ports
netstat -tulpn        # Show listening ports (older)
tcpdump -i eth0       # Packet capture
iftop                 # Bandwidth monitoring
```

File Operations:

```bash
find / -name filename               # Find file
find / -type f -size +100M          # Find large files
grep -r "string" /path              # Search in files
lsof                                # List open files
df -h                                # Disk space
du -sh /path                         # Directory size
```

***

## Conclusion

This comprehensive guide covers essential aspects of Linux security and hardening for ethical hackers. Remember these key principles:

1. Defense in Depth: Use multiple layers of security
2. Least Privilege: Grant minimum necessary permissions
3. Keep Updated: Regularly patch and update systems
4. Monitor Continuously: Implement logging and alerting
5. Test Regularly: Conduct security audits and penetration tests
6. Document Everything: Maintain clear security documentation
7. Stay Informed: Keep up with new vulnerabilities and techniques

Security is an ongoing process, not a one-time task. Regularly review and update your security measures to protect against evolving threats.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mainekhacker-1.gitbook.io/mainekhacker/linux-security-and-hardening-playbook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
