【Linux】iptables 之防火墙的应用及案例、策略、备份与还原(2)
一、案例——基于 IP 和端口的防火墙控制

实验环境:为网关、Web 服务器配置防火墙规则需求描述:1、为网站服务器编写入站规则 (1)允许接受响应本机 ping 测试请求的各种 ICMP 数据包 (2)允许访问本机中位于 80 端口的 Web 服务,禁止访问其他端口的 TCP 请求 (3)允许发往本机以建立连接或与已有连接相关的各种 TCP 数据包 (4)禁止其他任何形式的入站访问数据
搭建实验环境,结果如下:





为网站服务器编写入站规则允许接受响应本机 ping 测试请求的各种 ICMP 数据包


禁止其他任何形式的入站访问数据

内网服务器 ping 网关测试:

网关 ping 内网服务器测试:

允许访问本机中位于 80 端口的 Web 服务,禁止访问其他端口的 TCP 请求

允许发往本机以建立连接或与已有连接相关的各种 TCP 数据包

保存 iptables 设置


测试






2、为网关服务器编写转发规则 (1)允许局域网中的主机访问 Internet 中是 Web、FTP、DNS、邮件服务 (2)禁止局域网中的主机访问 web.qq.com、w.qq.com、im.qq.com 等网站,以防止通过 WebQQ 的方式进行在线聊天
允许局域网中的主机访问 Internet 中是 Web、FTP、DNS、邮件服务

禁止局域网中的主机访问 web.qq.com、w.qq.com、im.qq.com 等网站




保存 iptables 规则配置

二、SNAT 策略
1、作用
作用:局域网主机共享单个公网 IP 地址接入 Internet
2、SNAT 策略的原理
源地址转换,Source Network Address Translation 修改数据包的源地址

3、企业共享上网案例

前提条件: 局域网各主机正确设置 IP 地址/子网掩码 局域网各主机正确设置默认网关地址 Linux 网关支持 IP 路由转发



3.1、固定的外网 IP 地址






3.2、非固定外网 IP 地址或 ADSL

三、DNAT 策略
1、DNAT 原理
在 Internet 环境中,通过网关服务器中正确设置 DNAT 策略可实现企业所注册的网站或域名必须对应公网 IP 地址。

前提条件 局域网的 Web 服务器能够访问 Internet 网关的外网 IP 地址有正确的 DNS 解析记录 Linux 网关支持 IP 路由转发
1.1、DNAT 转发规则 1:发内网 Web 服务




1.2、DNAT 转换规则 2:发布时修改目标端口





四、iptables 防火墙规则的备份与还原
设置完防火墙规则后,可备份规则到文件中,以便日后进行还原,或以备份规则为依据编写防火墙脚本
> 为导出 iptables-save< 为导入 iptables-restore
1、导出(备份)防火墙规则
语法格式:
实例:

2、导入(还原)防火墙规则
语法格式:
实例:
查看规则,现在是空的:

导入规则:

重定向出的文件也可以是任意自定义的文件,若将规则保存到/etc/sysconfig/iptables 中,iptables 启动时自动还原规则。
五、企业防火墙脚本编程与规范【附加】
1、“网关型”防火墙脚本
好的防火墙脚本要包括以下部分:
定义基本变量,便于脚本的维护、重用
加载必要的内核模块,将频繁用到的模块载入到内核
调整/proc 参数,Linux 内核控制及调优
具体的防火墙规则,按表、链分别设置规则,包括默认策略
1.1、定义基本变量便于脚本的维护、重用
1.2、加载必要的内核模块将频繁用到的模块载入内核
……MOD ip_conntrackMOD ipt_LOGMOD xt_tcpudpMOD xt_multiport$MOD xt_macMOD ip_conntrack_ftp 支持 FTP 访问的连接状态跟踪
1.3、调整/proc 参数 Linux 内核控制及调优
1.4、具体的防火墙规则
按表、链分别设置规则,包括默认策略
清空原有规则:$IPT -t filter -X 删除 filter 表内的用户自定义的链IPT -t filter -F$IPT -t nat -F
设置默认策略:IPT -p FORWARD DROP$IPT -P OUTPUT ACCEPT
其他具体规则:IPT -t nat -A POSTROUTING -s INET_IF -j SNAT --to-source IPT -t nat -A PREROUTING -i INET_IP -p tcp --dport 80 -j DNAT --to-destination$LAN_WWW_IP
1.5、实例:




2、“主机型”防火墙脚本
将 OUTPUT 链的默认策略设为允许,不添加其他规则
将 INPUT 链的默认策略设为拒绝,只放行对 Web 服务的访问,以及响应本机访问请求的数据包
2.1、定义基本变量
IPT=”/sbin/iptables”……
2.2、调整/proc 参数
……
2.3、设置具体的防火墙规则
1>删除自定义的链、清空已有规则IPT -t filter -F
2>定义默认策略IPT -p FORWARD DROP$IPT -P OUTPUT ACCEPT
3>设置 filter 表中的各种规则IPT -A INPUT -m state --state ESTABLISHED,RELATED,NEW -j ACCEPT
2.4、实例:





版权声明: 本文为 InfoQ 作者【A-刘晨阳】的原创文章。
原文链接:【http://xie.infoq.cn/article/7c33c974dd7fdaee83d4619ac】。未经作者许可,禁止转载。
评论