The netfilter/ptables of the Linux firewall

Source: Internet
Author: User
Tags ack ftp connection local time printable characters ftp protocol iqiyi

Date: 2018.2.5
Li Qiang
Reference: man,info,magedu handouts, Universal Internet
Lab environment: VMware? Workstation Pro, Centos 6.9,centos 7.4,securecrt Version 8.1.4
Statement: The following English is purely personal translation, English Class B, welcome to correct, the following is purely personal understanding, and there is no right or wrong, just reference, piracy does not correct, can be limited, hope not fraught as well.
Version: v1-2018.2.5

For kernel-level functionality, provided by the NetFilter component, you need to install the Iptables package to configure this feature via commands.

1. References
官方站点:[http://www.netfilter.org]
2. Working principle
    • First of all, we need to know that the three flow of messages

      1, into the machine: pretouting----INPUT----User process space

      2, outflow of the machine: User process space----OUTPUT----postrouting

      3, forwarding: prerouting----FORWARD----postrouting

    • Transmission of packets in the kernel

      1, when a packet into the network card, will enter the pretouring chain, the kernel through the destination IP address of the packet with the routing table to determine whether the data need to be forwarded out

      2, if the packet is entered into the machine, it will enter the input chain, and then respond to the process of processing these packets, generating new packets, sent to the output chain, and then sent through the postrouting chain

      3, if the packet is to be forwarded, and the kernel allows forwarding, the packet will go through the forward chain, and then forward from the postrouting chain.

Five positions: Input,output,forward,prerouting,postroutig

netfilter对外提供五个hook function 对应上面五个位置,iptables通过在5个位置进行规则的设置来控制网络报文的转发netfilter前端管理工具    cui:iptables,firewall-cmd    gui:firewall-configip数据包处理的规则集rules,分组在chain上,然后存放于过滤表table中,chain默认有5类,table默认有4种。用户也可以将类似的规则rule分组成自定义的chain中,然后存放于table中。总之防火墙的功能,就是数据报文来了,kernel发现开启了防火墙的功能,然后根据防火墙设置的匹配条件,对数据包进行相应的处理。

The above explanation is too boring, so in other words, is a rich rich emperor, but also afraid of death, so please the Ace bodyguard to protect him, he found the bodyguard Long that is netfilter, tell him my safety depends on you, the results netfilter no matter, found a iptables outsourcing company , iptables company on the investigation site, sent a number of bodyguards stationed in 5 positions chain the past, respectively to achieve different functions (raw no good metaphor, issued tickets mangle, search filter, guide the NAT) respectively stationed at the door, in charge of access to personnel vehicles for inspection, Stationed in the courtyard, to handle the past personnel, stationed in the bedroom door, on the access to the employer and the exchange of people to check. Good personnel have been in place, the deployment has been in place specific how to check is a set of iptables company, told NetFilter Large, NetFilter said tube, and then to tell 5 bodyguards how to check, as to how to check, is certainly root big Boss, Root find Netfilter,netfilter said I do not understand, you do not tell iptables, and then Root tells Iptables need to achieve what needs, and then iptables to write the rules to tell NetFilter, you go so, NetFilter said that. Then 5 positions a number of bodyguards began to work, of course, if not enough to add is the custom of the chain, when Root did not know, the right to iptables and NetFilter, if iptables and netfilter collusion blind will be killed by their own, So said Qin Hui, Yansong, Wei the flow is to have to prevent. Nonsense to here.

    • Definition and classification of firewalls

      1. What is a firewall?

      工作与主机或者网络边缘,对进出的报文通过实现定义的规则进行检查,并且有匹配的规则的工作进行处理的一组硬件或者软件,甚至是二者结合

      2, the classification of the firewall

      主机防火墙、网络防火墙;硬件防火墙、软件防火墙;网络层防火墙、应用层防火墙

      3. Safety Protection Equipment

      硬件的应用层防火墙中可以集成AV和IPS组件。honeypot 蜜罐漏扫设备堡垒机
3. Iptables Command Line management tool Iptables how it works
Command-line tools that work in user space, write rules, and then send the written rules to NetFilter, telling the kernel how to handle data messages iptables There are four tables, five chains and some rules that make up four tables table filter: Data Filtering rules table NAT: Network address translation Rules table Mangle: Modify data marker bit rule Table raw: Turn off the connection tracking mechanism enabled on the NAT table, speed up packet traversal through the firewall with a high order of Raw-->mangle-->nat-->filter five built-in chain chain INPU T OUTPUT ForWord prerouting postrouting A series of rules in each table that can be viewed by iptable-t table-vnl, as in different table chain name but is not the same content.    Are independent of each other.        Each table represents a feature of Iptables 1, the filter table corresponds to the location of the processing is input,output and forward, so the filter table has only 3 built-in Input,output and forward series of rule sets. 2. The NAT table corresponds to the location of prerouting and postrouting and input and output, so there are only 4 built-in rrerouting and postrouting and input and output series rule sets in NAT tables.        Rrerouting is mainly used to do dnat,postrouting Snat 3, mangle table corresponding to the location can be 5 positions in any position. 4. Raw rule (rule-specification) match condition (matches) basic match: IP, port, TCP flags (SYN,ACK,FIN,RST,USG,PSH) extension match:        Time, state, etc., require additional dynamic library support, so use an extended match to ensure that the corresponding so file exists. Processing action (target) built-in action: Accept,drop,reject,snat,dnat,masqureade,mark,log Custom Action: Custom chain chain application location built-in Chain: Input,output,forward,prerouting,postrouting Custom chain: 

Steps to set up filtering in a network device

        1、先定义域,默认域有local,management,input,output,dmz        2、将接口加入到域中        3、定义域到域的数据流方向        4、定义规则        5、应用规则到域到域的方向,行程域间策略和域内策略iptables添加的要点        1、要实现哪些功能,判断-t 在哪个table上        2、报文流经的路径,判断对哪个chain操作        3、报文的流向,判断源和目的        4、匹配规则,业务需要chain中规则的次序        1、按照从上到下次序匹配,一旦匹配到不再向下匹配,因此匹配范围小的往上放        2、匹配度最多的往上放,能合并的规则尽量放到一条规则里去        3、所有都匹配不到后会去默认匹配规则
How to use the iptables command
    • Format
    iptables  -t table  command chain  rule-specificiton    rule-specifiction= match  target     match = [-m]     target= -j targetname per-targetname-options    table:主要有filter,nat,mangle,raw,security等    chain:内置有INPUT,OUTPUT,FORWORD,PREROUTING,POSTROUTING    targetname:        ACCEPT        DROP        REJECT:--reject-with:icmp-port-unreachable默认        RETURN:返回调用链        REDIRECT:端口重定向        LOG:记录日志,dmesg        MARK:做防火墙标记        DNAT:目标地址转换        SNAT:源地址转换        MASQUERADE:地址伪装
    • Options
    The options for chain are:-A,--append chain rule-specification//Append new rules to the following-I,--insert chain [rulenum] Rule-sp Ecification//Insert a new rule, insert the default into the first line, you can rulenum specify the order of insertion, where the rule moves backward-C,--check chain rule-specification//Check rule is No already exists, there is no hint, there is no report error message-D,--delete chain rule-specification//delete 1 or more rules, 2 formats, first specified rule delete, second specified ordinal delete-D,--    Delete Chain rulenum-f,--flush [chain]//Clears all the rules of the selection chain, if no chain is selected for all chain of the default current table, -R,--replace chain Rulenum rule-specification//Replace rule with specified ordinal-Z,--zero [chain [rulenum]]//clear In addition to the statistics of bytes and packets for all specified chain or chain rulenum, if not specified, all chain are zeroed-S,--list-rules [chain]//-L,--        list [chain]//lists the rules for the specified chain, does not perform all chain of the selected tables, usually with-VNL, n must be in front of L.                                   -V,--verbose//details,-VV, or-vvv more detailed-N,--numeric Digital format output, which, by default, resolves an IP address or port to a matched HOstname,protocols,service-X,--exact//Display accurate statistical values--line-numbers     The rule number in each chain is displayed when the rules is-N,--new-chain chain//Creates a user-defined chain -X,--delete-chain [chain]//delete user-defined empty chain, if not specified, delete all custom empty chain, if not NULL, first clear the rule with-F and then use-X-                           E,--rename-chain old-chain new-chain//modify user-defined chain name-p,--policy chain target  Set the default target for the specified chain, the default is accept--modprobe=command for the matching criteria: basic matching Criteria.     -P,--protocol protocol-p TCP--dport port[:p ort]: matches one or more contiguous destination ports--sport port[:p ORT] : Match one or more contiguous source ports--tcp-flags Mask Comp: (Flags:syn ACK FIN RST URG PSH all NONE) Mask: means to match        Which flags are flags, multiple separate comp with commas: Indicates which flags are flags 1, and multiple separated by commas--syn: equivalent to--tcp-flags syn,rst,ack,fin syn -P UDP--dporT port[:p ort]--sport port[:p ort]-p ICMP--icmp-type type[/code]|typename iptables- P icmp-h//Can get ICMP help iptables-p tcp-h//Can get help from TCP iptables-p udp-h//Can get help for UDP [!]-S,--so       Urce address[/mask][,...]  Specify check source IP address [!]-D,--destination address[/mask][,...] Specify the check destination IP address [!]-I,--in-interface name//Specify check-in interface address [!]-O,--out-interface name//means Fixed detection interface Address Extension matching conditions:-M,--match match Centos6 under man iptables Centos7 under man iptables-extensions often have-M multi         Port//Specify multiple disjoint addresses, up to 15, Port:port address range count 2 [!]--source-ports,--Sports Port[,port|,port:port] ... [!]         --destination-ports,--dports Port[,port|,port:port] ... [!] --ports Port[,port|,port:port] ...-m iprange//Specify the address range [!]--src-range from[-to] [!]--         Dst-range From[-to]-M mac-m string///to the application layer data in the message to do a pattern matching detection, kernel version needs to be greater than or equal to 2.6.14.      --algo {BM|KMP}  Specifies that the string match detection algorithm--from offset//start offset, defaults to 0--to offset//end offset, does not specify check entire packet [!]- -string pattern//Check matching given string pattern [!]--hex-string pattern Examples: # The string pattern can be              Used for simple text characters. Iptables-a input-p tcp--dport 80-m string--algo bm--string ' get/index.html '-j LOG # the HEX string pa Ttern can used for non-printable characters, like |0d 0a|              or |0d0a|.     Iptables-p UDP--dport 53-m string--algo BM--from all--to--hex-string ' |03|www|09|netfilter|03|org|00| '             -m time//based on how long the message arrives is matched to the specified time range. All time default to UTC format, note time conversion. --datestart Yyyy[-mm[-dd[thh[:mm[:ss]]] [--datestop YYYY[-MM[-DD[THH[:MM[:SS]] [] if--datestart and --datestop not specified, default from 1979-01-01 to 2038-01-19, so the specified date valid range is also so--timestart Hh:mm[:ss]--timestop hh:mm[: SS] Time range is 00:00:00 to 23:59:59 [!]--monthdays day[, day ...]    The number of each month, the value range is 1-31, February may be 28 or 29 days [!]--weekdays Day[,day ...] The day of the week, the value range is 1-7, or with the English initials 2 bit or 3 bit--kerneltz: Kernel time zone, not recommended, CentOS7 system defaults to UTC Note: CENTOS6 does not support Kerneltz,--loca Ltz Specify local time zone (default) Example: Iptables-a input-s 172.16.0.0/16-d 172.16.100.10-p TCP--dport 80-m-- Timestart 14:30--timestop18:30--weekdays sat,sun--kerneltz-j drop-m connlimit//Match the number of concurrent connections per client IP to prevent cc (Challe Nge Collapsar Challenge Black hole) attack--connlimit-upto N: The number of connections is less than or equal to n when matching--connlimit-above N: The number of connections is greater than n when the match is usually separate from the default deny or allow Example of using the Xu Policy: iptables-a input-d 172.16.100.10-p tcp--dport 22-m connlimit--connlimit-above 2-j rejec         T-m Limit//based on the rate of transmit/receive packets match token bucket filter--limit Rate[/second|/minute|/hour|/day]--limit-burst number Example: Iptables-i input-d 172.16.100.10-p ICMP--icmp-type 8-m limit--limit 3/minute--limit-burst 5-j A CCEPT-M state//According to the "Connection tracking mechanism" to check the status of the connection, more resources? ConntRack mechanism: Track the relationship between requests and responses on this machine?         The status is as follows: NEW: the request is made; there is no related information entry for this connection in the connection tracking repository, so it is recognized as the first request Established:new state, and the communication status in the connection tracking repository for the entry established for it before it expires Related: A newly initiated connection that is associated with an existing connection, such as the relationship between a data connection in the FTP protocol and a command connection INVALID: An invalid connection, such as an incorrect flag flag untracked: A connection that has not been traced, such as a raw table off Close Trace iptables command? [!] --state state? Example: Iptables-a input-d 172.16.100.10-p tcp-m multiport--dports 22,80-m State--state new,established-j ACCEP        T iptables-a output-s 172.16.100.10-p tcp-m multiport--sports 22,80-m State--state established-j ACCEPT ? The connected database/proc/net/nf_conntrack that has been traced and recorded? Adjust the maximum number of connections the connection tracking function can hold/proc/sys/net/nf_conntrack_max? is the connection tracking duration of the different protocols/proc/sys/net/netfilter/? Note: CentOS7 need to load module: modprobe nf_conntrack iptables command? Iptables's Link Tracking table has a maximum capacity of/proc/sys/net/nf_conntrack_max, the time-out links for various states are removed from the table, and subsequent connections may time out when the template is fully loaded. Solution Two: (1) Increase the value of Nf_conntrack_max vi/etc/sysctl.conf       Net.nf_conntrack_max = 393216 Net.netfilter.nf_conntrack_max = 393216 (2) Reduced Nf_conntrack timeout time vi/etc/sysctl.conf net.netfilter.nf_conntrack_tcp_timeout_established = Net.netfilter.nf_conntrac k_tcp_timeout_time_wait = Net.netfilter.nf_conntrack_tcp_timeout_close_wait = Net.netfilter.nf_conntr ack_tcp_timeout_fin_wait = iptables-t nat-l-n iptables command? Open Passive mode FTP service? (1) Dedicated module for loading FTP connection tracking: Trace module Path:/lib/modules/kernelversion/kernel/net/netfilter vim/etc/sysconfig/iptables-confi G configuration file iptables_modules= "Nf_conntrack_ftp" modproble nf_conntrack_ftp? (2) Release Request message: Command connection: NEW, established data connection: related, established iptables–i input-d localip-p Tcp-m St Ate--state related,established-j ACCEPT iptables-a input-d localip-p TCP--dport 21-m State--state new-j AC CEPT? (3) Release Response message: Iptables-i output-s localip-P tcp-m State--state established-j accept-j,--jump target 
Backup and recovery of iptables rules
因为iptables为命令行工具,通常命令行工具只在内存中生效,并不将配置写入磁盘。因此要想要配置下次启动依然生效,因此需要将配置写入文件,当然这里不用手动去修改文件。
    • CENTOS6 under
    iptables -S    1、service iptables save  //将规则覆盖保存至/etc/sysconfig/iptables文件中    2、iptables-save  > /path/to/backfile       //备份当前iptables规则到指定文件中,默认是stdout    3、iptables-restore  < /path/to/backfile     //恢复备份的iptables规则到当前中,-n ,不覆盖当前规则    4、因为我们可以通过备份的iptables规则文件,使用iptables-restore来进行还原,默认iptables是载入/etc/sysconfig/iptables中的规则,此时我们在/etc/rc.d/rc.local中,执行iptables-restore < /path/to/backfile会重新载入新的规则。    5、或者通过计划任务crontab或者at来通过iptables-restore来恢复iptables规则。
    • Centos7 under
    同6一样,但是因为7下iptables不再是服务了,所以iptables无法通过Centos6下的第一种方法,需要使用剩下的其他方法
Table chain Target
Raw
Mangle
Nat Prerouting,posttouring Dnat,snat,masquerade
Filter Input,output,forward Accpet,drop,reject
Practical Application Scenarios:

There is a problem is not to add the function of the note, a person does not know what you write every rule why East, this is not good.

    • 1, iptables

      Filter
      Nat

      Custom chain chain use:

        For example: Iptables-f iptables-n Web Create a custom chain IPTABLES-VNL iptables-a web-s 10.0.1.0/24-p tcp--dport 80-j ACCEPT Add Web chaining rules that allow local hosts to access Web services; iptables-i Web 1-m stri ng--algo kmp--string "old"-j REJECT insert 1th Web chain, the page containing the old string is forbidden to access, as long as the status is established should be released; Iptables-i web 2-p tcp-m State- -state established-j ACCEPT Insert Web chain 2nd, release status is established; At this time, intranet users access Web services: No access to curl httpd://172.18.11.111 is not accessible,
      Because the custom chain does not take effect directly, it only takes effect if it is called, iptables-a forward-p tcp-j the Web to invoke the Web custom chain on the FORWARD chain; The Web service is accessible to the intranet user;  
实现网络防火墙:实验环境:3台主机,1台模拟路由器,1台模拟客户端,1台模拟服务器1、上网时间控制:1,3,5的9:00-12:00 14:00-18:00 不允许上网2、访问网站控制:iqiyi,youku,tudou,不允许访问3、特地主机控制:172.18.0.100-1014、路由器只开启特定服务:http,https,ssh ,dns5、SNAT首先防火墙策略部署在路由器上,然后需要使用表natecho ‘net.ipv4.ip_forward=1‘ >> /etc/sysctl.confsysctl -p假设eth1连接内网,eth0连接外网iptables -t nat -A REROUTING -i eth1 -m iprange --src-range=172.18.0.100-101 -j MASQUERADEiptables -t nat -A REROUTING -i eth1 -m time  --timestart=01:00 --timestop=04:00 --weekday=1,3,5 -j REJECTiptables -t nat -A REROUTING -i eth1 -m time  --timestart=06:00 --timestop=10:00 --weekday=1,3,5 -j REJECTiptables -t nat -A REROUTING -i eth1 -m string --algo bm --string ‘iqiyi|youku|tudou‘ -j REJECTiptables -t nat -A POSTROUTING -o eth0 -s 172.18.0.0/16  -j MASQUERADEiptables -t nat -A POSTROUTING -j REJECT - 2、firewalld 暂时先这样子   

The netfilter/ptables of the Linux firewall

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.