Linux Kernel Forwarding Technology

Source: Internet
Author: User
Tags command access squid proxy

Objective

In the Linux kernel, kernel modules with packet filtering and firewall functionality are often integrated, with different kernel versions having different module names,
In the 2.4.x version and beyond, its name iptables has been replaced by the early ipchains and ancient times ipfwadm .
From the command line, you can lsmod | grep -i iptable view the information about the module that is currently loaded.

Iptables, as a kernel module, consists of packet filtering tables that contain the set of rules that the kernel uses to control packet filtering processing.
At the same time, Iptables also exists as a management tool for user space (userspace), which allows us to insert,
It is very easy to modify and remove rules from packet filtering tables, and you do not need to recompile the kernel each time you modify the rules.
The main discussion in this paper is also the function of iptables in user space.

Basic concepts

The forwarding mechanism of the Linux kernel is mainly checked 表(tables) , and iptables is used to set up, manage and check the IP packet filtering rules table in the Linux kernel.
A table is appended with the S description to define multiple tables, and each table contains several, and the 链路(chains) link represents a series of applications to match IP packets 规则(rules) .
The following explains the "three mountains" respectively. To make the concept clear, we explain from the bottom up:

Rule (rules)

The rule is also called rule-specification, its main function is to match the specific IP packet, and make the corresponding action, its format is:

rule-specification = [matches...] [target]

which

match = -m matchname [per-match-options]target = -j targetname [per-target-options]

MatchName represents the name of the matching format, and TargetName represents the name of the action being performed. Iptables defines a series of built-in formats and actions,
If the target is accepted for accept, masquerade means performing a router-like action (for NAT), etc., which can be man iptables-extensions viewed.

Link (chains)

The so-called link, as the name implies is the path of the IP packet transmission, a packet of the source and the purpose of the different, its path may be different.
Just like friends on the road, it is possible to go their separate ways at any node. These nodes are:

    • Pre_routing: When external data is just entered.
    • Post_routing: When external data is ready to leave.
    • Input: The destination address of the packet is the local socket.
    • Output: The packet is generated locally.
    • Forward: The packet is forwarded natively.

In fact, the link exists as a hook in the kernel, and at each node a callback function is reserved for the user to handle the packet (that is, with the rules mentioned earlier).
When the IP packet enters from the outside, the link that goes through is as follows:

After the network port receives the IP packet, first passes through the mangle and the NAT table the Pre_routing table processing, then determines whether the destination address is the native application,
If the path to the left is down, it is sent out after processing by the receiving program. If the kernel forwarding is not turned on, the destination address is not native IP packets will be discarded,
If forwarding is turned on, forward it from the network port to the right path. Each link point in the diagram can be modified and filtered appropriately for the IP packet.

Note: The prerouting chain will only match the first packet of the stream, that is, all other packages of the stream will not be checked by this chain.
So the prerouting chain can only do network address translation and cannot be used to do any filtering.

Table (Tables)

The current version of Iptables contains five separate tables, which are used depending on kernel options and which module is currently applied. The tables are described below:

    • Filter: The filter table is the default table used by the (iptables command) and contains the Input,forward and output links.
    • Nat: When you encounter an IP packet that creates a new link, the kernel looks for the NAT table, which contains the prerouting and postrouting links.
    • mangle: mangle tables are used for special package modifications, such as changing the Tos,ttl,mark. Contains only prerouting and output links before the kernel 2.4.17.
      The Input,forward and postrouting links are added in later versions.
    • Raw: Raw is primarily used to configure the Notrack behavior in connection tracking, which registers a higher priority callback in the NetFilter hook, so it can be in the Ip_conntrack table
      Other IP tables are called before. Raw contains the prerouting and output links.
    • Security: The security table is used for command access control (mandatory access controls, MAC) for the rules of the network. Mac is implemented by Linux security modules such as SELinux,
      The security table is called after the filter table, providing the input,output and forward links.
Specific applications

The production of tools to serve in the end, the light interpretation of nouns can not visually show the Linux powerful kernel forwarding mechanism, so with a few small examples to illustrate the iptables
Specific use, and according to the above introduction to write a script that has practical effect. The general format of the Iptables command is as follows:

iptables [-t table] {-a|-c|-d} chain rule-specification

Where the command is divided into three parts, that is, the specified table, links and rules mentioned above

-t table指定表的名字, 若不指定则默认为filter.-a chain表示在链路中增加规则, -c和-d分别表示检查和删除.剩余部分指定规则, 格式为`[matches...] [target]`

The complete command can be viewed through Iptables's manpages.

Example 1. As a firewall

Assuming such a scenario, we are connected to an annoying LAN, why is it annoying? Because there are a lot of scripting kids inside the LAN,
To go back and forth the scan does not say, also on some ports for blasting. So I want to simply generate a firewall, except that the gateway does not allow any of the subnets within the subnet
The IP is connected to me, even ping does not ping me.

Demand is clear, so how to achieve it? It's really simple, just the following command (assuming the subnet is 192.168.1.0/24):

 #1. Empty existing rule   iptables -T filter -f  < Span class= "hljs-comment" > #2. Open Gateway access rights   iptables -T filter -a  input -s  192.168.1.1-j accept #3. Specifies that the return of the ping is not filtered   span class= "kw" >iptables -T filter -a  input-p ICMP--icmp-type 0 -s  192.168.1.0/24-j accept #4. Turn off all other intranet access   iptables -T filter -a  input-p all -s  192.168.1.0/24-j Drop  

Generally speaking, the firewall policy is generally from the non-trust, with the policy (-p policy) to turn off all access rights, and then add the rule to open as required.
This is to add a rule on the basis of the default policy (accept) for simplicity. The current policies for each table can be iptables -t table -s viewed.
It is important to note that all rules are checked sequentially , and once the qualifying conditions are checked, they do not go down and check if all the rules do not match.
The default action is performed (the default policy). Therefore, it is best to add the rules from small to large.
In the # # command, we opened the ICMP type 0 input, that is, ping echo reply packet, so that others can not ping me at the same time, I could ping others, is not very convenient?

Example 2. As a router

In the control of the network often there is a situation, that is, the intranet is bound to the MAC address, the client to access the router must be added by the network administrator,
Because even if there is a WiFi password, the connection will not be able to obtain IP, and therefore cannot surf the Internet. My PC has been added to the network, but the phone, tablet, etc.
Device does not want to one by one to network management to add, then how to connect to the WiFi? There are many solutions, under Windows There are various Xxx-wifi software, Linux's
NetworkManager also has a solution similar to adding hotspots. Here is the solution to the iptables.

It is assumed that the notebook started the hotspot At0 and that the DHCP service is configured. Our subnet is still 192.168.1.0/24, the hotspot subnet is 10.0.0.0/24,
Share the same block of wireless card wlan0. At this time the subnet request will go to the wlan0, but the destination address is not me, according to can know, then
IP packets should be forwarded to the right side of the path, but need to change the network address before going out (NAT, see the principle and implementation of peer communication).
The rules for setting up NAT forwarding are also simple:

iptables-a postrouting -o wlan0 -j masquerade

This is the NAT rule that is configured when we use Wlan0 to surf the internet and use Wlan0 as a router, but this performance is not ideal,
More generally, we use one NIC to connect to the network (assuming Wlan0) and the other as the router (set to Wlan1).
In this case, you only need to forward the WLAN1 traffic to the Wlan0:

iptables -t filter -a forward -i wlan1 -o wlan0 -j acceptiptables -t filter -a forward -i wlan0 -o wlan1 -m state --state established,related -j acceptiptables -t nat -a postrouting -o wlan0 -j masquerade

Where masquerade means to provide a similar router forwarding behavior, that is, to go out of the TCP/UDP package to change the source address, for the incoming packet change the destination address,
The same function can be achieved with-j Snat, except that the IP address needs to be specified (this is the address in the Wlan0 network). Masquerade is specially designed
Used for connections that dynamically acquire IP addresses, such as Dial-Up Networking, DHCP connections, and so on. If you have a static IP, use Snat target to reduce overhead.

-a postrouting -o wlan0 -p tcp -j snat --to-source [wlan0-ip]# 这里不需要设置dnat, 因为snat会记住连接,把响应转发给对应的请求.不过为了例示还是写出来:-a-d [wlan0-ip] -p tcp -j dnat --to [client-ip]

It is worth mentioning that iptables essentially simply filters and processes data, so it is accurate to allow wlan1 traffic to be forwarded to Wlan0,
In fact, if the default policy is used, forward is allowed without additional settings.

Example 3. act as a transparent proxy

Different people have different requirements for agents, the most common is the HTTP proxy, generally provides the address and port number. We configure the use in the browser
Proxy and specify the address and port, the Internet surfing request will be received by the proxy server, and then, as necessary, from the destination site for us to request content,
or return the content directly from the cache. Suppose we have now configured and run a SQUID proxy server that works on port 3128.
Similar to being a router, but you need to change the destination port number in addition to changing the IP:

iptables -t nat -a prerouting -i80 -j dnat --to [wlan0-ip]:3128iptables -t nat -a prerouting -i80 -j3128

Transparent proxy full iptables configuration can refer to set up squid in Linux.

Postscript

The technical presentation of the Linux kernel forwarding feels pretty much the same, though not fully expressive of its powerful features,
But people who believe in need can extrapolate according to the basic rules; See someone else's iptables "script" through Google,
can also get a lot of inspiration. In addition to more specific commands on iptables, remember to use a simple method to check (maniptables).

Resources
    • Iptables Guide
    • Iptables/netfilter principle

Linux Kernel Forwarding Technology

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.