Iptables (firewall) and NetFilter

Source: Internet
Author: User
Tags ack

Iptables (firewall) and netfilter================================================= recommended blog:    http://www.360doc.com/ content/11/0506/09/706976_114731108.shtml#    http://drops.wooyun.org/tips/1424netfilter/iptables Introduction:    (1) IP packet filtering system is composed of two components of NetFilter and iptables.    (2) NetFilter is a part of integration in the kernel, its role is to define, save the corresponding rules,    (3) iptables is a tool to modify the filtering rules and other configuration of information, and these rules will be stored in the kernel space.    (4) NetFilter is a common architecture in the Linux core that provides a series of tables (tables) each consisting of several chains (chains), each of which can consist of one or several rules. Firewall Work Flow:


Message Flow: (1) flow into the machine: prerouting----INPUT ==> user space process. (2) Outgoing native: User space process ==> OUTPUT--postrouting (3) Forward: prerouting---FORWARD---postrouting comment:==> Enter user space, --Enter system space.            Four tables (the rule priority for different tables on the same chain is high and low): (1): Raw: Turns off the connection tracking mechanism enabled in the NAT table.            Table and Chain relationship: Prerouting, OUTPUT (2): mangle: Disassemble the message and modify it as needed. Table and Chain relationship: prerouting, INPUT-FORWARD, OUTPUT, Postrouting (3): Nat:network address translation (IP layer addresses, transfer            Layer address).            Table-Link Relationship: prerouting, INPUT, OUTPUT, Postrouting (4): Filter: Filtering, firewall.    Table and Chain relationship: output five-chain (NetFilter), INPUT-FORWARD: Five reference points to implement message management functions.             (1): prerouting: Packet entered before the routing table (2): INPUT: Destination is native after routing table (3): FORWARD: After routing table, destination is not native (4): OUTPUT:         Generated by this machine, outward forwarding (5): Postroutiong: Before sending to the NIC interface =================================================iptables use: Service Application:    CentOS 7 ~]# systemctl stop firewalld.service ~]# systemctl disable Firewalld.service    CentOS 6 ~]# service iptables stop ~]# chkconfig iptables off ......... ............ ......................................................................................................................... ...................   (1) command format: iptables [-t table] subcommand chain [matches ...] [Target] iptables [-t table name] command options [link name] [condition matching] [-j target action or jump] ... ..... ..... ..... ..... ..... ..... ..... ..... ..... .........................................................................................................................    .. -T Table:raw, Mangle, Nat, [filter] ~]# iptables-t raw-nvl ~]# iptables-t mangle-nvl ~]# iptable S-t NAT-NVL ~]# Iptables-nvl ......... .................... ............................. ...........................................................................................                (2) subcommand: (2.1) Chain Management:-n:new: Add a custom chain. ~]# IPTAbles-n test-x:delete: Deletes a custom empty chain.                    ~]# iptables-x mytest-p:policy: Sets the default policy for the chain.                Accept: Receive drop: Discard REJECT: Deny: It is best not to use REJECT on Internet access. ~]# iptables-t filter-p FORWARD drop ~]# iptables-t filter-p INPUT drop ~]# iptables-t Filter-p OUTPUT DROP Note: When setting the filter rule control, set Forward,input,output to DROP or reject-e:rename: rename                A chain that is not referenced (the reference count is 0) is customized.            ~]# IPTABLES-E Test mytest (2.2) Rule management:-a:append: Insert to End (last).            -i:insert: Insert to start (first).                -d:delete: Delete.            1:rule specification 2:rule number ~]# iptables-d OUTPUT 1-r:replace: Replace.            -f:flush: Clean, clear.                -z:zero: Qing 0.                    Each rule in the Iptables has two counters.                    1: All packets that are matched by this rule.            2: All bytes that are matched by this rule. s:selected, in the format of the Iptables-save commandThe rules on the display chain.                (2.3) View:-l:list, List Rule-n:numeric, display address and port in number format;-v:verbose, details;-VV,-VVV -x:exactly, displays the exact value of the counter instead of the unit conversion result--line-numbers: The number of the rule on the display chain ~]# IPTABLES-NVL--lin E-numbers combination:-nvl ~]# iptables-nvl ...... ..... ..... ..... ...................................  ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ....... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ....... ....... (3) Matches Matching Criteria: 1: Basic match: NetFilter matching mechanism [!]-S,--source address[/mask][,...]        : Original address match ~]# iptables-a input-s 172.18.0.0/16-j accept ~]# iptables-a output-s 172.18.0.0/16-j Accept ~]# iptables-a forward-s 172.18.0.0/16-j ACCEPT [!]-D,--destination address[/mask][,...] : Destination address matching ~]# iptables-a input-s 172.18.21.72-d 172.18.21.62-j ACCEPT ~]# iptables-a output-s 172.18.21. 62-d 172.18.21.72-j ACCEPT [!]-I,--in-interface name: the interface that restricts incoming packets, can only be used for prerouting, input and forward. [!]    -O,--out-interface name: The interface that restricts outgoing packets, can only be used for Output,forward and postrouting. [!] -P {TCP|UDP|ICMP}: Restriction protocol ~]# iptables-i input-s 172.18.21.72-d 172.18.21.62-p tcp-j ACCEPT ~]# iptables-i OUTP                    Ut-s 172.18.21.62-d 172.18.21.72-p tcp-j ACCEPT2: Extended match: The matching mechanism introduced by the expansion module,-M matchname Note:                    Implicit extension: The module can be loaded without using the-m option, provided that the-p option is used to match which protocol.    Explicit extension: The corresponding module must be loaded specifically by the-M option.  (1): Implicit extension: [!] -P,--protocol Protocol Protocol: Protocol: TCP, UDP, ICMP, ICMPv6, ESP, ah, SCTP, MH or "All" TCP: implicitly indicates "-                M TCP ", with dedicated options: [!]--source-port,--Sport port[:p ORT]: The source port that matches the TCP header in the packet, which can be a port range. [!]                    --destination-port,--dport port[:p ORT]: The destination port that matches the TCP header in the packet, which can be a port range. ~]# iptables-a input-s 0/0-D 172.18.21.62-p TCP--dport 22-j ACCEPT ~]# iptables-a output-s 172.                    18.21.62-d 0/0-P TCP--sport 22-j ACCEPT Comment: Release ssh connection. ~]# iptables-a Input-s 0/0-D 172.18.21.62-p TCP--dport 80-j ACCEPT ~]# iptables-a output-s 172.18.21.62-d 0/0 -P TCP--sport 80-j ACCEPT Comment: Open 80 port [!]--tcp-flags Mask Comp: Check the TCP flag bit specified in the message, and These logo bits must be 1 in comp,--tcp-flags syn,fin,ack,rst syn--tcp-flags Syn,fin,ack,rst ack, Fin [!]--syn:--syn equivalent to "--tcp-flags syn,fin,ack,rst syn"; TCP three-time handshake for the first time; UDP: Hidden Contains a specified "-M UDP" with dedicated options: [!]--source-port,--Sport port[:p ORT]: The source port that matches the UDP header in the packet; can be a port range; [!]--de Stination-port,--dport port[:p ORT]: The destination port of the UDP header in the matching message, which can be a port range; ICMP: Implied "-M ICMP" with dedicated options: [!]--ic                        Mp-type {Type[/code]|typename} Type/code:0/0:echo reply: Request                    8/0:echo Request: Response ~]# iptables-a output-s 172.18.21.62-d 0/0-P ICMP--icmp-type 8-j ACCEPT ~]# IPtables-a input-s 0/0-D 172.18.21.62-p ICMP--icmp-type 0-j ACCEPT ~]# iptables-a input-d 172.18 .21.62-p ICMP--icmp-type 8-j ACCEPT ~]# iptables-a output-s 172.18.21.62-p ICMP--icmp-type 0-j ACCEPT Comment: ICMP type:http://baike.baidu.com/link?url=rph8hhxwxtekvwxlmz2fcuhapru6dgg7-fdxfjout4qgann-4pwvact  Nf0jigniczeiog51fqzhwy8xep_tye_#7 (2): Explicit extension: (1): multiport: Multi-port matching: Defines multi-port matching in discrete ways, up to 15 ports can be specified [!]                --source-ports,--Sports Port[,port|,port:port] ... [!]                --destination-ports,--dports Port[,port|,port:port] ... [!] --ports Port[,port|,port:port] ... ~]# iptables-i input-s 0/0-D 172.18.21.62-p tcp-m multiport--DP Orts 22,80-j ACCEPT ~]# iptables-i output-d 0/0-S 172.18.21.62-p tcp-m multiport--sports 22,80-                 J ACCEPT (2): iprange: Specify a contiguous range of IP addresses to match the source address or destination address; [!]--src-range From[-to]: Source address range [!]--dst-range From[-to]: Destination address range ~]# iptables-a input-d 172.18.21.62-p tcp--dport 23-m iprange--src -range 172.18.21.1-172.18.21.100-j ACCEPT ~]# iptables-a output-s 172.18.21.62-p TCP--sport 23-m  IPRange--dst-range 172.18.21.1-172.18.21.100 (3): String matching detection of the application layer data in the message;--algo {BM|KMP}: (BM = Boyer-moore, KMP = knuth-pratt-morris) algorithm [!]--string Pattern: Given the string pattern to check; [!]--hex-str ing pattern: Given the string pattern to be checked; ~]# iptables-i output-s 172.18.100.6-d 0/0-P tcp--sport 80-m string--algo b  M--string "old"-j REJECT ~]# iptables-i output-s 172.18.21.62-d 0/0-P tcp--sport 80-m string--algo                BM--string "old"-j REJECT (4): Time: Matches the specified time/date range based on the date/day the message was received.                --datestart Yyyy[-mm[-dd[thh[:mm[:ss]]: The start date time.                --datestop Yyyy[-mm[-dd[thh[:mm[:ss]]]: End date time.                --timestart Hh:mm[:ss]: Start time. --Timestop Hh:mm[:ss]: End time. [!] --monthdays Day[,day ...]                : Matches which days in the one month. [!] --weekdays Day[,day ...]                : Matches which days of the week. ~]# iptables-r INPUT 4-d 172.18.100.6-p tcp--dport 23-m iprange--src-range 172.18.100.1-172.18.100.100-m time--tim  Estart 09:00:00--timestop 16:00:00--weekdays 1,2,3,4,5-j ACCEPT ~]# iptables-i input-d 172.18.21.62-p TCP--dport 23-m iprange--src-range 172.18.21.1-172.18.21.100-m time--timestart 09:00:00--timestop 18:00:00-j ACCEP                T (5): Connlimit: The number of concurrent connections per client host is limited, which is the maximum amount of connections that can be initiated concurrently for each client;--connlimit-upto N: The number of connections is less than or equal to N; --connlimit-above N: The number of connections is greater than n matches; ~]# iptables-a input-s 0/0-D 172.18.100.6-p TCP--dport 23-m CONNL Imit--connlimit-upto 2-j ACCEPT ~]# iptables-a input-s 0/0-D 172.18.21.62-p TCP--dport 23-m Connlim It--connlimit-upto 2-j ACCEPT ~]# iptables-a input-d 172.18.21.62-p tcp--dport 23-m connlimit! --connlimit-above 2-j ACCEPT (6): limit: Match the rate of the message based on the token bucket algorithm;--limit Rate[/second|/minute|/hour|/da  Y]--limit-burst number ~]# iptables-a input-d 172.18.21.62-p ICMP--icmp-type 8-m limit --limit 20/minute--limit-burst 3-j ACCEPT ~]# iptables-a output-s 172.18.21.62-p ICMP--icmp-type 0- J ACCEPT (7): state: is a subset of the Conntrack, used to track the status of the message [!]--state states INVALID: Unrecognized                    The connection.                    Established: The connection in the connection tracking template has a record.                    NEW: Connection request does not exist in the link tracking template.                    Related: The associated connection.                Untracked: The connection is not traced.                    1: Tracked and recorded connections: Cat/proc/net/nf_conntrack 2: Maximum number of connections that can be recorded by the connection tracking function (adjustable):/proc/sys/net/nf_conntrack_max                    ~]# sysctl-w net.nf_conntrack_max=300000 #第一种方式 Net.nf_conntrack_max = 300000    ~]# echo 200000 >/proc/sys/net/nf_conntrack_max #第二种方式                ~]# Cat/proc/sys/net/nf_conntrack_max 200000 Conntrack can track the connection The maximum value of the quantity depends on the setting of the/proc/sys/net/nf_conntrack_max, the connection that has been traced and recorded is in the/proc/net/nf_conntrack file, and the time-out connection is deleted, and when the template is full,                            Subsequent new connections may time out, workaround: (1) Increase the value of Nf_conntrack_max, (2) reduce the time-out of nf_conntrack entries; Connection tracking duration for different protocols:/proc/sys/net/netfilter/Example 1: ~]# iptables-a INPUT-                    s 172.18.0.0/16-d 172.18.21.62-p tcp-m multiport--dports 22,23,80-m State--state new,established-j ACCEPT ~]# iptables-a output-d 172.18.0.0/16-s 172.18.21.62-p tcp-m multiport--sports 22,23,80-m State--state E Stablished-j ACCEPT ~]# iptables-a input-d 172.18.21.62-p ICMP--icmp-type 8-m State--state New,e Stablished-j ACCEPT ~]# iptables-a output-s 172.18.21.62-p ICMP--icmp-type 0-m State--state ESTA      Blished-j ACCEPT Example 2:              ~]# iptables-a input-m State--state established-j ACCEPT ~]# iptables-a input-d 172  .18.21.62-p tcp-m multiport--dports 22,23,80-m State--state new-j ACCEPT ~]# iptables-a input-d 172.18.21.62-p ICMP--icmp-type 8-m State--state new-j ACCEPT ~]# iptables-a output-m State--st Ate Established-j ACCEPT Example 3: ~]# modinfo nf_conntrack_ftp ~]# MODPR OBE NF_CONNTRACK_FTP ~]# Lsmod | grep ftp nf_conntrack_ftp 11953 0 nf_conntrack 79206 7 NF  _conntrack_ftp,xt_connlimit,iptable_nat,nf_nat,nf_conntrack_ipv4,nf_conntrack_ipv6,xt_state ~]# Service                    vsftpd Restart ~]# iptables-a input-d 172.18.21.62-p TCP--dport 21-m State--state new-j ACCEPT ~]# iptables-i input-d 172.18.21.62-m State--state established-j ACCEPT........................................................................................................................ ...................................................        (4): Save and start Rule 1: Save: CentOS 6: ~]# service iptables save ~]# iptables-save >/etc/sysconfig/iptables        ~]# iptables-save >/path/to/some_rule_file CentOS 7: ~]# iptables-s >/path/to/some_rule_file ~]# iptables-save >/path/to/some_rule_file2: Start: Manual: ~]# Iptables-restore </path/from/some_rul    E_file CentOS 6:service iptables Restart Note: Automatically overloads rules from/etc/sysconfig/iptables files. Automatic: (1):/etc/rc.d/rc.local ~]# vi/etc/rc.d/rc.local Iptables-restore </path/f Rom/some_rule_file (2):/usr/bin/iptables.sh ~]# vi/usr/bin/iptables.sh iptables-res Tore </path/from/some_rule_file ......... ................... ....................... .......................................................................................................                (4) Handling action:-j targetname [per-target-options] 1:accept, DROP, REJECT 2:return: Returns the chain of calls Example: ~]# iptables-n Web ~]# iptables-a web-s 10.0.1.0/24-p TCP--dport 80 -j ACCEPT ~]# iptables-i web 1-m string--alog kmp--string "old"-j REJECT ~]# IP                    Tables-i Web 2-p tcp-m State--state established-j ACCEPT ~]# iptables-a forward-p tcp-j web                    ~]# iptables-a forward-s 10.0.1.0/24-p TCP--dport 22-m State--state new-j ACCEPT                ~]# iptables-a web-j Return Comment: Returns the caller (implied by default).                3:redirect: Port redirection, port mapping: Used only in prerouting and OUTPUT chains.                    --to-ports Port[-port] Example: ~]# modify the listening port to 8080. ~]# iptables-t nat-a prerouting-d 172.18.21.72-p TCP--dport 80-j REDIRECT--to-ports 8080 visit: http://172.18.21.72:8080 http://172.18.21.72 4:log: Log--log-level Level: Rank (default = 4): Emerg, Alert, Crit, Erro                R, warning, notice, info or Debug. --log-prefix prefix: Specifying prefix example: ~]# iptables-i FORWARD 2-s 10.0.1.0/24-p tcp-m Multipor                    T--dports 80,21,22,23-m State--state new-j log--log-prefix "(NEW connctions)" Logging location: ~]# cat/var/log/messages 5:mark: Firewall tag 6:snat: Source Address Translation: Modify source IP address in IP message: postrouting and INPUT (CentOS 7 Chain--to-source [IPADDR[-IPADDR]] Example: ~]# iptables-t NAT -A postrouting-s 10.0.1.0/24-j SNAT--to-source 172.18.21.71 ~]# iptables-t nat-a postrouting-s 10 .0.1.0/24-j SNAT--to-source 172.18.21.70-172.18.21.100 Note: Enable hosts in the local network to use unified addresses and external hostsCommunication, thus implementing the address spoofing request: initiated by the intranet host, modify the source IP, if modified by the administrator-defined response: Modify the target IP, the NAT automatically according to the tracking mechanism of the session table to implement the corresponding modification 7:dnat: Destination Address Translation: Modify the destination IP address in the IP message: rperouting and OUTPUT (CentOS 7) chain--to-destination [ipaddr[-ipaddr]][:p Ort[-por T]] Example 1: ~]# iptables-t nat-a prerouting-d 172.18.21.71-p tcp--dport 80-j DNAT--t O-destination 10.0.1.2 ~]# Curl http://172.18.21.71/Example 2: ~]# Modify 10.0 .1.2 Listener address is Listen 8090 ~]# iptables-t nat-a prerouting-d 172.18.21.71-p tcp--dport 80-j DNAT--to -destination 10.0.1.2:8090 ~]# Curl http://172.18.21.71/Note: Allow servers in the local network to use a uniform address to deliver services (publish service)                    , but hides its real address.                    Request: Initiated by the extranet host, modifies its destination address, as defined by the administrator.            Response: Modifies the source address, but the NAT automatically implements the corresponding modification based on the tracking mechanism in the session table. 8:masqerade: Address spoofing, Address dynamic Spoofing Example: ~]# iptables-t nat-a postrouting-s 10.0.1.0/24-j Masquer ADE 9:receNt:...................................................................................................................... ..................................................... Complete example: Setting the NIC address: Nmtui

Basic settings: Turn off the firewalld of CentOS6 iptables and CentOS7. Clear firewall rules for three hosts: ~]# iptables-f host: 172.18.21.71 Check to see if network card forwarding is turned on: ~]# Cat/proc/sys/net/ipv4/ip_forward turn on the net    Card forwarding: ~]# echo 1 >/proc/sys/net/ipv4/ip_forward Note: The address belongs to the kernel and does not belong to the NIC.  Note: 1:10.0.1.1 does not set the gateway when not ping 172.18.21.71, but can ping 10.0.1.1 2:172.18.21.71 set forward can ping 172.18.21.72, but not get                Ping response.                Host: 10.0.1.1 ~]# ping 172.18.21.72 Host: 172.18.21.72: Grab the package to view.    ~]# tcpdump-i eno16777736 ICMP comment: The 172.18.21.72 host responded but responded to the gateway. Add route: Host: 172.18.21.72 ~]# route add-net 10.0.1.0/24 GW 172.18.21.71 ~]# route-n Kernel I P routing table Destination Gateway genmask Flags Metric Ref use Iface 0.0.0. 0 172.18.0.1 0.0.0.0 UG 0 0 eno16777736 10.0.1.0 172.18.21.71 2 55.255.255.0 UG 0 0 0 eno16777736 172.18.0.0 0.0.0.0 255.255.0.0 U 0 0 eno16777736 Note: 10.0.1.2 host pi at this time    ng requests 172.18.21.72 to get a response.        Host: 172.18.21.71 ~]# iptables-p FORWARD DROP ~]# tcpdump-i eno16777736-nn ICMP-VV basic notation: Intranet ping outside Network ~]# iptables-a forward-s 10.0.1.0/24-d 0/0-P ICMP--icmp-type 8-j ACCEPT ~]# iptables-a forward-s 0/0-D  10.0.1.0/24-p ICMP--icmp-type 0-j ACCEPT extranet ping intranet ~]# iptables-a forward-s 10.0.1.0/24-d 0/0-P ICMP        --icmp-type 0-j Accept ~]# iptables-a forward-s 0/0-D 10.0.1.0/24-p ICMP--icmp-type 8-j ACCEPT merge notation: ~]# iptables-a forward-m State--state established-j ACCEPT Internal Ping external ~]# iptables-a forward-s 10. 0.1.0/24-p ICMP--icmp-type 8-m State--state new-j ACCEPT Extranet ping intranet ~]# iptables-a forward-s 0/0-D 1 0.0.1.0/24-p ICMP--icmp-type 8-m State--state New-j Accept allows both intranet and extranet to ping ~]# iptables-a forward-pIcmp-m State--state new-j ACCEPT ~]# lsmod | grep FTP intranet Access extranet service 80 and ~]# iptables-a forward-m State--state established,related-j ACCEPT ~]# iptabl Es-a forward-s 10.0.1.0/24-p TCP--dport 80-m State--state new-j ACCEPT ~]# iptables-a forward-s 10.0.1.0/2 4-p TCP--dport 21-m State--state new-j ACCEPT ~]# modprobe nf_conntrack_ftp combined notation: ~]# iptabl Es-a forward-m State--state established,related-j ACCEPT ~]# iptables-a forward-s 10.0.1.0/24-p tcp-m m Ultiport--dports 80,21-m State--state new-j ACCEPT


Iptables (firewall) and NetFilter

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.