Use iptales to implement a packet-over Firewall)

Source: Internet
Author: User
Tags touch command ftp client ftp protocol
I. Overview

Since the 1.1 kernel, Linux has already had the packet forwarding function. In the 2.0 kernel, we use ipfwadm to operate kernel packet forwarding rules. Later, in the 2.2 kernel
You are not familiar with ipchains to control the kernel package over the rules. Currently, the latest Linux kernel version is 2.4.1. In kernel 2.4, we no longer use ipchains,
Use iptables, a new kernel package overhead management tool. This new kernel package overhead tool will make it easier for users to understand and use it,
It will also have more powerful functions.

We have said that iptables is only a tool used to manage kernel packages. iptables can be used to add, insert, or delete rules in the core package filter table (chain. Actually
Netfilter (a general architecture in the Linux core) and its related modules (such as the iptables module and Nat module) are used to execute these excessive rules. Let's take a look at them.
How netfilter works.

Ii. Principles
Netfilter is a general architecture at the core of Linux. It provides a series of "tables" (tables). Each table consists of several "chains", and each chain can
One or more rules. We can understand that netfilter is a table container, a table is a chain container, and a chain is a rule container (1 ).

The default table is "filter", which contains three links: input, forward, and output. Each chain can have one or more rules. Each rule has
This defines "if the data packet header meets this condition, it will process this packet ". When a packet arrives at a chain, the system starts from the first rule.
Check whether the condition defined by the rule is met: if the condition is met, the system processes the data packet according to the method defined by the rule; if the condition is not met, continue to check the next
. Finally, if the packet does not comply with any rule in the chain, the system processes the packet according to the pre-defined policy of the chain.

Process 2 of the data packet in the filter table is shown. When a packet enters the system, the system first determines the chain to which the packet is sent based on the route table. There may be three situations.
:

1. If the destination address of the data packet is local, the system sends the data packet to the input chain. If the data packet passes the rule check, the packet is sent to the corresponding local process for processing.
After the rule check, the system will discard the package;
2. If the destination address of the packet is not the local machine, that is, the packet will be forwarded, the system sends the packet to the forward chain. If the packet passes the rule check
Process the corresponding local process; if the rule check fails, the system will discard the package;
3. If a data packet is generated by a local system process, the system sends it to the output chain. If the packet passes the rule check, the packet is sent to the corresponding local process for processing.
If the rule check fails, the system will discard the package.

From the above, we can see that netfilter is much clearer and better understood than the previous ipfwadm and ipchains ideas.
Ipchains are a good news for users who are always confused.

Iii. Preparations

1. System Requirements
Netfilter requires that the kernel version be no less than 2.3.5. When compiling a new kernel, You must select a project related to netfilter. These projects are usually located at "Networking
Options. Taking the 2.4.0 kernel as an example, we should select the following items:

[*] Kernel/user netlink socket
[] Routing messages
<*> Netlink device emulation
[*] Network packet filtering (replaces ipchains)
.......

Then, select "IP: netfilter configuration ---->:

Connection Tracking (required for masq/NAT)
FTP protocol support
IP Tables support (required for filtering/masq/NAT)
Limit match support
MAC address match support
Netfilter mark match support
Multiple port match support
ToS match support
Connection state match support
Packet Filtering
Reject target support
Full Nat
Masquerade target support
Redirect target support
Packet mangling
ToS target support
Mark target support
Log target support
Ipchains (2.2-style) Support
Ipfwadm (2.0-style) Support

The last two items can be deselected, but if you miss ipchains or ipfwadm, you can also select it to use ipchians in the 2.4 kernel.
Ipfwadm. However, you must note that iptables is consistent with ipchians/ipfwadm and cannot be enabled simultaneously when iptables is used.
Ipchains/ipfwadm. After compilation is successful, these module files are located in the following directory
/Lib/modules/2.4.0/kernel/NET/IPv4/Netfilter

When compiling the new kernel of 2.4.0, you should also pay attention to selecting the correct CPU option corresponding to your CPU in "Processor type and features"; otherwise, the new kernel
It cannot work normally.

2. Load Module

To use iptables, you must also load the relevant modules. Run the following command to load the relevant modules:
# Modprobe iptable_tables
The modprobe command automatically loads the specified module and its related modules. The iptables_filter module is automatically loaded at runtime.

Iii. Syntax

1. Chain Operations
Create a new chain (-N ).
Delete an empty chain (-x ).
Change the principle of a built-in chain (-P ).
Lists the rules (-l) in a chain ).
Clear all rules (-F) in a chain ).
Zero is the packet byte counter (-z) of all rules in a chain ).

2. Operations on Rules
Add (append) a new rule to the end of a chain (-.
Insert a new rule (-I) at a location in the chain, usually at the beginning.
Replace a rule (-R) at a certain position in the chain ).
Delete a rule (-d) at a location in the chain ).
Delete the first rule (-d) in the chain ).

3. Specify the source address and Destination Address

Use -- source/-- src/-S to specify the source address (here/Represents or means, the same below), and use -- destination/-- DST/-S to specify the destination address. Yes
Use the following four methods to specify an IP Address:
A. Use a complete domain name, such as "www.linuxaid.com.cn ";
B. Use an IP address, such as "192.168.1.1 ";
C. Use x. x/x. x to specify a network address, such as "192.168.1.0/255.255.255.0 ";
D. use X. x. x. x/x specifies a network address. For example, "192.168.1.0/24" indicates the number of valid digits of the subnet mask, which is usually used in UNIX environments.
Display Method.
The default subnet mask number is 32, that is, specifying 192.168.1.1 is equivalent to 192.168.1.1/32.

4. Specify the Protocol

You can use the -- protocol/-P option to specify the protocol, such as-p tcp.

5. Specify the network interface

You can use -- In-Interface/-I or -- Out-Interface/-O to specify network interfaces. It should be noted that for the input chain, only-I, that is, only
There are incoming packages. For the output chain, there may be only-O, that is, only outgoing packets. Only the forward chain can have both-I network interfaces and-o
Network interface. You can also specify an existing network interface, such as ppp0. This rule is valid only after successful dialing.

6. Specify IP fragmentation

During TCP/IP communication, each network interface has a maximum transmission unit (MTU). This parameter defines the maximum size of data packets that can be passed. If a number
When a packet is larger than this parameter value, the system divides it into several smaller packets (called IP fragments) for transmission, and the receiver reassembles these IP fragments to restore the whole.
Package.
However, when packet filtering is performed, IP fragmentation may cause the following problem: when the system divides large data packets into IP fragmentation for transmission, the first fragmentation contains the complete packet header
However, the subsequent fragments only contain part of the packet header, such as the source address and target address. Therefore, if we have such a rule:
Iptables-a forward-p tcp-s 192.168.1.0/24-D 192.168.2.100 -- dport 80-J accept
In this case, when the forward policy is drop, the system will only let the first IP Fragment pass, and the rest of the IP fragment will be lost, because the first fragment contains the complete
Header information can meet the conditions of the rule, and the remaining parts cannot pass because the header information is incomplete and cannot meet the conditions defined by the rule.
We can use the -- fragment/-F option to specify the second and later IP fragmentation. For example, in the preceding example, we can add such a rule to solve this problem.
Problem:
Iptables-a forward-F-s 192.168.1.0/24-D 192.168.2.100-J accept
However, it should be noted that there are already many instances that are launching IP fragmentation attacks (for example, sending a large number of IP fragments to Win98 NT4/SP5, 6 Win2k for DoS attacks), because
There is a security risk to allow IP fragmentation. We can use iptables matching extension to limit this, but this will affect the service quality.
This issue is discussed in detail.
  
7. Specify non-

Can be added before some options! To indicate unspecified values, such as "-S -! 192.168.1.1/32 indicates the IP address other than 192.168.1.1, "-p -! TCP"
Protocol except TCP.

8. TCP matching Extension

You can use the -- TCP-flags option to filter the flag of the TCP packet. This option is followed by two parameters: the first parameter is the flag to be checked.
The combination of SYN, ack, FIN, RST, URG, and PSH can be used to specify all flag bits. The second parameter is the flag whose flag value is 1. For example, if you want to filter out all SYN
The following rules can be used for TCP packets with 1 log:
Iptables-a forward-p tcp -- TCP-flags all syn-J Drop
Option -- SYN is a special case above, which is equivalent to the abbreviation of "-- TCP-flags SYN, RST, Ack SYN.

9. Mac matching Extension
You can use the-M option to expand the Matching content. The -- match MAC/-M Mac matching extension can be used to check the source MAC address of IP packets. In -- Mac-Source
And match the MAC address. For example:
Iptables-a forward-M Mac -- Mac-source 00: 00: BA: A5: 7d: 12-J Drop
Note that the source MAC address of an IP packet is changed to the MAC address of the router after it is forwarded by the router.

10. Limit matching Extension

Limit Extension is a very useful matching extension. You can use-M Nat to specify the value. The following two options are available:

-- Limit AVG: specifies the number of packets allowed to pass in a unit of time. The unit time can be/second,/minute,/hour,/day, or use the first letter,
For example, 5/Second is the same as 5/s, indicating that 5 packets can be sent per second. The default value is 3/hour.

-- Limit-burst number: Specifies the threshold value for the trigger event. The default value is 5.

It seems a little complicated. Let's look at an example:
The following rules are assumed:
Iptables-A input-p icmp-m limit -- limit 6/m -- limit-burst 5-J accept
Iptables-P input drop
Then ping the host from another host. The following occurs:
First, we can see that the responses from the first four packages are normal. Then, starting from the fifth package, we can receive a normal response every 10 seconds. This is because we have set a ticket
The number of data packets allowed to pass within the time (here is the minute) is 6 per minute, that is, one packet per 10 seconds. Secondly, we set the event trigger threshold to 5, so I
The first four packages are normal, but starting from the fifth package, the restriction rule takes effect, so only one normal response can be received every 10 seconds.
Suppose we stop the Ping and start the ping again 30 seconds later, then the phenomenon is:
The first two packages are normal, and packet loss starts from the third package. This is because here I allow a package to pass through for a period of 10 seconds. If the system does not receive a token within a period of time
The trigger value of the condition package will be restored to 1. Therefore, if we fail to pass the packet within 30 seconds, the trigger value of the system will be restored to 3, assume that
If a qualified package passes through, the system will completely restore the trigger value. I don't know if you understand it. Thank you for writing to discuss it.

11. Log target Extension

The default netfilter targets (that is, the system processes data packets once the rules are defined) include:
Aceept: receives and forwards packets.
Dorp: Packet Loss
The target extension module provides the extension target. Log targets provide the ability to record data packets. The target extension has the following parameters:
-- Log-level: Specifies the record information level. The levels include debug, info, notice, warning, err, crit, alert, and emerg, which correspond to numbers 7 to 0 respectively.
For more information, see the syslog. conf man manual.
-- Log-Prefix: A string with a maximum length of 30 characters that appears before each log.

12. Target extension of Reject

This target extension is exactly the same as the Dorp standard target, except for returning the sender with an "port unreachable" ICMP message.

Other extensions are commonly used. For more information, see packet-filtering-howto. Of course, the most direct way to get help is to view iptables
For example, if you want help with Mac matching extensions, you can run the "iptables-M Mac-help" command. If you want help with log target extensions, You can execute
"Iptables-J log-help" command.

4. iptables instances

First, let's take a look at the interaction principle between the server and client. Services provided by servers with certain functions are always provided by specific background programs. In TCP/IP networks
Bind a specific service to a specific TCP or UDP port. Then, the background program continuously listens to the port (Listen), once the client that meets the conditions is received
After the Service performs a TCP handshake, it establishes a connection with the client to respond to the customer's request. At the same time, a copy of the binding will be generated to continue listening to the client
.

For example, assume that one server a (IP address 1.1.1.1) in the network provides the WWW Service, and clients B (2.2.2.2) and C (3.3.3.3 ). First,
Server A runs the background program (such as APACHE) that provides the WWW Service and binds the service to port 80, that is, listening on port 80. When B initiates a connection
B will open a connection port greater than 1024 (defined port in 1024), assuming 1037. After receiving the request, a establishes a connection with port 80 to respond to B's
And generate a copy bound to port 80 to continue listening to client requests. If a receives a connection request from C (set the connection request port to 1071 ),
At the same time, a copy bound to port 80 is generated to continue listening to client requests. Because the system uses the source address, source port, destination address, and destination
To identify a connection, so each connection is unique here.

Server Client
Connection 1: A. B. C.1: 80 <=> A. B. C.4: 1037
Connection 2: A. B. C.1: 80 <=> A. B. C.7: 1071

Each specific service has its own specific port. Generally, ports smaller than 1024 are reserved ports, or defined ports. Low ports are allocated to the well-known
Ports from 512 to 1024 are usually reserved for special UNIX TCP/IP applications. For details, see the/etc/services file.
Rfc1700.

Assume that the network environment is as follows: a ddnleased line is used to connect to the Internet. The network topology is as follows:

+ -------------- +
| Intranet segment | eth1 + -------- + eth0 DDN
| + ------------ | Firewall | <==================> Internet
| 198.168.80.0 | + -------- +
+ -------------- +
Eth0: 198.199.37.254
Eth1: 198.168.80.254

The above IP addresses are all real IP addresses on the Internet, so IP spoofing is not used. In addition, we assume that the following servers exist in the Intranet:
WWW server: www.yourdomain.com 198.168.80.11
FTP server: ftp.yourdomain.com 198.168.80.12
Email server: mail.yourdomain.com 198.168.80.13

Next we will use iptables to build our packet filtering Firewall step by step. It should be noted that in this example, we mainly provide information about various internal servers.
Protection.

1. in/etc/rc. run the touch command in the D/directory to create the firewall file, run the chmod u + x firewll command to change the file attributes, and edit/etc/rc. d/RC. local
Add/etc/rc. d/firewall at the end to ensure that the script is automatically executed at startup.

2. Refresh all chain rules
#! /Bin/sh

Echo "Starting iptables rules ..."

# Refresh all chains

/Sbin/iptables-F

3. We will first disable forwarding of any packages, and then step by step set the packages that are allowed to pass.
Therefore, first set the firewall forward chain policy to drop:

/Sbin/iptables-P forward drop

4. Set the server package consideration rules:

It should be noted that the interaction between the server and client is always the same, that is, two-way, so we should not only set the rules for data packet forwarding, but also set
Rules returned by the data packet, we first establish a rule for excessive traffic from Internet packets.

WWW Service: the service port is 80 and adopts TCP or UDP protocol. The rule is: eth0 => allow packages for the WWW server on the Intranet.

########################### Define HTTP packets ########## ##########################

# Allow WWW request packets from Internet clients to www servers
/Sbin/iptables-a forward-p tcp-D 198.168.80.11 -- dport www-I eth0-J accept

FTP service: FTP service is a bit special, because two ports are required, because FTP has command channel and data channel. The command port is 21, the data port is 20, and the master
The connection process is as follows: the FTP client first initiates a connection request to the FTP server, and then establishes a command channel after three-step handshake.
Server requests to establish a data channel and start data transmission after successful transmission. Currently, Most FTP clients support the negative mode because this mode can improve security. FTP service collection
TCP protocol. The rule is: eth0 => only packages for Intranet FTP servers are allowed.

########################### Define FTP packets ######### ############################

# Allow FTP request packets from Internet clients to intranet FTP Server
/Sbin/iptables-a forward-p tcp-D 198.168.80.12 -- dport FTP-I eth0-J accept

Email Service: includes two Protocols: SMTP and POP3. For security, only internal POP3 services are provided.
SMTP security issues. The SMTP port is 21 and the TCP protocol is used. Eth0 => only allow SMTP requests for the email server.

########################### Define SMTP packets ########## ##########################
/Sbin/iptables-a forward-p tcp-D 198.168.80.13 -- dport SMTP-I eth0-J accept

5. Set excessive rules for Intranet customers:

In this example, our firewall is located at the gateway, So we mainly prevent attacks from the Internet and not from the Intranet. Assume that
The server is based on Linux. You can also set related excessive rules on each server to prevent attacks from the Intranet. For Internet-to-Intranet customers
The following rule is defined.

############ Define packets from Internet server to intranet #################### ###
/Sbin/iptables-a forward-P TCP/IP 0/0 -- Sport FTP-data-D 198.168.80.0/24-I eth0-J accept
/Sbin/iptables-a forward-p tcp-D 198.168.80.0/24! -Syn-I eth0-J accept
/Sbin/iptables-a forward-p udp-D 198.168.80.0/24-I eth0-J accept

Note: The first option allows Intranet customers to access the Internet's FTP server in passive mode; the second option is to receive non-Connection Request TCP packets from the Internet; and the last option is
Receives all UDP packets, mainly for OICQ and other services that use UDP.

6. Accept data packets from the entire intranet. We define the following rules:

############ Define packets from Internet server to intranet server ###############
/Sbin/iptables-a forward-s 198.168.80.0/24-I eth1-J accept

7. process IP fragmentation

We accept all IP fragments, but use the limit matching extension to limit the number of IP fragments that can be passed per unit time to prevent IP Fragment attacks.

################################ Define fregment rule #### ##############################
/Sbin/iptables-a forward-F-m limit -- limit 100/s -- limit-burst 100-J accept

Note: No matter where the IP address fragment comes from, it is allowed to pass 100 IP address fragments per second. This limit is triggered by 100 IP address fragments.

8. Set ICMP packet filtering

ICMP packets are usually used for network tests. Therefore, all ICMP packets are allowed to pass. However, Hackers often use ICMP attacks, such as ping of death.
Limit the limit matching extension:

################################# Define ICMP rule #### ##############################
/Sbin/iptables-a forward-p icmp-m limit -- limit 1/s -- limit-burst 10-J accept

Note: No matter where the ICMP packet comes from, it is allowed to pass one packet per second. The condition triggered by this restriction is 10 packets.

Through the above steps, we have established a relatively complete firewall. Only a limited number of ports are opened to the outside world, and the customer's seamless access to the Internet is also provided, and
It provides effective protection against IP fragmentation attacks and ICMP ping of death. The following is the complete script file content. You want to use this instance to access iptables
Method:

#! /Bin/sh

Echo "Starting iptables rules ..."

# Refresh all chains

/Sbin/iptables-F

########################### Define HTTP packets ########## ##########################

# Allow WWW request packets from Internet clients to www servers
/Sbin/iptables-a forward-p tcp-D 198.168.80.11 -- dport www-I eth0-J accept

########################### Define FTP packets ######### ############################

# Allow FTP request packets from Internet clients to intranet FTP Server
/Sbin/iptables-a forward-p tcp-D 198.168.80.12 -- dport FTP-I eth0-J accept

########################### Define SMTP packets ########## ##########################
/Sbin/iptables-a forward-p tcp-D 198.168.80.13 -- dport SMTP-I eth0-J accept

############ Define packets from Internet server to intranet #################### ###
/Sbin/iptables-a forward-P TCP/IP 0/0 -- Sport FTP-data-D 198.168.80.0/24-I eth0-J accept
/Sbin/iptables-a forward-p tcp-D 198.168.80.0/24! -Syn-I eth0-J accept
/Sbin/iptables-a forward-p udp-D 198.168.80.0/24-I eth0-J accept

############ Define packets from Intranet to Internet ###############
/Sbin/iptables-a forward-s 198.168.80.0/24-I eth1-J accept

################################ Define fregment rule #### ##############################

/Sbin/iptables-a forward-F-m limit -- limit 100/s -- limit-burst 100-J accept

################################# Define ICMP rule #### ##############################
/Sbin/iptables-a forward-p icmp-m limit -- limit 1/s -- limit-burst 10-J accept

V. Differences between iptables and ipchains

· The default chain name of iptables is changed from small to uppercase, And the meaning is no longer the same: the input and output are placed on the local machine and the Local Machine respectively.
Rules of data packets.
· The-I option only indicates the input network interface, and the-O option is used when the input network interface is used.
· TCP and UDP ports now need to be spelled out using the -- source-port or -- Sport (or -- destination-Port/-- dport) option and must be placed in "-P
After TCP "or"-p udp "options, because they are loaded with TCP and UDP extensions, respectively.
· In the past, the "-y" flag of TCP was changed to "-- SYN" and must be placed after "-p tcp.
· The original deny target is finally changed to drop.
· You can clear a single chain in the list.
· You can clear the rule counter while clearing the built-in chain.
· The current instantaneous value of the counter can be displayed when the list shows the chain.
· Reject and log are now extended, meaning they become independent kernel modules.
· The chain name can be up to 31 characters long.
· Masq is now changed to masquerade and uses different syntaxes. Redirect retains the original name, but also changes the syntax used.
Http://www.cx66.com/cxgzs/tips/1212.htm

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.