前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Linux】《how linux work》第九章 了解网络及其配置(3)

【Linux】《how linux work》第九章 了解网络及其配置(3)

原创
作者头像
阿东
修改2024-05-06 11:14:44
1790
修改2024-05-06 11:14:44
举报
文章被收录于专栏:《How Linux Work》《How Linux Work》

9.19 Network Address Translation (IP Masquerading)(网络地址转换(IP 伪装))

NAT is the most commonly used way to share a single IP address with a private network, and it’s nearly universal in home and small office networks. In Linux, the variant of NAT that most people use is known as IP masquerading.

NAT是最常用的一种方式,用于将单个IP地址与私有网络共享,几乎在家庭和小型办公网络中普遍使用。在Linux中,大多数人使用的NAT变体被称为IP伪装。

The basic idea behind NAT is that the router doesn’t just move packets from one subnet to another; it transforms them as it moves them. Hosts on the Internet know how to connect to the router, but they know nothing about the private network behind it. The hosts on the private network need no special configuration; the router is their default gateway.

NAT背后的基本思想是,路由器不仅仅是将数据包从一个子网转移到另一个子网;在转移数据包时,它还会对其进行转换。

互联网上的主机知道如何连接到路由器,但它们对其后面的私有网络一无所知。

私有网络上的主机不需要特殊配置;路由器是它们的默认网关。

The system works roughly like this:

系统的工作原理大致如下:

  1. A host on the internal private network wants to make a connection to the outside world, so it sends its connection request packets through the router.
  2. The router intercepts the connection request packet rather than passing it out to the Internet (where it would get lost because the public Internet knows nothing about private networks).
  3. The router determines the destination of the connection request packet and opens its own connection to the destination.
  4. When the router obtains the connection, it fakes a “connection established” message back to the original internal host.
  5. The router is now the middleman between the internal host and the destination. The destination knows nothing about the internal host; the connection on the remote host looks like it came from the router.
  6. 内部私有网络上的主机想要与外部世界建立连接,因此它将连接请求数据包通过路由器发送出去。
  7. 路由器拦截连接请求数据包,而不是将其传递到互联网上(因为公共互联网对私有网络一无所知,所以数据包会丢失)。
  8. 路由器确定连接请求数据包的目标,并打开自己与目标之间的连接。
  9. 当路由器获得连接后,它向原始的内部主机发送一个伪造的“连接已建立”消息。
  10. 现在,路由器成为内部主机和目标之间的中间人。目标对内部主机一无所知;远程主机上的连接看起来像是来自路由器。

This isn’t quite as simple as it sounds. Normal IP routing knows only source and destination IP addresses in the Internet layer. However, if the router dealt only with the Internet layer, each host on the internal network could establish only one connection to a single destination at one time (among other limitations), because there is no information in the Internet layer part of a packet to distinguish multiple requests from the same host to the same destination. Therefore, NAT must go beyond the Internet layer and dissect packets to pull out more identifying information, particularly the UDP and TCP port numbers from the transport layers. UDP is fairly easy because there are ports but no connections, but the TCP transport layer is complex

这并不像听起来的那么简单。

普通的IP路由仅在互联网层中知道源IP地址和目标IP地址。

然而,如果路由器仅处理互联网层,那么内部网络上的每个主机一次只能与单个目标建立一个连接(还有其他限制),因为在数据包的互联网层部分没有信息可以区分来自同一主机到同一目标的多个请求。

因此,NAT必须超越互联网层,并解析数据包以提取更多的标识信息,特别是来自传输层的UDP和TCP端口号。

UDP相对比较简单,因为它有端口但没有连接,但TCP传输层则更为复杂。

In order to set up a Linux machine to perform as a NAT router, you must activate all of the following inside the kernel configuration: network packet filtering (“firewall support”), connection tracking, IP tables support, full NAT, and MASQUERADE target support. Most distribution kernels come with this support.

为了将Linux机器设置为执行NAT路由器的功能,您必须在内核配置中激活以下所有内容:网络数据包过滤(“防火墙支持”),连接跟踪,IP表支持,完整的NAT,以及MASQUERADE目标支持。

大多数发行版内核都带有这些支持。

Next you need to run some complex-looking iptables commands to make the router perform NAT for its private subnet. Here’s an example that applies to an internal Ethernet network on eth1 sharing an external connection at eth0 (you’ll learn more about the iptables syntax in 9.21 Firewalls):

接下来,您需要运行一些看起来复杂的iptables命令,以使路由器对其私有子网执行NAT。

以下是一个示例,适用于在eth1上共享外部连接的内部以太网网络(您将在9.21防火墙中了解更多关于iptables语法的内容):

代码语言:sh
复制
# sysctl -w net.ipv4.ip_forward
# iptables -P FORWARD DROP
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# iptables -A FORWARD -i eth0 -o eth1 -m state --state 
ESTABLISHED,RELATED -j ACCEPT
# iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

NOTE Although NAT works well in practice, remember that it’s essentially a hack used to extend the lifetime of the IPv4 address space. In a perfect world, we would all be using IPv6 (the nextgeneration Internet) and using its larger and more sophisticated address space without any pain.注意: 尽管NAT在实践中表现良好,但请记住,它本质上是一种用于延长IPv4地址空间寿命的技巧。在一个完美的世界中,我们都将使用IPv6(下一代互联网),利用它更大、更复杂的地址空间而无需任何痛苦。

You likely won’t ever need to use the commands above unless you’re developing your own software, especially with so much special-purpose router hardware available. But the role of Linux in a network doesn’t end here.

除非您正在开发自己的软件,尤其是有这么多专用路由器硬件可用,否则您可能永远不需要使用上述命令。

但是,Linux在网络中的作用并不止于此。

9.20 Routers and Linux(路由 和 Linux)

In the early days of broadband, users with less demanding needs simply connected their machine directly to the Internet. But it didn’t take long for many users to want to share a single broadband connection with their own networks, and Linux users in particular would often set up an extra machine to use as a router running NAT.

在宽带的早期阶段,那些需求不太高的用户只需将自己的机器直接连接到互联网。

但是很快,许多用户想要将单个宽带连接与自己的网络共享,尤其是Linux用户经常会设置一台额外的机器作为运行NAT的路由器。

Manufacturers responded to this new market by offering specialized router hardware consisting of an efficient processor, some flash memory, and several network ports—with enough power to manage a typical simple network, run important software such as a DHCP server, and use NAT. When it came to software, many manufacturers turned to Linux to power their routers. They added the necessary kernel features, stripped down the user-space software, and created GUI-based administration interfaces.

制造商为了满足这个新市场需求,推出了专门的路由器硬件,包括高效的处理器、一些闪存和几个网络端口,具备足够的能力来管理典型的简单网络、运行重要的软件如DHCP服务器,并使用NAT。

在软件方面,许多制造商选择了Linux作为路由器的操作系统。

他们添加了必要的内核功能,精简了用户空间软件,并创建了基于GUI的管理界面。

Almost as soon as the first of these routers appeared, many people became interested in digging deeper into the hardware. One manufacturer, Linksys, was required to release the source code for its software under the terms of the license of one its components, and soon specialized Linux distributions such as OpenWRT appeared for routers. (The “WRT” in these names came from the Linksys model number.)

几乎在第一批这样的路由器出现后,很多人对硬件进行深入研究产生了兴趣。

其中一家制造商Linksys根据其一个组件的许可证条款被要求公开其软件的源代码,很快就出现了专门为路由器设计的Linux发行版,比如OpenWRT。

(这些名称中的“WRT”来自Linksys的型号编号。)

Aside from the hobbyist aspect, there are good reasons to use these distributions: They’re often more stable than the manufacturer firmware, especially on older router hardware, and they typically offer additional features. For example, to bridge a network with a wireless connection, many manufacturers require you to buy matching hardware, but with OpenWRT installed, the manufacturer and age of the hardware don’t really matter. This is because you’re using a truly open operating system on the router that doesn’t care what hardware you use as long as your hardware is supported.

除了业余爱好者的方面,使用这些发行版还有很好的理由:它们通常比制造商的固件更稳定,尤其是在旧的路由器硬件上,并且它们通常提供额外的功能。

例如,为了通过无线连接桥接网络,许多制造商要求你购买配套的硬件,但是如果安装了OpenWRT,制造商和硬件的年代实际上并不重要。

这是因为你在路由器上使用的是一个真正开放的操作系统,它不关心你使用的是什么硬件,只要你的硬件得到支持即可。

You can use much of the knowledge in this book to examine the internals of custom Linux firmware, though you’ll encounter differences, especially when logging in. As with many embedded systems, open firmware tends to use BusyBox to provide many shell features. BusyBox is a single executable program that offers limited functionality for many Unix commands such as the shell, ls, grep, cat, and more. (This saves a significant amount of memory.) In addition, the boot-time init tends to be very simple on embedded systems. However, you typically won’t find these limitations to be a problem, because custom Linux firmware often includes a web administration interface similar to what you’d see from a manufacturer.

你可以利用本书中的大部分知识来研究定制的Linux固件的内部结构,尽管你会遇到一些差异,特别是在登录时。

与许多嵌入式系统一样,开放固件通常使用BusyBox提供许多Shell功能。BusyBox是一个单一的可执行程序,为许多Unix命令(如shell、ls、grep、cat等)提供了有限的功能。

(这节省了大量的内存。)此外,嵌入式系统上的启动初始化过程通常非常简单。

然而,你通常不会发现这些限制是个问题,因为定制的Linux固件通常包含一个类似于制造商提供的Web管理界面。

9.21 Firewalls

Routers in particular should always include some kind of firewall to keep undesirable traffic out of your network. A firewall is a software and/or hardware configuration that usually sits on a router between the Internet and a smaller network, attempting to ensure that nothing “bad” from the Internet harms the smaller network. You can also set up firewall features for each machine where the machine screens all of its incoming and outgoing data at the packet level (as opposed to the application layer, where server programs usually try to perform some access control of their own). Firewalling on individual machines is sometimes called IP filtering.

特别是路由器,应该始终包含某种防火墙,以阻止不必要的流量进入您的网络。

防火墙是一种软件和/或硬件配置,通常位于路由器和较小网络之间,试图确保来自互联网的任何“坏”东西不会对较小网络造成伤害。

您还可以为每台机器设置防火墙功能,其中机器在数据包级别上筛选其所有传入和传出的数据(与应用层不同,应用程序通常尝试执行一些自己的访问控制)。

有时将在单独的机器上进行的防火墙操作称为IP过滤。

A system can filter packets when it

当系统进行以下操作时,它可以筛选数据包:

o receives a packet,

o sends a packet, or

o forwards (routes) a packet to another host or gateway. With no firewalling in place, a system just processes packets and sends them on their way. Firewalls put checkpoints for packets at the points of data transfer identified above. The checkpoints drop, reject, or accept packets, usually based on some of these criteria:

o The source or destination IP address or subnet

o The source or destination port (in the transport layer information)

o The firewall’s network interface

  • 接收数据包
  • 发送数据包
  • 转发(路由)数据包到另一个主机或网关。如果没有设置防火墙,系统只是处理数据包并将其发送出去。防火墙在数据传输点处设置数据包检查点。这些检查点通常根据以下一些标准来丢弃、拒绝或接受数据包:
  • 源IP地址或目标IP地址或子网
  • 源端口或目标端口(在传输层信息中)
  • 防火墙的网络接口

Firewalls provide an opportunity to work with the subsystem of the Linux kernel that processes IP packets. Let’s look at that now.

防火墙提供了与处理IP数据包的Linux内核子系统一起工作的机会。

现在让我们来看一下这个。

9.21.1 Linux Firewall Basics(Linux 防火墙基础知识)

In Linux, you create firewall rules in a series known as a chain. A set of chains makes up a table. As a packet moves through the various parts of the Linux networking subsystem, the kernel applies the rules in certain chains to the packets. For example, after receiving a new packet from the physical layer, the kernel activates rules in chains corresponding to input.

在Linux中,您可以通过一系列称为链的方式来创建防火墙规则。一组链构成了一个表。

当数据包在Linux网络子系统的各个部分之间移动时,内核会根据特定链中的规则对数据包进行处理。

例如,在从物理层接收到新数据包后,内核会激活与输入相对应的链中的规则。

All of these data structures are maintained by the kernel. The whole system is called iptables, with an iptables user-space command to create and manipulate the rules.

所有这些数据结构都由内核维护。整个系统被称为iptables,有一个iptables用户空间命令用于创建和操作规则。

NOTE There is a newer system called nftables that has a goal of replacing iptables, but as of this writing, iptables is the dominant system for firewalls.注意:还有一个名为nftables的新系统旨在取代iptables,但截至本文写作时,iptables仍然是主要的防火墙系统。

Because there can be many tables—each with their own sets of chains, each of which can contain many rules— packet flow can become quite complicated. However, you’ll normally work primarily with a single table named filterthat controls basic packet flow. There are three basic chains in the filtertable: INPUT for incoming packets, OUTPUT for outgoing packets, and FORWARD for routed packets.

由于可以有多个表,每个表都有自己的一组链,每个链都可以包含多个规则,因此数据包流动可能会变得非常复杂。

然而,通常您主要使用一个名为filter的表来控制基本的数据包流动。

filter表中有三个基本链:INPUT用于传入的数据包,OUTPUT用于传出的数据包,FORWARD用于路由的数据包。

Figure 9-5 and Figure 9-6 show simplified flowcharts for where rules are applied to packets in the filter table. There are two figures because packets can either come into the system from a network interface (Figure 9-5) or be generated by a local process (Figure 9-6). As you can see, an incoming packet from the network can be consumed by a user process and may not reach the FORWARD chain or the OUTPUT chain. Packets generated by user processes won’t reach the INPUT or FORWARD chains

图9-5和图9-6显示了规则在filter表中应用于数据包的简化流程图。

之所以有两个图,是因为数据包可以通过网络接口进入系统(图9-5),也可以由本地进程生成(图9-6)。

正如您所见,从网络进入的数据包可能会被用户进程消耗掉,不会到达FORWARD链或OUTPUT链。由用户进程生成的数据包不会到达INPUT或FORWARD链。

Figure 9-6. Chain-processing sequence for incoming packets from a local process
Figure 9-6. Chain-processing sequence for incoming packets from a local process

Figure 9-6. Chain-processing sequence for incoming packets from a local process

图9-6. 来自本地进程的入站数据包的链处理序列

This gets more complicated because there are many steps along the way other than just these three chains. For example, packets are subject to PREROUTING and POSTROUTING chains, and chain processing can also occur at any of the three lower network levels. For a big diagram for everything that’s going on, search the Internet for “Linux netfilter packet flow,” but remember that these diagrams try to include every possible scenario for packet input and flow. It often helps to break the diagrams down by packet source, as in Figure 9- 5 and Figure 9-6.

这变得更加复杂,因为除了这三个链之外,还有许多步骤。

例如,数据包会经过PREROUTING和POSTROUTING链,而且链处理也可以发生在三个较低的网络层中的任何一个。

如果想要了解正在进行的所有内容的大图表,请在互联网上搜索“Linux netfilter packet flow”,但请记住,这些图表试图包含每种可能的数据包输入和流动情景。

将图表按数据包来源进行拆分通常会有所帮助,如图9-5和图9-6所示。

9.21.2 Setting Firewall Rules(设置防火墙规则)

Let’s look at how the IP tables system works in practice. Start by viewing the current configuration with this command:

让我们来看看IP表系统在实践中是如何工作的。首先通过以下命令查看当前配置:

代码语言:sh
复制
# iptables -L

The output is usually an empty set of chains, as follows:

通常输出为空链集,如下所示:

代码语言:sh
复制
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Each firewall chain has a default policy that specifies what to do with a packet if no rule matches the packet. The policy for all three chains in this example is ACCEPT, meaning that the kernel allows the packet to pass through the packet-filtering system. The DROP policy tells the kernel to discard the packet. To set the policy on a chain, use iptables -P like this:

每个防火墙链都有一个默认策略,指定如果没有规则匹配数据包时该如何处理数据包。

在这个例子中,所有三个链的策略都是 ACCEPT,表示内核允许数据包通过数据包过滤系统。

DROP 策略告诉内核丢弃数据包。

要设置链上的策略,请使用 iptables -P 命令,如下所示:

代码语言:sh
复制
# iptables -P FORWARD DROP

WARNING Don’t do anything rash with the policies on your machine until you’ve read through the rest of this section警告:在仔细阅读完本节剩余内容之前,请不要随意更改您机器上的策略。

Say that someone at 192.168.34.63 is annoying you. To prevent them from talking to your machine, run this command:

假设有人在 192.168.34.63 上让您感到不悦。

为阻止他们与您的机器通讯,请运行以下命令:

代码语言:sh
复制
# iptables -A INPUT -s 192.168.34.63 -j DROP

The -A INPUT parameter appends a rule to the INPUT chain. The -s 192.168.34.63 part specifies the source IP address in the rule, and -j DROP tells the kernel to discard any packet matching the rule. Therefore, your machine will throw out any packet coming from 192.168.34.63.

-A INPUT参数将规则附加到INPUT链。

其中-s 192.168.34.63部分指定规则中的源IP地址,而-j DROP告诉内核丢弃与规则匹配的任何数据包。

因此,你的机器将丢弃来自192.168.34.63的任何数据包。

To see the rule in place, run iptables -L:

要查看已设置的规则,请运行iptables -L:

代码语言:sh
复制
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere

Unfortunately, your friend at 192.168.34.63 has told everyone on his subnet to open connections to your SMTP port (TCP port 25). To get rid of that traffic as well, run

代码语言:sh
复制
# iptables -A INPUT -s 192.168.34.0/24 -p tcp --destination-port 25 -j DROP

This example adds a netmask qualifier to the source address as well as -p tcp to specify TCP packets only. A further restriction, --destination-port 25, says that the rule should only apply to traffic to port 25. The IP table list for INPUT now looks like this:

这个例子在源地址上添加了一个netmask限定符,同时加上了-p tcp来指定仅限制TCP数据包。

进一步的限制是--destination-port 25,表示规则仅适用于流向端口25的流量。

现在,INPUT的IP表列表如下:

代码语言:sh
复制
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere
DROP tcp -- 192.168.34.0/24 anywhere tcp dpt:smtp

All is well until you hear from someone you know at 192.168.34.37 saying that they can’t send you email because you blocked their machine. Thinking that this is a quick fix, you run this command:

一切都很顺利,直到你收到来自你认识的某人(IP地址为192.168.34.37)的消息,说他们无法给你发邮件,因为你屏蔽了他们的设备。

认为这是一个快速解决方案,你运行了这个命令:

代码语言:sh
复制
# iptables -A INPUT -s 192.168.34.37 -j ACCEPT

However, it doesn’t work. To see why, look at the new chain:

然而,这并不奏效。

要了解原因,请看新的链条:

代码语言:sh
复制
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere
DROP tcp -- 192.168.34.0/24 anywhere tcp dpt:smtp
ACCEPT all -- 192.168.34.37 anywhere

The kernel reads the chain from top to bottom, using the first rule that matches.

内核从上到下读取链路,使用第一个匹配的规则。

The first rule does not match 192.168.34.37, but the second does, because it applies to all hosts from 192.168.34.1 to 192.168.34.254 and this second rule says to drop packets. When a rule matches, the kernel carries out the action and looks no further down in the chain. (You might notice that 192.168.34.37 can send packets to any port on your machine except port 25 because the second rule only applies to port 25.)

第一个规则不匹配192.168.34.37,但是第二个规则匹配,因为它适用于从192.168.34.1到192.168.34.254的所有主机,并且这个第二个规则指示丢弃数据包。

当规则匹配时,内核执行相应的动作,并且不再继续向下查找链路。

(你可能注意到192.168.34.37可以向你的机器的任意端口发送数据包,除了端口25,因为第二个规则只适用于端口25。)

The solution is to move the third rule to the top. First, delete the third rule with this command:

解决办法是将第三个规则移动到顶部。

首先,使用以下命令删除第三个规则:

代码语言:sh
复制
# iptables -D INPUT 3

Then insert that rule at the top of the chain with iptables -I:

然后用 iptables -I 将该规则插入链的顶端:

代码语言:sh
复制
# iptables -I INPUT -s 192.168.34.37 -j ACCEPT

To insert a rule elsewhere in a chain, put the rule number after the chain name (for example, iptables -I INPUT 4 ...).

要在链的其他位置插入规则,请在链名后加上规则编号(例如,iptables -I INPUT 4 ... )。

9.21.3 Firewall Strategies(防火墙策略)

Although the tutorial above showed you how to insert rules and how the kernel processes IP chains, we haven’t seen firewall strategies that actually work. Let’s talk about that now

尽管上面的教程向您展示了如何插入规则以及内核如何处理IP链,但我们还没有看到实际起作用的防火墙策略。现在让我们来谈谈这个问题。

There are two basic kinds of firewall scenarios: one for protecting individual machines (where you set rules in each machine’s INPUT chain) and one for protecting a network of machines (where you set rules in the router’s FORWARD chain). In both cases, you can’t have serious security if you use a default policy of ACCEPT and continuously insert rules to drop packets from sources that start to send bad stuff. You must allow only the packets that you trust and deny everything else.

防火墙有两种基本的场景:一种是保护单个机器的场景(在每台机器的INPUT链中设置规则),另一种是保护机器网络的场景(在路由器的FORWARD链中设置规则)。

在这两种情况下,如果您使用接受的默认策略并不断插入规则以丢弃来自开始发送不良内容的源的数据包,那么您将无法获得严格的安全性。

您必须仅允许您信任的数据包,并拒绝其他所有内容。

For example, say your machine has an SSH server on TCP port 22. There’s no reason for any random host to initiate a connection to any other port on your machine, and you shouldn’t give any such host a chance. To set that up, first set the INPUT chain policy to DROP:

例如,假设您的机器在TCP端口22上有一个SSH服务器。

任何随机主机都没有理由与您的机器的任何其他端口建立连接,您也不应该给予任何此类主机机会。

为了设置这一点,首先将INPUT链的策略设置为DROP:

代码语言:sh
复制
# iptables -P INPUT DROP

To enable ICMP traffic (for ping and other utilities), use this line:

要启用 ICMP 流量(用于 ping 和其他实用程序),请使用这一行:

代码语言:sh
复制
# iptables -A INPUT -p icmp -j ACCEPT

Make sure that you can receive packets you send to both your own network IP address and 127.0.0.1 (localhost). Assuming your host’s IP address is my_addr, do this:

确保您能接收到发送到自己网络 IP 地址和 127.0.0.1(localhost)的数据包。

假设主机的 IP 地址是 my_addr,请执行此操作:

代码语言:sh
复制
# iptables -A INPUT -s 127.0.0.1 -j ACCEPT
# iptables -A INPUT -s my_addr -j ACCEPT

If you control your entire subnet (and trust everything on it), you can replace my_addr with your subnet address and subnet mask, for example, 10.23.2.0/24.

如果您控制着整个子网(并信任子网中的一切),则可以用子网地址和子网掩码替换 my_addr,例如 10.23.2.0/24。

Now, although you still want to deny incoming TCP connections, you still need to make sure that your host can make TCP connections to the outside world. Because all TCP connections start with a SYN (connection request) packet, if you let all TCP packets through that aren’t SYN packets, you’re still okay:

现在,尽管您仍想拒绝传入的 TCP 连接,但仍需确保您的主机能与外界建立 TCP 连接。

由于所有 TCP 连接都是以 SYN(连接请求)数据包开始的,因此如果您允许所有非 SYN 数据包的 TCP 数据包通过,就不会有问题:

代码语言:sh
复制
# iptables -A INPUT -p tcp '!' --syn -j ACCEPT

Next, if you’re using remote UDP-based DNS, you must accept traffic from your name server so that your machine can look up names with DNS. Do this for all DNS servers in /etc/resolv.conf. Use this command (where the name server’s address is ns_addr):

接下来,如果使用的是基于 UDP 的远程 DNS,则必须接受来自名称服务器的流量,这样机器才能使用 DNS 查找名称。

对 /etc/resolv.conf 中的所有 DNS 服务器都要这样做。使用此命令(其中名称服务器地址为 ns_addr):

代码语言:sh
复制
# iptables -A INPUT -p udp --source-port 53 -s ns_addr -j ACCEPT

And finally, allow SSH connections from anywhere:

最后,允许从任何地方进行 SSH 连接:

代码语言:sh
复制
# iptables -A INPUT -p tcp --destination-port 22 -j ACCEPT

The preceding iptables settings work for many situations, including any direct connection (especially broadband) where an intruder is much more likely to port-scan your machine. You could also adapt these settings for a firewalling router by using the FORWARD chain instead of INPUT and using source and destination subnets where appropriate. For more advanced configurations, you may find a configuration tool such as Shorewall to be helpful.

前面的iptables设置适用于许多情况,包括任何直接连接(特别是宽带连接),在这种情况下,入侵者更有可能对您的计算机进行端口扫描。

您还可以通过在适当的地方使用源和目标子网,将这些设置适应于防火墙路由器,使用FORWARD链而不是INPUT链。

对于更高级的配置,您可能会发现Shorewall等配置工具很有帮助。

This discussion has only touched on security policy. Remember that the key idea is to permit only the things that you find acceptable, not to try to find and execute the bad stuff. Furthermore, IP firewalling is only one piece of the security picture. (You’ll see more in the next chapter.)

这次讨论只涉及安全策略。

请记住,关键思想是只允许您认为可以接受的事物,而不是试图找到并执行有害的东西。

此外,IP防火墙只是安全方案的一部分。(在下一章中您将看到更多内容。)

9.22 Ethernet, IP, and ARP(以太网,IP和ARP)

There is one interesting basic detail in the implementation of IP over Ethernet that we have yet to cover. Recall that a host must place an IP packet inside an Ethernet frame in order to transmit the packet across the physical layer to another host. Recall, too, that frames themselves do not include IP address information; they use MAC (hardware) addresses. The question is this: When constructing the Ethernet frame for an IP packet, how does the host know which MAC address corresponds to the destination IP address?

在实现以太网上的IP传输中,有一个有趣的基本细节我们还没有涉及到。

回想一下,为了将数据包通过物理层传输到另一个主机,主机必须将IP数据包放置在以太网帧中。

同样,帧本身不包含IP地址信息,而是使用MAC(硬件)地址。

问题是:在构建IP数据包的以太网帧时,主机如何知道哪个MAC地址对应于目标IP地址?

We don’t normally think about this question much because networking software includes an automatic system of looking up MAC addresses called Address Resolution Protocol (ARP). A host using Ethernet as its physical layer and IP as the network layer maintains a small table called an ARP cache that maps IP addresses to MAC addresses. In Linux, the ARP cache is in the kernel. To view your machine’s ARP cache, use the arp command. (As with many other network commands, the -n option here disables reverse DNS lookups.)

通常我们不会过多考虑这个问题,因为网络软件包含了一种自动查找MAC地址的系统,称为地址解析协议(ARP)。

一个使用以太网作为物理层和IP作为网络层的主机会维护一个小表,称为ARP缓存,用于将IP地址映射到MAC地址。

在Linux中,ARP缓存位于内核中。

要查看您机器的ARP缓存,请使用arp命令。

(与许多其他网络命令一样,此处的-n选项禁用了反向DNS查找。)

代码语言:sh
复制
$ arp -n
Address Hwtype Hwaddr Flags Mask Iface
10.1.2.141 ether 00:11:32:0d:ca:82 C eth0
10.1.2.1 ether 00:24:a5:b5:a0:11 C eth0
10.1.2.50 ether 00:0c:41:f6:1c:99 C eth0

When a machine boots, its ARP cache is empty. So how do these MAC addresses get in the cache? It all starts when the machine wants to send a packet to another host. If a target IP address is not in an ARP cache, the following steps occur:

当一台机器启动时,它的ARP缓存是空的。

那么这些MAC地址是如何进入缓存的呢?

一切都始于机器想要向另一台主机发送数据包。

如果目标IP地址不在ARP缓存中,将会按照以下步骤进行:

  1. The origin host creates a special Ethernet frame containing an ARP request packet for the MAC address that corresponds to the target IP address.
  2. The origin host broadcasts this frame to the entire physical network for the target’s subnet.
  3. If one of the other hosts on the subnet knows the correct MAC address, it creates a reply packet and frame containing the address and sends it back to the origin. Often, the host that replies is the target host and is simply replying with its own MAC address.
  4. The origin host adds the IP-MAC address pair to the ARP cache and can proceed.
  5. 源主机创建一个特殊的以太网帧,其中包含一个用于对应目标IP地址的MAC地址的ARP请求数据包。
  6. 源主机将此帧广播到目标子网的整个物理网络。
  7. 如果子网上的其他主机知道正确的MAC地址,它将创建一个包含该地址的回复数据包和帧,并将其发送回源主机。通常,回复的主机就是目标主机,并且只是简单地回复其自己的MAC地址。
  8. 源主机将IP-MAC地址对添加到ARP缓存中,并可以继续进行。

NOTE Remember that ARP only applies to machines on local subnets (refer to 9.4 Routes and the Kernel Routing Table to see your local subnets). To reach destinations outside your subnet, your host sends the packet to the router, and it’s someone else’s problem after that. Of course, your host still needs to know the MAC address for the router, and it can use ARP to find it.注意,ARP仅适用于本地子网上的机器(请参考9.4节的路由和内核路由表以查看您的本地子网)。要想到达子网外的目的地,您的主机将数据包发送到路由器,之后就成为其他人的问题了。当然,您的主机仍然需要知道路由器的MAC地址,并且可以使用ARP来找到它。

The only real problem you can have with ARP is that your system’s cache can get out-of-date if you’re moving an IP address from one network interface card to another because the cards have different MAC addresses (for example, when testing a machine). Unix systems invalidate ARP cache entries if there’s no activity after a while, so there shouldn’t be any trouble other than a small delay for invalidated data, but you can delete an ARP cache entry immediately with this command:

ARP唯一真正的问题是,如果您将IP地址从一个网络接口卡移动到另一个网络接口卡(例如在测试机器时),系统的缓存可能会变得过时。

Unix系统在一段时间后如果没有活动,将使ARP缓存条目无效,因此除了对无效数据的小延迟之外,不应该有任何问题。

但是,您可以立即使用以下命令删除ARP缓存条目:

代码语言:sh
复制
# arp -d host

You can also view the ARP cache for a single network interface with

您还可以通过以下命令查看单个网络接口的 ARP 缓存

代码语言:sh
复制
$ arp -i interface

The arp(8) manual page explains how to manually set ARP cache entries, but you shouldn’t need to do this.

arp(8) 手册页面解释了如何手动设置 ARP 缓存项,但您应该不需要这样做。

NOTE Don’t confuse ARP with Reverse Address Resolution Protocol (RARP). RARP transforms a MAC address back to a hostname or IP address. Before DHCP became popular, some diskless workstations and other devices used RARP to get their configuration, but RARP is rare today.注意 不要混淆 ARP 与反向地址解析协议(RARP)。RARP 将 MAC 地址转换回主机名或 IP 地址。在 DHCP 流行之前,一些无盘工作站和其他设备使用 RARP 获取配置,但现在 RARP 已经很少见了。

9.23 Wireless Ethernet(无线以太网)

In principle, wireless Ethernet (“WiFi”) networks aren’t much different from wired networks. Much like any wired hardware, they have MAC addresses and use Ethernet frames to transmit and receive data, and as a result the Linux kernel can talk to a wireless network interface much as it would a wired network interface. Everything at the network layer and above is the same; the main differences are additional components in the physical layer such as frequencies, network IDs, security, and so on.

原则上,无线以太网(“WiFi”)网络与有线网络并没有太大的区别。

就像任何有线硬件一样,它们具有MAC地址,并使用以太网帧来传输和接收数据,因此Linux内核可以像对待有线网络接口一样与无线网络接口进行通信。

在网络层及以上的所有内容都是相同的;主要的区别在于物理层中有额外的组件,如频率、网络ID、安全等等。

Unlike wired network hardware, which is very good at automatically adjusting to nuances in the physical setup without much fuss, wireless network configuration is much more open-ended. To get a wireless interface working properly, Linux needs additional configuration tools

与有线网络硬件不同,它非常擅长在物理设置中自动调整而不需要太多麻烦,无线网络配置则更加开放。

为了使无线接口正常工作,Linux需要额外的配置工具。

Let’s take a quick look at the additional components of wireless networks.

让我们快速了解一下无线网络的额外组件。

o Transmission details. These are physical characteristics, such as the radio frequency.

o Network identification. Because more than one wireless network can share the same basic medium, you have to be able to distinguish between them. The SSID (Service Set Identifier, also known as the “network name”) is the wireless network identifier.

o Management. Although it’s possible to configure wireless networking to have hosts talk directly to each other, most wireless networks are managed by one or more access points that all traffic goes through. Access points often bridge a wireless network with a wired network, making both appear as one single network.

o Authentication. You may want to restrict access to a wireless network. To do so, you can configure access points to require a password or other authentication key before they’ll even talk to a client.

o Encryption. In addition to restricting the initial access to a wireless network, you normally want to encrypt all traffic that goes out across radio waves.

o 传输细节。这些是物理特性,如无线电频率。

o 网络标识。因为多个无线网络可以共享同一个基本介质,所以你必须能够区分它们。SSID(服务集标识符,也称为“网络名称”)是无线网络的标识符。

o 管理。虽然可以将无线网络配置为主机直接互相通信,但大多数无线网络由一个或多个访问点管理,所有流量都通过这些访问点。访问点通常将无线网络与有线网络桥接起来,使其看起来像一个单一的网络。

o 认证。您可能希望限制对无线网络的访问。为此,您可以配置访问点要求客户端在进行通信之前输入密码或其他认证密钥。

o 加密。除了限制对无线网络的初始访问之外,通常还希望对通过无线电波传输的所有流量进行加密。

The Linux configuration and utilities that handle these components are spread out over a number of areas. Some are in the kernel: Linux features a set of wireless extensions that standardize user-space access to hardware. As far as user space goes, wireless configuration can get complicated, so most people prefer to use GUI frontends, such as the desktop applet for NetworkManager, to get things working. Still, it’s worth looking at a few of the things happening behind the scenes.

处理这些组件的Linux配置和实用程序分散在多个领域。

其中一些在内核中:Linux提供了一组无线扩展,用于标准化用户空间对硬件的访问。

就用户空间而言,无线配置可能会变得复杂,因此大多数人更喜欢使用GUI前端,例如NetworkManager的桌面小程序,来使事情正常运行。

不过,了解一下幕后发生的一些事情仍然是值得的。

9.23.1 iw

You can view and change kernel space device and network configuration with a utility called iw. To use iw, you normally need to know the network interface name for the device, such as wlan0. Here’s an example that dumps a scan of available wireless networks. (Expect a lot of output if you’re in an urban area.)

您可以使用一个名为iw的实用工具来查看和更改内核空间设备和网络配置。

要使用iw,通常需要知道设备的网络接口名称,例如wlan0。

以下是一个示例,显示可用无线网络的扫描结果(如果您在城市地区,可能会有大量输出)。

代码语言:sh
复制
# iw dev wlan0 scan

NOTE The network interface must be up for this command to work (if it’s not, run ifconfig wlan0 up), but you don’t need to configure any network layer parameters, such as an IP address. 注意:要使该命令生效,网络接口必须处于启动状态(如果没有启动,运行ifconfig wlan0 up),但您不需要配置任何网络层参数,例如IP地址。

If the network interface has joined a wireless network, you can view the network details like this:

如果网络接口已连接到无线网络,您可以像这样查看网络详细信息:

代码语言:sh
复制
# iw dev wlan0 link

The MAC address in the output of this command is from the access point that you’re currently talking to.

该命令输出中的MAC地址是您当前正在通信的接入点的地址。

NOTE The iw command distinguishes between physical device names such as phy0 and network interface names such as wlan0 and allows you to change various settings for each. You can even create more than one network interface for a single physical device. However, in nearly all basic cases, you’ll just use the network interface name. 注意:iw命令区分物理设备名称(如phy0)和网络接口名称(如wlan0),并允许您为每个名称更改各种设置。您甚至可以为单个物理设备创建多个网络接口。但是,在几乎所有基本情况下,您只需使用网络接口名称即可。

Use iw to connect a network interface to an unsecured wireless network as follows:

使用iw将网络接口连接到一个未加密的无线网络,可以按照以下步骤进行:

代码语言:sh
复制
# iw wlan0 connect network_name

Connecting to secured networks is a different story. For the rather insecure Wired Equivalent Privacy (WEP) system, you can use the keys parameter with the iw connect command. However, you shouldn’t use WEP if you’re serious about security

连接到受保护的网络则是另一回事。

对于相当不安全的Wired Equivalent Privacy(WEP)系统,您可以使用iw connect命令的keys参数。

然而,如果您对安全性比较重视,不应使用WEP。

9.23.2 Wireless Security(无线安全)

For most wireless security setups, Linux relies on a daemon called wpa_supplicant to manage both authentication and encryption for a wireless network interface. This daemon can handle both WPA (WiFi Protected Access) and WPA2 schemes of authentication, as well as nearly any kind of encryption technique used on wireless networks. When the daemon first starts, it reads a configuration file (by default, /etc/wpa_supplicant.conf) and attempts to identify itself to an access point and establish communication based on a given network name. The system is well documented; in particular, the wpa_supplicant(1) and wpa_supplicant.conf(5) manual pages are very detailed.

对于大多数无线安全设置,Linux依赖一个名为wpa_supplicant的守护进程来管理无线网络接口的身份验证和加密。

该守护进程可以处理WPA(WiFi Protected Access)和WPA2身份验证方案,以及几乎所有在无线网络上使用的加密技术。

当守护进程首次启动时,它会读取一个配置文件(默认为/etc/wpa_supplicant.conf),并尝试根据给定的网络名称向访问点标识自己并建立通信。

该系统有很好的文档支持,特别是wpa_supplicant(1)和wpa_supplicant.conf(5)手册非常详细。

Running the daemon by hand every time you want to establish a connection is a lot of work. In fact, just creating the configuration file is tedious due to the number of possible options. To make matters worse, all of the work of running iw and wpa_supplicant simply allows your system to join a wireless physical network; it doesn’t even set up the network layer. And that’s where automatic network configuration managers such as NetworkManager take a lot of pain out of the process. Although they don’t do any of the work on their own, they know the correct sequence and required configuration for each step toward getting a wireless network operational.

每次想要建立连接时手动运行守护进程是很麻烦的工作。

事实上,由于可能的选项数量,仅创建配置文件就很繁琐。更糟糕的是,运行iw和wpa_supplicant的所有工作只是让您的系统加入一个无线物理网络,甚至没有设置网络层。

而这正是自动网络配置管理器(如NetworkManager)在这个过程中承担了很多痛苦的地方。

虽然它们自己不做任何工作,但它们知道每个步骤的正确顺序和所需配置,以使无线网络正常运行。

9.24 Summary(摘要)

You can now see that understanding the positions and roles of the various network layers is critical to understanding how Linux networking operates and how to perform network configuration. Although we’ve covered only the basics, more advanced topics in the physical, network, and transport layers bear similarities to what you’ve seen. Layers themselves are often subdivided, as you just saw with the various pieces of the physical layer in a wireless network.

现在您可以看到,了解各个网络层的位置和角色对于理解Linux网络操作和执行网络配置至关重要。

虽然我们只涵盖了基础知识,但物理层、网络层和传输层的更高级主题与您所见到的内容有相似之处。

层本身通常会细分,就像您刚才在无线网络的物理层中看到的各个部分一样。

A substantial amount of action that you’ve seen in this chapter happens in the kernel, with some basic userspace control utilities to manipulate the kernel’s internal data structures (such as routing tables). This is the traditional way of working with the network. However, as with many of the topics discussed in this book, some tasks aren’t suitable for the kernel due to their complexity and need for flexibility, and that’s where userspace utilities take over. In particular, NetworkManager monitors and queries the kernel and then manipulates the kernel configuration. Another example is support for dynamic routing protocols such as Border Gateway Protocol (BGP), which is used in large Internet routers.

在本章中,您所见到的大部分操作都发生在内核中,使用一些基本的用户空间控制实用程序来操作内核的内部数据结构(如路由表)。

这是与网络一起工作的传统方式。

然而,与本书讨论的许多主题一样,由于其复杂性和灵活性的需求,一些任务并不适合在内核中进行,这就是用户空间实用程序接管的地方。

特别是,NetworkManager监视和查询内核,然后操作内核配置。

另一个例子是对动态路由协议(如边界网关协议BGP)的支持,它在大型互联网路由器中使用。

But you’re probably a little bit bored with network configuration by now. Let’s turn to using the network— the application layer.

但是您可能对网络配置有点厌倦了。让我们转向使用网络——应用层。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 9.19 Network Address Translation (IP Masquerading)(网络地址转换(IP 伪装))
  • 9.20 Routers and Linux(路由 和 Linux)
  • 9.21 Firewalls
    • 9.21.1 Linux Firewall Basics(Linux 防火墙基础知识)
      • 9.21.2 Setting Firewall Rules(设置防火墙规则)
        • 9.21.3 Firewall Strategies(防火墙策略)
        • 9.22 Ethernet, IP, and ARP(以太网,IP和ARP)
        • 9.23 Wireless Ethernet(无线以太网)
          • 9.23.1 iw
            • 9.23.2 Wireless Security(无线安全)
            • 9.24 Summary(摘要)
            相关产品与服务
            私有网络
            私有网络(Virtual Private Cloud,VPC)是基于腾讯云构建的专属云上网络空间,为您在腾讯云上的资源提供网络服务,不同私有网络间完全逻辑隔离。作为您在云上的专属网络空间,您可以通过软件定义网络的方式管理您的私有网络 VPC,实现 IP 地址、子网、路由表、网络 ACL 、流日志等功能的配置管理。私有网络还支持多种方式连接 Internet,如弹性 IP 、NAT 网关等。同时,您也可以通过 VPN 连接或专线接入连通腾讯云与您本地的数据中心,灵活构建混合云。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档