Practical Guide to High-Risk Port Control Strategies and Firewall Configuration in Linux

In today’s rapidly accelerating digital transformation, the Linux operating system, as the mainstream OS for servers and edge computing devices, directly impacts the protection of enterprise data assets and user privacy. This guide will present a practical security hardening solution from the core dimensions of security reinforcement, combined with code examples, focusing on two key areas: port control and system patch management.

Practical Guide to High-Risk Port Control Strategies and Firewall Configuration in Linux

1. High-Risk Port Management Strategies

1.1 Analysis of Current Port Security Status

According to statistics from the CVE vulnerability database, over 60% of initial attacks exploit unauthorized open default service ports. Common examples include:

  • Telnet (23): Transmits passwords in plaintext
  • FTP (21/20): Contains a reverse shell vulnerability
  • SSH (22): Weak passwords are easily brute-forced
  • RDP (3389): Vulnerable to blue screen attack vectors

1.2 Firewall Configuration Practices

iptables Configuration Template

# Clear existing rules
sudo iptables -F

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

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

# Open necessary ports (example)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT   # SSH
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT   # HTTP
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT  # HTTPS

# Save rules (CentOS/RHEL)
sudo service iptables save

# Persist configuration (Ubuntu/Debian)
sudo iptables-save > /etc/iptables/rules.v4

firewalld Configuration Example

# Add service rules
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# Open specific ports
sudo firewall-cmd --permanent --add-port=22/tcp

# Reload configuration
sudo firewall-cmd --reload

# Verify rules
sudo firewall-cmd --list-all

1.3 Service Hardening

# SSH Service Hardening (/etc/ssh/sshd_config)
Port 2222                    # Change default port
PermitRootLogin no           # Disable root direct login
PasswordAuthentication no    # Disable password authentication
PubkeyAuthentication yes     # Enable key authentication
ClientAliveInterval 300      # Set session timeout

# Restart service
sudo systemctl restart sshd

2. System Patch Management Standards

2.1 Patch Management Process

  1. 1. Vulnerability Monitoring: Configure automatic scanning tools (e.g., OpenVAS)
  2. 2. Environment Testing: Validate patch compatibility in a pre-release environment
  3. 3. Gray Release: Update production environment nodes in batches
  4. 4. Rollback Plan: Retain snapshots and backup files

2.2 Update Operation Practices

Debian/Ubuntu Systems

# Update source list
sudo apt update

# Perform security upgrade
sudo apt upgrade -y --with-new-pkgs

# Clean old kernels
sudo apt autoremove --purge

RHEL/CentOS Systems

# Check for available updates
sudo yum check-update

# Install security patches
sudo yum update -y --security

# Clean cache
sudo yum clean all

2.3 Automatic Update Configuration

# Debian/Ubuntu Automatic Updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# RHEL/CentOS Automatic Updates
sudo yum install yum-cron
sudo systemctl enable yum-cron
sudo systemctl start yum-cron

3. Deep Defense Hardening Measures

3.1 File System Hardening

# Set global umask
echo "umask 027" >> /etc/profile
source /etc/profile

# Protect critical files
sudo chattr +i /etc/passwd
sudo chattr +i /etc/shadow
sudo chattr +i /etc/group

3.2 Log Audit Enhancement

# Configure rsyslog
sudo nano /etc/rsyslog.conf
# Add the following line
*.* @logserver.example.com:514  # Forward logs to centralized server

# Install auditd auditing tool
sudo apt install auditd
sudo service auditd start
sudo auditctl -w /etc/passwd -p war -k passwd_change

3.3 Intrusion Prevention Configuration

# Install fail2ban
sudo apt install fail2ban

# Configure SSH protection rules (/etc/fail2ban/jail.local)
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400

4. Emergency Response Plan

4.1 Port Intrusion Response Process

  1. 1. Isolate the compromised host:
    sudo iptables -A INPUT -s 192.168.1.100 -j DROP
  2. 2. Process Analysis:
    ps auxf | grep suspicious_process
  3. 3. File Verification:
    rpm -Vf /path/to/critical_file

4.2 Patch Rollback Plan

  1. 1. Create a system snapshot:
    sudo timeshift --create --comments "Pre-patch snapshot"
  2. 2. Restore critical files:
    sudo cp /backup/etc_passwd.bak /etc/passwd

5. Security Hardening Verification Checklist

Check Item Verification Command Expected Result
SSH Port Modification <span>netstat -tuln | grep 22</span> Shows port 2222 listening
Firewall Status <span>sudo ufw status</span> Active status
System Update Status <span>sudo apt list --upgradable</span> No packages to update
Critical File Permissions <span>ls -l /etc/passwd</span> Permissions 644, owner root
Automatic Update Configuration <span>sudo systemctl status yum-cron</span> Active (running) status

6. File System Security Hardening

The file system is the foundational structure for data storage in the operating system, and its security directly relates to the overall protective capability of the system. This chapter will explore three aspects: permission control, file protection, and sensitive information encryption.

6.1 Fine-Grained Permission Management

Implementation Principle: Follow the principle of least privilege, ensuring that each user/process has only the minimum set of permissions necessary to complete their tasks.

Operational Practices:

# View file permissions
ls -l /etc/passwd

# Modify file permissions (example: restrict access to sensitive files)
sudo chmod 644 /etc/passwd       # Owner read/write, group and others read-only
sudo chmod 400 /etc/shadow       # Owner read-only

# Recursively modify directory permissions
sudo chmod -R 750 /var/log       # Owner read/write/execute, group read/execute, others no permissions

# Set special permission bits
sudo chattr +i /etc/passwd       # Immutable attribute
sudo chattr +a /var/log/audit/audit.log  # Append-only content

Permission Audit Tools:

  • <span>auditd</span>: Monitors access to critical files
  • <span>tiger</span>: File system permission scanning tool

6.2 Protection of Critical Files

Protected Objects:

  • • Password Files: <span>/etc/passwd</span>, <span>/etc/shadow</span>
  • • System Configurations: <span>/etc/sudoers</span>, <span>/etc/fstab</span>
  • • Log Files: <span>/var/log/auth.log</span>, <span>/var/log/syslog</span>

Protection Measures:

  1. 1. Attribute Hardening:
    sudo chattr +i /etc/sudoers    # Prevent accidental modification
  2. 2. Access Control Lists (ACL):
    setfacl -m u:www-data:r-- /etc/nginx/nginx.conf
  3. 3. File Integrity Verification:
    # Generate checksum
    sudo sha256sum /etc/passwd > file_checksums.txt
    
    # Periodic verification
    sha256sum -c file_checksums.txt

7. Log Auditing and Monitoring

Comprehensive log auditing is a core capability for responding to security incidents. This chapter will introduce the deployment of auditing systems, log analysis techniques, and the construction of alert mechanisms.

7.1 Auditing System Deployment

auditd Configuration:

# Install auditd
sudo apt install auditd -y

# Start service
sudo systemctl enable --now auditd

# Add audit rules
echo "-w /etc/passwd -p war -k passwd_changes" >> /etc/audit/rules.d/audit.rules
sudo systemctl restart auditd

Key Audit Points:

  • • User login/logout events
  • • File modification operations (especially sensitive files)
  • • Privilege escalation attempts
  • • Abnormal network connections

7.2 Log Analysis Techniques

Toolchain:

  • ELK Stack: Centralized log analysis platform
  • Splunk: Enterprise-level log analysis solution
  • Logwatch: Lightweight log reporting tool

Practical Analysis:

# Generate login report using aureport
sudo aureport --login -i

# Search for specific audit events
sudo ausearch -k passwd_changes --raw | aureport -f

# Configure Logwatch email alerts
sudo nano /etc/cron.daily/00logwatch
# Add the following content
/usr/sbin/logwatch --output mail --mailto [email protected] --detail high

7.3 Real-Time Monitoring Alerts

Alert Mechanism Construction:

  1. 1. Threshold Alerts:
    # Use fail2ban to monitor SSH brute force
    sudo nano /etc/fail2ban/jail.local
    [sshd]
    enabled = true
    maxretry = 3
    bantime = 3600
  2. 2. Anomaly Behavior Alerts:
    # Use auditd to monitor access to sensitive files
    sudo auditctl -w /etc/sudoers -p war -k sudoers_access
    sudo aureport -k sudoers_access --interpret

8. Intrusion Prevention System Construction

The Intrusion Prevention System (IPS) is an important component of the proactive defense system. This chapter will introduce the deployment of an IPS based on Snort and optimization of defense strategies.

8.1 Snort Intrusion Detection System

Deployment Steps:

  1. 1. Install Snort:
    sudo apt install snort
  2. 2. Configure Rule Set:
    # Download community rules
    sudo cp /etc/snort/snort.conf /etc/snort/snort.conf.bak
    sudo wget https://www.snort.org/rules/community -O /etc/snort/rules/community.rules
  3. 3. Start Service:
    sudo systemctl enable --now snort

Rule Optimization Suggestions:

  • • Regularly update the official rule set
  • • Customize private rules based on business scenarios
  • • Use pulledpork for automated rule management

8.2 Coordinated Defense Mechanism

Firewall Coordination:

# Use iptables to block malicious IPs
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
sudo iptables-save > /etc/iptables/rules.v4

Automated Response:

  • • Configure Snort to work with firewalld
  • • Integrate into SIEM systems for event closure processing

9. Security Hardening Verification and Continuous Optimization

Security hardening is not a one-time project; it requires establishing a continuous verification mechanism. This chapter will introduce methods for verifying hardening effectiveness and strategies for continuous optimization.

9.1 Verification of Hardening Effectiveness

Pentest:

  • • Use Metasploit for vulnerability verification
  • • Conduct port scanning with Nmap
  • • Implement social engineering tests

Compliance Checks:

  • • Use OpenSCAP for security configuration audits
  • • Regularly generate CIS benchmark reports

9.2 Continuous Optimization Strategies

Threat Intelligence Driven:

  • • Subscribe to threat intelligence from security vendors
  • • Establish an internal threat intelligence repository

Tracking Technological Evolution:

  • • Monitor CVE vulnerability disclosures
  • • Timely update protection strategies

Building a Security Culture:

  • • Conduct regular security training
  • • Establish a vulnerability reward program

Through the in-depth practice of the above nine topics, your Linux system will build a multi-layered security protection system that includes port control, patch management, file protection, log auditing, and intrusion prevention. It is recommended to conduct security configuration audits quarterly and penetration tests semi-annually, continuously improving protection strategies. Security construction has no endpoint; only an evolving protective system can cope with increasingly complex network threats.

Please open in the WeChat client

# Practical Guide to Linux System Security Hardening (Continued)

In the previous guide, we discussed several key areas of Linux system security hardening, including high-risk port management and system patch updates. This section will continue to delve deeper, focusing on file system hardening, log audit enhancement, and intrusion prevention configuration, helping you build a multi-layered defense system.

## 6. File System Security Hardening

The file system is the foundational structure for data storage in the operating system, and its security directly relates to the overall protective capability of the system. This chapter will explore three aspects: permission control, file protection, and sensitive information encryption.

### 6.1 Fine-Grained Permission Management

**Implementation Principle**: Follow the principle of least privilege, ensuring that each user/process has only the minimum set of permissions necessary to complete their tasks.

**Operational Practices**:

“`bash

# View file permissions

ls -l /etc/passwd

# Modify file permissions (example: restrict access to sensitive files)

sudo chmod 644 /etc/passwd # Owner read/write, group and others read-only

sudo chmod 400 /etc/shadow # Owner read-only

# Recursively modify directory permissions

sudo chmod -R 750 /var/log # Owner read/write/execute, group read/execute, others no permissions

# Set special permission bits

sudo chattr +i /etc/passwd # Immutable attribute

sudo chattr +a /var/log/audit/audit.log # Append-only content

“`

**Permission Audit Tools**:

– `auditd`: Monitors access to critical files

– `tiger`: File system permission scanning tool

### 6.2 Protection of Critical Files

**Protected Objects**:

– Password Files: `<span>/etc/passwd</span>, <span>/etc/shadow</span>

– System Configurations: `<span>/etc/sudoers</span>, <span>/etc/fstab</span>

– Log Files: `<span>/var/log/auth.log</span>, <span>/var/log/syslog</span>

**Protection Measures**:

1. **Attribute Hardening**:

“`bash

sudo chattr +i /etc/sudoers # Prevent accidental modification

“`

2. **Access Control Lists (ACL)**:

“`bash

setfacl -m u:www-data:r– /etc/nginx/nginx.conf

“`

3. **File Integrity Verification**:

“`bash

# Generate checksum

sudo sha256sum /etc/passwd > file_checksums.txt

# Periodic verification

sha256sum -c file_checksums.txt

“`

## 7. Log Auditing and Monitoring

Comprehensive log auditing is a core capability for responding to security incidents. This chapter will introduce the deployment of auditing systems, log analysis techniques, and the construction of alert mechanisms.

### 7.1 Auditing System Deployment

**auditd Configuration**:

“`bash

# Install auditd

sudo apt install auditd -y

# Start service

sudo systemctl enable –now auditd

# Add audit rules

echo “-w /etc/passwd -p war -k passwd_changes” >> /etc/audit/rules.d/audit.rules

sudo systemctl restart auditd

“`

**Key Audit Points**:

– User login/logout events

– File modification operations (especially sensitive files)

– Privilege escalation attempts

– Abnormal network connections

### 7.2 Log Analysis Techniques

**Toolchain**:

– **ELK Stack**: Centralized log analysis platform

– **Splunk**: Enterprise-level log analysis solution

– **Logwatch**: Lightweight log reporting tool

**Practical Analysis**:

“`bash

# Generate login report using aureport

sudo aureport –login -i

# Search for specific audit events

sudo ausearch -k passwd_changes –raw | aureport -f

# Configure Logwatch email alerts

sudo nano /etc/cron.daily/00logwatch

# Add the following content

/usr/sbin/logwatch –output mail –mailto [email protected] –detail high

“`

### 7.3 Real-Time Monitoring Alerts

**Alert Mechanism Construction**:

1. **Threshold Alerts**:

“`bash

# Use fail2ban to monitor SSH brute force

sudo nano /etc/fail2ban/jail.local

[sshd]

enabled = true

maxretry = 3

bantime = 3600

“`

2. **Anomaly Behavior Alerts**:

“`bash

# Use auditd to monitor access to sensitive files

sudo auditctl -w /etc/sudoers -p war -k sudoers_access

sudo aureport -k sudoers_access –interpret

“`

## 8. Intrusion Prevention System Construction

The Intrusion Prevention System (IPS) is an important component of the proactive defense system. This chapter will introduce the deployment of an IPS based on Snort and optimization of defense strategies.

### 8.1 Snort Intrusion Detection System

**Deployment Steps**:

1. **Install Snort**:

“`bash

sudo apt install snort

“`

2. **Configure Rule Set**:

“`bash

# Download community rules

sudo cp /etc/snort/snort.conf /etc/snort/snort.conf.bak

sudo wget https://www.snort.org/rules/community -O /etc/snort/rules/community.rules

“`

3. **Start Service**:

“`bash

sudo systemctl enable –now snort

“`

**Rule Optimization Suggestions**:

– Regularly update the official rule set

– Customize private rules based on business scenarios

– Use pulledpork for automated rule management

### 8.2 Coordinated Defense Mechanism

**Firewall Coordination**:

“`bash

# Use iptables to block malicious IPs

sudo iptables -A INPUT -s 192.168.1.100 -j DROP

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

“`

**Automated Response**:

– Configure Snort to work with firewalld

– Integrate into SIEM systems for event closure processing

## 9. Security Hardening Verification and Continuous Optimization

Security hardening is not a one-time project; it requires establishing a continuous verification mechanism. This chapter will introduce methods for verifying hardening effectiveness and strategies for continuous optimization.

### 9.1 Verification of Hardening Effectiveness

**Pentest**:

– Use Metasploit for vulnerability verification

– Conduct port scanning with Nmap

– Implement social engineering tests

**Compliance Checks**:

– Use OpenSCAP for security configuration audits

– Regularly generate CIS benchmark reports

### 9.2 Continuous Optimization Strategies

**Threat Intelligence Driven**:

– Subscribe to threat intelligence from security vendors

– Establish an internal threat intelligence repository

**Tracking Technological Evolution**:

– Monitor CVE vulnerability disclosures

– Timely update protection strategies

**Building a Security Culture**:

– Conduct regular security training

– Establish a vulnerability reward program

Through the in-depth practice of the above nine topics, your Linux system will build a multi-layered security protection system that includes port control, patch management, file protection, log auditing, and intrusion prevention. It is recommended to conduct security configuration audits quarterly and penetration tests semi-annually, continuously improving protection strategies. Security construction has no endpoint; only an evolving protective system can cope with increasingly complex network threats.

Leave a Comment