Showing posts with label SSH Security. Show all posts
Showing posts with label SSH Security. Show all posts

CentOS 9 System Hardening Plan – Ultimate Server Security Guide

CentOS 9 System Hardening Plan – Ultimate Server Security Guide

CentOS 9 System Hardening Plan is essential for admins who want to protect Linux servers from modern threats. In this guide, we walk through a comprehensive hardening checklist that includes firewall setup, SSH lockdown, intrusion detection, patch management, SELinux enforcement, auditing, and best security practices tailored for CentOS 9 workloads. Whether you’re securing a cloud instance, enterprise server, or development box, these steps will reduce your attack surface.

Why Hardening Matters for CentOS 9

Explain risks of unprotected servers + benefits of hardening. Add stat like: “80% of breaches start with weak server configurations.”

System Updates and Basic Preparation

System Package Updates

Update all system software packages to the latest version via the dnf command to obtain the latest security patches:

 
sudo dnf update -y && sudo dnf upgrade -y


User Privilege Management

1. Create Restricted Users and Authorize

Step 1: Create a standard user


 
sudo useradd secure_user  # Create a standard user named secure_user
sudo passwd secure_user   # Set a password for the user

Step 2: Grant sudo privileges

Add the user to the wheel group to obtain sudo privileges

 
sudo usermod -aG wheel secure_user


SSH Service Hardening

1. Prohibit Remote Root Login and Disable Password Authentication

Step 1: Edit the SSH configuration file

Open the SSH configuration file with vim: sudo vim /etc/ssh/sshd_config

 
PermitRootLogin no       # Disable remote root login
PasswordAuthentication no  # Disable password authentication, use key-based authentication instead


Step 2: Restart the SSH service

 
sudo systemctl restart sshd
sudo systemctl enable sshd  # Ensure it starts automatically on boot


Firewall Configuration (firewalld)

1. Configure Firewall Rules

Step 1: Start and set the firewall to enable on boot

 
sudo systemctl enable --now firewalld


Step 2: Open necessary ports

Example for opening HTTP (80), HTTPS (443), and SSH (22):

 
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload 


SELinux Configuration

1. Enable SELinux Enforcing Mode

Step 1: Edit the SELinux configuration file: sudo vim /etc/selinux/config

 
SELINUX=enforcing  # Set SELinux to enforcing mode


Step 2: Restart the system for the configuration to take effect: sudo reboot


Log Auditing and Monitoring (auditd)

1. Configure the Auditing Service

Step 1: Edit the audit configuration file

Edit auditd.conf: sudo vim /etc/audit/auditd.conf

 
max_log_file = 50  # Maximum log file size is 50MB
max_log_file_action = rotate  # Rotate logs when full


Step 2: Configure audit rules: sudo vim /etc/audit/rules.d/audit.rules

# Audit modifications to the /etc/shadow file -a always,exit -F arch=b64 -S open -S creat -S fchmod -S fchown -F path=/etc/shadow -F perm=0600 -k shadow_changes # Audit sudo operations -a always,exit -F arch=b64 -S sudo -F auid>=1000 -F auid!=4294967295 -k sudo_actions

Edit the audit rules file


Step 3: Restart the audit service

 
sudo systemctl restart auditd
sudo systemctl enable auditd


Disable Unnecessary Services

1. Disable Irrelevant System Services

Example for disabling mail service (Postfix) and telnet service:

 
sudo systemctl disable --now postfix
sudo systemctl disable --now telnet


File Permission Configuration

1. Adjust Critical File Permissions

 
sudo chmod 0600 /etc/shadow   # Restrict /etc/shadow to be readable and writable by root only
sudo chmod 0600 /etc/gshadow  # Restrict /etc/gshadow file permissions
sudo chmod 0750 /etc/sudoers  # Restrict /etc/sudoers file permissions
sudo chown root:root /etc/sudoers  # Ensure the file owner is root

Step 1: Restrict permissions on critical system files


Kernel Parameter Optimization

1. Adjust sysctl.conf Configuration

Optimize kernel parameters by editing the /etc/sysctl.conf file to enhance system security and performance. Example configuration:


sudo vim /etc/sysctl.conf


Add or modify the following content:

 
# Disable IP source routing checks to prevent spoofed source address attacks
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Enable SYN Cookies to defend against SYN flood attacks
net.ipv4.tcp_syncookies = 1

# Limit the maximum number of file descriptors the system core processes can open
fs.file-max = 65535

# Adjust TCP connection timeout parameters
net.ipv4.tcp_fin_timeout = 15        # TCP connection close timeout
net.ipv4.tcp_keepalive_time = 1200  # TCP keep-alive time

# Disable sending ICMP redirects to prevent routing deception
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Limit IPv4 fragment processing to prevent fragmentation attacks
net.ipv4.ipfrag_low_thresh = 4096
net.ipv4.ipfrag_high_thresh = 8192
net.ipv4.ipfrag_max_dist = 1024


Apply the configuration

 
sudo sysctl -p


Web Service (e.g., Apache) Hardening

1. Apache Service Security Configuration

Step 1: Install and configure Apache

 
sudo dnf install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd


Step 2: Edit the Apache configuration file

For example, restrict directory listing, disable unnecessary modules, etc. Edit /etc/httpd/conf/httpd.conf

 
Options -Indexes  # Disable directory listing
ServerTokens Prod  # Hide Apache version information
LoadModule userdir_module modules/mod_userdir.so  # Enable or disable modules as needed


Step 3: Configure the firewall to allow HTTP traffic

 
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload


Database Service (e.g., MySQL) Hardening

1. MySQL Service Hardening (Example)

If the server deploys MySQL, perform the following hardening:

 
sudo useradd mysql-secure
sudo mkdir /var/lib/mysql-secure
sudo chown -R mysql-secure:mysql-secure /var/lib/mysql-secure

Step 1: Create a dedicated user and directory


Step 2: Configure the MySQL configuration file

Edit /etc/my.cnf and add security-related configurations:

 
[mysqld]
user = mysql-secure        # Run using a dedicated user
bind-address = 127.0.0.1   # Allow local connections only (if remote access is needed, configure specific IPs)
skip-networking=1          # Disable remote network access; enable with caution if remote access is required
secure_file_priv = /tmp/   # Restrict file import/export paths
innodb_file_per_table = 1  # Independent tablespace for each table


Step 3: Initialize MySQL and set the password

 
sudo mysqld --initialize --user=mysql-secure --basedir=/usr --datadir=/var/lib/mysql-secure
sudo systemctl start mysqld
sudo mysql_secure_installation


Regular Security Scanning and Automation Scripts

1. Customized Security Scanning Scripts

Write automation scripts to regularly perform system updates and vulnerability scans. Example script:

 
#!/bin/bash
# File: security_auto_check.sh
# Function: Automatically update the system, perform vulnerability scans, and log results

# System update
sudo dnf update -y

# Run rkhunter deep scan
sudo dnf install -y rkhunter
sudo rkhunter --update
sudo rkhunter --check --sk  # --sk skips interactive prompts

# Run chkrootkit check
sudo dnf install -y chkrootkit
sudo chkrootkit

# Check SELinux status
selinux_status=$(sudo getenforce)
echo "Current SELinux status: $selinux_status"

# Check firewall rules
echo "Firewall rules list:"
sudo firewall-cmd --list-all

# Log results
log_file="/var/log/security_auto_check_$(date +%Y%m%d).log"
{
echo "==== $(date +%Y-%m-%d %H:%M:%S) ===="
echo "System update result: $?"
echo "rkhunter scan results:"
  sudo rkhunter --report-file stdout
echo "chkrootkit scan results:"
  sudo chkrootkit
echo "SELinux status: $selinux_status"
echo "Firewall rules:"
  sudo firewall-cmd --list-all
} >> $log_file


Grant execution permissions:

 
sudo chmod +x security_auto_check.sh


Execute via cron, for example, at 2:00 AM every day: sudo crontab -e


Add the line:

 
02 * * * /path/to/security_auto_check.sh


SSH Key Authentication Strengthening

1. Configure SSH Key Login and Disable Old Keys

 
ssh-keygen-trsa-b 4096 -C "your_email@example.com"

Step 1: Generate SSH key pairs (execute on the management side)

 
ssh-copy-id restricted_user@server_ip


Step 2: Copy the public key to the target server


Step 3: Disable password authentication and restart the SSH service



Edit /etc/ssh/sshd_config

 
PasswordAuthentication no


System Resource Limits and Process Monitoring

 
sudo systemctl restart sshd

1. Use ulimit to Restrict User Process Resources

Restrict system resources available to users via the /etc/security/limits.conf file, such as limiting the maximum number of processes and open files for the standard user secure_user:

 
sudo vim /etc/security/limits.conf


Add the following content

 
secure_user  hard  nproc  1024   # Max process limit set to 1024
secure_user  hard  nofile 65535  # Max open files limit set to 65535
secure_user  soft  nproc  512    # Soft process limit
secure_user  soft  nofile 32768  # Soft open files limit


Containerized Environment Security Hardening (if containers are deployed)

1. Docker Security Hardening (Example)

Step 1: Configure the Docker daemon

Edit /etc/docker/daemon.json and add security-related configurations:

 
{
"selinux-enabled": true,  # Enable SELinux integration
"userns-remap": "default",  # Enable user namespaces to restrict container access to the host
"live-restore": true,  # Keep containers running if the daemon becomes unavailable
"tls": true,  # Enable TLS encrypted communication
"tlscert": "/etc/docker/tls/server.pem",  # Path to TLS certificate
"tlskey": "/etc/docker/tls/server.key",   # Path to TLS private key
"tlscacert": "/etc/docker/tls/ca.pem"# Path to CA certificate
}


Step 2: Restart the Docker service

 
sudo systemctl restart docker
sudo systemctl enable docker


File System Integrity and Quota Management

1. File System Quota Configuration (Optional)

If you need to limit users' storage space usage on the file system, enable file system quotas:

Step 1: Check if the file system supports quotas

 
sudo xfs_info /dev/sda2 | grep quota

For example, if the root partition is /dev/sda2 and uses the xfs file system, check support status:


Step 2: Enable the quota feature

 
/dev/sda2 /                       xfs     defaults,usrquota,grpquota 00

Edit /etc/fstab and add usrquota,grpquota options to the partition requiring quotas:


Step 3: Mount and initialize quotas

 
sudo mount -o remount /
sudo quotacheck -cvug /  # Initialize user and group quota databases


Step 4: Set user quotas

For example, limit the disk space for user secure_user to 10GB:

 
sudo edquota secure_user

 
/dev/sda2: blocks=10240000


System Service Dependency Check and Cleanup

1. Clean Up Redundant and Unused Service Dependencies

Step 1: Use rpm-ostree (if using CoreOS or similar variants)

 
sudo rpm-ostree prune --keep=0

For systems based on rpm-ostree, clean up redundant packages


Step 2: General system cleanup using yum/dnf

 
sudo dnf autoremove -y

Clean up unused dependency packages


Network Security: IP Masquerading and NAT Restrictions

1. Configure IP Masquerading (NAT) Restrictions

If the server acts as a gateway, configure IP masquerading:

Step 1: Enable kernel IP forwarding

 
net.ipv4.ip_forward = 1

 
sudo sysctl -p

Edit /etc/sysctl.conf and add:


Step 2: Configure firewall NAT rules (using MASQUERADE as an example)

 
sudo iptables -t nat -A POSTROUTING -o enp0s3 -j MASQUERADE  # Replace enp0s3 with the actual external network interface


System Security Baseline Audit Tool Integration

Use cis-anaconda-config to Comply with CIS Benchmarks

Step 1: Install CIS compliance tools

 
sudo dnf install -y cis-anaconda-config


Step 2: Perform a CIS compliance check

 
sudo cis-anaconda-check


Security Extensions for Remote Management Tools

1. Configure Mosh as an Alternative to SSH (Optional)

Step 1: Install Mosh

 
sudo dnf install -y mosh


Step 2: Configure the firewall to allow Mosh ports

Mosh uses UDP ports 60000-61000 by default; open the port range:

 
sudo firewall-cmd --permanent --add-port=60000-61000/udp
sudo firewall-cmd --reload


Regular Review After System Hardening

1. Establish a Regular Review Checklist

Weekly Review:

Check for abnormal modifications to firewall rules

Verify that SSH key login is functioning normally

Check if log cleanup and archiving are normal

Monthly Review:

Run vulnerability scanning tools (ClamAV, rkhunter, etc.)

Check if file system quotas are in effect

Verify the effectiveness of system service dependency cleanup


Final Summary and Continuous Improvement

1. Continuously Optimize Hardening Strategies

Regularly update sysctl.conf, firewall rules, log policies, etc., based on actual system operation

Monitor official CentOS security advisories and update system patches promptly

Gradually implement new security policies and verify their effects during maintenance windows with minimal business impact

Plan Summary

The fourth part of this hardening plan focuses on file system quotas, service dependency cleanup, secure boot, network NAT, CIS compliance, remote tool extensions, and regular reviews to further strengthen the security and compliance of the CentOS 9 system. Actual implementation should be flexibly adjusted according to the specific business environment to ensure the system meets strict security requirements while maintaining stable operation.


Authoritative References