Iptables基础

    每一个对应的钩子,都应该有它的默认处理机制,就像手机为例,我们晚上十点后不期望打扰,但是对某些指定的时间又允许接入,有两种设定方式,第一可以设置白名单,仅在仅允许部分人可以晚上十点之后给我发送信息,其他人一律拒绝。第二可以设定黑名单,有些人晚上经常骚扰,就只拒绝接收这部分人的信息,其他人一律允许。同样的道理,我们的iptables也一样,只设定指定人可以访问这叫白名单,只拒绝部分人访问这叫黑名单;
    所以同一类规则当中,应该适应范围小的先生效,所以我们应当把同一类规则当中匹配范围较小的或者检查范围更严格的放在前面,自上而下进行检查,如果是不同类别的规则,我们应该把最长使用放在前面,比如一个web服务一个ssh服务,那么很显然,我们的web服务是访问较大的,所以我们应当将web服务的规则放在最前面;
规则
组成部分
    根据规则匹配条件来尝试匹配报文,一旦匹配成功,就由规则定义的处理动作做出处理;
匹配条件
基本匹配条件:-s、-d、-p、-l、-o
扩展匹配条件:-m
处理动作
基本处理动作:ACCEPT、DROP
扩展处理动作:REJECT、RETURN、LOG、REDIRECT...
自定义处理动作
Iptables链:
内置链:对应的钩子;
自定义链:用户内置链的扩展 和补充,可实现更灵活的规则管理;
添加规则的考量重点
1、要实现哪种功能:判断添加到哪个表上更合适;
2、报文流经的路径:判断添加到哪个链上更合适;
链:链上的规则次序,即为检查的次序;
    1、同类规则(访问同一应用),匹配反问较小的放上面;
    2、不同类规则(访问不同应用),匹配到报文频率较大的放在上面;
    3、将那些可由一条规则描述的多个规则合并在一起;
    4、设置默认策略;

iptables命令

    高度模块化,由诸多扩展模块实现其检查条件或处理动作的定义;
        /usr/lib64/xtables/
            IPv6:libip6t_
            IPv4:libipt_, libxt_
命令格式
iptables [-t table] {-A|-C|-D} chain rule-specification
iptables [-t table] -I chain [rulenum] rule-specification
iptables [-t table] -R chain rulenum rule-specification
iptables [-t table] -D chain rulenum
iptables [-t table] -S [chain [rulenum]]
iptables [-t table] {-F|-L|-Z} [chain [rulenum]] [options...]
iptables [-t table] -N chain
iptables [-t table] -X  [chain]
iptables [-t table] -P chain target
iptables [-t table] -E old-chain-name new-chain-name
rule-specification = [matches...]  [target]
match = -m matchname [per-match-options]
target = -j targetname [per-target-options]
规则格式:iptables   [-t table]   COMMAND   chain   [-m matchname [per-match-options]]   -j targetname [per-target-options]

    -t table:
        raw, mangle, nat, [filter]

    COMMAND:
        链管理:
            -N:new, 自定义一条新的规则链;
            -X: delete,删除自定义的规则链;
                注意:仅能删除 用户自定义的 引用计数为0的 空的 链;
            -P:Policy,设置默认策略;对filter表中的链而言,其默认策略有:
                ACCEPT:接受
                DROP:丢弃
                REJECT:拒绝
            -E:重命名自定义链;引用计数不为0的自定义链不能够被重命名,也不能被删除;
        规则管理:
            -A:append,追加;
            -I:insert, 插入,要指明位置,省略时表示第一条;
            -D:delete,删除;
                (1) 指明规则序号;
                (2) 指明规则本身;
            -R:replace,替换指定链上的指定规则;

            -F:flush,清空指定的规则链;
            -Z:zero,置零;
                iptables的每条规则都有两个计数器:
                    (1) 匹配到的报文的个数;
                    (2) 匹配到的所有报文的大小之和;                      
        查看:
            -L:list, 列出指定鏈上的所有规则;
                -n:numberic,以数字格式显示地址和端口号;
                -v:verbose,详细信息;
                    -vv, -vvv
                -x:exactly,显示计数器结果的精确值; 
                --line-numbers:显示规则的序号;

    chain:
        PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING

    匹配条件:
        基本匹配条件:无需加载任何模块,由iptables/netfilter自行提供;
            [!] -s, --source  address[/mask][,...]:检查报文中的源IP地址是否符合此处指定的地址或范围;
            [!] -d, --destination address[/mask][,...]:检查报文中的目标IP地址是否符合此处指定的地址或范围;
                所有地址:0.0.0.0/0
            [!] -p, --protocol protocol
                protocol: tcp, udp, udplite, icmp, icmpv6,esp, ah, sctp, mh or  "all"
                    {tcp|udp|icmp}
            [!] -i, --in-interface name:数据报文流入的接口;只能应用于数据报文流入的环节,只能应用于PREROUTING,INPUT和FORWARD链;
            [!] -o, --out-interface name:数据报文流出的接口;只能应用于数据报文流出的环节,只能应用于FORWARD、OUTPUT和POSTROUTING链;                                         
            -m:指明要使用的模块的;
            -j:处理结果;

    处理动作:
        -j targetname [per-target-options]
            ACCEPT
            DROP
            REJECT

匹配条件

基本匹配条件:PARAMETERS
扩展匹配条件:
    隐式扩展:在使用-p选项指明了特定的协议时,无需再同时使用-m选项指明扩展模块的扩展机制;
    显式扩展:必须使用-m选项指明要调用的扩展模块的扩展机制;
隐式扩展
    不需要手动加载扩展模块;因为它们是对协议的扩展,所以,但凡使用-p指明了协议,就表示已经指明了要扩展的模块;
tcp:
    [!] --source-port, --sport port[:port]:匹配报文的源端口;可以是端口范围;
    [!] --destination-port,--dport port[:port]:匹配报文的目标端口;可以是端口范围;
    [!] --tcp-flags  mask  comp
            mask is the flags which we should examine,  written as a comma-separated list,例如 SYN,ACK,FIN,RST
            comp is a comma-separated list  of  flags  which must be set,例如SYN
            例如:“--tcp-flags  SYN,ACK,FIN,RST  SYN”表示,要检查的标志位为SYN,ACK,FIN,RST四个,其中SYN必须为1,余下的必须为0;
    [!] --syn:用于匹配第一次握手,相当于”--tcp-flags  SYN,ACK,FIN,RST  SYN“;                             
udp:
    [!] --source-port, --sport port[:port]:匹配报文的源端口;可以是端口范围;
    [!] --destination-port,--dport port[:port]:匹配报文的目标端口;可以是端口范围;  
icmp:
    [!] --icmp-type {type[/code]|typename}
            echo-request:8
                    echo-reply:0

显式扩展

    必须要手动加载扩展模块, [-m matchname [per-match-options]];         
1、multiport
    This  module  matches  a  set  of  source  or  destination  ports. Up  to 15 ports can be specified.  A port range (port:port) counts as two ports.  It can only be used in conjunction with one of the following protocols: tcp,  udp, udplite, dccp and sctp.

    以离散或连续的 方式定义多端口匹配条件,最多15个;

    [!] --source-ports,--sports port[,port|,port:port]...:指定多个源端口;
    [!] --destination-ports,--dports port[,port|,port:port]...:指定多个目标端口;

    # iptables -I INPUT  -d 172.16.0.7 -p tcp -m multiport --dports 22,80,139,445,3306 -j ACCEPT

2、iprange
    以连续地址块的方式来指明多IP地址匹配条件;
    [!] --src-range from[-to]
    [!] --dst-range from[-to]

    # iptables -I INPUT -d 172.16.0.7 -p tcp -m multiport --dports 22,80,139,445,3306 -m iprange --src-range 172.16.0.61-172.16.0.70 -j REJECT

3、time
    This  matches  if the packet arrival time/date is within a given range.

     --timestart hh:mm[:ss]:起始时间
     --timestop hh:mm[:ss]:结束时间

     [!] --weekdays day[,day...]

     [!] --monthdays day[,day...]

    --datestart YYYY[-MM[-DD[Thh[:mm[:ss]]]]]
    --datestop YYYY[-MM[-DD[Thh[:mm[:ss]]]]]

     --kerneltz:使用内核配置的时区而非默认的UTC;

4、string
    This modules matches a given string by using some pattern matching strategy. 

    --algo {bm|kmp}
    [!] --string pattern
    [!] --hex-string pattern

    --from offset
    --to offset

    ~]# iptables -I OUTPUT -m string --algo bm --string "gay" -j REJECT

5、connlimit 
    Allows  you  to  restrict  the  number  of parallel connections to a server per client IP address (or client address block).

    --connlimit-upto n
    --connlimit-above n

    ~]# iptables -I INPUT -d 172.16.0.7 -p tcp --syn --dport 22 -m connlimit --connlimit-above 2 -j REJECT

6、limit 
    This  module  matches  at  a limited rate using a token bucket filter. 

    --limit rate[/second|/minute|/hour|/day]
    --limit-burst number

    ~]# iptables -I OUTPUT -s 172.16.0.7 -p icmp --icmp-type 0 -j ACCEPT

    限制本机某tcp服务接收新请求的速率:--syn, -m limit

7、state
        连接追踪,默认情况下,只要访问连接断开了,再次访问,对于服务器来讲就是一个新的连接,我们就想办法把这个连接记录下来,等下次访问的时候,我们的服务器能够识别这个请求来自于之前连接过的请求,如果没有记录那说明第一次来,那么这个时候记录下来,然后做相应的操作,就相当于在内核中开辟一段内存,记录;

    [!] --state state
        INVALID, ESTABLISHED, NEW, RELATED or UNTRACKED.

        NEW: 新连接请求;
        ESTABLISHED:已建立的连接;
        INVALID:无法识别的连接;
        RELATED:相关联的连接,当前连接是一个新请求,但附属于某个已存在的连接;
        UNTRACKED:未追踪的连接;

        state扩展:
            内核模块装载:
                nf_conntrack
                nf_conntrack_ipv4

                手动装载:
                    nf_conntrack_ftp 

    追踪到的连接:
        /proc/net/nf_conntrack

    调整可记录的连接数量最大值:
        /proc/sys/net/nf_conntrack_max

    超时时长:
        /proc/sys/net/netfilter/*timeout*

处理动作(跳转目标):

-j targetname [per-target-options]
    简单target:
        ACCEPT, DROP

    扩展target:
        REJECT
            This is used to send back an error packet in response to the matched packet: otherwise it is equivalent to  DROP  so it  is  a  terminating  TARGET,  ending  rule traversal.

            --reject-with type
                The type given can be icmp-net-unreachable, icmp-host-unreachable, icmp-port-unreachable, icmp-proto-unreach‐ able, icmp-net-prohibited, icmp-host-prohibited, or icmp-admin-prohibited (*), which return  the  appropriate ICMP  error  message (icmp-port-unreachable is the default).

        LOG
            Turn  on  kernel  logging of matching packets.

            --log-level
            --log-prefix

            默认日志保存于/var/log/messages

        RETURN:
            返回调用者,一般在自定义链上使用,返回到主链往下匹配;

    自定义链做为target,可以自己自定义一条链,然后基于它做处理
自定义链示例
    编写自定义链路仅允许指定主机ping我们的本机;
# 允许22端口通行
[root@node1 ~]# iptables -I INPUT -p tcp --dport 22 -j ACCEPT  
[root@node1 ~]# iptables -I INPUT -p tcp --sport 22 -j ACCEPT
# 开启默认拒绝策略
[root@node1 ~]# iptables -A INPUT -j REJECT
# 新建自定义链
[root@node1 ~]# iptables -N check_input
# 在自定义链上添加规则,只要是172.16.1.3发来的ICMP请求一律允许
[root@node1 ~]# iptables -I check_input -s 172.16.1.3 -p icmp -j ACCEPT
# 在INPUT链上做规则,只要是ICMP协议全部转交给check_input链做处理
[root@node1 ~]# iptables -I INPUT -p icmp -j check_input

# 在172.16.1.3做测试
[root@node2 ~]# ping -c 1 172.16.1.2
PING 172.16.1.2 (172.16.1.2) 56(84) bytes of data.
64 bytes from 172.16.1.2: icmp_seq=1 ttl=64 time=0.404 ms

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注