前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Linux】《how linux work》第十章 网络应用和服务(2)

【Linux】《how linux work》第十章 网络应用和服务(2)

原创
作者头像
阿东
发布2024-04-27 10:50:53
920
发布2024-04-27 10:50:53
举报
文章被收录于专栏:《How Linux Work》《How Linux Work》

10.5 Diagnostic Tools(诊断工具)

Let’s look at a few diagnostic tools that are useful for poking around the application layer. Some dig into the transport and network layers, because everything in the application layer eventually maps down to something in those lower layers.

让我们看一些有用的诊断工具,用于查看应用层。

有些工具会深入到传输层和网络层,因为应用层中的所有内容最终都会映射到这些较低的层中的某些内容。

As discussed in Chapter 9, netstat is a basic network service debugging tool that can display a number of transport and network layer statistics. Table 10-2 reviews a few useful options for viewing connections.

如第9章所讨论的,netstat是一种基本的网络服务调试工具,可以显示许多传输层和网络层的统计信息。

表10-2列出了一些有用的选项,用于查看连接。

Table 10-2. Useful Connection-Reporting Options for netstat

表10-2. netstat的有用连接报告选项

image.png
image.png

10.5.1 lsof

In Chapter 8, you learned that lsof can track open files, but it can also list the programs currently using or listening to ports. For a complete list of programs using or listening to ports, run

在第8章中,您了解到 lsof 可以跟踪打开的文件,但它也可以列出当前正在使用或监听端口的程序。

要获取使用或监听端口的程序的完整列表,请运行

代码语言:sh
复制
# lsof -i 

When run as a regular user, this command only shows that user’s processes. When run as root, the output should look something like this, displaying a variety of processes and users:

以普通用户身份运行此命令时,只会显示该用户的进程。

以 root 用户身份运行时,输出应该类似于以下内容,显示各种进程和用户:

image.png
image.png

This example output shows users and process IDs for server and client programs, from the old-style RPC services at the top, to the multicast DNS service provided by avahi, and even an IPv6-ready printer service (cupsd). The last two entries show client connections: an SSH connection and a secure web connection from the Chromium web browser. Because the output can be extensive, it’s usually best to apply a filter (as discussed in the following section).

这个示例输出显示了服务器和客户端程序的用户和进程ID,从顶部的旧式RPC服务,到由avahi提供的多播DNS服务,甚至是一个支持IPv6的打印机服务(cupsd)。

最后两个条目显示了客户端连接:一个SSH连接和来自Chromium网页浏览器的安全网页连接。

由于输出可能很庞大,通常最好应用过滤器(如下一节所讨论的)。

The lsof program is like netstat in that it tries to reverse-resolve every IP address that it finds into a hostname, which slows down the output. Use the -n option to disable name resolution:

lsof程序类似于netstat,它尝试将找到的每个IP地址反向解析为主机名,这会减慢输出速度。

使用-n选项来禁用名称解析:

代码语言:sh
复制
# lsof -n -i 

You can also specify -P to disable /etc/services port name lookups.

您还可以指定-P选项来禁用/etc/services端口名称查找。

Filtering by Protocol and Port(按协议和端口过滤)

If you’re looking for a particular port (say, you know that a process is using a particular port and you want to know what that process is), use this command:

如果您正在寻找特定的端口(比如,您知道某个进程正在使用特定端口,想要知道该进程是什么),可以使用以下命令:

代码语言:sh
复制
# lsof -i:port

The full syntax is as follows:

完整的语法如下:

代码语言:sh
复制
# lsof -iprotocol@host:port 

The protocol, @host, and :port parameters are all optional and will filter the lsof output accordingly. As with most network utilities, host and port can be either names or numbers. For example, if you only want to see connections on TCP port 80 (the HTTP port), use

协议、@主机和:端口号参数都是可选的,将根据它们过滤lsof输出。

与大多数网络工具一样,主机和端口可以是名称或数字。

例如,如果您只想看到TCP端口80(HTTP端口)上的连接,请使用:

代码语言:sh
复制
# lsof -iTCP:80

Filtering by Connection Status(通过连接状态过滤)

One particularly handy lsof filter is connection status. For example, to show only the processes listening on TCP ports, enter

连接状态是一个特别方便的 lsof 过滤器。

例如,要只显示监听 TCP 端口的进程,输入

代码语言:sh
复制
# lsof -iTCP -sTCP:LISTEN

This command gives you a good overview of the network server processes currently running on your system. However, because UDP servers don’t listen and don’t have connections, you’ll have to use -iUDP to view running clients as well as servers. This usually isn’t a problem, because you probably won’t have many UDP servers on your system.

这个命令可以让你清楚地了解当前在你的系统上正在运行的网络服务器进程。

然而,由于UDP服务器不监听也不建立连接,你需要使用-iUDP选项来查看正在运行的客户端以及服务器。

通常情况下这不会是一个问题,因为你的系统上可能不会有很多UDP服务器。

10.5.2 tcpdump

If you need to see exactly what’s crossing your network, tcpdump puts your network interface card into promiscuous mode and reports on every packet that crosses the wire. Entering tcpdump with no arguments produces output like the following, which includes an ARP request and web connection:

如果你需要准确查看穿过你的网络的内容,tcpdump会将你的网络接口卡置于混杂模式,并报告每一个经过的数据包。

输入无参数的tcpdump会产生如下输出,其中包括一个ARP请求和web连接:

代码语言:sh
复制
# tcpdump 
tcpdump: listening on eth0 
20:36:25.771304 arp who-has mikado.example.com tell duplex.example.com 
20:36:25.774729 arp reply mikado.example.com is-at 0:2:2d:b:ee:4e 
20:36:25.774796 duplex.example.com.48455 > mikado.example.com.www: S 
3200063165:3200063165(0) 
38815804[|tcp]> 
(DF) 
win 
5840 
<mss 
1460,sackOK,timestamp 
20:36:25.779283 mikado.example.com.www > duplex.example.com.48455: S 
ack 
3200063166 
win 
5792 
<mss 
3494716463:3494716463(0) 
1460,sackOK,timestamp 
4620[|tcp]> (DF) 
20:36:25.779409 duplex.example.com.48455 > mikado.example.com.www: . 
ack 1 win 
5840 <nop,nop,timestamp 38815805 4620> (DF) 
20:36:25.779787 duplex.example.com.48455 > mikado.example.com.www: P 
1:427(426) 
ack 1 win 5840 <nop,nop,timestamp 38815805 4620> (DF) 
20:36:25.784012 mikado.example.com.www > duplex.example.com.48455: . 
ack 427 
win 6432 <nop,nop,timestamp 4620 38815805> (DF) 
20:36:25.845645 mikado.example.com.www > duplex.example.com.48455: P 
1:773(772) 
ack 427 win 6432 <nop,nop,timestamp 4626 38815805> (DF) 
20:36:25.845732 duplex.example.com.48455 > mikado.example.com.www: . 
ack 773 
win 6948 <nop,nop,timestamp 38815812 4626> (DF) 
9 packets received by filter 
0 packets dropped by kernel

You can tell tcpdump to be more specific by adding filters. You can filter based on source and destination hosts, networks, Ethernet addresses, protocols at many different layers in the network model, and much more. Among the many packet protocols that tcpdump recognizes are ARP, RARP, ICMP, TCP, UDP, IP, IPv6, AppleTalk, and IPX packets. For example, to tell tcpdump to output only TCP packets, run

你可以通过添加过滤器来让tcpdump更具体。

你可以根据源主机、目标主机、网络、以太网地址、网络模型中的许多不同层面的协议等进行过滤,还有更多选项。

tcpdump能识别的许多数据包协议包括ARP、RARP、ICMP、TCP、UDP、IP、IPv6、AppleTalk和IPX数据包。

例如,要告诉tcpdump仅输出TCP数据包,可以运行:

代码语言:sh
复制
# tcpdump tcp

To see web packets and UDP packets, enter

要查看网络数据包和 UDP 数据包,请输入

代码语言:sh
复制
# tcpdump udp or port 80

NOTE If you need to do a lot of packet sniffing, consider using a GUI alternative to tcpdump such as Wireshark.注意 如果需要进行大量数据包嗅探,可考虑使用图形用户界面来替代 tcpdump,如 Wireshark。

Primitives(基元)

In the preceding examples, tcp, udp, and port 80 are called primitives. The most important primitives are in Table 10-3:

在前面的示例中,tcp、udp 和端口 80 被称为基元。表 10-3 列出了最重要的基元:

Table 10-3. tcpdump Primitives

表 10-3. tcpdump 基元

Table 10-3. tcpdump Primitives
Table 10-3. tcpdump Primitives

Operators(运算符)

The or used in the previous example is an operator. tcpdump can use multiple operators (such as and and !), and you can group operators in parentheses. If you plan to do any serious work with tcpdump, make sure to read the manual page, especially the section that describes the primitives.

在前面的示例中使用的 or 是一个运算符。tcpdump 可以使用多个运算符(比如 and 和 !),你可以将运算符分组在括号中。

如果你打算在 tcpdump 中进行任何严肃的工作,请务必阅读手册页,特别是描述基本操作的部分。

When Not to Use tcpdump(不应该使用 tcpdump 的情况)

Be very careful when using tcpdump. The tcpdump output shown earlier in this section includes only packet TCP (transport layer) and IP (Internet layer) header information, but you can also make tcpdump print the entire packet contents. Even though many network operators make it far too easy to look at their network packets, you shouldn’t snoop around on networks unless you own them.

在使用 tcpdump 时要非常小心。在本节中之前展示的 tcpdump 输出仅包含数据包的 TCP(传输层)和 IP(网络层)头部信息,但你也可以让 tcpdump 打印完整的数据包内容。

尽管许多网络运营商让查看他们的网络数据包变得非常容易,但你不应该在没有权限的情况下窥探网络。

10.5.3 netcat

If you need more flexibility in connecting to a remote host than a command like telnet host port allows, use netcat (or nc). netcat can connect to remote TCP/UDP ports, specify a local port, listen on ports, scan ports, redirect standard I/O to and from network connections, and more. To open a TCP connection to a port with netcat, run

如果您需要比telnet主机端口命令更灵活地连接到远程主机,可以使用netcat(或nc)。

netcat可以连接到远程TCP/UDP端口,指定本地端口,监听端口,扫描端口,重定向标准I/O到网络连接等等。

要使用netcat打开到端口的TCP连接,请运行

代码语言:sh
复制
$ netcat host port 

netcat only terminates when the other side of the connection ends the connection, which can confuse things if you redirect standard input to netcat. You can end the connection at any time by pressing CTRL-C. (If you’d like the program and network connection to terminate based on the standard input stream, try the sock program instead.)

netcat 只有在连接的另一端结束连接时才会终止,如果你将标准输入重定向到 netcat,这可能会导致混淆。你可以通过按下 CTRL-C 随时结束连接。

(如果你希望程序和网络连接根据标准输入流终止,请尝试使用 sock 程序。)

To listen on a particular port, run

要监听特定端口,请运行

代码语言:sh
复制
$ netcat -l -p port_number 

10.5.4 Port Scanning(端口扫描)

Sometimes you don’t even know what services the machines on your networks are offering or even which IP addresses are in use. The Network Mapper (Nmap) program scans all ports on a machine or network of machines looking for open ports, and it lists the ports it finds. Most distributions have an Nmap package, or you can get it at http://www.insecure.org/. (See the Nmap manual page and online resources for all that Nmap can do.)

有时候你甚至不知道你网络上的设备提供了哪些服务,甚至不知道哪些 IP 地址正在使用。

网络映射工具(Nmap)程序会扫描一台机器或一组机器上的所有端口,寻找开放的端口,并列出它所找到的端口。

大多数发行版都有 Nmap 软件包,或者你可以在 http://www.insecure.org/ 获取它。

(查看 Nmap 手册页和在线资源,了解 Nmap 的所有功能。)

When listing ports on your own machine, it often helps to run the Nmap scan from at least two points: from your own machine and from another one (possibly outside your local network). Doing so will give you an overview of what your firewall is blocking.

当列出自己机器上的端口时,通常最好从至少两个点运行 Nmap 扫描:从你自己的机器和另一个机器(可能是在本地网络之外的机器)。

这样做将让你了解你的防火墙正在阻止什么。

WARNING If someone else controls the network that you want to scan with Nmap, ask for permission. Network administrators watch for port scans and usually disable access to machines that run them.警告 如果有其他人控制你想要用 Nmap 扫描的网络,请先征得许可。网络管理员会监视端口扫描,并通常会禁止运行它们的设备的访问。

Run nmap host to run a generic scan on a host. For example:

运行 nmap host 命令在主机上运行一次通用扫描。

例如:

代码语言:sh
复制
$ nmap 10.1.2.2 
Starting Nmap 5.21 ( http://nmap.org ) at 2015-09-21 16:51 PST 
Nmap scan report for 10.1.2.2 
Host is up (0.00027s latency). 
Not shown: 993 closed ports 
PORT     
STATE SERVICE 
22/tcp   open  ssh 
25/tcp   open  smtp 
80/tcp   open  http 
111/tcp  open  rpcbind 
8800/tcp open  unknown 
9000/tcp open  cslistener 
9090/tcp open  zeus-admin 
Nmap done: 1 IP address (1 host up) scanned in 0.12 seconds

As you can see, a number of services are open here, many of which are not enabled by default on most distributions. In fact, the only one here that’s usually on by default is port 111, the rpcbind port.

正如您所见,这里打开了许多服务,其中许多在大多数发行版上默认情况下都未启用。实际上,这里通常默认启用的仅有一个,即端口111,即rpcbind端口。

10.6 Remote Procedure Call (RPC)

What about the rpcbind service that you just saw in the scan in the preceding section? RPC stands for remote procedure call, a system residing in the lower parts of the application layer. It’s designed to make it easier for programmers to access network applications by leveraging the fact that programs call functions on remote programs (identified by program numbers) and the remote programs return a result code or message.

你刚刚在前面的扫描中看到的rpcbind服务怎么样?RPC代表远程过程调用,是位于应用层较低部分的系统。它旨在通过利用程序调用远程程序(由程序号标识)并远程程序返回结果代码或消息的方式,使程序员更容易访问网络应用程序。

RPC implementations use transport protocols such as TCP and UDP, and they require a special intermediary service to map program numbers to TCP and UDP ports. The server is called rpcbind, and it must be running on any machine that wants to use RPC services.

RPC实现使用诸如TCP和UDP之类的传输协议,并且它们需要一个特殊的中间服务来将程序号映射到TCP和UDP端口。该服务器称为rpcbind,任何想要使用RPC服务的机器都必须运行该服务。

To see what RPC services your computer has, run

要查看你的计算机具有哪些RPC服务,运行以下命令:

代码语言:sh
复制
$ rpcinfo -p localhost 

RPC is one of those protocols that just doesn’t want to die. The Network File System (NFS) and Network Information Service (NIS) systems use RPC, but they are completely unnecessary on standalone machines. But whenever you think that you’ve eliminated all need for rpcbind, something else comes up, such as File Access Monitor (FAM) support in GNOME.

RPC是那种似乎不愿消亡的协议之一。

网络文件系统(NFS)和网络信息服务(NIS)系统使用RPC,但在独立机器上完全是不必要的。

但是,每当您认为已经消除了对rpcbind的所有需求时,又会出现其他问题,比如GNOME中的文件访问监视器(FAM)支持。

10.7 Network Security(网络安全)

Because Linux is a very popular Unix flavor on the PC platform, and especially because it is widely used for web servers, it attracts many unpleasant characters who try to break into computer systems. 9.21 Firewalls discussed firewalls, but that’s not really the whole story on security.

由于Linux是PC平台上非常流行的Unix版本,特别是因为它广泛用于Web服务器,吸引了许多不怀好意的人物试图侵入计算机系统。9.21 防火墙讨论了防火墙,但这并不是安全的全部故事。

Network security attracts extremists—those who really like to break into systems (whether for fun or money) and those who come up with elaborate protection schemes who really like to swat away people trying to break into their systems. (This, too, can be very profitable.) Fortunately, you don’t need to know very much to keep your system safe. Here are a few basic rules of thumb:

网络安全吸引了极端分子——那些真的喜欢入侵系统的人(无论是为了乐趣还是金钱),以及那些设计复杂保护方案的人,他们真的喜欢击退试图入侵他们系统的人。

(这也可以非常有利可图。)幸运的是,你不需要了解太多就能保护好你的系统。以下是一些基本的经验法则:

o Run as few services as possible. Intruders can’t break into services that don’t exist on your system. If you know what a service is and you’re not using it, don’t turn it on for the sole reason that you might want to use it “at some later point.”

  • 尽可能运行尽可能少的服务。入侵者无法入侵你系统上不存在的服务。如果你知道一个服务是什么,而你又没有使用它,不要仅仅因为你可能想在“以后的某个时候”使用它而打开它。

o Block as much as possible with a firewall. Unix systems have a number of internal services that you may not know about (such as TCP port 111 for the RPC port-mapping server), and no other system in the world should know about them. It can be very difficult to track and regulate the services on your system because many different kinds of programs listen on various ports. To keep intruders from discovering internal services on your system, use effective firewall rules, and install a firewall at your router.

  • 尽可能使用防火墙阻止一切。Unix系统有许多内部服务,你可能不知道它们的存在(比如TCP端口111用于RPC端口映射服务器),世界上没有其他系统应该知道它们。 - 要跟踪和管理系统上的服务可能非常困难,因为许多不同种类的程序会监听各种端口。 - 为了防止入侵者发现你系统上的内部服务,使用有效的防火墙规则,在你的路由器上安装一个防火墙。

o Track the services that you offer to the Internet. If you run an SSH server, Postfix, or similar services, keep your software up-to-date and get appropriate security alerts. (See 10.7.2 Security Resources for some online resources.)

  • 跟踪你向互联网提供的服务。如果你运行SSH服务器、Postfix或类似的服务,请保持软件更新,并获取适当的安全警报。(参见10.7.2 安全资源,了解一些在线资源。)

o Use “long-term support” distribution releases for servers. Security teams normally concentrate their work on stable, supported distribution releases. Development and testing releases such Debian Unstable and Fedora Rawhide receive much less attention.

  • 对于服务器,使用“长期支持”发行版。安全团队通常会集中精力在稳定、受支持的发行版上进行工作。开发和测试发行版如Debian Unstable和Fedora Rawhide接受的关注要少得多。

o Don’t give an account on your system to anyone who doesn’t need one. It’s much easier to gain superuser access from a local account than it is to break in remotely. In fact, given the huge base of software (and the resulting bugs and design flaws) available on most systems, it can be easy to gain superuser access to a system after you get to a shell prompt. Don’t assume that your friends know how to protect their passwords (or choose good passwords in the first place).

  • 不要为不需要的人在你的系统上创建账户。 - 从本地账户获取超级用户权限比远程入侵要容易得多。 - 事实上,鉴于大多数系统上可用的软件(以及由此产生的漏洞和设计缺陷),一旦你进入一个shell提示符,很容易获得系统的超级用户权限。 - 不要假设你的朋友知道如何保护他们的密码(或者一开始就选择好密码)。

o Avoid installing dubious binary packages. They can contain Trojan horses. That’s the practical end of protecting yourself. But why is it important to do so? There are three basic kinds of network attacks:

  • 避免安装可疑的二进制软件包。它们可能包含特洛伊木马。 - 这是保护自己的实际结束。但为什么这么做很重要呢?网络攻击有三种基本类型:

o Full compromise. This means getting superuser access (full control) of a machine. An intruder can accomplish this by trying a service attack, such as a buffer overflow exploit, or by taking over a poorly protected user account and then trying to exploit a poorly written setuid program.

  • 完全破坏。这意味着获得对机器的超级用户权限(完全控制)。 - 入侵者可以通过尝试服务攻击,比如缓冲区溢出攻击,或者接管一个保护不力的用户账户,然后尝试利用一个编写不好的setuid程序来实现这一点。

o Denial-of-service (DoS) attack. This prevents a machine from carrying out its network services or forces a computer to malfunction in some other way without the use of any special access. These attacks are harder to prevent, but they are easier to respond to.

  • 拒绝服务(DoS)攻击。这会阻止机器执行其网络服务,或者以其他方式迫使计算机发生故障,而无需使用任何特殊访问。 - 这些攻击更难预防,但更容易应对。

o Malware. Linux users are mostly immune to malware such as email worms and viruses, simply because their email clients aren’t stupid enough to actually run programs that they get in message attachments. But Linux malware does exist. Avoid downloading and installing binary software from places that you’ve never heard of.

  • 恶意软件。Linux用户大多免疫于恶意软件,如电子邮件蠕虫和病毒,仅仅因为他们的电子邮件客户端并不愚蠢到实际运行他们在消息附件中收到的程序。 - 但Linux上确实存在恶意软件。避免从你从未听说过的地方下载和安装二进制软件。10.7.1 Typical Vulnerabilities

There are two important kinds of vulnerabilities to worry about: direct attacks and clear-text password sniffing. Direct attacks try to take over a machine without being terribly subtle. The most common is a buffer overflow exploit, where a careless programmer doesn’t check the bounds of a buffer array. The attacker fabricates a stack frame inside a huge chunk of data, dumps it to the remote server, and then hopes that the server overwrites its program data and eventually executes the new stack frame. Although a somewhat complicated attack, it’s easy to replicate.

有两种重要的漏洞需要担心:直接攻击和明文密码嗅探。直接攻击试图接管机器而不太敏锐。

最常见的是缓冲区溢出利用,一个粗心的程序员没有检查缓冲区数组的边界。

攻击者在大量数据中制造一个栈帧,将其转储到远程服务器,然后希望服务器覆盖其程序数据并最终执行新的栈帧。

虽然这是一个有些复杂的攻击,但很容易复制。

A second attack to worry about is one that captures passwords sent across the wire as clear text. As soon as an attacker gets your password, it’s game over. From there, the assailant will inevitably try to gain superuser access locally (which is much easier than making a remote attack), try to use the machine as an intermediary for attacking other hosts, or both.

第二种需要担心的攻击是捕获明文传输的密码。

一旦攻击者获取到你的密码,游戏就结束了。

从那里开始,攻击者将不可避免地尝试在本地获得超级用户访问权限(比进行远程攻击容易得多),尝试使用该机器作为攻击其他主机的中介,或两者兼而有之。

NOTE If you have a service that offers no native support for encryption, try Stunnel ( http://www.stunnel.org/), an encryption wrapper package much like TCP wrappers. Like tcpd, Stunnel is especially good at wrapping inetd services.注意:如果您有一个不支持加密的服务,请尝试使用 Stunnel(http://www.stunnel.org/),这是一个类似于 TCP wrappers 的加密包装程序。与 tcpd 一样,Stunnel 尤其擅长包装 inetd 服务。

Some services are chronic attack targets due to poor implementation and design. You should always deactivate the following services (they’re rarely activated by default on most systems):

由于实施和设计不当,有些服务长期成为攻击目标。

应始终停用以下服务(大多数系统默认情况下很少激活这些服务):

  • ftpd For whatever reason, all FTP servers seem plagued with vulnerabilities. In addition, most FTP servers use clear-text passwords. If you have to move files from one machine to another, consider an SSH based solution or an rsync server.
  • telnetd, rlogind, rexecd All of these pass remote session data (including passwords) in clear-text form. Avoid them unless you happen to have a Kerberos-enabled version.
  • fingerd Intruders can get user lists and other information with the finger service.
  • ftpd 由于某种原因,所有 FTP 服务器似乎都深受漏洞困扰。此外,大多数 FTP 服务器使用明文密码。 - 如果您必须从一台机器移动文件到另一台机器,请考虑使用基于 SSH 的解决方案或一个 rsync 服务器。
  • telnetd、rlogind、rexecd 所有这些服务以明文形式传递远程会话数据(包括密码)。 - 除非您碰巧有一个启用了 Kerberos 的版本,否则应避免使用它们。
  • fingerd 入侵者可以通过 finger 服务获取用户列表和其他信息。10.7.2 Security Resources

Here are three good security sites:

o http://www.sans.org/ Offers training, services, a free weekly newsletter listing the top current vulnerabilities, sample security policies, and more.

o http://www.cert.org/ A place to look for the most severe problems.

o http://www.insecure.org/ This is the place to go for Nmap and pointers to all sorts of network exploittesting tools. It’s much more open and specific about exploits than are many other sites.

这里有三个优秀的网络安全网站:

  • http://www.sans.org/ 提供培训、服务、免费每周简报列出当前顶级漏洞、示例安全策略等。
  • http://www.cert.org/ 是寻找最严重问题的地方。
  • http://www.insecure.org/ 这是一个获取Nmap和各种网络漏洞测试工具指针的地方。它比许多其他网站更加开放和具体关于漏洞利用。

If you’re interested in network security, you should learn all about Transport Layer Security (TLS) and its predecessor, Secure Socket Layer (SSL). These user-space network levels are typically added to networking clients and servers to support network transactions through the use of public-key encryption and certificates. A good guide is Davies’s Implementing SSL/TLS Using Cryptography and PKI (Wiley, 2011).

如果你对网络安全感兴趣,你应该全面了解传输层安全性(TLS)及其前身安全套接字层(SSL)。

这些用户空间网络层通常添加到网络客户端和服务器中,通过公钥加密和证书支持网络交易。

一个好的指南是戴维斯(Davies)的《使用密码学和PKI实现SSL/TLS》(Wiley,2011年)。

10.8 Looking Forward(展望未来)

If you’re interested in getting your hands dirty with some complicated network servers, two very common ones are the Apache web server and the Postfix email server. In particular, Apache is easy to install and most distributions supply a package. If your machine is behind a firewall or NAT-enabled router, you can experiment with the configuration as much as you’d like without worrying about security.

如果你对涉足一些复杂的网络服务器感兴趣,那么两个非常常见的服务器是Apache Web服务器和Postfix邮件服务器。

特别是,Apache很容易安装,大多数发行版都提供了相关软件包。

如果你的机器位于防火墙或启用NAT的路由器后面,你可以随意尝试不用担心安全性的配置。

Throughout the last few chapters, we’ve been gradually moving from kernel space into user space. Only a few utilities discussed in this chapter, such as tcpdump, interact with the kernel. The remainder of this chapter describes how sockets bridge the gap between the kernel’s transport layer and the user-space application layer. It’s more advanced material, of particular interest to programmers, so feel free to skip to the next chapter if you like.

在过去的几章中,我们逐渐从内核空间移动到用户空间。

本章仅讨论了几个与内核交互的实用工具,比如tcpdump。

本章的其余部分描述了套接字如何弥合内核的传输层和用户空间应用层之间的差距。

这是更加高级的内容,特别适合程序员,如果你愿意,可以随意跳到下一章。

10.9 Sockets: How Processes Communicate with the Network(套接字:进程如何与网络通信)

We’re now going to shift gears a little and look at how processes do the work of reading data from and writing data to the network. It’s easy enough for processes to read from and write to network connections that are already set up: All you need are some system calls, which you can read about in the recv(2) and send(2) manual pages. From the point of view of a process, perhaps the most important thing to know is how to refer to the network when using these system calls. On Unix systems, a process uses a socket to identify when and how it’s talking to the network. Sockets are the interface that processes use to access the network through the kernel; they represent the boundary between user space and kernel space. They’re often also used for interprocess communication (IPC).

现在我们将稍作转变,看看进程如何从网络读取数据和向网络写入数据。

对于进程来说,从已经建立好的网络连接中读取数据和写入数据是相当容易的:你只需要一些系统调用,你可以在 recv(2) 和 send(2) 的手册页面中找到相关信息。

从进程的角度来看,也许最重要的是在使用这些系统调用时如何引用网络。

在Unix系统中,进程使用套接字来识别它何时以及如何与网络通信。

套接字是进程通过内核访问网络的接口;它们代表了用户空间和内核空间之间的边界。

它们经常也被用于进程间通信(IPC)。

There are different types of sockets because processes need to access the network in different ways. For example, TCP connections are represented by stream sockets (SOCK_STREAM, from a programmer’s point of view), and UDP connections are represented by datagram sockets (SOCK_DGRAM).

由于进程需要以不同的方式访问网络,因此存在不同类型的套接字。

例如,TCP连接由流套接字(SOCK_STREAM,从程序员的角度看)表示,而UDP连接由数据报套接字(SOCK_DGRAM)表示。

Setting up a network socket can be somewhat complicated because you need to account for socket type, IP addresses, ports, and transport protocol at particular times. However, after all of the initial details are sorted out, servers use certain standard methods to deal with incoming traffic from the network.

设置网络套接字可能会有些复杂,因为您需要考虑套接字类型、IP地址、端口和特定时间的传输协议。

然而,一旦所有初始细节都得到解决,服务器就会使用某些标准方法来处理来自网络的传入流量。

The flowchart in Figure 10-1 shows how many servers handle connections for incoming stream sockets. Notice that this type of server involves two kinds of sockets: a listening socket and a socket for reading and writing. The master process uses the listening socket to look for connections from the network. When a new connection comes in, the master process uses the accept() system call to accept the connection, which creates the read/write socket dedicated to that one connection. Next, the master process uses fork() to create a new child process to deal with the connection. Finally, the original socket remains the listener and continues to look for more connections on behalf of the master process.

图 10-1 中的流程图显示了许多服务器如何处理输入流套接字的连接。

请注意,这种服务器涉及两种套接字:监听套接字和用于读写的套接字。

主进程使用监听套接字查找来自网络的连接。

当有新的连接进来时,主进程会使用 accept() 系统调用来接受该连接,从而创建专用于该连接的读写套接字。

接着,主进程使用 fork() 创建一个新的子进程来处理该连接。

最后,原始套接字仍作为监听器,继续代表主进程寻找更多连接。

After a process has set up a socket of a particular type, it can interact with it in a way that fits the socket type. This is what makes sockets flexible: If you need to change the underlying transport layer, you don’t have to rewrite all of the parts that send and receive data; you mostly need to modify the initialization code.

在一个进程建立了特定类型的套接字之后,它可以以适合套接字类型的方式与之交互。

这就是套接字灵活的原因:如果你需要更改底层传输层,你不必重写所有发送和接收数据的部分;

你只需修改初始化代码即可。

image.png
image.png

Figure 10-1. One method for accepting and processing incoming connections

图10-1. 一种接受和处理传入连接的方法

If you’re a programmer and you’d like to learn how to use the socket interface, Unix Network Programming, Volume 1, 3rd edition, by W. Richard Stephens, Bill Fenner, and Andrew M. Rudoff (Addison-Wesley Professional, 2003) is the classic guide. Volume 2 also covers interprocess communication.

如果您是一名程序员,想学习如何使用套接字接口,那么《Unix网络编程》第1卷,第3版,作者W. Richard Stephens、Bill Fenner和Andrew M. Rudoff(Addison-Wesley Professional,2003年)是经典指南。

第2卷也涵盖了进程间通信。

10.10 Unix Domain Sockets(Unix 域套接字)

Applications that use network facilities don’t have to involve two separate hosts. Many applications are built as client-server or peer-to-peer mechanisms, where processes running the same machine use interprocess communication (IPC) to negotiate what work needs to be done and who does it. For example, recall that daemons such as systemd and NetworkManager use D-Bus to monitor and react to system events.

使用网络设施的应用程序不一定要涉及两个独立的主机。

许多应用程序被构建为客户端-服务器或对等机制,其中在同一台计算机上运行的进程使用进程间通信(IPC)来协商需要执行什么工作以及由谁执行。

例如,诸如 systemd 和 NetworkManager 等守护进程使用 D-Bus 监控并响应系统事件。

Processes can use regular IP networking over localhost (127.0.0.1) to communicate, but instead, typically use a special kind of socket, which we briefly touched upon in Chapter 3, called a Unix domain socket. When a process connects to a Unix domain socket, it behaves almost exactly like a network socket: It can listen for and accept connections on the socket, and you can even choose between different kinds of socket types to make it behave like TCP or UDP.

进程可以通过本地主机(127.0.0.1)上的常规 IP 网络进行通信,但通常会使用一种特殊类型的套接字,我们在第 3 章中简要介绍过,称为 Unix 域套接字

当一个进程连接到一个 Unix 域套接字时,它几乎与网络套接字的行为完全相同:它可以在套接字上监听并接受连接,甚至可以选择不同类型的套接字来使其表现得像 TCP 或 UDP 一样。

NOTE It’s important to remember that a Unix domain socket is not a network socket, and there’s no network behind one. You don’t even need networking to be configured to use one. And Unix domain sockets don’t have to be bound to socket files. A process can create an unnamed Unix domain socket and share the address with another process.注意 重要的是要记住 Unix 域套接字不是网络套接字,它背后没有网络。甚至不需要配置网络就可以使用它。而且 Unix 域套接字不必绑定到套接字文件上。一个进程可以创建一个未命名的 Unix 域套接字,并与另一个进程共享地址。10.10.1 Advantages for Developers(开发者的优势)

Developers like Unix domain sockets for IPC for two reasons. First, they allow developers the option to use special socket files in the filesystem to control access, so any process that doesn’t have access to a socket file can’t use it. And because there’s no interaction with the network, it’s simpler and less prone to conventional network intrusion. For example, you’ll usually find the socket file for D-Bus in /var/run/dbus:

开发者喜欢使用 Unix 域套接字进行进程间通信有两个原因。

首先,它们允许开发者使用文件系统中的特殊套接字文件来控制访问权限,因此任何没有访问权限的进程都无法使用它。

而且由于不涉及网络交互,这样做更简单,且不容易受到传统网络入侵的影响。

例如,通常你会在 /var/run/dbus 目录下找到 D-Bus 的套接字文件:

代码语言:sh
复制
$ ls -l /var/run/dbus/system_bus_socket 
srwxrwxrwx 1 root root 0 Nov 9 08:52 /var/run/dbus/system_bus_socket

Second, because the Linux kernel does not have to go through the many layers of its networking subsystem when working with Unix domain sockets, performance tends to be much better.

第二,由于Linux内核在使用Unix域套接字时无需经过许多层网络子系统,因此性能往往更好。

Writing code for Unix domain sockets is not much different from supporting normal network sockets. Because the benefits can be significant, some network servers offer communication through both network and Unix domain sockets. For example, the MySQL database server mysqld can accept client connections from remote hosts, but it usually also offers a Unix domain socket at /var/run/mysqld/mysqld.sock.

编写Unix域套接字的代码与支持普通网络套接字并无太大不同。

由于好处可能非常显著,一些网络服务器提供通过网络和Unix域套接字进行通信的功能。

例如,MySQL数据库服务器mysqld可以接受来自远程主机的客户端连接,但通常也提供位于/var/run/mysqld/mysqld.sock的Unix域套接字。

10.10.2 Listing Unix Domain Sockets(列出 Unix 域套接字)

You can view a list of Unix domain sockets currently in use on your system with lsof -U:

您可以使用命令 lsof -U 查看当前系统上正在使用的 Unix 域套接字列表:

代码语言:sh
复制
# lsof -U 

COMMAND mysqld PID 19701 USER mysql /var/run/mysqld/mysqld.sock chromium- socket tlsmgr socket tlsmgr 26534 juser 30480 postfix FD 30480 postfix TYPE DEVICE SIZE/OFF 12u unix 0xe4defcc0 5u 5u 6u unix 0xeeac9b00 unix 0xc3384240 unix 0xe20161c0 NODE NAME 0t0 35201227 0t0 42445141 0t0 17009106 0t0 10965 private/tlsmgr

--snip--

The listing will be quite long because many modern applications make extensive use of unnamed sockets. You can identify the unnamed ones because you’ll see socket in the NAME output column.

由于许多现代应用程序广泛使用未命名套接字,因此清单将会相当长。

您可以通过在“NAME”输出列中看到套接字来识别未命名套接字。

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 10.5 Diagnostic Tools(诊断工具)
    • 10.5.1 lsof
      • Filtering by Protocol and Port(按协议和端口过滤)
      • Filtering by Connection Status(通过连接状态过滤)
    • 10.5.2 tcpdump
      • Primitives(基元)
      • Operators(运算符)
      • When Not to Use tcpdump(不应该使用 tcpdump 的情况)
    • 10.5.3 netcat
      • 10.5.4 Port Scanning(端口扫描)
      • 10.6 Remote Procedure Call (RPC)
      • 10.7 Network Security(网络安全)
      • 10.8 Looking Forward(展望未来)
      • 10.9 Sockets: How Processes Communicate with the Network(套接字:进程如何与网络通信)
      • 10.10 Unix Domain Sockets(Unix 域套接字)
        • 10.10.2 Listing Unix Domain Sockets(列出 Unix 域套接字)
        相关产品与服务
        云数据库 MySQL
        腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
        http://www.vxiaotou.com