Chuyển tới nội dung chính

Hướng Dẫn Hardening Linux Server - Bảo Mật Toàn Diện

Giới Thiệu

Server hardening là quá trình tăng cường bảo mật hệ thống bằng cách giảm thiểu attack surface, vá các lỗ hổng và triển khai các biện pháp bảo vệ nhiều lớp. Bài viết này sẽ hướng dẫn bạn hardening một Linux server theo chuẩn CIS (Center for Internet Security) Benchmark.

Tầm quan trọng:

  • 🔒 Ngăn chặn 80% các cuộc tấn công phổ biến
  • 🛡️ Bảo vệ dữ liệu nhạy cảm
  • ⚖️ Đáp ứng compliance requirements (PCI-DSS, HIPAA, SOC2)
  • 📊 Giảm risk và incident response time

Thời gian thực hiện: 2-3 giờ
Độ khó: Nâng cao
Áp dụng cho: Ubuntu 22.04, Debian 11, CentOS/RHEL 8+

Threat Model và Attack Vectors

Các Mối Đe Dọa Phổ Biến

┌─────────────────────────────────────────┐
│ Attack Surface │
├─────────────────────────────────────────┤
│ 1. Brute Force SSH │
│ 2. Privilege Escalation │
│ 3. Malware/Rootkits │
│ 4. DDoS Attacks │
│ 5. Zero-day Exploits │
│ 6. Social Engineering │
│ 7. Insider Threats │
└─────────────────────────────────────────┘

![Sơ đồ Attack Vectors - Đặt ảnh tại /static/img/security/attack-vectors.png]

Phần 1: SSH Hardening

SSH là vector tấn công phổ biến nhất. Hardening SSH là bước đầu tiên và quan trọng nhất.

Bước 1: Tạo SSH Key Pair Mạnh

# Tạo ED25519 key (khuyến nghị, mạnh hơn RSA)
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519

# Hoặc RSA 4096 bit
ssh-keygen -t rsa -b 4096 -C "[email protected]" -f ~/.ssh/id_rsa

# Set quyền đúng
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

Copy public key lên server:

# Method 1: ssh-copy-id
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server-ip

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

# Set permissions trên server
ssh user@server-ip "chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

Bước 2: Cấu Hình SSH Daemon

# Backup file config gốc
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Edit config
sudo nano /etc/ssh/sshd_config

Cấu hình hardened SSH:

# Basic settings
Port 2222 # Đổi port (không phải 22)
Protocol 2 # Chỉ dùng SSH protocol 2
PermitRootLogin no # Tắt root login
MaxAuthTries 3 # Giới hạn số lần thử
MaxSessions 2 # Giới hạn số session

# Authentication
PubkeyAuthentication yes # Bật SSH key
PasswordAuthentication no # TẮT password login
PermitEmptyPasswords no # Không cho phép password rỗng
ChallengeResponseAuthentication no # Tắt challenge-response

# Restrict users
AllowUsers deployuser admin # Chỉ cho phép specific users
# AllowGroups ssh-users # Hoặc cho phép theo group

# Security options
X11Forwarding no # Tắt X11
PermitUserEnvironment no # Không cho set environment
AllowAgentForwarding no # Tắt agent forwarding
AllowTcpForwarding no # Tắt TCP forwarding
PermitTunnel no # Tắt tunnel

# Timing settings
LoginGraceTime 30 # Timeout cho login
ClientAliveInterval 300 # Ping client mỗi 5 phút
ClientAliveCountMax 2 # Disconnect sau 2 lần không response

# Crypto settings (chỉ dùng thuật toán mạnh)
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],hmac-sha2-512,hmac-sha2-256

# Logging
SyslogFacility AUTH
LogLevel VERBOSE # Log chi tiết để audit

# Banner
Banner /etc/ssh/banner # Hiển thị warning banner

Tạo warning banner:

sudo nano /etc/ssh/banner
***************************************************************************
AUTHORIZED ACCESS ONLY
***************************************************************************
Unauthorized access to this system is forbidden and will be prosecuted by law.
By accessing this system, you agree that your actions may be monitored.
***************************************************************************

Restart SSH và test:

# Test config trước khi restart
sudo sshd -t

# Nếu OK, restart SSH
sudo systemctl restart sshd

# QUAN TRỌNG: Mở terminal mới để test, KHÔNG đóng session hiện tại
# Test từ máy khác
ssh -i ~/.ssh/id_ed25519 -p 2222 user@server-ip

Bước 3: Cấu Hình Fail2Ban

# Cài đặt Fail2Ban
sudo apt update
sudo apt install fail2ban -y

# Tạo file config local
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

Cấu hình Fail2Ban:

[DEFAULT]
# Ban time: 1 giờ
bantime = 3600
# Window time: 10 phút
findtime = 600
# Max retry: 3 lần
maxretry = 3
# Ban action: iptables
banaction = iptables-multiport
# Email notification
destemail = [email protected]
sendername = Fail2Ban
action = %(action_mwl)s

[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 7200

[sshd-ddos]
enabled = true
port = 2222
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600

Tạo custom filter cho SSH brute force:

sudo nano /etc/fail2ban/filter.d/sshd-aggressive.conf
[Definition]
failregex = ^%(__prefix_line)s(?:error: PAM: )?[aA]uthentication (?:failure|error|failed) for .* from <HOST>( via \S+)?\s*$
^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from <HOST>\s*$
^%(__prefix_line)sFailed (?:password|publickey) for .* from <HOST>(?: port \d*)?(?: ssh\d*)?$
^%(__prefix_line)sROOT LOGIN REFUSED.* FROM <HOST>$
^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>$

ignoreregex =

Khởi động Fail2Ban:

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

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

![Screenshot Fail2Ban status - Đặt ảnh tại /static/img/security/fail2ban-status.png]

Phần 2: Firewall Configuration

UFW (Uncomplicated Firewall)

# Reset UFW (nếu đã cấu hình trước đó)
sudo ufw --force reset

# Mặc định: deny incoming, allow outgoing
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH (port đã đổi)
sudo ufw allow 2222/tcp comment 'SSH'

# Allow HTTP/HTTPS
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

# Limit SSH connections (rate limiting)
sudo ufw limit 2222/tcp

# Allow specific IP only
sudo ufw allow from 203.0.113.10 to any port 2222 proto tcp

# Enable firewall
sudo ufw enable

# Check status
sudo ufw status verbose

iptables (Advanced)

# Flush existing rules
sudo iptables -F
sudo iptables -X

# 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
sudo iptables -A OUTPUT -o lo -j ACCEPT

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

# Allow SSH with rate limiting
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
sudo iptables -A INPUT -p tcp --dport 2222 -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

# Allow ping (ICMP) but rate limit
sudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

# Drop invalid packets
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# Log dropped packets
sudo iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: " --log-level 7

# Save rules
sudo apt install iptables-persistent -y
sudo netfilter-persistent save

Script tự động:

#!/bin/bash
# firewall-setup.sh

# Save to file
sudo iptables-save > /etc/iptables/rules.v4
sudo ip6tables-save > /etc/iptables/rules.v6

echo "Firewall rules saved!"

Phần 3: Kernel Hardening

Sysctl Security Parameters

# Backup config gốc
sudo cp /etc/sysctl.conf /etc/sysctl.conf.backup

# Edit sysctl
sudo nano /etc/sysctl.conf

Thêm các parameters bảo mật:

# === IP Forwarding ===
# Tắt IP forwarding (trừ khi dùng làm router)
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0

# === Network Security ===
# Bật SYN cookies (chống SYN flood)
net.ipv4.tcp_syncookies = 1

# Không accept ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# Không accept source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0

# Bật reverse path filtering (chống IP spoofing)
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Không accept ICMP redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

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

# Ignore ICMP ping requests (optional - có thể gây khó troubleshoot)
# net.ipv4.icmp_echo_ignore_all = 1

# Ignore broadcast pings
net.ipv4.icmp_echo_ignore_broadcasts = 1

# === IPv6 Security ===
# Tắt IPv6 nếu không dùng
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

# === Memory Protection ===
# Bật ASLR (Address Space Layout Randomization)
kernel.randomize_va_space = 2

# Hạn chế truy cập kernel logs
kernel.dmesg_restrict = 1

# Hạn chế ptrace (chống debug process)
kernel.yama.ptrace_scope = 1

# Hạn chế kernel pointer leaks
kernel.kptr_restrict = 2

# === File System Security ===
# Tăng số lượng inotify watches
fs.inotify.max_user_watches = 524288

# Protected hardlinks
fs.protected_hardlinks = 1

# Protected symlinks
fs.protected_symlinks = 1

# === Core Dumps ===
# Tắt core dumps (chứa sensitive data)
kernel.core_uses_pid = 1
fs.suid_dumpable = 0

# === TCP Hardening ===
# TCP timestamps (tắt để chống fingerprinting)
net.ipv4.tcp_timestamps = 0

# Giảm TCP keepalive time
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15

# Bật TCP Fast Open
net.ipv4.tcp_fastopen = 3

Áp dụng changes:

# Apply changes
sudo sysctl -p

# Verify
sudo sysctl -a | grep -E "ip_forward|tcp_syncookies|randomize_va_space"

Phần 4: Mandatory Access Control (MAC)

Option 1: AppArmor (Ubuntu/Debian)

# Kiểm tra AppArmor status
sudo aa-status

# Install utilities
sudo apt install apparmor-utils apparmor-profiles apparmor-profiles-extra -y

# Set profiles to enforce mode
sudo aa-enforce /etc/apparmor.d/*

# Check loaded profiles
sudo aa-status | grep profiles

Tạo custom profile:

# Generate profile cho application
sudo aa-genprof /usr/bin/myapp

# Edit profile
sudo nano /etc/apparmor.d/usr.bin.myapp

Example profile:

#include <tunables/global>

/usr/bin/myapp {
#include <abstractions/base>
#include <abstractions/nameservice>

# Capabilities
capability net_bind_service,
capability setuid,
capability setgid,

# Network access
network inet stream,
network inet6 stream,

# File access
/usr/bin/myapp mr,
/etc/myapp/** r,
/var/log/myapp/* w,
/var/run/myapp.pid w,

# Deny access to sensitive files
deny /etc/shadow r,
deny /etc/passwd w,
}

Load profile:

sudo apparmor_parser -r /etc/apparmor.d/usr.bin.myapp

Option 2: SELinux (RHEL/CentOS)

# Kiểm tra SELinux status
sestatus

# Set to enforcing mode
sudo setenforce 1

# Make permanent
sudo nano /etc/selinux/config
# SELINUX=enforcing

# Install utilities
sudo yum install policycoreutils-python-utils setools-console -y

# Check contexts
ls -Z /var/www/html

# Restore default contexts
sudo restorecon -Rv /var/www/html

# Allow specific actions
sudo setsebool -P httpd_can_network_connect 1

Phần 5: Audit và Logging

Cài Đặt auditd

# Install auditd
sudo apt install auditd audispd-plugins -y

# Start service
sudo systemctl start auditd
sudo systemctl enable auditd

Cấu hình audit rules:

sudo nano /etc/audit/rules.d/hardening.rules
# Delete all existing rules
-D

# Buffer size
-b 8192

# Failure mode (0=silent 1=printk 2=panic)
-f 1

# === Audit System Calls ===
# Monitor unauthorized access attempts
-a always,exit -F arch=b64 -S open,openat,truncate,ftruncate -F exit=-EACCES -k access_denied
-a always,exit -F arch=b64 -S open,openat,truncate,ftruncate -F exit=-EPERM -k access_denied

# Monitor file deletions
-a always,exit -F arch=b64 -S unlink,unlinkat,rename,renameat -k file_deletion

# === Monitor Critical Files ===
# passwd changes
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/group -p wa -k group_changes
-w /etc/gshadow -p wa -k gshadow_changes

# sudo usage
-w /etc/sudoers -p wa -k sudoers_changes
-w /etc/sudoers.d/ -p wa -k sudoers_changes

# SSH configuration
-w /etc/ssh/sshd_config -p wa -k sshd_config_changes

# Kernel modules
-w /sbin/insmod -p x -k kernel_modules
-w /sbin/rmmod -p x -k kernel_modules
-w /sbin/modprobe -p x -k kernel_modules
-a always,exit -F arch=b64 -S init_module,delete_module -k kernel_modules

# === Monitor privileged commands ===
-a always,exit -F path=/usr/bin/passwd -F perm=x -k privileged_passwd
-a always,exit -F path=/usr/bin/sudo -F perm=x -k privileged_sudo
-a always,exit -F path=/usr/bin/su -F perm=x -k privileged_su

# === Network ===
-a always,exit -F arch=b64 -S socket,connect,bind -k network_modifications

# Make configuration immutable (phải reboot để thay đổi)
-e 2

Reload rules:

sudo augenrules --load
sudo systemctl restart auditd

# View rules
sudo auditctl -l

# Search audit logs
sudo ausearch -k passwd_changes
sudo ausearch -k privileged_sudo

Centralized Logging với rsyslog

# Cấu hình remote logging
sudo nano /etc/rsyslog.d/50-remote.conf
# Send logs to central server
*.* @@log-server.example.com:514

# Or TCP
*.* @@log-server.example.com:514

# Filter specific logs
:msg, contains, "failed" @@log-server.example.com:514

Phần 6: User và Permission Management

Tạo Security Groups

# Tạo group cho SSH access
sudo groupadd ssh-users

# Add user vào group
sudo usermod -aG ssh-users deployuser

# Verify
groups deployuser

Hardening User Accounts

# Set password policies
sudo nano /etc/login.defs
# Password aging
PASS_MAX_DAYS 90 # Đổi password mỗi 90 ngày
PASS_MIN_DAYS 7 # Không được đổi password trước 7 ngày
PASS_WARN_AGE 14 # Cảnh báo 14 ngày trước khi hết hạn
PASS_MIN_LEN 12 # Độ dài tối thiểu 12 ký tự

# Umask
UMASK 027 # Stricter file permissions

# Timeout
TMOUT=900 # Auto logout sau 15 phút idle

Cài đặt libpam-pwquality:

sudo apt install libpam-pwquality -y

# Configure
sudo nano /etc/security/pwquality.conf
# Minimum length
minlen = 12

# Require different char classes
minclass = 3

# Require lowercase
lcredit = -1

# Require uppercase
ucredit = -1

# Require digits
dcredit = -1

# Require special chars
ocredit = -1

# Maximum consecutive repeated chars
maxrepeat = 3

# Check against dictionary
dictcheck = 1

Disable Unnecessary Users

# List all users
cat /etc/passwd

# Disable unused system accounts
sudo usermod -s /usr/sbin/nologin bin
sudo usermod -s /usr/sbin/nologin sys
sudo usermod -s /usr/sbin/nologin games

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

Phần 7: Malware Detection và Rootkit Scanner

ClamAV Antivirus

# Install ClamAV
sudo apt install clamav clamav-daemon -y

# Update virus definitions
sudo systemctl stop clamav-freshclam
sudo freshclam
sudo systemctl start clamav-freshclam

# Scan hệ thống
sudo clamscan -r -i /home
sudo clamscan -r -i --exclude-dir="^/sys" /

# Scheduled scan
echo "0 2 * * * root /usr/bin/clamscan -r -i / --log=/var/log/clamav/scan.log" | sudo tee -a /etc/crontab

rkhunter (Rootkit Hunter)

# Install
sudo apt install rkhunter -y

# Update database
sudo rkhunter --update

# Scan system
sudo rkhunter --check --skip-keypress

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

# Schedule daily scan
sudo nano /etc/cron.daily/rkhunter
#!/bin/bash
/usr/bin/rkhunter --check --skip-keypress --report-warnings-only
sudo chmod +x /etc/cron.daily/rkhunter

AIDE (Advanced Intrusion Detection Environment)

# Install AIDE
sudo apt install aide -y

# Initialize database (lần đầu - mất ~10 phút)
sudo aideinit

# Copy database
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Check system integrity
sudo aide --check

# Update database after legitimate changes
sudo aide --update
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Phần 8: Security Scanning và Compliance

Lynis Security Audit

# Install Lynis
sudo apt install lynis -y

# Run full audit
sudo lynis audit system

# View report
sudo cat /var/log/lynis.log

# Get hardening suggestions
sudo lynis show suggestions

![Screenshot Lynis audit results - Đặt ảnh tại /static/img/security/lynis-audit.png]

OpenSCAP Compliance Checking

# Install OpenSCAP (Ubuntu)
sudo apt install libopenscap8 -y

# Download CIS benchmark
wget https://github.com/ComplianceAsCode/content/releases/download/v0.1.63/scap-security-guide-0.1.63.zip
unzip scap-security-guide-0.1.63.zip

# Run scan
sudo oscap xccdf eval \
--profile xccdf_org.ssgproject.content_profile_cis \
--results scan-results.xml \
--report scan-report.html \
scap-security-guide-0.1.63/ssg-ubuntu2004-ds.xml

# View HTML report
firefox scan-report.html

Phần 9: Monitoring và Alerting

Setup Monitoring Script

#!/bin/bash
# security-monitor.sh

LOG_FILE="/var/log/security-monitor.log"

echo "=== Security Check $(date) ===" >> $LOG_FILE

# Check for failed SSH attempts
echo "Failed SSH attempts:" >> $LOG_FILE
grep "Failed password" /var/log/auth.log | tail -n 10 >> $LOG_FILE

# Check for sudo usage
echo "Sudo usage:" >> $LOG_FILE
grep "sudo:" /var/log/auth.log | tail -n 10 >> $LOG_FILE

# Check listening ports
echo "Listening ports:" >> $LOG_FILE
netstat -tulpn | grep LISTEN >> $LOG_FILE

# Check for rootkit
rkhunter --check --skip-keypress --report-warnings-only >> $LOG_FILE

# Send alert if suspicious activity
if grep -q "WARNING" $LOG_FILE; then
mail -s "Security Alert on $(hostname)" [email protected] < $LOG_FILE
fi
chmod +x security-monitor.sh
# Run every hour
echo "0 * * * * root /root/security-monitor.sh" | sudo tee -a /etc/crontab

Testing Security

Penetration Testing Tools

# Nmap port scan (từ máy khác)
nmap -sS -sV -p- server-ip

# SSH brute force test
hydra -l root -P /usr/share/wordlists/rockyou.txt ssh://server-ip:2222

# Web vulnerability scan
nikto -h https://server-ip

Internal Security Audit

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

# Check for world-writable files
find / -xdev -type f -perm -0002 -ls 2>/dev/null

# Check for files without owner
find / -nouser -o -nogroup 2>/dev/null

# Check password hashes
sudo cat /etc/shadow | cut -d: -f2 | grep -v "!" | grep -v "*"

Checklist Hardening Hoàn Chỉnh

☐ SSH hardening (key auth, non-standard port)
☐ Firewall configured và tested
☐ Fail2Ban running và monitoring
☐ Kernel parameters hardened
☐ AppArmor/SELinux enforcing
☐ Audit daemon running
☐ Strong password policies
☐ Unnecessary services disabled
☐ Automatic security updates enabled
☐ Antivirus installed và updated
☐ Rootkit scanner scheduled
☐ File integrity monitoring (AIDE)
☐ Security audit passed (Lynis score > 80)
☐ All logs sent to central server
☐ Monitoring và alerting configured
☐ Backup strategy implemented
☐ Incident response plan documented
☐ Regular penetration testing scheduled

Tài Liệu Tham Khảo

Kết Luận

Bạn đã hoàn thành hardening Linux server với multiple layers of security. Server này có thể chống lại hầu hết các cuộc tấn công phổ biến và đáp ứng các security compliance standards.

Ghi nhớ: Security là một process liên tục, không phải one-time task. Luôn:

  • Cập nhật system thường xuyên
  • Review logs daily
  • Audit security quarterly
  • Stay updated với latest threats

Tags: #linux-security #hardening #ssh-security #firewall #compliance #cis-benchmark #penetration-testing

Cập nhật lần cuối: 19/12/2025
Tác giả: BacPV Docs Team