Iptables Realization NAT It's the most basic function , Most home routing is based on SNAT Way to get online , Use Iptables Realize the Internet DNAT It's also very simple. , But it's often abnormal NAT The phenomenon of .
 The following command will access 1., A lot of people just do this step , And then the test doesn't connect properly .
iptables -t nat -A PREROUTING -p tcp -d  -j DNAT --to 

 Imagine client access at this point 1.1.1.1 The data flow of :
 Client access 1.
.1 according to Iptables DNA Send packets to 2., At this time source IP For the client IP
.2 After processing, according to the source IP Return data directly to the client , You know, the client is direct and 1.1.1.1 Connected 
 so what , The client doesn't know , Can't connect properly 

 Finally, I'll add another SNAT The rules , Will be sent to 2..1 Acting as a proxy server .
iptables -t nat -A POSTROUTING -d 2.2.2.2 -j SNAT --to-source 1.1.1.1

 Don't forget to turn on kernel forwarding :
echo  > /proc/sys/net/ipv4/ip_forward

DNAT target

This target It's used for destination network address translation , Namely The purpose of rewriting the package IP Address . If a package is matched , Then all packets belonging to the same stream will be automatically converted , Then it can be routed to the right host or network .DNAT target It's very useful . such as , Yours web The server LAN Inside , And no one can be in Internet The truth used on IP Address , Then you can use this target Give Way The firewall takes everything to itself HTTP Port packets are forwarded to LAN Inside, the real web The server . The destination address can also be a range , In this case ,DNAT Each stream is randomly assigned an address . therefore , We can use this target Do some kind of load balancing .

Be careful ,DNAT target Can only be used in nat Tabular PREOUTING and OUTPUT In the chain , Or in the chain called by these two chains . But also note that , contain DNAT target Can't be called by any other chain , Such as POSTROUTING.

Table 6-16.  DNAT target

Option --to-destination

Example iptables -t nat -A PREROUTING -p tcp -d 15.45.23.67 --dport 80 -j DNAT --to-destination 192.168.1.1-192.168.1.10

Explanation Specify to write IP The address of the head , This is where the packet is forwarded to . The above example is to send all the addresses to 15.45.23.67 All packets are forwarded to a segment LAN The private address used , namely 192.168.1.1 To 192.168.1.10. As mentioned earlier , under these circumstances , Each stream is randomly assigned an address to forward to , But the same stream Always use the same address . We can also specify only one IP Address as a parameter , In this way, all packets are forwarded to the same machine . We can also specify a port or a range of ports after the address . such as :-- to-destination 192.168.1.1:80 or 192.168.1.1:80-100.SNAT The grammar and this target The same as , It's just different purposes . it is to be noted that , Only use first --protocol It specifies TCP or UDP agreement , To use the port .

because DNAT There's a lot to do , So I want to be a little more wordy . Let's take an example to understand how it works . such as , I want to pass. Internet Link to our website , but yes HTTP server In our intranet , And we have only one legal one IP, It's the firewall IP——$INET_IP. The firewall also has an intranet IP ——$LAN_IP,HTTP server Of IP yes %HTTP_IP( Of course, it's on the intranet ). In order to fulfill our vision , The first thing to do is to add this simple rule to nat Tabular PREROUTING In the chain :

iptables -t nat -A PREROUTING --dst$INET_IP -p tcp --dport 80 -j DNAT / --to-destination $HTTP_IP

Now? , All from Internet To the 、 To the firewall 80 All packets will be forwarded ( Or be called DNAT) To those on the intranet HTTP Server . If you are in the Internet On trial Check it out , All right . Try again from the intranet , It doesn't work at all . This is actually a routing problem . Now let's analyze this problem . For easy reading , We put access to our server on the extranet It's the machine of IP The address is $EXT_BOX.

The package address is $EXT_BOX Let's go , The destination address is $INET_IP The machine of .

The packet arrives at the firewall .

A firewall DNAT( That's forwarding ) This package , And the package will go through a lot of other chain inspection and processing .

The packet leaves the firewall to $HTTP_IP Forward .

Package arrival HTTP The server , The server will respond through the firewall , Of course , This requires that the firewall be used as HTTP arrive $EXT_BOX Gateway for . In general , The firewall is HTTP The default gateway for the server .

The firewall then does Un-DNAT( Is to follow DNAT Do it the other way around ), It's like the firewall itself replied to the request packet from the Internet .

It seems that the return package has not gone through such complicated processing 、 It's all right back to $EXT_BOX.

Now? , Let's consider and HTTP The server is on the same intranet ( This refers to the network where all computers can directly access each other without going through a router , It's not the case that servers and clients are divided into different subnets ) What happens when your customers visit it . Let's assume that the client's IP by $LAN_BOX, Other settings are the same as above .

The bag leaves $LAN_BOX, Go to $INET_IP.

The packet arrives at the firewall .

The quilt DNAT, And it's going to go through other processes . But the bag didn't go through SNAT To deal with , So the package still uses its own source address , Namely $LAN_BOX( translator's note : This is it. IP Transport package Characteristics , Change the destination address only according to the destination , But it doesn't change its source address with the router because the transmission process has to go through many routers , Unless you change the source address alone . In fact, this step of processing and The treatment of foreign bags is the same , But that's the problem with intranet packages , So here's why ).

The packet leaves the firewall , arrive HTTP The server .

HTTP The server is trying to reply to this package . It sees in the routing database that the packet is from a machine in the same network , So it sends the reply packet directly to the source address of the request packet ( Now it's the destination address of the reply package ), That is to say $LAN_BOX.

The reply packet arrives at the client , But it can be confusing , Because this package is not from the machine it visited . such , It will throw the bag away and wait “ real ” My reply package .

There is a simple solution to this problem , Because these packets have to go into the firewall , And they all need to do DNAT To get to the address , So we just have to do SNAT Operation is can . such as , Let's consider the example above , If for those who enter the firewall and are going to the address for $HTTP_IP、 Port is 80 My bag is made of SNAT operation , So these bags are like from $LAN_IP Here we are . such ,HTTP The server will send the reply packet to the firewall , And the firewall will do it again Un-DNAT operation , And send the package to the client . The rules for solving problems are as follows Next :

iptables -t -nat -A POSTROUTING -p tcp --dst$HTTP_IP --dport 80 -j SNAT / --to-source $LAN_IP

Remember , In the order of running POSTROUTING The chain is the last of all , So when the package reaches the chain , Has been done DNAT Operation , So we have to base our rules on the intranet address $HTTP_IP( The destination of the bag ) To match the package .

Warning : The rule we just wrote will have a great impact on the log , This kind of influence should be said to be very bad , Because from Internet Packets pass through the firewall one after another DNAT and SNAT Handle , To get to HTTP The server ( The above example ), therefore HTTP The server thinks the packet is from the firewall , And don't know that the real source is something else IP. such , When it records service , The source address of all access records is firewall IP Not the real source of access . If we want to know about the visit based on these records, it is impossible . So the above “ Simple Way ” It's not a wise choice , But it does solve “ Be able to access ” The problem of , It's just that I didn't take the logs into consideration .

Other services have similar problems . such as , you are here LAN It's built in SMTP The server , Then you need to set up a firewall so that you can forward SMTP The flow of data . So you create an open SMTP Relay server for , Then comes the problem of logs .

Be sure to pay attention to , The problem here is that there is no establishment DMZ Or a network of similar structures , And the users in the intranet access the server's external network address .( translator's note : Because if it's built DMZ, Or the server and client are divided into different subnets , Then there's no need to be so troublesome . Because the source of all access is not in the network where the server is located , So there's no need to do SNAT To change the source address of the package 了 , So recording is not a problem . If the intranet client directly accesses the intranet address of the server, it's even better )

A better solution is for you LAN Set up a separate DNS The server ( translator's note : such , Intranet customers use the website name to visit HTTP Server time ,DNS You can parse it into an intranet Address . The client can directly access HTTP The intranet address of the server , Thus avoiding the operation through the firewall , And the source address of the packet can also be HTTP Server log usage , There's no top There is something wrong with the log .), Or just build DMZ got ( This is the best way , But you have to have money , Because there are so many devices ).

The above examples should be considered more comprehensively , There is still one problem to be solved , It's the firewall itself HTTP What happens to the server , Can I access it normally ? Do you think? :) It is a pity that , Now the match is I still can't , Just think about it . The basis of our discussion here is to assume that the machine accesses HTTP The Internet address of the server , Then the client will see the page content , But that's not what it wants to see ( it What you want is DNAT Yes ), without HTTP service , The customer can only receive error messages . The reason why the rules given above don't work is that the request packets sent from the firewall don't go through those two chains . Remember the chain of packets sent by firewall itself :) We will be having nat Tabular OUTPUT Add the following rule to the chain :

iptables -t nat -A OUTPUT --dst$INET_IP -p tcp --dport 80 -j DNAT / --to-destination $HTTP_IP

With the last rule , It's all right . and HTTP If the server is not in the same network, it can access the service normally , The machine in the same network can also access the service normally , The firewall itself can also be Often visit the service , There's no problem . This mood , To paraphrase 《 A Chinese Odyssey 》 A sentence from , Namely “ The world is quiet again ”.( Don't say you don't know what 《 A Chinese Odyssey 》)

I think you should be able to understand that these rules only explain how packets are properly DNAT and SNAT Of . besides , stay filter Other rules are needed in the table ( stay FORWARD chain in ), To allow a particular package to pass through what was written earlier ( stay POSTROUTING Chain and OUTPUT In the chain ) The rules . Don't forget , The bags arrive at FORWARD The chain was already in PREROUTING It's in the chain DNAT After that , In other words, their destination address has been rewritten , Pay attention to this when writing rules .

SNAT target

This target It is used for source network address translation , Namely Rewrite the source of the package IP Address . When we have several machines sharing one Internet When the connection , You can use it . Open it in the kernel first ip Forward capability , And then another one SNAT The rules , You can change the source address of all packets from the local network to Internet The address of the connection . If we don't do this and forward packets directly to the local network ,Internet The machine on board doesn't know where to send the reply , Because in the local network, we usually use IANA A section of address specially designated by the organization , They can't be in Internet The use of .SNAT target Its function is to make all packets from the local network appear to be sent from one machine , This machine is usually a firewall .

SNAT Can only be used in nat Tabular POSTROUTING In the chain . As long as the first eligible package of the connection is wrapped SNAT 了 , Then all other packages of this connection will be automatically SNAT, And this rule also applies to all packets in the stream where the connection is located .

POSTROUTING chain

Our final task should be to construct network address translation , Right ? At least for me . We are nat Tabular POSTROUTING There's only one rule in it , It will be good for all from Internet Interface ( For me, , This is a eth0) Send out the package NAT operation . In all the example scripts , There are some variables , They need to be properly configured . Options -t Specify where to go Insert a rule in a table , Here is nat surface . command -A Explain that we are going to add rules to POSTROUTING At the end of the chain .-o$INET_IFACE Specify to match all slave interfaces INET_IFACE The bag that went out , Here we are using eth0. Last , We put target Set to SNAT. such , All packages that match this rule are created by SNAT target After processing , Their source address is Internet The address of the interface . Don't forget to SNAT But there must be IP Address of the , use --to-source Let's set it up .

PREROUTING chain

seeing the name of a thing one thinks of its function ,PREROUTING chain (nat Tabular ) Is to do network address translation work before routing . then , Packets are then routed , Will be sent to filter Tabular INPUT or FORWARD chain . The only reason we're talking about this chain here is , We feel obliged to point out again that you should not do any filtering in this chain .PREROUTING The chain will only match the first one in the stream package , in other words , All other packets of this stream will not be checked by this chain . in fact , In this script , We didn't use it at all PREROUTING chain . If you want to do something about some bags DNAT operation , for example , You put web service It's in the LAN , This is where you put the rules , of PREROUTING The details of the chain are in the chapter table and chain .

iptables -L Commands can also be viewed nat Table and mangle The contents of the table

iptables -L -t nat

cat /proc/net/ip_conntrack | less

iptables -F -t nat ( eliminate NAT surface )

iptables --list Look at the filter table

New rules on file

./iptables save

stay /proc/net/ip_conntrack There is also the flow of packages in the file

dnat,snat More articles about

  1. ubuntu in DNAT SNAT Configuration experiment .

    1.      Purpose chart 1 Pictured 1 Shown , Yes A,B Two computers , among A Configured as normal PC,B It's the gateway . Realized by A To a nonexistent IP launch tcp Connect , And to this nonexistent ip send data . In response to this tcp The connection is B in ...

  2. Iptables Implement public IP DNAT/SNAT

    Iptables Realization NAT It's the most basic function , Most home routing is based on SNAT Way to get online , Use Iptables Realize the Internet DNAT It's also very simple. , But it's often abnormal NAT The phenomenon of . The following command will access 1.1.1.1 ...

  3. [ turn ]IPTABLES in SNAT and MASQUERADE The difference between

    IPtables Can be flexible to do a variety of network address conversion (NAT) There are two main types of network address conversion :SNAT and DNAT SNAT yes source network address translation Source address to destination translation ...

  4. Talking about iptables Inbound Outbound and NAT example

    -------------- This is a summary of my work notes , The suitable ones can be used directly , Not suitable , It can be modified appropriately !--------------- iptbales Default ACCEPT Strategy , It's also called communication strategy , In this case, you can do ...

  5. arm,iptables: No chain/target/match by that name.

    Recently due to project needs , You need to turn on the firewall function . Company has arm linux 3.0x86 linux 3.2x86 linux 2.4 The three embedded . You need to turn on the firewall function . perform “whereis iptabl ...

  6. iptables Detailed instructions

    One : Preface A firewall , In fact, to put it bluntly , It is used to realize Linux The function of access control under , It can be divided into hardware or software firewalls . No matter in which network , The place where the firewall works must be at the edge of the network . And our task is to define the firewall ...

  7. iptables The rules make up

    One . Four tables, five chains Part of the : Four tables + 5 Chain (Hook point) + The rules Four tables :filter nat mangle raw Five chains :PREROUTING INPUT FORWARD OUTP ...

  8. 【 turn 】IPtables Learning notes

    Write it at the front , Let's test and play iptables Remember to configure those things when you do , Remember to delete after the test , The blogger forgot to delete one input REJECT A record of the chain , Follow up tests set up apache The server , Always inaccessible , Finally, we found that ...

  9. understand Docker Stand alone container network

    stay ”  understand Docker Stand alone container network  “ In the article , One more Docker The function of container network has not been mentioned yet , That's it Docker Port mapping for container . The service port of the container P’ The port bound to the host P On , In the end, there is an effect : The external program is connected with ...

Random recommendation

  1. 2016 ACM/ICPC Asia Regional Dalian Online 1010 Weak Pair dfs order + Block

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total Submissio ...

  2. OpenCV From the beginning to the end of the series —— How to scan images 、 Using look-up tables and timing

    Purpose How to traverse every pixel in the image ? OpenCV How to store the matrix values of ? How to test the performance of our algorithm ? What is a look-up table ? Why use it ? The test case Color space reduction . The specific method is : Divide an existing color space value by an input ...

  3. UVa442 Matrix Chain Multiplication

    // UVa442 Matrix Chain Multiplication // The question : Input n A matrix dimension and some matrix chain multiplication expressions , Output the number of multiplications . Assume A and m*n Of ,B yes n*p Of , that AB yes m*p Of , Multiplication ...

  4. Bluetooth LE( Low power Bluetooth ) - The fifth part

    review : In previous articles in this series, we completed the discovery BLE Sensors and connections . Now all that's left is to get data from it , But it's not as simple as it seems . In this article we will discuss GATT And how to promote the data exchange between host and sensor ...

  5. Vue Direct access between component instances

    In front of the word Sometimes the parent component needs to access the child component , The child component accesses the parent component , Or a sub component accessing the root component . In the component instance ,Vue Provides the corresponding properties , Include $parent.$children.$refs and $root, These properties are all attached to ...

  6. SecureCRT Connect local Vmware virtual machine (CentOS) Indicates that the connection timed out “Connection timed out”

    Tested it , Directly in Vmware Of VM Inside can ping Hostel host . But the host cannot ping through VM. Later found that the local network settings inside vmware Of NAT The network card is set to fill in the address and DNS. Change to auto get . ask ...

  7. Deep learning Dubbo series ( The beginning )

    This document is a series of learning documents This series of documents explains in detail dubbo Use , It basically covers dubbo All the features of . In the following article, we will introduce in detail . If you're relying on dubbo As part of your business engineering RPC Communication framework , Here is your reference hand ...

  8. I don't understand package.json

    Here's the thing , This morning, , The back-end classmates clone We have a small program project , Hope to run on his computer . However , Here's the awkward part , He was in npm install after , The project didn't work as planned , And throw a big mistake . after ...

  9. PHP Deserialization vulnerability learning

    serialize: serialize unserialize: Deserialization Simple explanation : serialize Turn an object into a string , Can be used to save unserialize hold serialize The serialized string becomes ...

  10. Use IntelliJ IDEA To configure Maven( turn )

    Original address : Use IntelliJ IDEA To configure Maven 1. download Maven  Official address :http://maven.apache.org/download.cgi Unzip and create a new local repository folder 2. with ...