← 返回首页
🛡️

Linux防火墙配置基础

📂 devops ⏱ 2 min 223 words

Linux防火墙配置基础

防火墙概述

防火墙是网络安全的第一道防线,用于控制进出网络的流量。Linux提供了多种防火墙工具。

iptables基础

四表五链

四表:

五链:

基本规则

# 查看规则
iptables -L -n
iptables -L -n -v

# 清除所有规则
iptables -F

# 允许SSH(端口22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许HTTP(端口80)
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# 允许HTTPS(端口443)
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 拒绝其他入站流量
iptables -A INPUT -j DROP

规则管理

# 插入规则到指定位置
iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT

# 删除规则
iptables -D INPUT -p tcp --dport 8080 -j ACCEPT

# 清除计数器
iptables -Z

保存和恢复规则

# Debian/Ubuntu
iptables-save > /etc/iptables/rules.v4
iptables-restore < /etc/iptables/rules.v4

# CentOS/RHEL
service iptables save

firewalld基础

firewalld是CentOS 7+默认的防火墙管理工具,提供了更易用的接口。

基本操作

# 启动/停止/状态
systemctl start firewalld
systemctl stop firewalld
systemctl status firewalld

# 开机自启
systemctl enable firewalld
systemctl disable firewalld

# 查看规则
firewall-cmd --list-all

区域(Zone)

firewalld使用区域来管理不同的信任级别:

区域 说明
drop 丢弃所有流量
block 拒绝所有流量
public 公共网络(默认)
external 外部网络
internal 内部网络
trusted 信任所有流量

端口管理

# 开放端口
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --add-port=8080-8090/tcp --permanent

# 关闭端口
firewall-cmd --remove-port=80/tcp --permanent

# 查看已开放端口
firewall-cmd --list-ports

# 重新加载配置
firewall-cmd --reload

服务管理

# 开放服务
firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent

# 关闭服务
firewall-cmd --remove-service=http --permanent

# 查看已开放服务
firewall-cmd --list-services

# 查看可用服务
firewall-cmd --get-services

端口转发

# 将80端口转发到8080
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080 --permanent
firewall-cmd --reload

实践:配置Web服务器防火墙

#!/bin/bash
# Web服务器防火墙配置脚本

# 允许SSH
firewall-cmd --add-service=ssh --permanent

# 允许HTTP/HTTPS
firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent

# 允许MySQL(仅内部访问)
firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port port="3306" protocol="tcp" accept' --permanent

# 拒绝其他流量(默认行为)
firewall-cmd --reload
firewall-cmd --list-all

总结

防火墙是保护系统安全的重要工具。合理配置防火墙规则,可以有效防止未授权访问,保护系统和数据安全。