防火墙
- 防火墙分类
- iptables的表和链
- iptables的filter表
- iptables的nat表
- iptables配置文件
- firewallld服务
防火墙分类
- 软件防火墙和硬件防火墙
- 包过滤防火墙和应用层防火墙
- CentOS 6 默认的防火墙是iptables
- CentOS 7 默认的防火墙是firewalld(底层使用netfilter)
iptables的表和链
- 规则表(iptables的功能)
- filter nat mangle raw(四个表)
- 规则链
- INPUT OUTPUT FORWARD(客户断访问到服务器时,用INPUT规则链;服务器向客户端发数据,用OUTPUT规则链;FORWARD 转发)
- PREROUTING(路由前转换,改变目标地址) POSTROUTING(路由后转换,改变源地址)
iptables 规则表的基本使用
iptables的filter表
- iptables -t filter 命令 规则链 规则(filter是声明,要做数据包过滤这件事;命令表示这件事具体要做什么;规则链表示具体要过滤的规则,是从进入去过滤还是从出去去过滤;规则就是具体要干什么事了,比如进来的数据,限制哪个IP哪个端口哪个协议。。)
- 命令
- -L
- -A -l
- -D -F -P
- -N -X -E
// 查看规则
iptables -t filter -L
// 添加规则,允许10.0.0.1进入
iptables -t filter -A INPUT -s 10.0.0.1 -j ACCEPT
// -L 如果ip有对应的域名,显示域名
// -n 有IP直接显示IP,不解析域名(速度快)
// -v 比不加v显示更详细的信息
iptables -t filter -nvL
// 如果使用的filter表,filter是可以省略的
iptables -L
// 查看nat表
iptables -t nat -vnL
man iptables
iptables 过滤规则的使用
// 添加规则的命令
// -A 在已有的规则后面添加
// -I 在第一条去进行添加
// 允许10.0.0.2
iptables -t filter -A INPUT -s 10.0.0.2 -j ACCEPT
iptables -vnL
// 丢弃10.0.0.2
iptables -t filter -A INPUT -s 10.0.0.2 -j DROP
// 上面的配置,数据包是能够进来的,匹配到第一条ACCEPT时,数据包已经进入到系统中了,DROP就不生效(顺序决定了数据包是否能进入系统)
iptablels -vnL
// -I 插入到第一条
iptables -I INPUT -s 10.0.0.3 -j DROP
iptables -vnL
// policy 默认规则,如果所有的都没匹配,执行默认规则
Chain INPUT(policy ACCEPT 0 packets, 0 bytes)
// 把默认规则改成DROP
iptables -P INPUT DROP
// 把默认规则改成ACCEPT
iptables -P INPUT ACCEPT
// -F 清除添加的规则(不会修改默认规则ACCEPT/DROP)
iptables -F
// -D 只删除某一条规则
// -N 添加自定义规则链
// -X 删除自定义规则链
// -E 重命名自定义规则
// 控制某一段IP -s 源IP -d 目的IP
iptables -A INPUT -s 10.0.0.0/24 -j ACCEPT
// in out 网络接口卡 -i eth0 -o eth0
// -p 用来指定协议 -p tcp --dport 80
// 使用示例,除了一个外其他都禁止
iptables -t filter -A INPUT -i eth0 -s 10.0.0.2 -p tcp --dport 80 -j ACCEPT
iptables -t filter -A INPUT -j DROP
iptables nat表的使用
- iptables -t nat 命令 规则链 规则
- PREROUTING 目的地址转换
- POSTROUTING 源地址转换
// 目的地址转换。希望用户把我这台机器当服务器,我再把数据包转运给真正的服务器
iptables -t nat -A PREROUTING -i eth0 -d 114.11.11.11 -p tcp --dport 80 -j DNAT --to-destination 10.0.0.1
// 源地址转换。内网的所有请求都会被伪装成111.1122.113.114发到外网去
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth1 -j SNAT --to-source 111.112.113.114
iptables的配置文件
- /etc/sysconfig/iptables
- CentOS 6
- service iptables save|start|stop|restart
- CentOS 7
- yum install iptables-services
平常我们配的规则是保存在内存里面的,重启机器就会失效。为了长久生效,可以把它保存在内存。
firewalld
- firewalld 的特点
- 支持区域"zone"概念
- firewall-cmd
- systemctl start|stop|enable|disable firewalld.service
# 查看所有内容,服务/端口
firewall-cmd --list-all
firewall-cmd --list-interfaces
firewall-cmd --list-ports
firewall-cmd --list-services
firewall-cmd --get-zones
# 添加服务
firewall-cmd --add-service=https
# 添加端口
firewall-cmd --add-port=81/tcp
# --permanent 永久生效
firewall-cmd --add-port=82/tcp --permanent
# 添加的永久规则,--reload才能生效
firewall-cmd --reload
firewall-cmd --remove-source=10.0.0.1