The implementation of firewalls in Linux systems: Iptables/netfilter

Source: Internet
Author: User
Tags ack ranges

Firewall: Includes a software firewall (Iptables/netfilter-based packet filtering firewall) and hardware firewall, at the host or network edge of the message through the firewall to detect a certain conditions filtering a series of components.

The implementation of firewalls in Linux systems:
The use of Iptables/netfilter can not only implement the host firewall (the Security Service scope is limited to a current host), but also can implement the network Firewall (Security Service scope is the current LAN).
The framework of firewall in Netfilter:linux system kernel, the main body of firewall function realization;
Iptables: An application tool in user space that writes data transfer matching rules for NetFilter;

Iptables structure: iptables consists of tables, tables consists of chains, and chains is composed of rules.

iptables table (tables) and Chain (chains):
Chain (5 kinds):
Input chain (processing of data from external)
Output chain (processing outward-sent data)
Forward chain (to forward data to other devices on this machine)
Prerouting Chain (handles packets that have just arrived at the native and before the route is forwarded; the destination IP address in the conversion data packet is used for Dnat)
Postrouting chain (processing of packets that are about to leave the machine; Source IP address in the conversion data packet for Snat)

Table with filter, NAT, Mangle, raw four kinds of built-in tables:

    1. Filter Table: Used to implement filters, packet filtering firewall function
      Filter is the default table for Iptables, with the following three built-in chains:
      Input chain (processing data from external)
      output chain (processing outgoing data)
      Forward chain (to forward data to other devices on this computer)
    2. NAT table: Used to modify the source address or destination address of a message, modify the port number, use for address translation and address Spoofing
      NAT table contains three built-in chains: Prerouting chain, prerouting chain, output chain
      Prerouting chain (processing packets that have just arrived at the native and before the route is forwarded; the destination IP address in the conversion data packet is used for Dnat)
      Postrouting chain (processing the packet that is about to leave the machine; The source IP address in the conversion data message is used for Snat)
      Output chain (processing native data packets)
      INPUT (the newly added chain in the version after iptables1.4 for processing incoming data packets)
    3. mangle table: Disassemble the message and modify the message format before re-encapsulating the message, can be used for flow control and tagging data
      mangle table has 5 built-in Chains: Prerouting, Postrouting, OUTPUT, INPUT, FORWARD
    4. Raw table: Turn off connection tracking mechanism initiated on NAT table
      Raw table has 2 built-in Chains: Prerouting, OUTPUT

        Note: Rules in the same rule chain in each table have precedence order (high to low): raw--- Mangle--NAT---Filter  

The flow of data messages:
1. Inbound data--the destination IP address is a valid IP address of the firewall host data message:
Prerouting---routing table (Routing table)----INPUT
2. Outbound data-The source IP address is a valid IP address of the firewall host data message:
Prerouting---routing table (Routing table)--OUTPUT--postrouting
3. Forwarding data-source, destination IP address is not a valid IP address of the firewall host, need to pass through the firewall data message:
Prerouting---routing table (Routing table)--FORWARD---postrouting

Iptables (Rules):
Iptables: Rule authoring Tool, non-interactive command-line tool, can only write one rule at a time and send to NetFilter to execute;
The rule matching order of NetFilter is: first match;
First match: Each rule is matched from top to bottom, and the other matching rules are no longer retrieved as long as there are rules that match the data packet;

CentOS 6 and Previous versions: write rules using the iptables command;
CentOS 7:firewall-cmd Command Writing rules, Iptables command can still be used (recommended);
Stop the FIREWALLD service and cancel its autorun:

Systemctl Disable Firewalld.service
        # systemctl stop firewalld.service

To add the right rules, you need to consider the following questions in advance:
1. The flow path of the data message, determined to add the rules to the correct link on the right table;
2. Determine the function that the rule implements to select the correct table;
3. Determine the content of the specific matching criteria to be used to match the data of interest;
4. Determine the default matching condition and execution action of the chain;

Iptables command: Rule authoring tool
Rule (match condition + processing action): match rule or recognition condition, as defined by the requirements to match conditions for incoming, outgoing, or native messages, and specify a specific processing method after matching
Match condition: basic match condition and extended match condition
Basic match condition: Match condition of specific attribute in message header of simple IP, TCP, UDP and other protocol
extended match condition: need to use extended function module (implicit and Explicit) to match
Implicit extension: Ambiguous to indicate which specific module to use, but actually do use extension to complete conditional matching
Explicit extension: You must explicitly indicate which specific module is used to complete the conditional matching
action:
Basic Action (Packet filter action): Accept,drop , REJECT
Extended action: processing actions that need to be performed with the extension module

Considerations when defining rules: the order in which the rules are matched is matched from top to bottom: 1) The same class of rules, the minimum matching range should be written on the top; 2) The rules of the same class, the higher the matching frequency should be written on the above; 3) We recommend not modifying the chain as much as possible.    The default policy is to block all data, and if you want to set a rule that blocks all data, set the rules that block all data in the last bar of the chain; rules for the writing and optimization of iptables rules: 1. All inbound and outbound connected data with a status of established can be safely released; 2. Services to the same class of functions of the rules, the more stringent matching conditions should be placed in front of the rule chain, the more relaxed the conditions are placed in the back; 3. The rule that serves different kinds of functions, the greater the likelihood of matching messages should be placed in front of the rule chain, the probability of matching is small in the back; 4. It is recommended that the last rule be set to block all data passing, not directly modifying the default policy; Common format written by iptables rules: iptables [-t table] COMMAND CHAIN [-M matchname] [per-match-option S]-j targetname [per-target-options] Option Description:-T table: Specifies which table to perform the function of, the table that can be selected includes: Raw,mangle,nat and filter, if this option is omitted, it means using the default        Table--filter table;-M MatchName: Typically, you must write when you configure an explicit extended match condition, or omit to configure a basic match condition or an implicit extended match condition;-j targetname: Specifies the processing action of the packet for all matching criteria; Command: Chain operation commands:-P,--policy chain Target defines the default policy for the specified chain; There are usually two action choices, namely: ACCE PT and drop; n,--new-chain chain creates a new custom rule chain, and the rules on the new chain must be called by the rules on the built-in chain to take effect; X,--delete-chain [chain] DeleteIn addition to a custom chain called 0 of the built-in chain, the-E,--rename-chain old-chain new-chain Rename the custom chain with 0 calls to the built-in chain; -F,--flush [chain] clears the rule on the specified chain (all chains in the table), the action command for the rule:-A,--append chain RULE-SP Ecification appends a rule at the end of the specified chain;-D,--delete chain rule-specification-d,--d Elete chain Rulenum Deletes a rule from the specified chain, either specifying a specific rule or indicating the number of the rule on the chain;-I,--insert chain [rulenum] Ru  Le-specification inserts a rule on the specified chain, by default inserting the new rule into the first rule of the chain, or by specifying the rule number, which is called the rule rulenum on the specified chain;                --replace chain Rulenum Rule-specification replaces the rule rulenum on the instruction chain with the rules in the command line; it is not a specific condition in the rule, but a complete replacement of the whole rule;                            -L, the--list [chain] list displays all rules on the specified chain (all chains) for a given table, and other common options that you can use:                            -V,--verbose: Displays information in more detailed formats, as well as-VV; n,--numeric: Digitally display all information in the rule, including information such as hostname and port number; -X,--exact: Accurate display of the results of the counter; Each rule has two counters: 1. The number of messages matched by the rule;                2. Total number of bytes of the message matched by the rule;--line-numbers: Displays the number of rules on the specified chain; other commands: -Z,--zero [chain [Rulenum]] set the rule counter of the specified chain to 0; common targets:log: Streams for matched data packets Not affect the transmission of the data packet itself; Mark: The setting of the firewall tag for matching data packets; Masquerade: Source Address spoofing, a special source IP address translation; redire CT: Destination IP address and port redirection; REJECT: block the transmission of data messages and return messages to the source of the data messages; SNAT: source IP address translation; DNAT: Destination IP address translation; A Ccept: Release of matched data packets; DROP: block for matched data packets; RETURN: jump between rule chains; match criteria: By default, different conditions in the same command The relationship between the existence of logical "and";!: Inverse for matching results, except for ...                    The basic matching condition: [!]-S,--source address[/mask][,...] Check the matching range of the source IP address in the data packet; it can be a single IP address, or it can be a subnet, a master network, a network of IP address settings, etc. 0.0.0.0/0 represents all IP addresses in the entire IP address stack, and if omitted, means that all source IP addresses will be matched; [!]-D ,--deStination address[/mask][,...]  Check the matching range of the destination IP address in the data packet, can be a single IP address, or it can be a subnet, a master network, such as IP address settings; 0.0.0.0/0 represents all IP addresses in the entire IP address stack, and if omitted, means that all destination IP addresses will be matched;                    -I,--in-interface name checks if the inbound interface of the data message can be matched by this condition; [!]-O,--out-interface name Check that the outbound interface of the data message can be matched by this condition; extended match condition: implicit extended match condition and explicit extended match condition implicitly extended match condition: [!]-P,- -PROTOCOL protocol [!]-P, [-M matchname]--protocol protocol Check data packets the package header of a specified protocol                        Whether there are attributes or fields that match the criteria, the protocols that can be specified here include: TCP, UDP, Udplite, ICMP, ICMPv6, ESP, ah, SCTP, MH, all TCP Protocol (TCP module): [!]--source-port,--Sport port[:p ORT] [!]--de                            Stination-port,--dport port[:p ort] is used to specify the matching criteria for the source port and/or destination port, only one port or a contiguous set of port ranges can be specified at a time, and a discrete port cannot be specified; [!] --tcp-flags Mask Comp is used to specify each flag bit in the TCP protocol headerMatch conditions; URG, SYN, RST, PSH, ACK, FIN, all, NONE m                            Ask: Set the list of flags to be detected, separated by "," between the flags, comp: must be placed in the "1" flag list, the remaining in the mask table in the flag bit must be set to "0"; [!]                            --syn equivalent to:--tcp-flags syn,rst,ack,fin syn UDP protocol (UDP module): [!]                                --source-port,--Sport port[:p ORT] [!]--destination-port,--dport port[:p ort]                            Used to specify the matching criteria for the source port and/or destination port, only one port or a contiguous set of port ranges can be specified at a time, and no discrete ports can be specified; ICMP protocol (ICMP module): [!] --icmp-type {type[/code]|typename} common Icmp-type:echo-re                         Quest, code 8; echo-reply, code 0; explicit extended match condition: 1.multiport extension:                     One-time write to multiple discrete ports or multiple sets of contiguous ports, the maximum limit of 15 sets of ports, each port range occupies two ports;   Protocols that can be supported: TCP, UDP, Udplite, DCCP, SCTP.                            Related options: [!]--source-ports,--Sports Port[,port|,port:port] ... [!]                            --destination-ports,--dports Port[,port|,port:port] ... [!]                                --ports Port[,port|,port:port] ...--dports 22,80,3306-j ACCEPT Example: ~]# iptables-i forward-s 192.168.100.100-d 172.16.69.2-p tcp-m multiport--dports 22,8 0,3306-j ACCEPT ~]# iptables-i forward-d 192.168.100.100-s 172.16.69.2-p tcp-m multip                        ORT--sports 22,80,3306-j ACCEPT 2.iprange extension: With any number of consecutive IP address access as a matching condition; Related options: [!]--src-range from[-to] [!]--dst-range From[-t        O]-m iprange--src-range 192.168.100.1-192.168.100.100 Example:                        ~]# iptables-i forward-m iprange--src-range 192.168.100.1-192.168.100.100-d 172.16.69.2-p TCP -M multiport--dports 22,80,3306-j ACCEPT ~]# iptables-i forward-m iprange--dst-range 192.168.100.1-192.168.100.100-s 172.16.69.2-p tcp-m multiport--sports 22,80,3306-j ACCEPT 3.string Extension: String matching detection of application layer data in data packet; related options:--algo {b M|KMP}--string "string" Example: ~]#                        Iptables-i forward-s 172.16.69.2-m string--algo BM--string "Dafa"-j REJECT 4.time Extension: Match detection According to the time of the packet arriving at the firewall and the specified time range; related options:--datestart yyyy[                                    -MM[-DD[THH[:MM[:SS]] []] [--datestop YYYY[-MM[-DD[THH[:MM[:SS]] Define only an absolute time range;                                --timestart Hh:mm[:ss]--timestop Hh:mm[:ss]                                    Define a periodic time range; [!]--monthdays Day[,day ...]                                    Define each day of the month; 1-31 [!]--weekdays Day[,day ...] Define the day of the week; Value: Mon, Tue, Wed, Thu, Fri, Sat, Sun, or values from 1 to 7, or Mo, Tu, et C. Example: ~]# iptables-i forward-m time--timestart 08:00:00--ti Mestop 17:59:59!                        --weekdays 6,7-o eno16777736-j REJECT 5.state Extended Connection status detection, based on the connection tracking mechanism; Conntrack related options: [!]--state State IPT Ables Definition of connection state: INVALID, established, NEW, related or untracked; Inva LID: UnrecognizedConnection state, invalid communication state; Syn,fin established: The state of the connection has been established; connection state; NEW: The status of the connection has not been established;                        Related: An interconnected state of connection with other established connections, associated State or derivative state, untracked: an untraceable state;                            The location in the kernel where the connection tracking state data is stored:/proc/net/nf_conntrack The maximum number of connections that can be traced:/proc/sys/net/nf_conntrack_max Note: The maximum number of connections recorded here, it is recommended to adjust the size to large enough if necessary, in order to make the most efficient use of memory resources, the status of cached connection tracking can not be saved indefinitely, so Set the corresponding timeout time;/proc/sys/net/netfilter/nf_conntrack*timeout* use connection tracking to set the FTP server's access control System: ~]# iptables-a input-m State--state established,related-j ACCEPT ~]#                        Iptables-a input-d 172.16.69.2-p tcp-m multiport--dports 21,22,80,3306-m State--state new-j ACCEPT ~]# iptables-a input-j DROP Note: The Nf_conntrack_ftp kernel module needs to be loaded; ~]# m Odprobe nv_conntrack_ftp                            To set the automatic loading of the NF_CONNTRACK_FTP module: Set/etc/sysconfig/iptables-config                        Iptables_modules= "NF_CONNTRACK_FTP" uses connection tracking to set up common rules on the output chain: ~]# iptables-a output-m State--state established-j ACCEPT ~]# iptables-a output-j DR The OP 6.mac extension implements MAC address matching detection for prerouting, FORWARD or input chains;                    Off option [!]--mac-source address matches source MAC addresses, which must be in the form of: XX:XX:XX:XX:XX:XX                            7.connlimit expansion: Match detection of concurrent connections based on each client IP address; related options:                            --connlimit-upto n This condition can be matched when the client's current number of concurrent connections is less than or equal to N, and this condition is usually used in conjunction with the Accept action;                    --connlimit-above n This condition can be matched when the client's current number of concurrent connections is greater than N; This condition is usually used in conjunction with the drop or reject action; 8.limit expansion: Matching detection based on the rate of data packets sent and received by the server; related options:--limit rate[/sec Ond|/minute|/hour|/day] The rate at which the server side can receive the maximum unit time;--limit-burst Numb  The maximum number of data messages that ER can receive at initial time; Example: ~]# iptables-i INPUT 1-p ICMP--icmp-type 8-m limit--limit 15/minute--limit-burst 8-j ACCEPT

Example of a host firewall basic match condition configuration:
1. Allow the specified host to access the local SSH service:
~]# iptables-t filter-a input-s 172.16.0.1-p tcp--dport 22-j ACCEPT

2.默认阻止所有其他主机到本机的所有数据通信:    方法一:~]# iptables -P INPUT DROP (不推荐,如果使用iptables -F命令后果很可怕)    方法二:~]# iptables -A INPUT -j REJECT (推荐操作)3.配置172.16.0.0/16网段中所有的主机可以访问本地的httpd服务:    ~]# iptables -I INPUT -s 172.16.0.0/16 -p tcp --dport 80 -j ACCEPT4.允许本机ping通外部主机,但不允许外部主机ping通本机:    ~]# iptables -I INPUT 2 -d 172.16.72.2 -p icmp --icmp-type echo-reply -j ACCEPT5.为了避免木马程序的植入运行,可以设置OUTPUT链上的防火墙规则:    ~]# iptables -A OUTPUT -d 172.16.0.1 -p tcp --sport 22 -j ACCEPT    ~]# iptables -A OUTPUT -j REJECT    ~]# iptables -I OUTPUT -d 172.16.0.0/16 -p tcp --sport 80 -j ACCEPT    ~]# iptables -I OUTPUT 2 -p icmp --icmp-type echo-request -j ACCEPT

Configuration example of a network firewall basic matching condition:
~]# iptables-a forward-j REJECT
~]# iptables-i forward-s 192.168.100.100-d 172.16.69.2-p tcp--dport 3306-j ACCEPT
~]# iptables-i FORWARD 2-s 172.16.69.2-d 192.168.100.100-p tcp--sport 3306-j ACCEPT
~]# iptables-i FORWARD 3-p icmp-j ACCEPT

    注意:凡是通过FORWARD链来设置的网络防火墙的匹配规则,数据的往返过程必须同时被打开,才能保证路由功能的正常进行

Custom rule chain: There are a number of similar rules that are not used to match most data, so you can set such rules in a custom chain, which can reduce the time of rule matching and improve the matching efficiency; (using the case of custom chains)
To create a custom rule chain:
~]# Iptables-n Udp_match//udp_match This chain must be unique.

向自定义规则链添加规则:    ~]# iptables -A udp_match -d 172.16.72.2,192.168.100.1 -p udp -m multiport --dports 53,67,69,137,138 -j ACCEPT    ~]# iptables -A udp_match -j RETURN        //自定义规则链的最后一条规则,可以返回主链,进行后续规则匹配;更改自定义规则链的名称:    前提:要改名的自定义规则链的引用计数必须为0;    ~]# iptables -E udp_match udp删除自定义规则链:    前提:要改名的自定义规则链的引用计数必须为0且链上不能有任何规则;    ~]# iptables -X udp在主链上引用自定义规则链:    ~]# iptables -I INPUT -p udp -j udp   

Iptables/netfilter which comes:
General writing Format:
iptables [-t table] COMMAND chain [-M matchname [per-match-options]] [-j targetname [per-target-options]]

iptables规则的保存和重载:    CentOS 7:        建议:为了兼容CentOS 6及以前版本,可以考虑将iptables的规则定义保存于/etc/sysconfig/iptables文件中;        规则保存:            ~]# (umask 077 ; iptables-save > /etc/sysconfig/iptables)        规则恢复:            ~]# iptables-restore < /etc/sysconfig/iptables    CentOS 6和之前的版本:        规则保存:            ~]# iptables-save > /etc/sysconfig/iptables            ~]# service iptables save        规则恢复:            ~]# iptables-restore < /etc/sysconfig/iptables            ~]# service iptables restart

Add:
First, NAT table:
Function:
1.NAT (translation): Network address Translation
1) Snat:source-address NAT, source address network address translation
Typically used to allow a host in the LAN to use a private IPv4 address to access the external network or the Internet; The network address translation of the source address is usually completed after routing, so in Iptables, the Snat class rules should be configured on the postrouting chain;

            For iptables, there are two things: a. Static address translation: one-to-one address translation, a private address to a public address, B. Address spoofing: Multiple-to-an address translation, multiple private IP addresses            A public IP address to access the network; 2) dnat:destination-address NAT, the destination network address translation is typically used to allow hosts in the external network or the Internet to access network services on a server using a private IPV4 address in the LAN; In general, the network address translation of the destination address needs to be completed before routing is selected, so in iptables, such rules should be configured on the prerouting chain; 2.napt:network Address and Port translation, net Address Port translation: Network address translation + port mapping snat:this target is only valid in the NAT table, in the postrouting and INPUT chains, and U    Ser-defined chains which is only called from those chains. Common options:--to-source [ipaddr[-ipaddr]][:p Ort[-port]] Note: In Rhel or CentOS system release Linux, the ipaddr specified by Snat must be the IP address configured and in effect on the current host            ; Example: ~]# iptables-t nat-a postrouting-s 192.168.100.0/24-j SNAT--to-source 172.16.72.72 ~]# iptables-t nat-a postrouting-s 192.168.100.0/24-j Masquerade//Source address camouflage technology, without specifying a specific internal global address, Iptables automatically determines the The IP address is used as the internal global address, and the source address is converted; Dnat:this target is only valid in the NAT table, in THe prerouting and OUTPUT chains, and user-defined chains which is only called from those chains. Common options:--to-destination [ipaddr[-ipaddr]][:p Ort[-port]] Example: ~]# iptables-t nat-a prerouting-d 192.168.1  00.1-p TCP--dport 80-j DNAT--to-destination 172.16.69.2:8000 functions the same as: 1. Firewall rules that set NAT translation on the router: ~]#  Iptables-t nat-r prerouting 1-d 192.168.100.1-j DNAT--to-destination 172.16.69.2 2. Do port redirection on the destination server: need to use redirect                Target ~]# iptables-t nat-a prerouting-p tcp--dport 80-j REDIRECT--to-ports 8000 REDIRECT This target was only valid in the NAT table, in the prerouting and OUTPUT chains, and user-defined chains WHI                 CH is only called from those chains. --to-ports Port[-port]

Second, LOG target:
It is only the function of opening the kernel to log the matching data packets, and not doing any other operations on the data;//If the data packets are matched by the rule of target log, the following rules will be matched in the normal matching order;

常用选项:--log-level level :定义记录日志等级    Level of logging, which can be (system-specific) numeric or  a  mnemonic.    Possible  values  are  (in  decreasing  order of priority): emerg, alert, crit, error, warning, notice, info or debug.--log-prefix prefix :日志前缀,描述日志是怎样被记录下来的(不超过29个字符)    Prefix log messages with the specified prefix; up to 29 letters long, and useful for distinguishing messages in the logs.示例:~]# iptables -t filter -A FORWARD -p tcp --dport 80 -j LOG --log-level info --log-prefix "IPTAB-LOG-"        //注意:默认情况下,日志会记录在rsyslog服务所定义的默认日志文件中,/var/log/messages;

The implementation of firewalls in Linux systems: Iptables/netfilter

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.