Summary and application of Linux Iptables

Source: Internet
Author: User

Summary and application of Linux iptables

First, firewall, Iptables introduction

1, the firewall is used for the implementation of Linux access control functions, it is divided into hardware or software firewall two kinds. Regardless of the network in which the firewall works, it must be at the edge of the network. And our task is to define how the firewall works, this is the firewall policy, rules, in order to allow it to access the network of IP, data detection. A common three or four-layer firewall, called the network layer of the firewall (this layer of source and destination address detection), there are 7 layers of firewalls, in fact, is the proxy layer of the gateway (the source port or destination port, source address or destination address to check).

2, Iptabels Introduction: Netfilter/iptables (referred to as iptables) composed of Linux platform packet filtering firewall, as with most Linux software, this packet filtering firewall is free, it can replace the expensive commercial firewall solution, Complete features such as packet filtering, packet redirection, and network address translation (NAT).

Iptables, formerly known as Ipfirewall (Kernel 1.x ERA), is a simple access control tool for data packet detection, which is ported from FreeBSD and can work in the kernel. When the kernel developed into the 2.x series, the software was renamed IPChains, it can define multiple rules, string them together, and now, it is called iptables, you can make a list of rules to achieve absolute detailed access control functions.

Working in user space, defining the rules of the tool itself is not considered a firewall. Defined rules that allow netfilter in kernel space to be read and implemented to allow firewalls to work. Where the kernel must be placed, it must be the place where the TCP/IP protocol stack is located. And this TCP/IP protocol stack must pass the place, can implement the reading rule is called NetFilter (Network filter). So the real firewall function is NetFilter, which is the internal structure of implementing packet filtering in the Linux kernel.

5 locations were selected in the kernel space:

1) in kernel space: from one network interface to another network interface

2) The packet flows from the kernel into the user space

3) packets that flow out of the user space

4) Enter/leave the external network interface of the machine

5) Enter/leave the Local intranet interface

These 5 positions are also known as five hooks (hook functions), also called Five rule chains.

1) prerouting (before route) # #对数据包作路由选择前应用此链中的规则, Note: Remember! All the data packets are processed by this chain when they come in.

2) INPUT (packet inflow port) # #进来的数据包应用此规则链中的策略

3) FORWARD (forwarding pipe card) # #转发数据包时应用此规则链中的策略

4) OUTPUT (packet egress) # #外出的数据包应用此规则链中的策略

5) postrouting (after routing) # #对数据包作路由选择后应用此链中的规则, note: All packets are processed by this chain first.

This is the NetFilter rules of the five rule chain, any one packet, as long as through the machine, will pass through one of these five chains

3, the order of precedence between the rule chain has three kinds of situations:

1) Inbound Data flow: packets from the outside to the firewall, first by the prerouting rule chain processing (whether to modify the packet address, etc.), then routing (to determine where the packet should be sent to), If the target host of a packet is a firewall native (such as a packet of Internet users accessing a Web server in a firewall host), then the kernel passes it to the input chain for processing (deciding whether to allow the pass, etc.). Respond to applications (such as Apache servers) that are later handed over to the upper system.

2) forwarding Data flow: From outside the packet arrives at the firewall, first by the prerouting rule chain processing, then routing, if the destination address of the packet is another external address (such as LAN users through the gateway to access the QQ site packet), The kernel passes it to the forward chain for processing (forwarding or blocking) and then handing it over to the postrouting rule chain (whether to modify the address of the packet).

3) Outbound Data flow: The firewall native to the external address sent packets (such as in the firewall host to test the public DNS server), first by the output rule chain processing, then routing, and then passed to the postrouting rule chain (whether to modify the address of the packet) for processing.


Ii. working mechanism of iptables

1, iptables packet transmission process, such as:

650) this.width=650; "src=" http://s4.51cto.com/wyfs02/M00/76/17/wKiom1ZJ0DWiL_-CAAGzFuFb8QU167.jpg "title=" 1-1. JPG "alt=" wkiom1zj0dwil_-caagzfufb8qu167.jpg "/>

Description

1) When a packet enters the network card, it first enters the prerouting chain, the kernel according to the packet destination IP to determine whether it needs to be forwarded out.

2) If the packet is entered into the machine, it will move down the graph to reach the input chain. After the packet has been sent to the input chain, any process will receive it. Programs running on this computer can send packets that go through the output chain and then reach the postrouting chain.

3) If the packet is to be forwarded out and the kernel allows forwarding, the packet will move to the right as shown, passing through the forward chain, then reaching the postrouting chain output

2. Iptables rules table and chain relationship

The iptables contains 4 tables, the filter table, the NAT table, the Mangle table, and the raw table, respectively, for packet filtering, network address translation, packet refactoring (modification), and data tracking processing.

Chain (chains) is the path of packet propagation, each chain is actually a checklist in many rules, each chain can have one or several rules. When a packet arrives at a chain, the iptables starts checking from the first rule in the chain to see if the packet satisfies the conditions defined by the rule. If satisfied, the system processes the packet according to the method defined by the rule, otherwise iptables will continue to check the next rule, and if the packet does not conform to any of the rules in the chain, Iptables will process the packet based on the default policy defined by the chain.

Note that you must understand the relationship and function of these tables and chains, see:

650) this.width=650; "src=" http://s4.51cto.com/wyfs02/M01/76/15/wKioL1ZJ0KfCtaenAALXBNWIZTw430.jpg "title=" 1-2. JPG "alt=" wkiol1zj0kfctaenaalxbnwiztw430.jpg "/>

Rule Table Description:

1) Filter table (Filter packet kernel module: iptables_filter)--Three chains: INPUT, FORWARD, OUTPUT

2) NAT table (for network address translation (IP, port) kernel module: iptable_nat)--Three chains: Prerouting, Postrouting, OUTPUT

3) mangle table (Modify the service type of the packet, TTL, and can configure the route to implement the QoS kernel module: iptable_mangle)--five chains: prerouting, Postrouting, INPUT, OUTPUT, FORWARD

4) Raw table (determines whether the packet is processed by the state tracking mechanism: iptable_raw)--Two chains: OUTPUT, prerouting

Order of precedence between rule tables:

Raw--mangle--nat--filter


Iii. Basic usage of iptables

Starter Script:/etc/init.d/iptables {start|stop|restart|save}

Save saves the written rules to/etc/sysconfig/iptables and reads the rules in this file the next time you start. You can also use Iptables-save to redirect to a file, and the next time you can use the Iptables-restore command to import the rule.

1) Basic Syntax:

iptables [-t TABLE] COMMAND CHAIN [RULE] [-j TARGET]

Common parameter Options

-T: Indicates the name of the table being processed, by default the filter

-a|-d|-i| R: Add, delete, insert, replace matching rules, followed by the corresponding chain name to be processed

-F: Refresh Rule Library

-Z: Empty counter

-N|-X|-E: Create, delete, rename a chain yourself

-P: Set default policy, often used to set blacklist, whitelist

-L: Lists the firewall rules for the corresponding table, you can use the following sub-options

-N: Displays the IP address and port number in digital form

-V-VV-VVV: Show the verbosity of the information

-X: Accurately displays the number of packets matched to and the number of bytes in the package

--line-numbers: Lists serial numbers for each rule

--modprobe=command: The necessary modules can be loaded through this

2) Description of matching conditions:

Common matching Criteria

-S: Indicates the source address of the message

-D: Specify the destination address of the message

-P: Specify the protocol for the message

-I: The NIC that indicates the incoming message, used with the input chain

-O: The NIC that indicates the message goes out, used with output

Note: Each option can be added before! To take the reverse

Extended Match

Extended match: Implicit extension, explicit extension, implicit extension is a supplemental description of the-p specified protocol, and explicit extension is using-m to specify specific additional extension options.

Common implicit extensions:

Extended options for the TCP protocol:

--sport: Specifies the source port, and the UDP protocol also applies

--dport: Specifies the destination port, and the UDP protocol also applies

--tcp-flags: Indicates the status of the TCP message when the format:--tcp-flags mask (the status value to check) comp (for the status value of 1), you can set the status value has a SYN ACK FIN RST URG PSH, all represents all States, None means that all are not set

For example:--tcp-flags All check all States are 1

--tcp-flags All NONE Check all states are 0

--syn only check for SYN status flag bit 1

Common extensions for ICMP protocols:

The types of ICMP-TYPE:ICMP messages, commonly 0 and 8, 0 for response messages, and 8 for request messages.

Common Explicit Extensions:

IPRange: Indicates the IP range

--src-range: Indicates the range of source addresses

Usage:--src-range from[-to] Example:--src-range 192.168.1.1-192.168.1.24

--dst-range: Indicates the scope of the destination address, using the same--src-range

Multiport: Indicates multi-port, only for TCP and UDP protocols

--sports: Indicates multiple source ports

Example:--sports 21,22,80,53

--dports: Indicates multiple destination ports

--ports: Indicates multiple ports, which include the source and destination ports

Connlimit: Limit the number of concurrent connections

--connlimit-above: Number of concurrent connections for the same client

--connlimit-msak: Indicates the number of masked bits of the client (prefix length)

Limit: Limiting the transfer rate

--limit-rate: Limiting the rate of transmission

Usage:--limit Rate[/second|/minute|/hour|/day]

--limit-brust:brust is the token bucket, which contains the number of tokens. Simply put, the client only has the token to transfer the data, and the number of tokens will accumulate

String: The filter string

--algo: Indicates the type of encryption that matches the string KMP and BM (named after the person's name)

--string: Indicates a matching string

--hex-string: Matched strings are given in hexadecimal form

--from: Indicates the beginning of the matching string, default is 0

--to: Indicates the end of the matched string, which is 65535 by default

Time: Limit times and dates

--datestart: Start date, format: YYYY[-MM[-DD[THH[:MM[:SS] []]

--datestop: Due date, format ibid.

--timestart: Start time, format is: Hh:mm[:ss]

--timestop: Cut-off time, format ibid.

--weekdays: Specified days: Mon, Tue, Wed, Thu, Fri, Sat,sun can also be used 1-7

--monthdays Day: Indicates a specific number of days in one months and 1-31 can be used

State: Indicates the status of the connection

--state: Indicates the state of the connection, with the status:

NEW: The newly established connection

Established: Established connection

Related: Associated connection

Invilid: Indicates an invalid state

Recent: Blocks a large number of requests, such as attacks that can prevent DOS

3) The address list is maintained inside the kernel, and this list can be modified by--set,--rcheck,--update and--remove four ways. --set,--rcheck,--update and--remove are mutually exclusive and cannot be used simultaneously. Recent module rules have a return value (a Boolean value), which is true to perform-j specified action.

--set: Adds an address to the address list, including the timestamp of the address

--name: Specifies the name of the address list, which defaults to the default

--rsource--rdest: Indicates whether the current rule is applied to the source or destination address of the packet, and the default is the source address

--rcheck: Check if the address is in the address list

--remove: Remove the address list from the

--update: As with Rcheck, but he will refresh the timestamp

--hitcount: The number of hits in the specified time (number of matches in the address list), which must be used with both-rcheck and--update

--seconds: Usage:--seconds N (Limit the address in the packet to the address list is less than n), must be used in conjunction with-rcheck and--update

4) Target:

Generally there are-j options specified, common are: drop,accept,reject,dnat,snat,masquerade,retrun,mark,log

Drop,accept,reject Common and filtered packets

Dnat,snat,masquerade used in the address translation module

Dnat often used with--to-destination to indicate the address of the destination address translation

Snat is often used in conjunction with--to-source to indicate the address of the destination address translation, but sometimes the address is dynamically obtained, so it is necessary to dynamically indicate the address to be converted with the help of Masquerade.

Retrun: is a jump, usually used on a custom chain, when a message cannot be matched in a self-defined chain, it is returned to the main chain

LOG: Is the definition of the logging function, the common options are--log-prefix (used to label information in the log information),--log-level (to indicate the level of the log)

Iv. practicing and consolidating

Note: The following exercise iptables firewall input and output default policy to drop;

1. The Web server that restricts the local host is not allowed to access in Monday; the rate of new requests cannot exceed 100 per second; The Web server contains the admin string and the page is not allowed; The Web server only allows the response message to leave the unit;

# iptables-t filter-a input-d 192.168.2.5-p TCP--dport 80-m state--state new-m limit--limit 100/second-m time! --weekdays mon-j ACCEPT

# iptables-t filter-a input-d 192.168.2.5-p TCP--dport 80-m State--state established-j ACCEPT

# iptables-t filter-a output-s 192.168.2.5-p TCP--sport 80-m State--state established-m string--algo KMP! --string "Admin"-j ACCEPT

2, in the working hours, that is, Monday to Friday 8:30-18:00, open the local FTP service to the 192.168.2.0 network host access; Data download requests must not exceed 5 per minute

# iptables-t Filter-r INPUT 2-d 192.168.2.5-s 192.168.2.0/24-p TCP--dport 21-m State--state new,established-m Tim E--weekdays mon,tus,wed,thu,fri--timestart 08:00:00--timestop 18:00:00-j ACCEPT

# iptables-t Filter-r INPUT 192.168.2.5-s 192.168.2.0/24-p tcp-m State--state related-m limit--limit 5/min -j ACCEPT

# iptables-t filter-a input-d 192.168.2.5-s 192.168.2.0/24-p tcp-m State--state established-j ACCEPT

# iptables-t filter-a output-d 192.168.2.0/24-s 192.168.2.5-p tcp-m State--state established-j ACCEPT

3, open the local SSH service to the host in 192.168.2.10-192.168.2.20, the new request to establish a rate of not more than 2 a minute, only allow the response message through its service port to leave the machine;

# iptables-t filter-a input-d 192.168.2.5-p TCP--dport 22-m State--state new-m iprange--src-range 192.168.2.10-19 2.168.2.20-m Limit--limit 2/min-j ACCEPT

# iptables-t filter-a input-d 192.168.2.5-p TCP--dport 22-m State--state established-m iprange--src-range 192.168 .2.10-192.168.2.20-j ACCEPT

# iptables-t filter-a output-s 192.168.2.5-p tcp--sport 22-m iprange--dst-range 192.168.2.10-192.168.2.20-m State --state established-j ACCEPT

4, reject the TCP flag bit all 1 and all 0 of the message access to the machine;

# iptables-t filter-a input-d 192.168.2.5-p--tcp-flags all all-j DROP


5, allow the native ping other host, but not open the other host ping this machine;

# iptables-a input-p ICMP--icmp-type 8-d 192.168.2.5-j DROP

# iptables-a output-p ICMP--icmp-type 0-s 192.168.2.5-j ACCEPT


This article is from the "10,000-hour Law" blog, be sure to keep this source http://daisywei.blog.51cto.com/7837970/1713246

Summary and application of Linux Iptables

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.