在 Linux 系统中,端口加固(Port Hardening)是保障系统安全的重要措施之一。以下是一些常见的端口加固方法和 Linux 命令,用于增强系统对网络端口的防护:
一、常见端口加固方法
1. 关闭不必要的端口
- 使用
netstat或ss查看监听端口:sudo netstat -tuln | grep :<port> - 关闭不必要的端口(如 22、80、443 等):
sudo systemctl stop ssh sudo systemctl disable ssh sudo systemctl stop apache2 sudo systemctl disable apache2
2. 限制端口的访问
- 使用
iptables或nft策略限制访问:sudo iptables -A INPUT -p tcp --dport <port> -s <ip> -j DROP - 保存策略:
sudo service iptables save
3. 使用 ufw(Ubuntu/Debian)或 firewalld(CentOS/RHEL)
- 安装并启用
ufw:sudo apt install ufw -y sudo ufw enable sudo ufw default deny sudo ufw allow 22/tcp - 保存策略:
sudo ufw save sudo ufw reload
4. 使用 sshd_config 限制 SSH 端口
- 修改
/etc/ssh/sshd_config,将Port设置为一个非默认端口(如 2222):sudo nano /etc/ssh/sshd_config - 重启 SSH 服务:
sudo systemctl restart ssh
5. 使用 telnet 或 nc 限制连接
- 限制使用
telnet或nc连接的 IP:sudo iptables -A INPUT -p tcp --dport 23 -s <ip> -j DROP
二、使用 iptables 或 nft 配置防火墙
示例:使用 iptables 防止特定 IP 访问特定端口
sudo iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j DROP
sudo iptables -A INPUT -p tcp --dport 80 -s 192.168.1.100 -j DROP
示例:使用 nft(适用于较新的 Linux 发行版)
sudo nft add rule ip filter input tcp dport 22 reject
sudo nft add rule ip filter input tcp dport 80 reject
三、使用 firewalld 配置防火墙
安装和启用 firewalld:
sudo apt install firewalld -y
sudo systemctl enable firewalld
sudo systemctl start firewalld
配置策略:
sudo firewall-cmd --permanent --add-port=22/tcp
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload
四、使用 sshd_config 配置 SSH
sudo nano /etc/ssh/sshd_config
- 设置
Port 2222(或其他非默认端口) - 重启 SSH:
sudo systemctl restart ssh
五、使用 systemd 管理服务
确保只允许必要的服务运行:
sudo systemctl enable ssh
sudo systemctl disable apache2
sudo systemctl disable nginx
六、使用 auditd 监控端口访问
sudo auditctl -w /var/log/secure -p 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 -a always,exit -F path=/var/log/secure
七、使用 netstat 检查端口监听状态
sudo netstat -tuln | grep :<port>
八、使用 ss 替代 netstat(更高效)
sudo ss -tuln | grep :<port>
总结
| 方法 | 工具 | 适用系统 | 说明 |
|---|---|---|---|
| 关闭端口 | systemctl / ufw |
Ubuntu, Debian, CentOS | 关闭不必要端口 |
| 防止访问 | iptables / nft |
Linux 系统 | 限制特定 IP 或端口 |
使用 sshd_config |
sshd_config |
Linux | 配置 SSH 端口 |
使用 firewalld |
firewalld |
CentOS, RHEL | 配置防火墙策略 |
如需进一步定制或自动化脚本,请告诉我你的具体需求(如:自动化防火墙规则、日志监控等)。
