[Translation] NAT - Network Address Translation (2016)

[Translation] NAT - Network Address Translation (2016)

Published at 2019-02-17 | Last Update

Translator's Preface

This translation from 2016 of an English blog NAT - Network Address - Search.com .

Due to the limited level translator, this is not free from errors or omissions place. If in doubt, consult the original text.

The following is a translation.


1 Introduction

Network address translation typically involves "in IP packets through a router or firewall, edit the source and / or destination address" ( Wikipedia by: the NAT ).

This article describes what is NAT, NAT and in how to use Linux (or, more broadly, various Unix derivative version) how to configure NAT on. However, this article does not cover all the details NAT, and the main readers want to know: In modern computer networks it can be used to do, and what not to do.

Next will first look at the structure of the IP packet, and then briefly describes some of the features (Linux) kernel, then entered, introduced one of the most common NAT scenarios, namely, through the router (in this case, one of iptables support Linux machines) to a private subnet to connect to the Internet.

Back then, I will introduce several other possibilities, such as redirection, or how to use a proxy (proxy) to bypass the firewall. But I can not guarantee that these solutions are the most intelligent, most powerful or the most sophisticated design, the reader should only treat them as some examples of programs show the NAT function (proof of concept).

The network data packets 2

This section discusses only IP packets based on TCP and UDP protocols.

Introduction IP packet, see IPv4 AT Wikipedia . This article will be used wherein the two fields: source IP and destination IP.

TCP and UDP are transport layer protocols, description, see respectively:

  1. TCP at Wikipedia
  2. UDP at Wikipedia

Transport layer will use the port number, paper for simplicity that each (network) process carried out independent of port number, for example, HTTP service running on port 80, SSH service running on port 22.

An IP address plus a port number of a defined transport layer socket. is the only socket, a socket and a client server socket define a connection (Connection), one end of the data transmitted, the other end will be received. For example, socket 123.123.123.123:65432and socket 112.112.112.112:80set up a connection, it may be 123.123.123.123browser on the machine being accessed is located 112.112.112.112on the surface of the HTTP service.

Server program generally uses the standard port numbers, called "well known ports" (known port number), see the well known ports at IANA or Well Known the ports AT Wikipedia . The client program uses a temporary port number, a general increase from 1023 up, select an available.

3 Linux and Netfilter

Linux kernel has a packet filter frame (packet filter framework), is called the netfilter (item address netfilter.org ). This framework makes Linux machine can work as a router. Next we will use a command-line tool to create complex iptables rules, modify and filter data packets. Not surprisingly, the most important rules and NAT-related, are in natthis (iptables) table inside. This table has three pre-set chain: PRETOUTING, OUTPUTand POSTROUTING.

PREROUTINGAnd POSTROUTINGis the most important chain. As the name implies, PRETOUTINGcatena alberghiera responsible for processing the packet just arrived at the network interface, then the route is determined not done yet, and therefore do not know that the packet destined for the machine (local), or other hosts within the network. After the package PRETOUTINGafter chain, the route determination. If the object is a native, then the next process will not involve the NAT; if the objective is other machine within the network, that packet will be forwarded to that machine, provided that the machine is configured to allow forwarding.

Before forwarding the packet leaves the machine, it will go through the POSTROUTINGchain. For native packets generated where there is a difference: it will go through OUTPUTcatena alberghiera, then through the POSTROUTINGchain.

To use NAT, we first need to configure the machine. The following example, the #beginning of the Notes, $>the beginning of the command.

# IMPORTANT: Activate IP-forwarding in the kernel!

# Disabled by default!
$> echo "1" > /proc/sys/net/ipv4/ip_forward

# Load various modules. Usually they are already loaded 
# (especially for newer kernels), in that case 
# the following commands are not needed.
 
# Load iptables module:
$> modprobe ip_tables

# activate connection tracking
# (connection's status are taken into account)
$> modprobe ip_conntrack

# Special features for IRC:
$> modprobe ip_conntrack_irc

# Special features for FTP:
$> modprobe ip_conntrack_ftp

The above configuration should be sufficient. If you encounter an error, probably because you do not specify the kernel routing options relevant at compile time, please refer here .

Examples 4: The private network is connected to the Internet via NAT

We know that the structure of an IP packet, but also know how to manipulate data packets in Linux, so then you can use it. The most widely used NAT scenario should be that: all machines in a private subnet to share an Internet connection . Then we start from this example.

4.1 Analogy: landlord and tenant letters transceiver

We do use the analogy of an example of an image to be more easily understood NAT.

Consider the following scenario:

There are a landlord, several of his tenants, and several postman.

Several mail landlord can send and receive mail, but no tenants, therefore, all the tenants directly to the postman letters are discarded. However, tenants can have their letters to the landlord, the landlord will these letters to the post office. The question then is: how to send and receive letters tenants involved in it?

One solution is to:

The landlord-tenant different letters into his own different mailbox, and the letter on the tenant's address (in a sense is an invalid address because mail this address will be discarded directly postman) into one of your mailbox address . Therefore, the reply will be placed in the appropriate mailbox mailman landlord, the landlord can easily judge the letter belongs to which tenant and forwarded to them (the landlord will own address and then changes back before the tenant's address transmitted, so tenants will not find mail address been modified). In this way a sense is the best, because it is completely transparent to the tenants, they are completely unaware of the postman is unable to process mail sent directly to the tenants.

4.2 from tenant problems to the computer world

NAT issues of principle and more tenants are very similar:

  • Tenant corresponding to the IP address within the local subnet , different tenants (on the NAT router) to specify different port number (Port)
  • Landlord correspond NAT router
  • Mail recipient corresponding to any host on the Internet

A socket is an IP address plus a port.

Tenant communication process:

  1. Tenants will mail into office landlords
  2. The landlord will send the address (in this case the tenant address) into one of his own e-mail address
  3. When the landlord received a reply, you will receive an address (in this case one of your e-mail address) into the address corresponding to the tenants

The case of the local network and the process is similar:

  1. All hosts (clients) in a subnet to send packets through the socket to a particular router (router address by setting all of the gateway machine to achieve, through an Ethernet or other data is the underlying transport protocols)
  2. Router the sender of a socket for their replacement (not yet used) socket
  3. The socket receives data, the router will modify the socket address corresponding client socket, and forwarded to it

We assume that the client gateway settings are correct, and that the rest is how to configure the router.

Fortunately, each netfilter framework will set a (to or out into the) rules, automatically sets its reverse rules, so we only need to set the rules in one direction can be. Choose which direction to set the rules? Usually choose a direction uncertain small. For example, "Replace all packets sent from the local network address" than the "modified if the client had sent something to the server, the server sends the data that will be in some way" is much simpler.

How to Set Rules 4.3

We hope to achieve is: emanating from the local network, the Internet is the purpose of the package, will modify the sender address is the address of the router.

Next, assume that the local network router go eth0port, go to the Internet network eth1port. So as we expect to complete the command functions :

# Connect a LAN to the internet
$> iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

Explanation:

  • iptables - Tools to configure the kernel
  • -t nat- Specify the name of natthe iptables table configure NAT rules
  • -A POSTROUTING- Additional (A: Append) iptables rule to the POSTROUTINGchain
  • -o eth1- Specifies the only eth1 sent packets do operation (o: output)
  • -j MASQUERADE- rule matching operation after the success Masquerade (disguise) packets, for example, modifying the source address to a router address

Further Incidentally, (in addition to the client over the packet) packet router itself also relates to the above processing logic, because they also been POSTROUTINGcatena alberghiera (see figure above). However, because the router is to do when a client socket (IP + Port) conversion, it will be selected from the unused port, so the port and the port NAT do its own package used is certainly different. Thus, while its own package will be subject to the above rules, but not modified.

The network interface may be any type, such as ISDN and SDL interfaces are possible (usually ppp0or ippp0). Can ifconfigview all (active) interface:

# Display available network interfaces
$> ifconfig

4.4 NAT deficiencies

Now, local computer can access the Internet, but in turn, we look at a machine on the Internet to access the local machine will be what happens.

Machine on the Internet to establish a connection to the local machine, then, the only information it can use is to use IP address of the router plus a port number. In most cases, this port is not in use, so over the packet will be rejected. Even better luck, this port is a port of the router doing NAT, the package is still likely to be rejected because the port is already on the Internet and other hosts to establish a connection.

Therefore, to establish a connection is almost impossible on the Internet from the machine to the local machine.

For regular service, you can statically map the router ports to local services, for example, the router forwards packets received on port 80 to the local machine's HTTP server.

5 Closer Look iptables

With the above basis, we see the detail iptables features. Help command:

# Abstract structure of an iptables instruction:
iptables [-t table] command [match pattern] [action]

For NAT, you must choose nattable.

5.1 selection table

The following command will choose the nattable:

# Choosing the nat-table
# (further arguments abbreviated by [...])
iptables -t nat [...]

mangleAnd filtertable and it has nothing to do NAT, so this does not describe. Because the default table is a filtertable, so we followed every time specified-t nat .

5.2 several important command

The most important of several commands:

# In the following "chain" represents
# one of the chains PREROUTING, OUTPUT and POSTROUTING

# add a rule:
$> iptables -t nat -A chain [...]

# list rules:
$> iptables -t nat -L

# remove user-defined chain with index 'myindex':
$> iptables -t nat -D chain myindex

# Remove all rules in chain 'chain':
$> iptables -t nat -F chain

Complete iptables command to view the man page:

# manual pages of iptables
$> man iptables

Press qexit help.

5.3 Selecting matching mode (pattern)

Pattern matching to specify specific packets to be processed. Here are a few important examples, complete pattern information, see iptables man page.

# actions to be taken on matched packets
# will be abbreviated by '[...]'.
# Depending on the match pattern the appropriate chain is selected.

# TCP packets from 192.168.1.2:
$> iptables -t nat -A POSTROUTING -p tcp -s 192.168.1.2 [...]

# UDP packets to 192.168.1.2:
$> iptables -t nat -A POSTROUTING -p udp -d 192.168.1.2 [...]

# all packets from 192.168.x.x arriving at eth0:
$> iptables -t nat -A PREROUTING -s 192.168.0.0/16 -i eth0 [...]

# all packets except TCP packets and except packets from 192.168.1.2:
$> iptables -t nat -A PREROUTING -p ! tcp -s ! 192.168.1.2 [...]

# packets leaving at eth1:
$> iptables -t nat -A POSTROUTING -o eth1 [...]

# TCP packets from 192.168.1.2, port 12345 to 12356
# to 123.123.123.123, Port 22
# (a backslash indicates contination at the next line)
$> iptables -t nat -A POSTROUTING -p tcp -s 192.168.1.2 \
   --sport 12345:12356 -d 123.123.123.123 --dport 22 [...]

Most options have a length of two formats, for example --source, and -swrite, long format up trouble, but easier to read.

5.4 action after match

At this point, we have to specify the matching pattern to filter packets, the next step is to choose the appropriate action. For natTable, there are several actions: SNAT, MASQUERADE, DNAT, REDIRECT, you will need -jto specify. Their format (representation as will be described in the next section):

# In the following the table selection, the command and the match pattern
# will be abbreviated using [...]

# Source-NAT: Change sender to 123.123.123.123
$> iptables [...] -j SNAT --to-source 123.123.123.123

# Mask: Change sender to outgoing network interface
$> iptables [...] -j MASQUERADE

# Destination-NAT: Change receipient to 123.123.123.123, port 22
$> iptables [...] -j DNAT --to-destination 123.123.123.123:22

# Redirect to local port 8080
$> iptables [...] -j REDIRECT --to-ports 8080

6 Several iptables action

Explain in detail the four actions.

6.1 SNAT - to modify the source IP is the new fixed IP (static)

The previous example of a local private network connected to the Internet, we have used the Source NAT (SNAT). As the name implies, the sender's address is statically modified.

In the example we have chosen MASQUERADEthe reason is that: for SNAT, IP converted must be explicitly specified . If the router is configured static IP address, that SNAT is the most appropriate choice because it is more than MASQUERADEfaster, which will need to check the IP address configured on the specified output port for each packet.

Because SNAT only the packets leave the router meaningful, so it is only used in the POSTROUTINGchain in.

# Options for SNAT (abstract of manual page)
--to-source <ipaddr>[-<ipaddr>][:port-port]

6.2 MASQUERADE - dynamically modify the source IP address is a new IP (network interface dynamically obtain IP)

And SNATsimilar, but dynamic access to each package will specify the output IP interface (NIC), so if the IP address of the interface sending a change in MASQUERADEthe rules will not be affected, can work; and for SNATit is necessary to re-adjust the rules.

And SNATthe same, MASQUERADEonly POSTROUTINGmakes sense chain. However, and SNATdifferent, MASQUERADEit does not support the more detailed configuration items.

6.3 DNAT - modifies the destination IP

If you want to change the destination IP address of the packet, it requires the use of Destination NAT (DNAT).

DNAT can be used to run the server behind the firewall.

Obviously, the receiving terminal modifications must be done before routing decisions, thus suitable for DNAT PRETOUTINGand OUTPUT(for locally generated) catena alberghiera .

# Options for DNAT (abstract of manual page)
--to-destination <ipaddr>[-<ipaddr>][:port-port] 

6.3 REDIRECT - the packet is redirected to another port of the machine

REDIRECT is a special scene of DNAT. The router packet to be redirected to another local port, may be implemented, for example, a transparent proxy function. And, like DNAT, REDIRECT apply PRETOUTINGand OUTPUTchain.

# Options for REDIRECT (abstract of manual page)
--to-ports <port>[-<port>] 

7 NAT application (Applications)

Obscure (cryptic) The first example in this article (the local network connected to the Internet) commands that might make you a bit confused. Then we gradually give some explanation of command parameters, the reader should understand more clearly some than before. Problems may range from "people how to write such a cryptic instruction" to "good, how can I use these arcane commands it?" This chapter will give some examples of how to use NAT. Range of applications and is not limited, but I will try to cover some of the most common scenarios.

7.1 Transparent Proxy

Suppose we have a local network connected to the Internet through NAT. We need a HTTP proxy running on port 8080 router, local network handle HTTP traffic.

First, think of solutions is: to allow each user to set their browser to use a proxy server, then a ban on all port 80 traffic. For a small network, this approach may be satisfactory, but can not be extended to a large network, because in this way need to be configured for each client. (Also lost the "transparent proxy" meaning).

使用 NAT,我们有另一种可能:所有从 80 端口进来的流量,重定向到 8080 端口。相应 的命令:

# Transparent proxying:
# (local net at eth0, proxy server at port 8080)
$> iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 \
   -j REDIRECT --to-ports 8080 

当然,8080 端口要有 HTTP 代理运行。另外,你的服务器可能做一些特殊配置(甚至特殊 编译)才能支持透明代理。

透明代理的缺点是 CPU load 会升高(尤其是大型网络),对太新或太旧的浏览器可能有兼 容性问题。

7.2 绕过防火墙

在继续本文之前,我首先要发出警告:

每位读者在使用以下提供的技术之前,都需要确认这些步骤是否会破坏你们的现有环境! 使用如下命令带来的风险是读者自己的,对不当使用以下命令和技术带来的损坏,我不负 任何责任!

你可能意想不到,NAT 在这种场景下可以派上用场。

我们假设路由器只有少量端口可以被本地网络访问。

首先要找到这些已经被打开的(open)端口。一个的常用工具是 nmap(请只扫描你自己的机器,扫描未知的机器会被认为 是入侵行为的前奏)。

# Scan a machine:
# (Replace www.example.com by an appropriate machine)
$> nmap www.example.com

以上命令会扫描出很多端口,其中大部分处于 “closed” 状态(该端口上没有服务),另 外有一部分处于 “filtered” 状态(该端口上没有连接),可能有一些处于 “open” 状态( 服务正在该端口上运行)。我们假设 5000 以下的端口除了 80 都处于 closed 状态,但是 5000 以上的端口有 可达的。

为了实现可以连接任意外网机器的 5000 以下的任意端口,需要一个位于防火墙之前的机器 (称为跳板机,位置没有关系,只要网络可达,并且它自己没有被防火墙限制),它要能被 访问,并且支持 NAT (iptables)。假设这台机器 IP 为 111.111.111.111

7.2.1 配置内网机器可以 SSH 到跳板机

首先需要 SSH 登录到 111.111.111.111(由于防火墙限制 5000 以下端口,SSH 端口默 认是 22,因此需要在防火墙外面找机器才能登录)。然后在 111.111.111.111 上执行:

# Redirect SSH from port 5000 to port 22:
$> iptables -t nat -A PREROUTING -p tcp --dport 5000 -j REDIRECT --to-ports 22

这个命令做的事情就是,将 5000 端口 进来的流量重定向到本机的 22 端口(SSH)。

然后,我们在防火墙内的机器上,就可以通过 5000 端口用 SSH 访问工作站了,工作站会 将请求转向 111.111.111.11122 端口。

或者,你也可以配置 111.111.111.111 的 SSH 进程直接运行在 5000 端口,这样就不需 要以上 iptables 规则了。

7.2.2 通过跳板机从内网连接到公网举例:邮件服务器 POP3

现在,你可以在跳板机 111.111.111.111 上配置连接其他机器或服务(运行在其他端口 )的 NAT 规则来。

例如,通过跳板机的 5001 端口连接机器 123.123.123.123 的 110 (POP3)端口,执行:

# redirect port 5001 to port 110 (POP3) at 123.123.123.123:
$> iptables -t nat -A PREROUTING -p tcp --dport 5001 \
   -j DNAT --to-destination 123.123.123.123:110
   
# Change sender to redirecting machine:
$> iptables -t nat -A POSTROUTING -p tcp --dport 110 \
   -j MASQUERADE

这里用的是 MASQUERADE,但用 SNAT 也是可以的(-j SNAT --to-source 111.111.111.111)。

用同样的方式,我们可以(从内网)连接到(外网机器的)其他端口,只要跳板机上的可用 端口足够多。即使是安全连接(例如 IMAPS)也可以这样操作,但需要忽略安全证书的警告 (只要我们知道自己在做什么)。对于上面的 POP3 例子,你还需要配置你的邮件客户端, 将服务器地址设置为 111.111.111.111,端口为 5001

7.2.3 通过跳板机绕过 HTTP 监控

假设网络供应商为 80 端口的所有连接设置了代理(例如,透明代理),然后监控所有的网络 流量(内容),我们使用 NAT 可以绕过它。

和上面类似,在跳板机上寻找一个可用端口,例如 5002,做透明代理。

然后,在你自己的(内网)机器上,执行:

# redirect http-Traffic going to Port 80 to 111.111.111.111:5002:
$> iptables -t nat -A OUTPUT -p tcp --dport 80 \
   -j DNAT --to-destination 111.111.111.111:5002

这样就成功绕过了供应商的代理(我们使用透明代理绕过了供应商的透明代理!)。

或者,不需要 iptables 规则,你可以设置浏览器的默认端口是 5002,但是这可能有一些 潜在的问题。

总结本节的透明代理方案步骤:

  1. 首先找到找到一个可用端口,可以让内网机器和跳板机建立 SSH 连接
  2. 静态地将可用端口重定向到期望的地址(大部分情况下都是 HTTP 服务)

如果想实现动态重定向,那两个 TCP 端口(其中一个用于 SSH)和一个 UDP 端口足够了, 据此可以实现从内网机器连接到任意外网机器的任意端口,唯一的不足是每次只能有一个连 接(每种协议)。

7.3 通过 NAT 从外网访问内网服务

运行在 NAT 路由器后面的内网服务器,默认是不能被外部网络直接访问的。例如,假设我 们有一个 HTTP 服务运行在内网机器 192.168.1.2,NAT 路由器的地址是 192.168.1.1 ,并通过另一张有公网 IP 123.123.123.123 的网卡连接到了外部网络。

要使得外网机器可以访问 192.168.1.2 的服务,需要执行:

# redirect http traffic to 192.168.1.2:
$> iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 80 -j DNAT --to 192.168.1.2

然后,就可以通过公网 IP 123.123.123.123 的 80 端口访问 192.168.1.2 的 HTTP 服务了。

8 相关文章

类似的文章:

  1. http://iptables-tutorial.frozentux.net/iptables-tutorial.html, 非常详细的关于 iptables 的文章
  2. http://www.faqs.org/docs/Linux-mini/TransparentProxy.html, 关于透明代理更深入的介绍
  3. http://www.barryodonovan.com/publications/lg/108/, netfilter extension 来实现更多的功能

9 结束语,致谢及其他

netfilter 框架非常强大,而且一旦熟悉其语法后,配置还是比较简单的。基于 iptables/netfilter 可以完成很多功能,虽然一些命令看起来可能比较晦涩,但拿几个例子稍加训练之后,你就 会发现它们都符合特定的模式,可以用于快速简单的管理。

感谢每一位能读到这里的耐心读者 :-) 另外我还要感谢我的运行 SUSE 10.1 的笔记本,没 有在写作本文的时候挂掉。

我的母语不是英语,因此如果读者能指出本文措辞语句的一些可改进之处,我将非常高兴。 这里 (见原文,这里不贴是防止给原作者带去潜在的垃圾邮件,事实上原作者贴的是图片而不是 文本,也应该有此考虑)是我的联系邮箱。

Guess you like

Origin www.cnblogs.com/taosiyu/p/12025003.html