缘由
这是一篇 IPTABLES 的实践教程,同时也是安全部署的一部分。大多数服务器服务商可能自带所谓 “防火墙”, 但其原理不透明,可能仅在公网IP交换机侧作了一些功夫,服务器提供者和同一机房的设备也许仍然可通过内部网络进行敏感服务的访问甚至渗透等。若你的服务器部署了一些敏感应用,建议手动部署 IPTABLES 防火墙,必要时确认服务器所关联的块存储(如EBS)的加密状态。这里主要针对内核层的网络安全策略进行展开。
开始实践
以下命令在 Ubuntu 24.04 Linux 6.8.1 测试通过,网络环境为 IPv4 单栈。
第一步:允许远程 SSH 和 ICMP 访问,并阻止其他访问
这里默认的 ssh 端口为 22,使用以下命令允许 ssh 的访问。
# Allow ssh traffic
sudo iptables -t filter -A INPUT -p tcp -m tcp —-dport 2221 -m comment —comment “Allow ssh” -j ACCEPT
# Allow ICMP traffic
sudo iptables -t filter -A INPUT -p icmp -m icmp --icmp-type 8 -m comment —-comment “Allow ICMP” -j ACCEPT
# Drop other traffics
sudo iptables -t filter -P INPUT -m comment —-comment “Drop other traffic” -j DROP
Code language: PHP (php)
第二步:放行本地回环和关联的连接
默认的本地回环接口名为 lo
。
# Allow local-loopback
sudo iptables -t filter -A INPUT -i lo -m comment --comment "Allow loopback" -j ACCEPT
# Allow related traffics
sudo iptables -t filter -A INPUT -m state --state RELATED,ESTABLISHED -m comment —comment “Allow related traffic” -j ACCEPT
Code language: PHP (php)
第三步:放行宿主服务(如 Web)
默认的 HTTP 端口为 80,HTTPS 端口为 443。
# Allow http
sudo iptables -t filter -A INPUT -p tcp -m tcp --dport 80 -m comment --comment "Allow http" -j ACCEPT
# Allow https
sudo iptables -t filter -A INPUT -p tcp -m tcp --dport 443 -m comment --comment "Allow https" -j ACCEPT
Code language: PHP (php)
第四步:放行容器服务(如Docker容器)
默认公网网口名为 eth0, docker 为 docker0。
阻止公网访问 Docker
sudo iptables -t filter -A DOCKER-USER -i eth0 -m comment —-comment “Drop traffic to docker” -j DROP
允许公网访问 Docker 服务
sudo iptables -t filter -A DOCKER-USER -i eth0 -p tcp -m tcp —dport 12345 -j DROP
大功告成
若步骤正确,你的服务器应阻止你所设定的服务外的流量。
Pro Tip
你应定期扫描服务器端口以确保服务未被意外暴露,工具如 rustscan 可显著提升扫描速度。
了解 Starx's Home 的更多信息
订阅后即可通过电子邮件收到最新文章。