iptables

 

#/sbin/iptables -I INPUT -p tcp –dport 80 -j ACCEPT
#/sbin/iptables -I INPUT -p tcp –dport 22 -j ACCEPT
#/etc/rc.d/init.d/iptables save

 

 1、绑定网关IP的mac地址。
arp -s 192.168.1.1 A8:15:4D:BA:C4:B2 (主路由的mac地址)
以上保存为启动命令

2、设定防火墙规则
iptables -A INPUT -s ! 192.168.1.1  -j DROP
iptables -A FORWARD -s  192.168.1.1 -j DROP
并将TTL设了一下,防止ISP通过TTL检测做坏事
iptables -t mangle -A FORWARD -j TTL –ttl-inc 1
把以上保存为防火墙命令

DD-WRT的启动命令上
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
echo 1 > /proc/sys/net/ipv4/ip_forward

echo 10 > /proc/sys/net/ipv4/icmp_ratelimit

 

 

iptables简介
netfilter/iptables(简称为iptables)组成Linux平台下的包过滤防火墙,与大多数的Linux软件一样,这个包过滤防火墙是免费的,它可以代替昂贵的商业防火墙解决方案,完成封包过滤、封包重定向和网络地址转换(NAT)等功能。

iptables基础
规则(rules)其实就是网络管理员预定义的条件,规则一般的定义为“如果数据包头符合这样的条件,就这样处理这个 数据包”。规则存储在内核空间的信息包过滤表中,这些规则分别指定了源地址、目的地址、传输协议(如TCP、UDP、ICMP)和服务类型(如HTTP、 FTP和SMTP)等。当数据包与规则匹配时,iptables就根据规则所定义的方法来处理这些数据包,如放行(accept)、拒绝(reject)和丢弃(drop)等。配置防火墙的主要工作就是添加、修改和删除这些规则。
链 (chains)是数据包传播的路径,每一条链其实就是众多规则中的一个检查清单,每一条链中可以有一条或数条规则。当一个数据包到达一个链 时,iptables就会从链中第一条规则开始检查,看该数据包是否满足规则所定义的条件。如果满足,系统就会根据该条规则所定义的方法处理该数据包;否 则iptables将继续检查下一条规则,如果该数据包不符合链中任一条规则,iptables就会根据该链预先定义的默认策略来处理数据包。
表(tables)提供特定的功能,iptables内置了4个表,即filter表、nat表、mangle表和raw表,分别用于实现包过滤,网络地址转换、包重构(修改)和数据跟踪处理。

Iptables表、链、规则(图3)
iptables_第1张图片

iptables传输数据包的过程
① 当一个数据包进入网卡时,它首先进入PREROUTING链,内核根据数据包目的IP判断是否需要转送出去。
② 如果数据包就是进入本机的,它就会沿着图向下移动,到达INPUT链。数据包到了INPUT链后,任何进程都会收到它。本机上运行的程序可以发送数据包,这些数据包会经过OUTPUT链,然后到达POSTROUTING链输出。
③ 如果数据包是要转发出去的,且内核允许转发,数据包就会如图所示向右移动,经过FORWARD链,然后到达POSTROUTING链输出。(图4)
iptables_第2张图片

iptables命令格式

iptables的命令格式较为复杂,一般的格式如下:
iptables [-t table] 命令 [chain] [rules] [-j target]
table——指定表明
命令——对链的操作命令
chain——链名
rules——规则
target——动作如何进行
1.表选项
表选项用于指定命令应用于哪个iptables内置表,iptables内置包括filter表、nat表、mangle表和raw表。
2.命令选项iptables命令格式

命令 说明
-P或–policy <链名> 定义默认策略
-L或–list <链名> 查看iptables规则列表
-A或—append <链名> 在规则列表的最后增加1条规则
-I或–insert <链名> 在指定的位置插入1条规则
-D或–delete <链名> 从规则列表中删除1条规则
-R或–replace <链名> 替换规则列表中的某条规则
-F或–flush <链名> 删除表中所有规则
-Z或–zero <链名> 将表中数据包计数器和流量计数器归零

3.匹配选项
匹配 说明
-i或–in-interface <网络接口名> 指定数据包从哪个网络接口进入,如ppp0、eth0和eth1等
-o或–out-interface <网络接口名> 指定数据包从哪块网络接口输出,如ppp0、eth0和eth1等
-p或—proto协议类型 < 协议类型> 指定数据包匹配的协议,如TCP、UDP和ICMP等
-s或–source <源地址或子网> 指定数据包匹配的源地址
–sport <源端口号> 指定数据包匹配的源端口号,可以使用“起始端口号:结束端口号”的格式指定一个范围的端口
-d或–destination <目标地址或子网> 指定数据包匹配的目标地址
–dport目标端口号 指定数据包匹配的目标端口号,可以使用“起始端口号:结束端口号”的格式指定一个范围的端口

4.动作选项
动作 说明
ACCEPT 接受数据包
DROP 丢弃数据包
REDIRECT 与DROP基本一样,区别在于它除了阻塞包之外, 还向发送者返回错误信息。
SNAT 源地址转换,即改变数据包的源地址
DNAT 目标地址转换,即改变数据包的目的地址
MASQUERADE IP伪装,即是常说的NAT技术,MASQUERADE只能用于ADSL等拨号上网的IP伪装,也就是主机的IP是由ISP分配动态的;如果主机的IP地址是静态固定的,就要使用SNAT
LOG 日志功能,将符合规则的数据包的相关信息记录在日志中,以便管理员的分析和排错

iptables命令格式(图5)
iptables_第3张图片

iptables过滤条件(图6)
iptables_第4张图片

iptables的语法

1.定义默认策略
当数据包不符合链中任一条规则时,iptables将根据该链预先定义的默认策略来处理数据包,默认策略的定义格式如下。
iptables [-t表名] <-P> <链名> <动作> ?参数说明如下。
[-t表名]:指默认策略将应用于哪个表,可以使用filter、nat和mangle,如果没有指定使用哪个表,iptables就默认使用filter表。
<-P>:定义默认策略。
<链名>:指默认策略将应用于哪个链,可以使用INPUT、OUTPUT、FORWARD、PREROUTING、OUTPUT和POSTROUTING。
<动作>:处理数据包的动作,可以使用ACCEPT(接受数据包)和DROP(丢弃数据包)。

2.查看iptables规则
查看iptables规则的命令格式为:
iptables [-t表名] <-L> [链名]
参数说明如下。
[-t表名]:指查看哪个表的规则列表,表名用可以使用filter、nat和mangle,如果没有指定使用哪个表,iptables就默认查看filter表的规则列表。
<-L>:查看指定表和指定链的规则列表。
[链名]:指查看指定表中哪个链的规则列表,可以使用INPUT、OUTPUT、FORWARD、PREROUTING、OUTPUT和POSTROUTING,如果不指明哪个链,则将查看某个表中所有链的规则列表。

3.增加、插入、删除和替换规则
相关规则定义的格式为:
iptables [-t表名] <-A | I | D | R> 链名 [规则编号] [-i | o 网卡名称] [-p 协议类型] [-s 源IP地址 | 源子网] [--sport 源端口号] [-d目标IP地址 | 目标子网] [--dport目标端口号] <-j动作>
参数说明如下。
[-t表名]:定义默认策略将应用于哪个表,可以使用filter、nat和mangle,如果没有指定使用哪个表,iptables就默认使用filter表。
-A:新增加一条规则,该规则将会增加到规则列表的最后一行,该参数不能使用规则编号。
-I:插入一条规则,原本该位置上的规则将会往后顺序移动,如果没有指定规则编号,则在第一条规则前插入。
-D:从规则列表中删除一条规则,可以输入完整规则,或直接指定规则编号加以删除。
-R:替换某条规则,规则被替换并不会改变顺序,必须要指定替换的规则编号。
<链名>:指定查看指定表中哪个链的规则列表,可以使用INPUT、OUTPUT、FORWARD、PREROUTING、OUTPUT和POSTROUTING。
[规则编号]:规则编号用于插入、删除和替换规则时用,编号是按照规则列表的顺序排列,规则列表中第一条规则的编号为1。
[-i | o 网卡名称]:i是指定数据包从哪块网卡进入,o是指定数据包从哪块网卡输出。网卡名称可以使用ppp0、eth0和eth1等。
[-p 协议类型]:可以指定规则应用的协议,包含TCP、UDP和ICMP等。
[-s 源IP地址 | 源子网]:源主机的IP地址或子网地址。
[--sport 源端口号]:数据包的IP的源端口号。
[-d目标IP地址 | 目标子网]:目标主机的IP地址或子网地址。
[--dport目标端口号]:数据包的IP的目标端口号。
<-j动作>:处理数据包的动作,各个动作的详细说明可以参考前面的说明。

4.清除规则和计数器
在新建规则时,往往需要清除原有的、旧的规则,以免它们影 ?响新设定的规则。如果规则比较多,一条条删除就会十分麻烦, ?这时可以使用iptables提供的清除规则参数达到快速删除所有的规 ?则的目的。
定义参数的格式为:
iptables [-t表名] <-F | Z>
参数说明如下。
[-t表名]:指定默认策略将应用于哪个表,可以使用filter、nat和mangle,如果没有指定使用哪个表,iptables就默认使用filter表。
-F:删除指定表中所有规则。
-Z:将指定表中的数据包计数器和流量计数器归零。

NAT的定义
NAT英文全称是Network Address Translation,称是网络地址转换,它是一个IETF标准,允许一个机构以一个地址出现在Internet上。NAT将每个局域网节点的地址转换 成一个IP地址,反之亦然。它也可以应用到防火墙技术里,把个别IP地址隐藏起来不被外界发现,使外界无法直接访问内部网络设备,同时,它还帮助网络可以 超越地址的限制,合理地安排网络中的公有Internet 地址和私有IP地址的使用。

NAT的类型

静态NAT(Static NAT)
静态NAT设置起来最为简单和最容易实现的一种,内部网络中的每个主机都被永久映射成外部网络中的某个合法的地址。

动态地址NAT(Pooled NAT)
动态地址NAT是在外部网络中定义了一系列的合法地址,采用动态分配的方法映射到内部网络。
动态地址NAT只是转换IP地址,它为每一个内部的IP地址分配一个临时的外部IP地址,主要应用于拨号,对于频繁的远程联接也可以采用动态NAT。

网络地址端口转换NAPT(Port-Level NAT)
NAPT是把内部地址映射到外部网络的一个IP地址的不同端口上。
最熟悉的一种转换方式。NAPT普遍应用于接入设备中,它可以将中小型的网络隐藏在一个合法的IP地址后面。NAPT与动态地址NAT不同,它将内部连接映射到外部网络中的一个单独的IP地址上,同时在该地址上加上一个由NAT设备选定的TCP端口号。

iptables实例

禁止客户机访问不健康网站
【例1】添加iptables规则禁止用户访问域名为www.sexy.com的网站。
iptables -I FORWARD -d www.sexy.com -j DROP
【例2】添加iptables规则禁止用户访问IP地址为20.20.20.20的网站。
iptables -I FORWARD -d 20.20.20.20 -j DROP

禁止某些客户机上网
【例1】添加iptables规则禁止IP地址为192.168.1.X的客户机上网。
iptables -I FORWARD -s 192.168.1.X -j DROP
【例2】添加iptables规则禁止192.168.1.0子网里所有的客户机上网。
iptables -I FORWARD -s 192.168.1.0/24 -j DROP

禁止客户机访问某些服务
【例1】禁止192.168.1.0子网里所有的客户机使用FTP协议下载。
iptables -I FORWARD -s 192.168.1.0/24 -p tcp –dport 21 -j DROP
【例2】禁止192.168.1.0子网里所有的客户机使用Telnet协议连接远程计算机。
iptables -I FORWARD -s 192.168.1.0/24 -p tcp –dport 23 -j DROP

强制访问指定的站点
【例】强制所有的客户机访问192.168.1.x这台Web服务器。
iptables -t nat -I PREROUTING -i eth0 -p tcp –dport 80 -j DNAT –to-destination 192.168.1.x:80

禁止使用ICMP协议
【例】禁止Internet上的计算机通过ICMP协议ping到NAT服务器的ppp0接口,但允许内网的客户机通过ICMP协议ping的计算机。
iptables -I INPUT -i ppp0 -p icmp -j DROP

发布内部网络服务器
【例1】发布内网10.0.0.3主机的Web服务,Internet用户通过访问防火墙的IP地址即可访问该主机的Web服务。
iptables -t nat -I PREROUTING -p tcp –dport 80 -j DNAT –to-destination 10.0.0.3:80
【例2】发布内网10.0.0.3主机的终端服务(使用的是TCP协议的3389端口),Internet用户通过访问防火墙的IP地址访问该机的终端服务。
iptables -t nat -I PREROUTING -p tcp –dport 3389 -j DNAT –to-destination 10.0.0.3:3389

 

 

iptables 的历史以及工作原理

 
1.iptables的发展:
 
iptables 的前身叫ipfirewall (内核1.x时代),这是一个作者从freeBSD上移植过来的,能够工作在内核当中的,对数据包进行检测的一款简易访问控制工具。但是 ipfirewall工作功能极其有限(它需要将所有的规则都放进内核当中,这样规则才能够运行起来,而放进内核,这个做法一般是极其困难的)。当内核发 展到2.x系列的时候,软件更名为ipchains,它可以定义多条规则,将他们串起来,共同发挥作用,而现在,它叫做iptables,可以将规则组成一个列表,实现绝对详细的访问控制功能
 
他们都是工作在用户空间中,定义规则的工具,本身并不算是防火墙。它们定义的规则,可以让在内核空间当中的netfilter来读取,并且实现让防火墙工作。而放入内核的地方必须要是特定的位置,必须是tcp/ip的协议栈经过的地方。而这个tcp/ip协议栈必须经过的地方,可以实现读取规则的地方就叫做 netfilter.(网络过滤器)
 
    作者一共在内核空间中选择了5个位置,
    1.内核空间中:从一个网络接口进来,到另一个网络接口去的
    2.数据包从内核流入用户空间的
    3.数据包从用户空间流出的
    4.进入/离开本机的外网接口
    5.进入/离开本机的内网接口
        
2.iptables的工作机制
 
从 上面的发展我们知道了作者选择了5个位置,来作为控制的地方,但是你有没有发现,其实前三个位置已经基本上能将路径彻底封锁了,但是为什么已经在进出的口 设置了关卡之后还要在内部卡呢? 由于数据包尚未进行路由决策,还不知道数据要走向哪里,所以在进出口是没办法实现数据过滤的。所以要在内核空间里设置转发的关卡,进入用户空间的关卡,从 用户空间出去的关卡。那么,既然他们没什么用,那我们为什么还要放置他们呢?因为我们在做NAT和DNAT的时候,目标地址转换必须在路由之前转换。所以我们必须在外网而后内网的接口处进行设置关卡。        
 
这五个位置也被称为五个钩子函数(hook functions),也叫五个规则链。
1.PREROUTING (路由前)
2.INPUT (数据包流入口)
3.FORWARD (转发管卡)
4.OUTPUT(数据包出口)
5.POSTROUTING(路由后)
        这是NetFilter规定的五个规则链,任何一个数据包,只要经过本机,必将经过这五个链中的其中一个链。       
 
3.防火墙的策略
 
防火墙策略一般分为两种,一种叫“通”策略,一种叫“堵”策略,通策略,默认门是关着的,必须要定义谁能进堵策略则是,大门是洞开的,但是你必须有身份认证,否则不能进。所以我们要定义,让进来的进来,让出去的出去,所以通,是要全通,而堵,则是要选择。当我们定义的策略的时候,要分别定义多条功能,其中:定义数据包中允许或者不允许的策略,filter过滤的功能,而定义地址转换的功能的则是nat选项。为了让这些功能交替工作,我们制定出了“表”这个定义,来定义、区分各种不同的工作功能和处理方式。
 
我们现在用的比较多个功能有3个:
1.filter 定义允许或者不允许的
2.nat 定义地址转换的 
                3.mangle功能:修改报文原数据
 
我们修改报文原数据就是来修改TTL的。能够实现将数据包的元数据拆开,在里面做标记/修改内容的。而防火墙标记,其实就是靠mangle来实现的。
 
小扩展:
对于filter来讲一般只能做在3个链上:INPUT ,FORWARD ,OUTPUT
对于nat来讲一般也只能做在3个链上:PREROUTING ,OUTPUT ,POSTROUTING
而mangle则是5个链都可以做:PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING
 
iptables/netfilter(这款软件)是工作在用户空间的,它可以让规则进行生效的,本身不是一种服务,而且规则是立即生效的。而我们iptables现在被做成了一个服务,可以进行启动,停止的。启动,则将规则直接生效,停止,则将规则撤销。 
iptables还支持自己定义链。但是自己定义的链,必须是跟某种特定的链关联起来的。在一个关卡设定,指定当有数据的时候专门去找某个特定的链来处理,当那个链处理完之后,再返回。接着在特定的链中继续检查。
 
注意:规则的次序非常关键,谁的规则越严格,应该放的越靠前,而检查规则的时候,是按照从上往下的方式进行检查的。
 
三.规则的写法:
 
iptables定义规则的方式比较复杂:
格式:iptables [-t table] COMMAND chain CRETIRIA -j ACTION
-t table :3个filter nat mangle
COMMAND:定义如何对规则进行管理
chain:指定你接下来的规则到底是在哪个链上操作的,当定义策略的时候,是可以省略的
CRETIRIA:指定匹配标准
-j ACTION :指定如何进行处理
 
比如:不允许172.16.0.0/24的进行访问。
iptables -t filter -A INPUT -s 172.16.0.0/16 -p udp --dport 53 -j DROP
当然你如果想拒绝的更彻底:
iptables -t filter -R INPUT 1 -s 172.16.0.0/16 -p udp --dport 53 -j REJECT
 
iptables -L -n -v#查看定义规则的详细信息
 
四:详解COMMAND:
 
1.链管理命令(这都是立即生效的)
-P :设置默认策略的(设定默认门是关着的还是开着的)
默认策略一般只有两种
iptables -P INPUT (DROP|ACCEPT)  默认是关的/默认是开的
比如:
iptables -P INPUT DROP 这就把默认规则给拒绝了。并且没有定义哪个动作,所以关于外界连接的所有规则包括Xshell连接之类的,远程连接都被拒绝了。
        -F: FLASH,清空规则链的(注意每个链的管理权限)
    iptables -t nat -F PREROUTING
    iptables -t nat -F 清空nat表的所有链
        -N:NEW 支持用户新建一个链
            iptables -N inbound_tcp_web 表示附在tcp表上用于检查web的。
        -X: 用于删除用户自定义的空链
            使用方法跟-N相同,但是在删除之前必须要将里面的链给清空昂了
        -E:用来Rename chain主要是用来给用户自定义的链重命名
            -E oldname newname
         -Z:清空链,及链中默认规则的计数器的(有两个计数器,被匹配到多少个数据包,多少个字节)
            iptables -Z :清空
 
2.规则管理命令
         -A:追加,在当前链的最后新增一个规则
         -I num : 插入,把当前规则插入为第几条。
            -I 3 :插入为第三条
         -R num:Replays替换/修改第几条规则
            格式:iptables -R 3 …………
         -D num:删除,明确指定删除第几条规则
        
3.查看管理命令 “-L”
附加子命令
-n:以数字的方式显示ip,它会将ip直接显示出来,如果不加-n,则会将ip反向解析成主机名。
-v:显示详细信息
-vv
-vvv :越多越详细
-x:在计数器上显示精确值,不做单位换算
--line-numbers : 显示规则的行号
-t nat:显示所有的关卡的信息
 
五:详解匹配标准
 
1.通用匹配:源地址目标地址的匹配
-s:指定作为源地址匹配,这里不能指定主机名称,必须是IP
IP | IP/MASK | 0.0.0.0/0.0.0.0
而且地址可以取反,加一个“!”表示除了哪个IP之外
-d:表示匹配目标地址
-p:用于匹配协议的(这里的协议通常有3种,TCP/UDP/ICMP)
-i eth0:从这块网卡流入的数据
流入一般用在INPUT和PREROUTING上
-o eth0:从这块网卡流出的数据
流出一般在OUTPUT和POSTROUTING上
        
2.扩展匹配
2.1隐含扩展:对协议的扩展
    -p tcp :TCP协议的扩展。一般有三种扩展
--dport XX-XX:指定目标端口,不能指定多个非连续端口,只能指定单个端口,比如
--dport 21  或者 --dport 21-23 (此时表示21,22,23)
--sport:指定源端口
--tcp-fiags:TCP的标志位(SYN,ACK,FIN,PSH,RST,URG)
    对于它,一般要跟两个参数:
1.检查的标志位
2.必须为1的标志位
--tcpflags syn,ack,fin,rst syn   =    --syn
表示检查这4个位,这4个位中syn必须为1,其他的必须为0。所以这个意思就是用于检测三次握手的第一次包的。对于这种专门匹配第一包的SYN为1的包,还有一种简写方式,叫做--syn
    -p udp:UDP协议的扩展
        --dport
        --sport
    -p icmp:icmp数据报文的扩展
        --icmp-type:
echo-request(请求回显),一般用8 来表示
所以 --icmp-type 8 匹配请求回显数据包
echo-reply (响应的数据包)一般用0来表示
                  
2.2显式扩展(-m)
     扩展各种模块
      -m multiport:表示启用多端口扩展
      之后我们就可以启用比如 --dports 21,23,80
                  
        
六:详解-j ACTION
 
常用的ACTION:
DROP:悄悄丢弃
一般我们多用DROP来隐藏我们的身份,以及隐藏我们的链表
REJECT:明示拒绝
ACCEPT:接受
custom_chain:转向一个自定义的链
DNAT
SNAT
MASQUERADE:源地址伪装
REDIRECT:重定向:主要用于实现端口重定向
MARK:打防火墙标记的
RETURN:返回
在自定义链执行完毕后使用返回,来返回原规则链。
 
练习题1:
     只要是来自于172.16.0.0/16网段的都允许访问我本机的172.16.100.1的SSHD服务
     分析:首先肯定是在允许表中定义的。因为不需要做NAT地址转换之类的,然后查看我们SSHD服务,在22号端口上,处理机制是接受,对于这个表,需要 有一来一回两个规则,如果我们允许也好,拒绝也好,对于访问本机服务,我们最好是定义在INPUT链上,而OUTPUT再予以定义就好。(会话的初始端先 定义),所以加规则就是:
     定义进来的: iptables -t filter -A INPUT -s 172.16.0.0/16 -d 172.16.100.1 -p tcp --dport 22 -j ACCEPT
     定义出去的: iptables -t filter -A OUTPUT -s 172.16.100.1 -d 172.16.0.0/16 -p tcp --dport 22 -j ACCEPT
     将默认策略改成DROP:
 iptables -P INPUT DROP
 iptables -P OUTPUT DROP
 iptables -P FORWARD DROP
 
七:状态检测:
 
是一种显式扩展,用于检测会话之间的连接关系的,有了检测我们可以实现会话间功能的扩展
        什么是状态检测?对于整个TCP协议来讲,它是一个有连接的协议,三次握手中,第一次握手,我们就叫NEW连接,而从第二次握手以后的,ack都为1,这 是正常的数据传输,和tcp的第二次第三次握手,叫做已建立的连接(ESTABLISHED),还有一种状态,比较诡异的,比如:SYN=1 ACK=1 RST=1,对于这种我们无法识别的,我们都称之为INVALID无法识别的。还有第四种,FTP这种古老的拥有的特征,每个端口都是独立的,21号和 20号端口都是一去一回,他们之间是有关系的,这种关系我们称之为RELATED。
所以我们的状态一共有四种:
        NEW
        ESTABLISHED
        RELATED
        INVALID
 
所以我们对于刚才的练习题,可以增加状态检测。比如进来的只允许状态为NEW和ESTABLISHED的进来,出去只允许ESTABLISHED的状态出去,这就可以将比较常见的反弹式木马有很好的控制机制。
        
对于练习题的扩展:
进来的拒绝出去的允许,进来的只允许ESTABLISHED进来,出去只允许ESTABLISHED出去。默认规则都使用拒绝
iptables -L -n --line-number  :查看之前的规则位于第几行
    改写INPUT
        iptables -R INPUT 2 -s 172.16.0.0/16 -d 172.16.100.1 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
        iptables -R OUTPUT 1 -m state --state ESTABLISHED -j ACCEPT
    此时如果想再放行一个80端口如何放行呢?
        iptables -A INPUT -d 172.16.100.1 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
        iptables -R INPUT 1 -d 172.16.100.1 -p udp --dport 53 -j ACCEPT
 
练习题2:
假如我们允许自己ping别人,但是别人ping自己ping不通如何实现呢?
分析:对于ping这个协议,进来的为8(ping),出去的为0(响应).我们为了达到目的,需要8出去,允许0进来
 
在出去的端口上:iptables -A OUTPUT -p icmp --icmp-type 8 -j ACCEPT
在进来的端口上:iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT
 
小扩展:对于127.0.0.1比较特殊,我们需要明确定义它
iptables -A INPUT -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
iptables -A OUTPUT -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
 
八:SNAT和DNAT的实现
 
由于我们现在IP地址十分紧俏,已经分配完了,这就导致我们必须要进行地址转换,来节约我们仅剩的一点IP资源。那么通过iptables如何实现NAT的地址转换呢?
 
1.SNAT基于原地址的转换
基于原地址的转换一般用在我们的许多内网用户通过一个外网的口上网的时候,这时我们将我们内网的地址转换为一个外网的IP,我们就可以实现连接其他外网IP的功能
所以我们在iptables中就要定义到底如何转换:
定义的样式:
比如我们现在要将所有192.168.10.0网段的IP在经过的时候全都转换成172.16.100.1这个假设出来的外网地址:
iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j SNAT --to-source 172.16.100.1
这样,只要是来自本地网络的试图通过网卡访问网络的,都会被统统转换成172.16.100.1这个IP.
那么,如果172.16.100.1不是固定的怎么办?
我 们都知道当我们使用联通或者电信上网的时候,一般它都会在每次你开机的时候随机生成一个外网的IP,意思就是外网地址是动态变换的。这时我们就要将外网地 址换成 MASQUERADE(动态伪装):它可以实现自动寻找到外网地址,而自动将其改为正确的外网地址。所以,我们就需要这样设置:
         iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j MASQUERADE
         这里要注意:地址伪装并不适用于所有的地方。
 
2.DNAT目标地址转换
对于目标地址转换,数据流向是从外向内的,外面的是客户端,里面的是服务器端 通过目标地址转换,我们可以让外面的ip通过我们对外的外网ip来访问我们服务器不同的服务器,而我们的服务却放在内网服务器的不同的服务器上
 
    如何做目标地址转换呢?:
iptables -t nat -A PREROUTING -d 192.168.10.18 -p tcp --dport 80 -j DNAT --todestination 172.16.100.2
        目标地址转换要做在到达网卡之前进行转换,所以要做在PREROUTING这个位置上
 

iptables 指令

语法:

         iptables [-t table] command [match] [-j target/jump]

         -t 参数用来指定规则表,内建的规则表有三个,分别是:nat、mangle 和 filter,

          当未指定规则表时,则一律视为是 filter。

各个规则表的功能如下:

           nat 此规则表拥有 Prerouting 和 postrouting 两个规则链,主要功能为进行一对一、一对多、多对多等网址转译工作(SNATDNAT),由于转译工作的特性,需进行目的地网址转译的封包,就不需要进行来源网址转译,反之亦然,因此为了提升改写封包的率,在防火墙运作时,每个封包只会经过这个规则表一次。如果我们把封包过滤的规则定义在这个数据表里,将会造成无法对同一包进行多次比对,因此这个规则表除了作网址转译外,请不要做其它用途。

           mangle 此规则表拥有 Prerouting、FORWARD 和 postrouting 三个规则链。除了进行网址转译工作会改写封包外,在某些特殊应用可能也必须去改写封包(TTL、TOS)或者是设定 MARK(将封包作记号,以进行后续的过滤),这时就必须将这些工作定义在 mangle 规则表中,由于使用率不高,我们不打算在这里讨论 mangle 的用法。

           filter 这个规则表是预设规则表,拥有 INPUT、FORWARD 和 OUTPUT 三个规则链,这个规则表顾名思义是用来进行封包过滤的理动作(例如:DROP、 LOG、 ACCEPT 或 REJECT),我们会将基本规则都建立在此规则表中。

 

主要包含::   命令表     用来增加(-A、-I)删除(-D)修改(-R)查看(-L)规则等;

                      常用参数   用来指定协议(-p)、源地址(-s)、源端口(--sport)、目的地址(-d)、目的端口(--dport)、

                                      进入网卡(-i)、出去网卡(-o)等设定包信息(即什么样的包);

                                     用来描述要处理包的信息。

                      常用处理动作    用   -j   来指定对包的处理(ACCEPT、DROP、REJECT、REDIRECT等)。

 

1、常用命令列表:  常用命令(-A追加规则、-D删除规则、-R修改规则、-I插入规则、-L查看规则)

命令 -A, --append

范例 iptables -A INPUT ...

说明 新增规则(追加方式)到某个规则链(这里是INPUT规则链)中,该规则将会成为规则链中的最后一条规则。

命令 -D, --delete

范例 iptables -D INPUT --dport 80 -j DROP

      iptables -D INPUT 1

说明 从某个规则链中删除一条规则,可以输入完整规则,或直接指定规则编号加以删除。

命令 -R, --replace

范例 iptables -R INPUT 1 -s 192.168.0.1 -j DROP

说明 取代现行规则,规则被取代后并不会改变顺序。(1是位置)

命令 -I, --insert

范例 iptables -I INPUT 1 --dport 80 -j ACCEPT

说明 插入一条规则,原本该位置(这里是位置1)上的规则将会往后移动一个顺位。

命令 -L, --list

范例 iptables -L INPUT

说明 列出某规则链中的所有规则。

命令 -F, --flush

范例 iptables -F INPUT

说明 删除某规则链(这里是INPUT规则链)中的所有规则。

命令 -Z, --zero

范例 iptables -Z INPUT

说明 将封包计数器归零。封包计数器是用来计算同一封包出现次数,是过滤阻断式攻击不可或缺的工具。

命令 -N, --new-chain

范例 iptables -N allowed

说明 定义新的规则链。

命令 -X, --delete-chain

范例 iptables -X allowed

说明 删除某个规则链。

命令 -P, --policy

范例 iptables -P INPUT DROP

说明 定义过滤政策。 也就是未符合过滤条件之封包,预设的处理方式。

命令 -E, --rename-chain

范例 iptables -E allowed disallowed

说明 修改某自订规则链的名称。

 

2、常用封包比对参数:(-p协议、-s源地址、-d目的地址、--sport源端口、--dport目的端口、-i 进入网卡、-o 出去网卡)

参数           -p, --protocol                    (指定协议)

范例 iptables -A INPUT -p tcp           (指定协议)      -p all   所有协议,  -p !tcp 去除tcp外的所有协议。

说明 比对通讯协议类型是否相符,可以使用 ! 运算子进行反向比对,例如:-p ! tcp ,

意思是指除 tcp 以外的其它类型,包含udp、icmp ...等。如果要比对所有类型,则可以使用 all 关键词,例如:-p all。

参数          -s, --src, --source                  (指定源地址,指定源端口--sport)

例如: iptables -A INPUT -s 192.168.1.1

说明 用来比对封包的来源 IP,可以比对单机或网络,比对网络时请用数字来表示屏蔽,

例如:-s 192.168.0.0/24,比对 IP 时可以使用 ! 运算子进行反向比对,

例如:-s ! 192.168.0.0/24。

参数         -d, --dst, --destination           (指定目的地址,指定目的端口--dport)

例如: iptables -A INPUT -d 192.168.1.1

说明 用来比对封包的目的地 IP,设定方式同上。

参数         -i, --in-interface                      (指定入口网卡)      -i  eth+   所有网卡

例如: iptables -A INPUT -i eth0

说明 用来比对封包是从哪片网卡进入,可以使用通配字符 + 来做大范围比对,

例如:-i eth+ 表示所有的 ethernet 网卡,也以使用 ! 运算子进行反向比对,

例如:-i ! eth0。

参数        -o, --out-interface                   (指定出口网卡)

例如: iptables -A FORWARD -o eth0

说明 用来比对封包要从哪片网卡送出,设定方式同上。

参数        --sport, --source-port              (源端口)

例如: iptables -A INPUT -p tcp --sport 22

说明 用来比对封包的来源端口号,可以比对单一埠,或是一个范围,

例如:--sport 22:80,表示从 22 到 80 端口之间都算是符合件,

如果要比对不连续的多个埠,则必须使用 --multiport 参数,详见后文。比对埠号时,可以使用 ! 运算子进行反向比对。

参数        --dport, --destination-port     (目的端口)

例如: iptables -A INPUT -p tcp --dport 22

说明 用来比对封包的目的端口号,设定方式同上。

参数       --tcp-flags                                  (只过滤TCP中的一些包,比如SYN包,ACK包,FIN包,RST包等等)

例如: iptables -p tcp --tcp-flags SYN,FIN,ACK SYN

说明  比对 TCP 封包的状态旗号,参数分为两个部分,第一个部分列举出想比对的旗号,

           第二部分则列举前述旗号中哪些有被设,未被列举的旗号必须是空的。TCP 状态旗号包括:SYN(同步)、ACK(应答)、

FIN(结束)、RST(重设)、URG(紧急)PSH(强迫推送) 等均可使用于参数中,除此之外还可以使用关键词 ALL 和

NONE 进行比对。比对旗号时,可以使用 ! 运算子行反向比对。

参数 --syn

例如: iptables -p tcp --syn

说明 用来比对是否为要求联机之 TCP 封包,与 iptables -p tcp --tcp-flags SYN,

FIN,ACK SYN 的作用完全相同,如果使用 !运算子,可用来比对非要求联机封包。

参数 -m multiport --source-port

例如: iptables -A INPUT -p tcp -m multiport --source-port 22,53,80,110

说明 用来比对不连续的多个来源埠号,一次最多可以比对 15 个埠,可以使用 !

运算子进行反向比对。

参数 -m multiport --destination-port

例如: iptables -A INPUT -p tcp -m multiport --destination-port 22,53,80,110

说明 用来比对不连续的多个目的地埠号,设定方式同上。

参数 -m multiport --port

例如: iptables -A INPUT -p tcp -m multiport --port 22,53,80,110

说明 这个参数比较特殊,用来比对来源埠号和目的埠号相同的封包,设定方式同上。

注意:在本范例中,如果来源端口号为 80目的地埠号为 110,这种封包并不算符合条件。

参数 --icmp-type

例如: iptables -A INPUT -p icmp --icmp-type 8

说明 用来比对 ICMP 的类型编号,可以使用代码或数字编号来进行比对。

请打 iptables -p icmp --help 来查看有哪些代码可用。

参数 -m limit --limit

例如: iptables -A INPUT -m limit --limit 3/hour

说明 用来比对某段时间内封包的平均流量,上面的例子是用来比对:每小时平均流量是

否超过一次 3 个封包。 除了每小时平均次外,也可以每秒钟、每分钟或每天平均一次,

默认值为每小时平均一次,参数如后: /second、 /minute、/day。 除了进行封数量的

比对外,设定这个参数也会在条件达成时,暂停封包的比对动作,以避免因骇客使用洪水

攻击法,导致服务被阻断。

参数 --limit-burst

范例 iptables -A INPUT -m limit --limit-burst 5

说明 用来比对瞬间大量封包的数量,上面的例子是用来比对一次同时涌入的封包是否超

过 5 个(这是默认值),超过此上限的封将被直接丢弃。使用效果同上。

参数 -m mac --mac-source

范例 iptables -A INPUT -m mac --mac-source 00:00:00:00:00:01

说明 用来比对封包来源网络接口的硬件地址,这个参数不能用在 OUTPUT 和 Postrouting规则炼上,这是因为封包要送出到网后,才能由网卡驱动程序透过 ARP 通讯协议查出目的地的 MAC 地址,所以 iptables 在进行封包比对时,并不知道封包会送到个网络接口去。

参数 --mark

范例 iptables -t mangle -A INPUT -m mark --mark 1

说明 用来比对封包是否被表示某个号码,当封包被比对成功时,我们可以透过 MARK 处理动作,将该封包标示一个号码,号码最不可以超过 4294967296。

参数 -m owner --uid-owner

范例 iptables -A OUTPUT -m owner --uid-owner 500

说明 用来比对来自本机的封包,是否为某特定使用者所产生的,这样可以避免服务器使用

root 或其它身分将敏感数据传送出,可以降低系统被骇的损失。可惜这个功能无法比对出

来自其它主机的封包。

参数 -m owner --gid-owner

范例 iptables -A OUTPUT -m owner --gid-owner 0

说明 用来比对来自本机的封包,是否为某特定使用者群组所产生的,使用时机同上。

参数 -m owner --pid-owner

范例 iptables -A OUTPUT -m owner --pid-owner 78

说明 用来比对来自本机的封包,是否为某特定行程所产生的,使用时机同上。

参数 -m owner --sid-owner

范例 iptables -A OUTPUT -m owner --sid-owner 100

说明 用来比对来自本机的封包,是否为某特定联机(Session ID)的响应封包,使用时

机同上。

参数 -m state --state

范例 iptables -A INPUT -m state --state RELATED,ESTABLISHED

说明 用来比对联机状态,联机状态共有四种:INVALID、ESTABLISHED、NEW 和 RELATED。

INVALID 表示该封包的联机编号(Session ID)无法辨识或编号不正确。

ESTABLISHED 表示该封包属于某个已经建立的联机。

NEW 表示该封包想要起始一个联机(重设联机或将联机重导向)。

RELATED 表示该封包是属于某个已经建立的联机,所建立的新联机。例如:FTP-DATA 联机必定是源自某个 FTP 联机。

3、常用的处理动作: (-j  指定对满足条件包的处理,常用动作有ACCEPT接受报、DROP丢弃报、REJECT丢弃报并通知对方、REDIRECT重定向包等)

-j   参数用来指定要进行的处理动作,常用的处理动作包括:ACCEPT、REJECT、DROP、REDIRECT、MASQUERADE、LOG、DNAT、SNAT、MIRROR、QUEUE、RETURN、MARK,分别说明如下:

ACCEPT        将封包放行,进行完此处理动作后,将不再比对其它规则,直接跳往下一个规则链(natostrouting)。

REJECT          拦阻该封包,并传送封包通知对方,可以传送的封包有几个选择:ICMP port-unreachable、ICMP echo-reply 或是 tcp-reset(这个封包会要求对方关闭联机),进行完此处理动作后,将不再比对其它规则,直接中断过滤程序。

例如:iptables -A FORWARD -p TCP --dport 22 -j REJECT --reject-with tcp-reset

DROP            丢弃封包不予处理,进行完此处理动作后,将不再比对其它规则,直接中断过滤程序。

REDIRECT       将封包重新导向到另一个端口(PNAT),进行完此处理动作后,将会继续比对其它规则。

                       这个功能可以用来实作通透式porxy 或用来保护 web 服务器。

                例如:iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

MASQUERADE              改写封包来源 IP 为防火墙 NIC IP,可以指定 port 对应的范围,进行完此处理动作后,直接跳往下一个规则(mangleostrouting)。这个功能与 SNAT 略有不同,当进行 IP 伪装时,不需指定要伪装成哪个 IP,IP 会从网卡直接读,当使用拨接连线时,IP 通常是由 ISP 公司的 DHCP 服务器指派的,这个时候 MASQUERADE 特别有用。

                例如:iptables -t nat -A POSTROUTING -p TCP -j MASQUERADE --to-ports 1024-31000

LOG              将封包相关讯息纪录在 /var/log 中,详细位置请查阅 /etc/syslog.conf 组态档,进行完此处理动作后,将会继续比对其规则。

                例如:iptables -A INPUT -p tcp -j LOG --log-prefix "INPUT packets"

SNAT             改写封包来源 IP 为某特定 IP 或 IP 范围,可以指定 port 对应的范围,进行完此处理动作后,将直接跳往下一个规则(mangleostrouting)。

                例如:iptables -t nat -A POSTROUTING -p tcp-o eth0 -j SNAT --to-source 194.236.50.155-194.236.50.160:1024-32000

DNAT            改写封包目的地 IP 为某特定 IP 或 IP 范围,可以指定 port 对应的范围,进行完此处理动作后,将会直接跳往下一个规炼(filter:input 或 filter:forward)。

               例如:iptables -t nat -A PREROUTING -p tcp -d 15.45.23.67 --dport 80 -j DNAT --to-destination 192.168.1.1-192.168.1.10:80-100

MIRROR        镜射封包,也就是将来源 IP 与目的地 IP 对调后,将封包送回,进行完此处理动作后,将会中断过滤程序。

QUEUE          中断过滤程序,将封包放入队列,交给其它程序处理。透过自行开发的处理程序,可以进行其它应用,

                      例如:计算联机费......等。

RETURN        结束在目前规则炼中的过滤程序,返回主规则炼继续过滤,如果把自订规则炼看成是一个子程序,那么这个动作,就相当提早结束子程序并返回到主程序中。

MARK          将封包标上某个代号,以便提供作为后续过滤的条件判断依据,进行完此处理动作后,将会继续比对其它规则。

               例如:iptables -t mangle -A PREROUTING -p tcp --dport 22 -j MARK --set-mark 2


四.拓展模块
1.按来源MAC地址匹配
# iptables -t filter -A FORWARD -m --mac-source 00:02:b2:03:a5:f6 -j DROP
拒绝转发来自该MAC地址的数据包
2.按多端口或连续端口匹配
     20: 表示20以后的所有端口
     20:100 表示20到100的端口
:20 表示20之前的所有端口
     -m multiport [--prots, --sports,--dports]

例子:

# iptables -A INPUT -p tcp -m multiport --dports 21,20,25,53,80 -j ACCEPT 【多端口匹配】
# iptables -A INPUT -p tcp --dport 20: -j ACCEPT
# iptables -A INPUT -p tcp --sport 20:80 -j ACCEPT
# iptables -A INPUT -p tcp --sport :80 -j ACCEPT


3.还可以按数据包速率和状态匹配
-m limit --limit 匹配速率 如: -m limit --limit 50/s -j ACCEPT
-m state --state 状态 如: -m state --state INVALID,RELATED -j ACCEPT


4.还可以限制链接数
-m connlimit --connlimit-above n 限制为多少个              
        例如:
        iptables -I FORWARD -p tcp -m connlimit --connlimit-above 9 -j DROP        //表示限制链接数最大为9个

5、模拟随机丢包率
       iptables -A FORWARD -p icmp -m statistic --mode random --probability 0.31  -j REJECT   //表示31%的丢包率
       或者
       -m random --average 5 -j DROP 表示模拟丢掉5%比例的包
设置延时 3s :

tc qdisc add dev eth0 root netem delay 3000ms

可以在 3000ms 后面在加上一个延时,比如 ’3000ms 200ms‘表示 3000ms ± 200ms ,延时范围 2800 – 3200 之间.
结果显示如下

 
Linux 中丢包模拟

设置丢包 50% ,iptables 也可以模拟这个,但一下不记的命令了,下次放上来:

tc qdisc change dev eth0 root netem loss 50%

上面的设丢包,如果给后面的 50% 的丢包比率修改成 ’50% 80%’ 时,这时和上面的延时不一样,这是指丢包比率为 50-80% 之间。
/etc/sysconfig/iptables文件保存了端口的规则

1、查看本机关于IPTABLES的设置情况
[root@tp ~]# iptables -L -n
2、清除原有规则.
不管你在安装linux时是否启动了防火墙,如果你想配置属于自己的防火墙,那就清除现在filter的所有规则.
[root@tp ~]# iptables -F 清除预设表filter中的所有规则链的规则
[root@tp ~]# iptables -X 清除预设表filter中使用者自定链中的规则
3、设定预设规则
[root@tp ~]# iptables -p INPUT DROP
[root@tp ~]# iptables -p OUTPUT ACCEPT
[root@tp ~]# iptables -p FORWARD DROP
上面的意思是,当超出了IPTABLES里filter表里的两个链规则(INPUT,FORWARD)时,不在这两个规则里的数据包怎么处理呢,那就是DROP(放弃).应该说这样配置是很安全的.我们要控制流入数据包
而对于OUTPUT链,也就是流出的包我们不用做太多限制,而是采取ACCEPT
4、添加规则.
首先添加INPUT链,INPUT链的默认规则是DROP,所以我们就写需要ACCETP(通过)的链
为了能采用远程SSH登陆,我们要开启22端口.
[root@tp ~]# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
[root@tp ~]# iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
[root@tp ~]# iptables -A OUTPUT -p tcp --sport 80 -j ACCEPT ,其他同理.)
如果做了WEB服务器,开启80端口.
[root@tp ~]# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
如果做了邮件服务器,开启25,110端口.
[root@tp ~]# iptables -A INPUT -p tcp --dport 110 -j ACCEPT
[root@tp ~]# iptables -A INPUT -p tcp --dport 25 -j ACCEPT
如果做了FTP服务器,开启21端口
[root@tp ~]# iptables -A INPUT -p tcp --dport 21 -j ACCEPT
[root@tp ~]# iptables -A INPUT -p tcp --dport 20 -j ACCEPT
如果做了DNS服务器,开启53端口
[root@tp ~]# iptables -A INPUT -p tcp --dport 53 -j ACCEPT
如果你还做了其他的服务器,需要开启哪个端口,照写就行了.
允许icmp包通过,也就是允许ping,
[root@tp ~]# iptables -A OUTPUT -p icmp -j ACCEPT (OUTPUT设置成DROP的话)
[root@tp ~]# iptables -A INPUT -p icmp -j ACCEPT (INPUT设置成DROP的话)
允许loopback!(不然会导致DNS无法正常关闭等问题)
IPTABLES -A INPUT -i lo -p all -j ACCEPT (如果是INPUT DROP)
IPTABLES -A OUTPUT -o lo -p all -j ACCEPT(如果是OUTPUT DROP)
下面写OUTPUT链,OUTPUT链默认规则是ACCEPT,所以我们就写需要DROP(放弃)的链.
减少不安全的端口连接
[root@tp ~]# iptables -A OUTPUT -p tcp --sport 31337 -j DROP
[root@tp ~]# iptables -A OUTPUT -p tcp --dport 31337 -j DROP
有些些特洛伊木马会扫描端口31337到31340(即黑客语言中的 elite 端口)上的服务。

下面写一下更加细致的规则,就是限制到某台机器
如:我们只允许192.168.0.3的机器进行SSH连接
[root@tp ~]# iptables -A INPUT -s 192.168.0.3 -p tcp --dport 22 -j ACCEPT
如果要允许,或限制一段IP地址可用 192.168.0.0/24 表示192.168.0.1-255端的所有IP.
24表示子网掩码数.但要记得把 /etc/sysconfig/iptables 里的这一行删了.
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT 因为它表示所有地址都可以登陆.
或采用命令方式:
[root@tp ~]# iptables -D INPUT -p tcp --dport 22 -j ACCEPT
在下面就是FORWARD链,FORWARD链的默认规则是DROP,所以我们就写需要ACCETP(通过)的链,对正在转发链的监控.
开启转发功能,(在做NAT时,FORWARD默认规则是DROP时,必须做)
[root@tp ~]# iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
[root@tp ~]# iptables -A FORWARD -i eth1 -o eh0 -j ACCEPT
丢弃坏的TCP包
[root@tp ~]#iptables -A FORWARD -p TCP ! --syn -m state --state NEW -j DROP
处理IP碎片数量,防止攻击,允许每秒100个
[root@tp ~]#iptables -A FORWARD -f -m limit --limit 100/s --limit-burst 100 -j ACCEPT
设置ICMP包过滤,允许每秒1个包,限制触发条件是10个包.
[root@tp ~]#iptables -A FORWARD -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
我在前面只所以允许ICMP包通过,就是因为我在这里有限制。
配置一个NAT表防火墙
1、查看本机关于NAT的设置情况
[root@tp rc.d]# iptables -t nat -L
如果你想清除,命令是
[root@tp ~]# iptables -F -t nat
[root@tp ~]# iptables -X -t nat
[root@tp ~]# iptables -Z -t nat
2、添加规则
添加规则,我们只添加DROP链.因为默认链全是ACCEPT.
防止外网用内网IP欺骗
[root@tp sysconfig]# iptables -t nat -A PREROUTING -i eth0 -s 10.0.0.0/8 -j DROP
[root@tp sysconfig]# iptables -t nat -A PREROUTING -i eth0 -s 172.16.0.0/12 -j DROP
[root@tp sysconfig]# iptables -t nat -A PREROUTING -i eth0 -s 192.168.0.0/16 -j DROP
drop非法连接
[root@tp ~]# iptables -A INPUT -m state --state INVALID -j DROP
[root@tp ~]# iptables -A OUTPUT -m state --state INVALID -j DROP
[root@tp ~]# iptables-A FORWARD -m state --state INVALID -j DROP

允许所有已经建立的和相关的连接
[root@tp ~]# iptables-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
[root@tp ~]# iptables-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
[root@tp ~]# /etc/rc.d/init.d/iptables save
这样就可以写到/etc/sysconfig/iptables文件里了.写入后记得把防火墙重起一下,才能起作用.
[root@tp ~]# service iptables restart
 
 
iptables -F
iptables -X
iptables -F -t mangle
iptables -t mangle -X
iptables -F -t nat
iptables -t nat -X
首先,把三个表清空,把自建的规则清空。
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD ACCEPT
设定INPUT、OUTPUT的默认策略为DROP,FORWARD为ACCEPT。

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
先把“回环”打开,以免有不必要的麻烦。

iptables -A INPUT -i eth+ -p icmp --icmp-type 8 -j ACCEPT
iptables -A OUTPUT -o eth+ -p icmp --icmp-type 0 -j ACCEPT
在所有网卡上打开ping功能,便于维护和检测。

iptables -A INPUT -i eth0 -s 192.168.100.250 -d 192.168.100.1 -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -o eth0 -d 192.168.100.250 -s 192.168.100.1 -p tcp --sport 22 -j ACCEPT
打开22端口,允许远程管理。(设定了很多的附加条件:管理机器IP必须是250,并且必须从eth0网卡进入)

iptables -A INPUT -i eth0 -s 192.168.100.0/24 -p tcp --dport 3128 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -d 192.168.100.0/24 -p tcp --sport 3128 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth1 -s 192.168.168.0/24 -p tcp --dport 3128 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth1 -d 192.168.168.0/24 -p tcp --sport 3128 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth2 -p tcp --dport 32768:61000 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth2 -p tcp --sport 32768:61000 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth2 -p udp --dport 53 -j ACCEPT
iptables -A INPUT -i eth2 -p udp --sport 53 -j ACCEPT


iptables -A INPUT -i eth0 -s 192.168.100.0/24 -p tcp --dport 3128 -m state --state NEW,ESTABLISHED -j ACCEPT
允许192.168.100.0/24网段的机器发送数据包从eth0网卡进入。如果数据包是tcp协议,而且目的端口是3128(因为REDIRECT已经把80改为3128了。nat表的PREROUTING是在filter表的INPUT前面的。)的,再而且,数据包的状态必须是NEW或者ESTABLISHED的(NEW代表tcp三段式握手的“第一握”,换句话说就是,允许客户端机器向服务器发出链接申请。ESTABLISHED表示通过握手已经建立起链接),通过。

iptables -A OUTPUT -o eth2 -p tcp --sport 32768:61000 -m state --state NEW,ESTABLISHED -j ACCEPT
我们先来看这一句。现在你的数据包已经进入到linux服务器防火墙上来了。squid需要代替你去访问,所以这时,服务器就成了客户端的角色,所以它要使用32768到61000的私有端口进行访问。(大家会奇怪应该是1024到65535吧。其实CentOS版的linux所定义的私有端口是32768到61000的,你可以通过cat /proc/sys/net/ipv4/ip_local_port_range,查看一下。)再次声明:这里是squid以客户端的身份去访问其他的服务器,所以这里的源端口是32768:61000,而不是3128!

iptables -A INPUT -i eth2 -p tcp --dport 32768:61000 -m state --state ESTABLISHED -j ACCEPT
当然了,数据有去就有回。

iptables -A OUTPUT -o eth0 -d 192.168.100.0/24 -p tcp --sport 3128 -m state --state ESTABLISHED -j ACCEPT
数据包还得通过服务器,转到内网网卡上。请注意,这里,是squid帮你去访问了你想要访问的网站。所以在内网中,你的机器是客户端角色,而squid是服务器角色。这与刚才对外访问的过程是不同的。所以在这里,源端口是3128,而不是32768:61000。

iptables -A OUTPUT -o eth2 -p udp --dport 53 -j ACCEPT
iptables -A INPUT -i eth2 -p udp --sport 53 -j ACCEPT
当然,DNS是不可缺少的。

iptables -A INPUT -i eth+ -p tcp --dport 80 -j LOG --log-prefix "iptables_80_alert" --log-level info
iptables -A INPUT -i eth+ -p tcp --dport 21 -j LOG --log-prefix "iptables_21_alert" --log-level info
iptables -A INPUT -i eth+ -p tcp --dport 22 -j LOG --log-prefix "iptables_22_alert" --log-level info
iptables -A INPUT -i eth+ -p tcp --dport 25 -j LOG --log-prefix "iptables_25_alert" --log-level info
iptables -A INPUT -i eth+ -p icmp --icmp-type 8 -j LOG --log-prefix "iptables_icmp8_alert" --log-level info
当然了,来点日志记录会对网管员有所帮助。
iptables 基本命令使用举例


      一、链的基本操作
1、清除所有的规则。
1)清除预设表filter中所有规则链中的规则。
# iptables -F
2)清除预设表filter中使用者自定链中的规则。
#iptables -X
#iptables -Z
2、设置链的默认策略。一般有两种方法。
1)首先允许所有的包,然后再禁止有危险的包通过放火墙。
#iptables -P INPUT ACCEPT
#iptables -P OUTPUT ACCEPT
#iptables -P FORWARD ACCEPT
2)首先禁止所有的包,然后根据需要的服务允许特定的包通过防火墙。
#iptables -P INPUT DROP
#iptables -P OUTPUT DROP
#iptables -P FORWARD DROP
3、列出表/链中的所有规则。默认只列出filter表。
#iptables -L
4、向链中添加规则。下面的语句用于开放网络接口:
#iptables -A INPUT -i lo -j ACCEPT
#iptables -A OUTPUT -o lo -j ACCEPT
#iptables -A INPUT -i eth0 -j ACEPT
#iptables -A OUTPUT -o eth1 -j ACCEPT
#iptables -A FORWARD -i eth1 -j ACCEPT
#iptables -A FORWARD -0 eth1 -j ACCEPT
注意:由于本地进程不会经过FORWARD链,因此回环接口lo只在INPUT和OUTPUT两个链上作用。
5、使用者自定义链。
#iptables -N custom
#iptables -A custom -s 0/0 -d 0/0 -p icmp -j DROP
#iptables -A INPUT -s 0/0 -d 0/0 -j DROP
二、设置基本的规则匹配
1、指定协议匹配。
1)匹配指定协议。
#iptables -A INPUT -p tcp
2)匹配指定协议之外的所有协议。
#iptables -A INPUT -p !tcp
2、指定地址匹配。
1)指定匹配的主机。
#iptables -A INPUT -s 192.168.0.18
2)指定匹配的网络。
#iptables -A INPUT -s 192.168.2.0/24
3)匹配指定主机之外的地址。
#iptables -A FORWARD -s !192.168.0.19
4)匹配指定网络之外的网络。
#iptables -A FORWARD -s ! 192.168.3.0/24
3、指定网络接口匹配。
1)指定单一的网络接口匹配。
#iptables -A INPUT -i eth0
#iptables -A FORWARD -o eth0
2)指定同类型的网络接口匹配。
#iptables -A FORWARD -o ppp+
4、指定端口匹配。
1)指定单一端口匹配。
#iptables -A INPUT -p tcp --sport www
#iptables -A INPUT -p udp –dport 53
2)匹配指定端口之外的端口。
#iptables -A INPUT -p tcp –dport !22
3)匹配端口范围。
#iptables -A INPUT -p tcp –sport 22:80
4)匹配ICMP端口和ICMP类型。
#iptables -A INOUT -p icmp –icimp-type 8
5)指定ip碎片。

个网络接口都有一个MTU(最大传输单元),这个参数定义了可以通过的数据包的最大尺寸。如果一个数据包大于这个参数值时,系统会将其划分成更小的数据包
(称为ip碎片)来传输,而接受方则对这些ip碎片再进行重组以还原整个包。这样会导致一个问题:当系统将大数据包划分成ip碎片传输时,第一个碎片含有
完整的包头信息(IP+TCP、UDP和ICMP),但是后续的碎片只有包头的部分信息(如源地址、目的地址)。因此,检查后面的ip碎片的头部(象有
TCP、UDP和ICMP一样)是不可能的。假如有这样的一条规则:
#iptables -A FORWARD -p tcp -s 192.168.1.0/24 -d 192.168.2.100 –dport 80 -j ACCEPT
并且这时的FORWARD的policy为DROP时,系统只会让第一个ip碎片通过,而余下的碎片因为包头信息不完整而无法通过。可以通过—fragment/-f 选项来指定第二个及以后的ip碎片解决上述问题。
#iptables -A FORWARD -f -s 192.168.1.0/24 -d 192.168.2.100 -j ACCEPT
注意现在有许多进行ip碎片攻击的实例,如DoS攻击,因此允许ip碎片通过是有安全隐患的,对于这一点可以采用iptables的匹配扩展来进行限制。
三、设置扩展的规则匹配(举例已忽略目标动作)
1、多端口匹配。
1)匹配多个源端口。
#iptables -A INPUT -p tcp -m multiport –sport 22,53,80,110
2)匹配多个目的端口。
#iptables -A INPUT -p tcp -m multiport –dpoort 22,53,80
3)匹配多端口(无论是源端口还是目的端口)
#iptables -A INPUT -p tcp -m multiport –port 22,53,80,110
2、指定TCP匹配扩展
使用 –tcp-flags 选项可以根据tcp包的标志位进行过滤。
#iptables -A INPUT -p tcp –tcp-flags SYN,FIN,ACK SYN
#iptables -A FROWARD -p tcp –tcp-flags ALL SYN,ACK
上实例中第一个表示SYN、ACK、FIN的标志都检查,但是只有SYN匹配。第二个表示ALL(SYN,ACK,FIN,RST,URG,PSH)的标志都检查,但是只有设置了SYN和ACK的匹配。
#iptables -A FORWARD -p tcp --syn
选项—syn相当于”--tcp-flags SYN,RST,ACK SYN”的简写。
3、limit速率匹配扩展。
1)指定单位时间内允许通过的数据包个数,单位时间可以是/second、/minute、/hour、/day或使用第一个子母。
#iptables -A INPUT -m limit --limit 300/hour
2 )指定触发事件的阀值。
#iptables -A INPUT -m limit –limit-burst 10
用来比对一次同时涌入的封包是否超过10个,超过此上限的包将直接丢弃。
3)同时指定速率限制和触发阀值。
#iptables -A INPUT -p icmp -m limit –-limit 3/m –limit-burst 3
表示每分钟允许的最大包数量为限制速率(本例为3)加上当前的触发阀值burst数。任何情况下,都可保证3个数据包通过,触发阀值burst相当于允许额外的包数量。
4)基于状态的匹配扩展(连接跟踪)
每个网络连接包括以下信息:源地址、目标地址、源端口、目的端口,称为套接字对(socket pairs);协议类型、连接状态(TCP协议)
和超时时间等。防火墙把这些信息称为状态(stateful)。状态包过滤防火墙能在内存中维护一个跟踪状态的表,比简单包过滤防火墙具有更大的安全性,命令格式如下:
iptables -m state –-state [!]state [,state,state,state]
其中,state表是一个逗号分割的列表,用来指定连接状态,4种:
>NEW: 该包想要开始一个新的连接(重新连接或连接重定向)
>RELATED:该包是属于某个已经建立的连接所建立的新连接。举例:
FTP的数据传输连接和控制连接之间就是RELATED关系。
>ESTABLISHED:该包属于某个已经建立的连接。
>INVALID:该包不匹配于任何连接,通常这些包被DROP。
例如:
(1)在INPUT链添加一条规则,匹配已经建立的连接或由已经建立的连接所建立的新连接。即匹配所有的TCP回应包。
#iptables -A INPUT -m state –state RELATED,ESTABLISHED
(2)在INPUT链链添加一条规则,匹配所有从非eth0接口来的连接请求包。
#iptables -A INPUT -m state -–state NEW -i !eth0
又如,对于ftp连接可以使用下面的连接跟踪:
(1)被动(Passive)ftp连接模式。
#iptables -A INPUT -p tcp --sport 1024: --dport 1024: -m state –-state ESTABLISHED -j ACCEPT
#iptables -A OUTPUT -p tcp --sport 1024: --dport 1024: -m
state -–state ESTABLISHED,RELATED -j ACCEPT
(2)主动(Active)ftp连接模式
#iptables -A INNPUT -p tcp --sport 20 -m state –-state ESTABLISHED,RELATED -j ACCEPT
#iptables -A OUTPUT -p tcp –OUTPUT -p tcp –dport 20 -m state --state ESTABLISHED -j ACCEPT
 

Linux下用arptables防arp攻击
静态绑定MAC和向网关报告正确的本机MAC地址
arptables -F
arptables -P INPUT ACCEPT
#默认策略
arptables -A INPUT --src-ip 192.168.1.1 --src-mac 7A:31:14:42:10:01 -j ACCEPT
#允许本网段特定MAC可进入,且IP与MAC相符
arptables -A INPUT --src-mac ! 74:8E:F8:53:DC:C0 -j DROP
#拒绝非网关MAC
arptables -A INPUT --src-ip ! 192.168.1.1 -j DROP
#拒绝非网关IP
 DD-WRT wik建议在命令行先测试确认规则. 这样,如果碰巧出了大错误(比如关闭了route的入口), 简单的重启路由器即可修复,
而不用硬件重置. 想使得规则在路由器重启后仍然生效,需要把它们保存在刚才提到的防火墙脚本中.

基本用法
iptables -[AD] 链名 规则 [选项]
iptables -[RI] 链名 规则序号 规则 [选项]
iptables -D 链名 规则序号 [选项]
iptables -[LFZ] [链名] [选项]
iptables -[NX] 链名
iptables -E 旧链名 新链名
iptables -P 链名 target [选项]
iptables -h (打印这个帮助信息)

命令
--append -A chain     附加到链上
--delete  -D chain     从链上删除匹配的规则
--delete  -D chain rulenum    从链上删除规则 rulenum (1 = first)
--insert  -I chain [rulenum]  Insert in chain as rulenum (default 1=first)
--replace -R chain rulenum  Replace rule rulenum (1 = first) in chain
--list      -L [chain]    List the rules in a chain or all chains
--flush   -F [chain]    Delete all rules in  chain or all chains
--zero    -Z [chain]   Zero counters in chain or all chains
--new    -N chain      Create a new user-defined chain
--delete-chain      -X [chain]   Delete a user-defined chain
--policy  -P chain target      Change policy on chain to target
--rename-chain   -E old-chain new-chain      Change chain name, (moving any references)

选项
--proto    -p [!] proto
                              protocol: by number or name, eg. `tcp'
--source  -s [!] address[/mask]
                              source specification. The mask can be either a network mask or a plain number,
                              specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is
                              equivalent to 255.255.255.0. A "!" argument before the address specification inverts the
                              sense of the address.
--destination  -d [!] address[/mask]
                              destination specification
--sport [!] port[:endport]
                              source port (use `:' when specifying range)
--dport [!] port[:endport]
                              destination port
--in-interface  -i [!] input name[+]
                              network interface name ([+] for wildcard)
--jump    -j target
                              target for rule (may load target extension)
--match  -m match
                              extended match (may load extension)
--state state
                              connection states to match:
                                   INVALID NEW ESTABLISHED RELATED
--tcp-flags [!] mask
                              match when the TCP flags are as specified:
                                   SYN ACK FIN RST URG PSH ALL NONE
--numeric    -n         numeric output of addresses and ports
--out-interface -o [!] output name[+]
                              network interface name ([+] for wildcard)
--table        -t table  table to manipulate (default: `filter')
--verbose   -v          verbose mode
--line-numbers         print line numbers when listing
--exact       -x          expand numbers (display exact values)
--fragment  -f          match second or further fragments only
--modprobe=<command>     try to insert modules using this command
--set-counters PKTS BYTES    set the counter during insert/append
--version    -V          print package version

MAC v1.3.7 options:
 --mac-source [!] XX:XX:XX:XX:XX:XX
                              Match source MAC address

接口
When using the -i or -o to define the physical interfaces, remember that by default:
vlan0 is the 4 LAN ports
vlan1 is the WAN port (ppp0 is the WAN interface when PPPoE is used)
eth1 is the WIFI
br0 is a bridge connecting the 4 LAN and the WIFI together

Note: ppp0 is the WAN interface when PPPoE is used. This information is from IPv6 page and quoted here: "The detailled configuration steps are targeted toward users with a basic DHCP connection for the WAN part. So, if using PPPoE will require replacing vlan1 with ppp0 in each instance. Other connection types will vary."

Tip: To list the network interfaces on the router use 'ifconfig' on the command line.

表Tables, 链Chains, 和操作Targets

表Tables

The main tables we are concerned with are the "filter" table and the "nat" table. To list the contents of either table, do

iptables -t filter -L
iptables -t nat -L

The filter table is default and this includes chains like INPUT, OUTPUT, and FORWARD. The nat table is for Network Address Translation and it includes the PREROUTING and POSTROUTING chains.

链Chains

INPUT is for packets destined to or entering the router's local sockets.

OUTPUT is for packets sourced from or leaving the router's local sockets.

FORWARD is for packets being forwarded through the router (e.g. packets not necessarily destined for local sockets).

PREROUTING is for manipulating packets before they are routed.

POSTROUTING is for manipulating packets after they are routed.

 

操作Targets

ACCEPT - packets are accepted/allowed

DROP - packets are dropped/denied

REJECT - packets are rejected/denied

logaccept - packets are accepted and logged to /tmp/var/log/messages

logdrop - packets are dropped and logged to /tmp/var/log/messages

logreject - packets are rejected and logged to /tmp/var/log/messages

DNAT is for altering packet's destination address.

SNAT is for altering packet's source address.

TRIGGER - dynamically redirect input ports based on output traffic (aka port triggering)

 

TRIGGER Target Options

The trigger target has additional options which must appear immediately after it on the command line

--trigger-type [dnat|in|out] 
--trigger-proto [tcp|udp|all]    (if this option is not specificed the default is all)
--trigger-match [port[-port]]   (a port or a range of ports which the outbound connection uses)
--trigger-relate [port[-port]]    (a port or range of ports to open on the inbound side)

例子

 

Listing the rules in a chain

首先我想看看我的INPUT链中的规则,这是流量进入我的路由器遇到的第一个链。

iptables -L INPUT

You will find that it is really slow to list all many rules after you enter the above iptables command since it is doing reverse DNS lookups to convert IP addresses to host names. You can add -n option to only see numerical addresses. (Note '0.0.0.0/0' = 'anywhere' (any address, any port); and '0' prot is 'any' protocol.)

iptables -nL INPUT

To get a little more detailed list, with actual IP numbers and packet counts for each rule, I can do

iptables -vnL INPUT

Suppose I might want to add a rule so that I can ssh into my router from a specific host/address outside. Then I might type the following:

iptables -A INPUT -p tcp -s 150.100.whatever.something --dport 22 -j logaccept

So I am saying: Append to the INPUT chain a rule allowing protocol tcp, with a source address of <my external IP that i want access from> traffic destined for port 22 on my router, jump to logaccept. I could have used -j ACCEPT which simply jumps to ACCEPT, but in this case I want to log it just to keep track so I use logaccept, which is a chain we have set up for this purpose.

Note: Simply adding a rule to the INPUT chain may be enough to allow remote SSH access from the WAN. However, if your router is still in NAT/Gateway mode and you wish to remap the SSH port to something less traditional on the WAN side (say port 2222), you may Insert a PREROUTING rule instead. This is actually how the GUI does it when you enable remote WAN SSH management.

 

iptables -A INPUT -p tcp -m tcp -d `nvram get lan_ipaddr` --dport 22 -j logaccept 
iptables -t nat -A PREROUTING -p tcp -m tcp -d `nvram get wan_ipaddr` --dport 2222 -j DNAT --to-destination `nvram get lan_ipaddr`:22

 

Now if I type

iptables -L INPUT 

I see my shiny new rule appended to the INPUT chain. However, this is no good because in my case I have a rule blocking this traffic which occurs BEFORE the rule allowing it.

How do I change it? Simple.

First let's delete the rule we just made

iptables -L INPUT --line-numbers

will list the rules with their rule numbers. Let's say our rule is number 11

iptables -D INPUT 11   

Clearly this Deletes rule number 11 from the input chain.

Now instead of Appending I am going to Insert my rule into the number 1 (by default) position.

iptables -I INPUT -p tcp -s 150.100.whatever.something --dport 22 -j logaccept

So now rule number 1 is my new rule and the other rules have all shifted down a position.

If I wanted to change the IP address or any other aspect of my ssh rule I could use the -R (Replace) option for a specific rule number, and simply type in the new rule, i.e.

iptables -R INPUT 1 -p tcp -s 100.100.200.100 --dport 22 -j ACCEPT

This would replace rule number 1 on the INPUT chain with the new rule which has a new source IP address and jumps to ACCEPT instead of logaccept.

One more example: I want to run a mini web server on my router. Let's assume that it is already running on port 8000 and I can access it from the LAN side, but not from the WAN side. With

iptables -I INPUT -p tcp -d 192.168.1.1 --dport 8000 -j logaccept

the port 8000 will be opened. But I also have to setup NAT PREROUTING, so that the kernel forwards all packets on port 8000 from the outside to itself, 192.168.1.1:

iptables -t nat -I PREROUTING -p tcp -d $(nvram get wan_ipaddr) --dport 8000 -j DNAT --to 192.168.1.1:8000
 
 

端口转发至特定局域网IPPort Forwarding to a specific LAN IP

 

 

Port Forwarding can be accomplished from within the web interface here. However, the very same thing can be done a bit differently (tested and working), via command line. --u3gyxap: Example with port 443 and IP 192.168.1.2

iptables -t nat -I PREROUTING -p tcp -d $(nvram get wan_ipaddr) --dport 443 -j DNAT --to 192.168.1.2:443
iptables -I FORWARD -p tcp -d 192.168.1.2 --dport 443 -j ACCEPT

If you want to restrict the source IP (a question that is asked a lot on the forums), add -s 123.45.67.89 to one of your rules (replacing the IP address with the real one of course).

iptables -t nat -I PREROUTING -p tcp -s 123.45.67.89 -d $(nvram get wan_ipaddr) --dport 443 -j DNAT --to 192.168.1.2:443
iptables -I FORWARD -p tcp -d 192.168.1.2 --dport 443 -j ACCEPT

This should make it so only one IP address is able to access your forwarded port from the Internet.

In order for me to get this to work (v.24) I needed to put the "-s 123.45.67.89" in the "iptables -I FORWARD" command also - When it was in the PREROUTING command only I was still able to access the internal resource from any IP address!

 

拒绝登录特定IPDeny access to a specific IP address

iptables -I FORWARD -d 123.123.123.123 -j DROP

Which would DROP all packets destined to the given IP. Useful to block access to whatnot. If you want to log the entry when the IP is blocked you would set the jump location to logdrop, instead of DROP.

 


拒绝登录特定子网Deny access to a specific Subnet

iptables -I FORWARD -s 192.168.2.0/255.255.255.0 -j DROP

Deny access to a specific IP address range with Logging

iptables -I FORWARD -m iprange --src-range 192.168.1.10-192.168.1.13 -j logdrop

Many builds do not have the iprange match but you can use clever subnet masks to accomplish something similar as well, if the range aligns well on subnet boundaries. You may also be able to download a version of iptables that includes the iprange match via Optware.


 Deny access to a specific Outbound IP address with logging

iptables -I OUTPUT -d 239.255.255.250 -j logdrop

This becomes useful if there is a program that wants to gain an outbound connection to a specific address, but you don't want to allow the connection. In this specific example Windows uses this IP incorrectly as a broadcast address (search Google for more info). While viewing your router logs you will see Windows broadcast to this IP several times per minute. By default the router passes the broadcast and announces to everyone outside of your router that your PC exists. This rule will block traffic to this specific outbound IP and add an entry into the router log.


Block SMTP traffic except to specified hosts

Simple Mail Transfer Protocol operates on tcp port 25.

/usr/sbin/iptables -I FORWARD 1 -p tcp -d safe.server1.com --dport 25 -j logaccept
/usr/sbin/iptables -I FORWARD 2 -p tcp -d safe.server2.com --dport 25 -j logaccept
/usr/sbin/iptables -I FORWARD 3 -p tcp --dport 25 -j logdrop

Which would accept and log all smtp traffic to safe.server1.com and safe.server2.com, while blocking and dropping all other outgoing smtp traffic.


 Block outgoing SMTP traffic except from specified hosts

Simple Mail Transfer Protocol operates on tcp port 25.

iptables -I FORWARD 1 -p tcp -s 192.168.1.2 --dport 25 -j ACCEPT
iptables -I FORWARD 2 -p tcp -s 192.168.1.1/24 --dport 25 -j REJECT

Which would accept outgoing SMTP traffic from your internal SMTP server (192.168.1.2) but reject outgoing SMTP traffic from all other hosts on your LAN (192.168.1.1/24). Useful to enforce all your LAN clients to use your internal SMTP server, as well as to block any viruses and spam-generating trojans from sending mail to remote servers on their own.

Change "REJECT" to "logdrop" or "ACCEPT" to "logaccept" to add logging.

Caution! This will also block internal users from using your external IP as their SMTP server.


 Allow HTTP traffic only to specific domain(s)

Similarly, we can use the above method to filter other ports and protocols as well, such as standard web traffic operating on tcp port 80.

iptables -I FORWARD 1 -p tcp -d dd-wrt.com --dport 80 -j ACCEPT
iptables -I FORWARD 2 -p tcp --dport 80 -j DROP

Which would accept all http traffic to dd-wrt.com, while blocking outgoing http traffic to anywhere else. If you wish to allow multiple sites, insert additional rules before the DROP (making sure to order and number them correctly).


Block all traffic except HTTP HTTPS and FTP

This example blocks everything except our normal web traffic, encrypted (ssl), and the file transfer protocol.

iptables -I FORWARD 1 -p tcp -m multiport --dports 21,80,443 -j ACCEPT
iptables -I FORWARD 2 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -I FORWARD 3 -j DROP

Caution! Users are still able to get through the firewall if they are sly enough to use these permitted port numbers for their P2P or other application. In that case, you should consider using Access Restrictions to mitigate the possibility of that happening.


 Reject clients from accessing the router's configuration

This should prevent clients on the LAN (interface br0) from accessing the configuration interface of the router through any of the following ports (telnet/23, ssh/22, http/80, https/443)

iptables -I INPUT -i br0 -p tcp --dport telnet -j REJECT --reject-with tcp-reset
iptables -I INPUT -i br0 -p tcp --dport ssh -j REJECT --reject-with tcp-reset
iptables -I INPUT -i br0 -p tcp --dport www -j REJECT --reject-with tcp-reset
iptables -I INPUT -i br0 -p tcp --dport https -j REJECT --reject-with tcp-reset

Tip: If you disable management from the LAN, be sure to enable remote management on the WAN (or vice versa) or you will probably lock yourself out of the router.


 Restrict access by MAC address

In this example, we will demonstrate how to restrict access to the router's web interface by MAC address. In other words, only the computer having the specified MAC address should be able to access the web interface from the LAN.

First, if there are no Access Restrictions policies enabled and filtering by MAC addresses, you may need to insert the iptables mac module manually:

insmod ipt_mac
iptables -I INPUT -p tcp --dport 80 -m mac ! --mac-source 00:12:34:56:78:9A -j REJECT --reject-with tcp-reset

Notice the ! (bang) which is another new concept introduced here. It means "NOT". So, by inspecting the rule closely, we see that it will REJECT packets destined to port 80 of the router so long as they do NOT originate from our computer with the desired MAC address.

Caution! As usual when dealing with MAC addresses, be aware that it is possible for malicious user(s) to spoof their MAC address with that of a trusted machine. You can help combat this by use of static ARP entries, VLANs, etc.


 Modifying the TTL

The Time To Live is the maximum number of routers a packet will travel through before it is discarded. In certain situations, it may prove useful to increase it (typically) in order to make your network more reliable.

  • Example 1: Set the incoming TTL to 10, before the router routes it into the LAN
iptables -t mangle -I PREROUTING -i `nvram get wan_iface` -j TTL --ttl-set 10
  • Example 2: Set the outgoing TTL to 128, just as if a Windows machine was connected directly to the modem.
iptables -t mangle -I POSTROUTING -o `nvram get wan_iface` -j TTL --ttl-set 128
  • Example 3: Try to hide the fact that an outgoing packet was routed, by incrementing the TTL by one.
iptables -t mangle -I POSTROUTING -o `nvram get wan_iface` -j TTL --ttl-inc 1

Firewall Forwarded Ports

如果开启了DD-WRT的SPI 防火墙功能, 路由器会被很好的保护. 而iptables一个使用的用途是保护转发到内网IP的特定端口。这样做最简单的方法是:

  • 通过DD-WRT的web页面"端口转发"建立转现内网IP的端口转发。
  • Supplement those rules with custom iptables on the Firewall script found under Administration - Commands interface to restrict which hosts can access the ports involved

端口转发例子

The current port forwarded setup via the web GUI will be used as the basis to illustrate some examples:

  • Application: ssh Port: 4022 Protocol: TCP forward to IP address: 192.168.1.5 Port: 22
  • Application: ftp Port: 21 Protocol: TCP forward to IP address: 192.168.1.6 Port: 21

The example here port forwards external IP on port 4022 to internal server 192.168.1.5:22 for ssh and external port 21 to internal server 192.168.1.6:21 for ftp.


防火墙规则例子

你可能想限制ssh端口来防范脚本小子, and prevent brute force attack. 这样你可以限制一分钟可尝试建立3次新ssh链接. 任何进一步破解ssh端口的尝试会被丢弃:

iptables -I FORWARD -p tcp -d 192.168.1.5 --dport 22 -j DROP
iptables -I FORWARD -p tcp --dport 22 -m state --state NEW -m limit --limit 3/min -j ACCEPT
iptables -I FORWARD -p tcp --dport 22 -m state --state RELATED,ESTABLISHED -j ACCEPT

FTP access can also be limited to a certain network or network range in the following manner:

iptables -I FORWARD -p tcp -d 192.168.1.6 --dport 21 -j DROP
iptables -I FORWARD -p tcp -s 198.133.219.0/24 --dport 21 -j ACCEPT
iptables -I FORWARD -p tcp -s 69.147.64.0/18 --dport 21 -j ACCEPT
iptables -I FORWARD -p tcp --dport 21 -m state --state RELATED,ESTABLISHED -j ACCEPT

You can of course combine both, rate limit and IP addresses limiting. This following example limits ssh connection from 207.171.160.0/19 with the same rate limit applied, along with the FTP rules all on the same script:

# limit SSH connection from script kiddies in Amazon's network
iptables -I FORWARD -p tcp -d 192.168.1.5 --dport 22 -j DROP
iptables -I FORWARD -p tcp -s 207.171.160.0/19 --dport 22 -m state --state NEW -m limit --limit 3/min -j ACCEPT
iptables -I FORWARD -p tcp --dport 22 -m state --state RELATED,ESTABLISHED -j ACCEPT
# limit FTP connection to two subnets
iptables -I FORWARD -p tcp -d 192.168.1.6 --dport 21 -j DROP
iptables -I FORWARD -p tcp -s 198.133.219.0/24 --dport 21 -j ACCEPT
iptables -I FORWARD -p tcp -s 69.147.64.0/18 --dport 21 -j ACCEPT
iptables -I FORWARD -p tcp --dport 21 -m state --state RELATED,ESTABLISHED -j ACCEPT


For multiport INPUT (or FORWARD if you choose) rate limiting, the following syntax rules can be esstablshed:

 

wanf=`nvram get wan_iface`
iptables -I INPUT 2 -i $wanf -p tcp -m multiport --dports 21,22,80,82 -j logdrop
iptables -I INPUT 2 -i $wanf -p tcp -m state --state NEW -m multiport --dports 21,22,80,82 -m limit --limit 3/minute --limit-burst 2 -j logaccept

 

To verify that the rules are working, open a terminal session and type iptables -vnL | more


If you're adding a lot of rules, it helps to separate them with comments using the # prefix. You can of course use the basics of iptables explained in this article to make your rules more complex to suit your needs. However, instead of ordering the rules, the examples here merely insert these new ones on top of the FORWARD chain. This ensures that the firewall rules that limit traffic appear on top of the chain and gets applied first.

You may examine these rules on the router at anytime by accessing the router's command prompt and running the command "iptables -vnL"


 Logging

You can consider turning on logging temporarily for any of your rules. This is useful if you're testing new setup to confirm that the rules are doing what you intend to block or allow. First enable logging via the web UI at Security - Firewall tab. Then substitute the jump target or "-j" to a logging target for each of your iptables rule:

  • DROP with logdrop
  • REJECT with logreject
  • ACCEPT with logaccept

Example if you wanted to check and confirm if traffic forwarded to port 21 is correctly dropped you would substitute:

iptables -I FORWARD -p tcp -d 192.168.1.6 --dport 21 -j DROP

with

iptables -I FORWARD -p tcp -d 192.168.1.6 --dport 21 -j logdrop

Logged data can be viewed on the web UI on the same page or on the command prompt in the file "/var/log/messages"


Firewall blocks DHCP renewal responses

iptables -I INPUT -p udp --dport 68 -j ACCEPT

The default configuration of the firewall blocks DHCP renewal responses which causes the router's DHCP client to request a new IP and for current connections to be dropped whether the address changes or not. ~phuzi0n Use this command to fix it. Replace ACCEPT with logaccept to verify it is functioning.


警告

在开机程序中增加 iptables 命令会增加把自己困在盒子外面不能操作的风险,那样除了重新开始别无他法. 如果你在试验新的命令,在iptables命令之前增加一段等待的时间,可以避免陷入这种困境. 这样在命令起作用之前给自己,比如说5分钟(sleep 300)的时间。如果命令事与愿违,你又不能登陆,简单的通过关机重启,你就有5分钟时间能登陆进去.

你可能感兴趣的:(iptables)