Linux之Iptables简易应用(1)

加载内核模块

在早期版本的Linux内核,iptables的NAT,一般不能使用FTP的20端口,可以使用下面命令加载模块
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_conntrack_ftp.ko
insmod /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter/ip_nat_ftp.ko
或使用modprobe命令加载(推荐modprobe,因为insmod不解决依赖关系)
允许NAT转换FTP的跟踪连接,如下:
modprobe ip_nat_ftp
允许本机FTP的跟踪连接,这样就不必设置允许20和被动端口了
modprobe ip_conntrack_ftp

脚本中常用配置:

modules="ip\_conntrack\_ftp ip\_conntrack\_irc ip\_nat\_pptp ip\_gre ip\_conntrack\_pptp ip\_conntrack\_proto\_gre"
for mod in $modules
do
    testmod=`lsmod | grep "${mod}"`
    if [ "$testmod" == "" ]; then
        modprobe $mod
    fi
done

基于近些年Linux内核版本的系统,比如rhel6+,还未仔细分析过是否默认支持上述模块,没有的话,可以根据业务场景选择是否加载。

基本操作

iptables规则执行顺序是从上到下,前面的匹配后就不再看后面的。
基本语法:
iptables [-t table] -[AD] chain rule-specification [options]
iptables [-t table] -I chain [rulenum] rule-specification [options]
iptables [-t table] -R chain rulenum rule-specification [options]
iptables [-t table] -D chain rulenum [options]
iptables [-t table] -[LFZ] [chain] [options]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target [options]
iptables [-t table] -E old-chain-name new-chain-name

iptables -A 添加一条规则到末尾
iptables -D 删除
iptables -I 插入一条规则到最前面
iptables -R 替换
iptables -vnL 列表
iptables -vnL --line-numbers 列表时同时显示策略号,方便更新局部策略,而不需要重新配置所有策略。

常用模块和参数

iprange

–src-range ip-ip Match source IP in the specified range.
–dst-range ip-ip
例:
-m iprange --src-range 192.168.10.2-192.168.10.6
iptables -I INPUT -m iprange --src-range 192.168.10.2-192.168.10.6 -p tcp --dport 22 -j ACCEPT

icmp

-p icmp --icmp-type 类型 ping: type 8 pong: type 0

sport和dport

-p tcp
-p udp
–sport 和–dport 必须配合-p 参数使用

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 -p tcp or -p udp.

   --source-ports [!] port[,port[,port:port...]]
          Match if the source port is one of the given ports.  The flag --sports is a convenient alias for this option.

   --destination-ports [!] port[,port[,port:port...]]
          Match if the destination port is one of the given ports.  The flag --dports is a convenient alias for this option.

   --ports [!] port[,port[,port:port...]]
          Match if either the source or destination ports are equal to one of the given ports.

例:
-p tcp -m multiport --dports 20,21,22

state

-m state --state 状态 状态:NEW、RELATED、ESTABLISHED、INVALID
NEW:有别于tcp 的syn
ESTABLISHED:连接态
RELATED:衍生态,与conntrack 关联(比如FTP常用)
INVALID:不能被识别属于哪个连接或没有任何状态

mac

mac --mac-source [!] address
        Match source MAC address.  It must be of the form XX:XX:XX:XX:XX:XX.  Note that this only makes sense for packets  coming  from
        an Ethernet device and entering the PREROUTING, FORWARD or INPUT chains.

line-numbers

--line-numbers
              When listing rules, add line numbers to the beginning of each rule, corresponding to that rule's position in the chain.

limit

   This module matches at a limited rate using a token bucket filter.  A rule using this extension will match until this limit is reached
   (unless the flag is used).  It can be used in combination with the LOG target to give limited logging, for example.

   --limit rate
          Maximum average matching rate: specified as a number, with an optional second minute hour or day suffix;  the
          default is 3/hour.
   注意:
   limit 英语上看是限制的意思,但实际上只是按一定速率去匹配而已,要想限制的话后面要再跟一条DROP,但使用下面这条就不必了。

   --limit-burst number
          Maximum  initial  number  of  packets  to  match: this number gets recharged by one every time the limit specified above is not
          reached, up to this number; the default is 5.

comment

   Allows you to add comments (up to 256 characters) to any rule.
   --comment comment
   Example:
          iptables -A INPUT -s 192.168.0.0/16 -m comment --comment "A privatized IP block"

-j 动作

-j有如下动作:
DROP 丢弃
ACCEPT 接受
LOG 记入日志,默认是message
–log-tcp-options :记录tcp header的相关资讯
–log-ip-options :记录ip header的相关资讯
RETURN 返回父链,例:假设一个包进入了INPUT 链,匹配了某条target 为–jump EXAMPLE_CHAIN 规则,然后进入了子链EXAMPLE_CHAIN。在子链中又匹配了某条规则,恰巧target 是–jump RETURN,那包就返回INPUT 链了。如果在INPUT链里又遇到了–jump RETURN,那这个包就要交由缺省的策略来处理了。
SNAT 更换源地址,NAT
DNAT 更换目的地址,NAT
MASQUERADE 伪装为-o选项指定的网卡上的IP,比SNAT和DNAT负载稍高

SNAT示例

通常用于客户端上外网
iptables -t nat -A POSTROUTING -s 192.168.0.0/255.255.255.0 -d 1.2.3.0/255.255.255.0 -j SNAT --to-source 192.168.1.2
特别注意192.168.1.2是本系统的出站网口IP,通过ip a可以查看到

DNAT示例

通常用于服务器端口的发布
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to X.X.X.X:8080

应用案例

通过iptables实现跨地域转发端口

iptables端口代理,做到像nginx,haproxy一样转发TCP请求,但是它不能关心应用层的东西,比机主机头,没有超时时间限制,除非网络不稳定

开启系统路由

echo "1" > /proc/sys/net/ipv4/ip_forward

或者修改/etc/sysctl.conf
net.ipv4.ip_forward = 1
然后执行sysctl -p 永久生效

添加nat策略到转发服务器iptables主脚本(假设通过脚本管理iptables且有一个主脚本),在转发服务器添加,示例如下

iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
iptables -t nat -F PREROUTING
iptables -t nat -F POSTROUTING
iptables -t nat -A PREROUTING -i eth0 -d 转发服务器本机系统ip -p tcp -m multiport --dport 80,8080 -j DNAT --to-destination 目标服务器公网ip
iptables -t nat -A POSTROUTING -o eth0 -d 目标服务器公网ip -p tcp -m multiport --dport 80,8080 -j SNAT --to-source 转发服务器本机系统ip

运行防火墙主脚本

LOG示例

iptables -A INPUT -s x.x.x.x -j LOG --log-tcp-options --log-ip-options --log-prefix '[IPTABLES IMLOG] : ’

调节MTU

iptables -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1400:1536 -j TCPMSS --clamp-mss-to-pmtu

简单限速

-A FORWARD -m limit -d 192.168.0.2 --limit 86/sec -j ACCEPT # 这句意思是限定每秒只转发86个到达192.168.0.2的数据包(约每秒128KB 一个数据包是1.5KB)

-A FORWARD -d 192.168.0.2 -j DROP #这句作用是超过限制的到达192.168.0.2的数据包不通过)
上面两条同时应用才有效。

通过状态模块实现FTP策略

对于FTP,如果有允许状态RELATED,ESTABLISHED的规则,并加载了ip_conntrack_ftp模块
就不必再单独允许20和被动端口,如:
modprobe ip_conntrack_ftp
modprobe ip_nat_ftp
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -s -p tcp --dport 21 -j ACCEPT

防攻击示例

丢弃坏的TCP包
[root@tp ~]#iptables -A FORWARD -p TCP ! --syn -m state --state NEW -j DROP

处理IP碎片数量,防止攻击,允许每秒100个,-f就是指定碎片包
[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包通过,就是因为我在这里有限制.

限制 ping (echo-request) 传入的速度
限制前, 可正常每 0.2 秒 ping 一次
ping your.linux.ip -i 0.2

限制每秒只接受一个 icmp echo-request 封包
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 1 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j Drop
–limit 1/s 表示每秒一次; 1/m 则为每分钟一次
–limit-burst 表示允许触发 limit 限制的最大次数

限制 ssh 连入频率
建立自订 Chain, 限制 tcp 连线每分钟一次, 超过者触发 Log 记录 (记录在 /var/log/messages)
iptables -N ratelimit
iptables -A ratelimit -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A ratelimit -p tcp --syn -m limit --limit 1/m --limit-burst 1 -j ACCEPT
iptables -A ratelimit -p tcp -j LOG --log-level “NOTICE” --log-prefix “[RATELIMIT]”
iptables -A ratelimit -p tcp -j Drop

引用自定义Chain, 限制 ssh (tcp port 22) 连入频率
iptables -A INPUT -p tcp --dport 22 -s 192.168.0.0/16 -j ACCEPT (特定 IP 来源不受限制)
iptables -A INPUT -p tcp --dport 22 -j ratelimit
结合sshd_config设定
LoginGraceTime 30 密码输入时限为 30 秒
MaxAuthTries 2 最多只能输入 3 次密码

防治 SYN-Flood 碎片攻击
iptables -N syn-flood
iptables -A syn-flood -m limit --limit 100/s --limit-burst 150 -j RETURN
iptables -A syn-flood -j DROP
iptables -I INPUT -j syn-flood

控制单个IP的最大并发连接数
iptables -I INPUT -p tcp --dport 80 -m connlimit --connlimit-above 30 -j REJECT #允许单个IP的最大连接数为 30
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT

控制单个IP在一定的时间(比如60秒)内允许新建立的连接数
iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --update --seconds 60 --hitcount 30 -j REJECT
iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --set -j ACCEPT
#单个IP在60秒内只允许最多新建30个连接

iptables也有缓存cc或ddos攻击的能力,但现如果很多cc和ddos都不是iptables能解决的,这里就略了。

初始化和默认策略示例

初始化(不会影响默认策略)
iptables -F 清空规则
iptables -X 清除自定义规则链
iptables -Z 将所有chain计数归零

默认策略,通过iptables -A或-I等是不会改变默认策略的。
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

iptables -t nat -P PREROUTING ACCEPT
iptables -t nat -P OUTPUT ACCEPT
iptables -t nat -P POSTROUTING ACCEPT
iptables -t nat -F
iptables -t nat -X

常规简易配置综合脚本范例

一个非常简易通用适用于大部分场景的基础脚本,基于此广泛应用于rhel5-rhel9系列和ubuntu系列的数千台系统,有充分的实践过程,可靠且易于维护。
在有docker或k8s的环境中,建议基于此改用自定义链维护自定义策略,在本文通过自定义链并写入开机启动的解决案例中有采用自定义链的方式可参考。

#!/bin/bash
###################################
# function iptables 常用linux防火墙主脚本 默认阻止所有,允许部分
![](https://img-blog.csdnimg.cn/img_convert/9a8cb5f8c0ec69e6499adead0da6e95b.png)



最全的Linux教程,Linux从入门到精通

======================

1.  **linux从入门到精通(第2版)**

2.  **Linux系统移植**

3.  **Linux驱动开发入门与实战**

4.  **LINUX 系统移植 第2版**

5.  **Linux开源网络全栈详解 从DPDK到OpenFlow**



![华为18级工程师呕心沥血撰写3000页Linux学习笔记教程](https://img-blog.csdnimg.cn/img_convert/59742364bb1338737fe2d315a9e2ec54.png)



第一份《Linux从入门到精通》466页

====================

内容简介

====

本书是获得了很多读者好评的Linux经典畅销书**《Linux从入门到精通》的第2版**。本书第1版出版后曾经多次印刷,并被51CTO读书频道评为“最受读者喜爱的原创IT技术图书奖”。本书第﹖版以最新的Ubuntu 12.04为版本,循序渐进地向读者介绍了Linux 的基础应用、系统管理、网络应用、娱乐和办公、程序开发、服务器配置、系统安全等。本书附带1张光盘,内容为本书配套多媒体教学视频。另外,本书还为读者提供了大量的Linux学习资料和Ubuntu安装镜像文件,供读者免费下载。



![华为18级工程师呕心沥血撰写3000页Linux学习笔记教程](https://img-blog.csdnimg.cn/img_convert/9d4aefb6a92edea27b825e59aa1f2c54.png)



**本书适合广大Linux初中级用户、开源软件爱好者和大专院校的学生阅读,同时也非常适合准备从事Linux平台开发的各类人员。**

> 需要《Linux入门到精通》、《linux系统移植》、《Linux驱动开发入门实战》、《Linux开源网络全栈》电子书籍及教程的工程师朋友们劳烦您转发+评论




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化的资料的朋友,可以点击这里获取!](https://bbs.csdn.net/topics/618542503)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值