说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C8-IA32/buffer_overflow.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
8.10. Real World: Buffer Overflow
C 语言不会自动做数组越界检查。访问数组边界以外的内存是有问题的,常常导致段错误之类的错误。然而,聪明的攻击者可以注入恶意代码,故意越过数组(也称为缓冲区,buffer)的边界,迫使程序以非预期的方式执行。在最坏的情况下,攻击者可以运行代码获得 root 权限,也就是对计算机系统的操作系统级访问权。利用程序中已知的缓冲区越界错误来达到目的的软件,称为缓冲区溢出攻击(buffer overflow exploit)。
The C language does not perform automatic array bounds checking. Accessing memory outside of the bounds of an array is problematic and often results in errors such as segmentation faults. However, a clever attacker can inject malicious code that intentionally overruns the boundary of an array (also known as a buffer) to force the program to execute in an unintended manner. In the worst cases, the attacker can run code that allows them to gain root privilege, or OS-level access to the computer system. A piece of software that takes advantage of the existence of a known buffer overrun error in a program is known as a buffer overflow exploit.
本节我们使用 GDB 和汇编语言,完整剖析缓冲区溢出攻击的机制。阅读本章之前,建议先看看讲解用 GDB 检查汇编代码的那一章。
In this section, we use GDB and assembly language to fully characterize the mechanics of a buffer overflow exploit. Prior to reading this chapter we encourage you to explore the chapter discussing GDB for inspecting assembly code.
8.10.1. 著名的缓冲区溢出案例
8.10.1. Famous Examples of Buffer Overflow
缓冲区溢出攻击出现于 20 世纪 80 年代,直到 21 世纪头几年一直是计算机行业的头号祸害。虽然许多现代操作系统已经能防御最简单的缓冲区溢出攻击,但粗心的编程错误仍然可能让现代程序门户大开。最近在 Skype1、Android2、Google Chrome3 等软件中都发现过缓冲区溢出漏洞。
Buffer overflow exploits emerged in the 1980s and remained a chief scourge of the computing industry through the early parts of the 2000s. While many modern operating systems have protections against the simplest buffer overflow attacks, careless programming errors can still leave modern programs wide open to attack. Buffer overflow exploits have recently been discovered in Skype1, Android2, Google Chrome3, and others.
下面是几个著名的历史案例。
Here are some notable historic examples of buffer overflow exploits.
莫里斯蠕虫(The Morris Worm)
莫里斯蠕虫4于 1988 年从 MIT 释放到 ARPANet 上(为的是掩盖它出自康奈尔大学一名学生之手),它利用了 UNIX finger 守护进程(
fingerd)中的一个缓冲区越界漏洞。在 Linux 和其他类 UNIX 系统中,守护进程(daemon)是一类在后台持续运行的进程,通常执行清理和监控任务。fingerd守护进程返回关于某台计算机或某个人的友好报告。最要命的是,这个蠕虫的复制机制会把它多次发送到同一台计算机上,把系统拖到无法使用的地步。尽管作者声称这个蠕虫只是一次无害的智力练习,但复制机制让它极易传播,也很难清除。此后多年,还有其他蠕虫利用缓冲区溢出攻击未经授权进入系统,著名的有 Code Red(2001)、MS-SQLSlammer(2003)和 W32/Blaster(2003)。
The Morris Worm
The Morris Worm4 was released in 1988 on ARPANet from MIT (to hide that it was written by a student at Cornell) and exploited a buffer overrun vulnerability that existed in the Unix finger daemon (
fingerd). In Linux and other Unix-like systems, a daemon is a type of process that continuously executes in the background, usually performing clean-up and monitoring tasks. Thefingerddaemon returns a user-friendly report on a computer or person. Most crucially, the worm had a replication mechanism that caused it to be sent to the same computer multiple times, bogging down the system to an unusable state. Although the author claimed that the worm was meant as a harmless intellectual exercise, the replication mechanism enabled the worm to spread easily and made it difficult to remove. In future years, other worms would employ buffer overflow exploits to gain unauthorized access into systems. Notable examples include Code Red (2001), MS-SQLSlammer (2003), and W32/Blaster (2003).
AOL 聊天大战(AOL Chat Wars)
前微软工程师 David Auerbach5 详细讲述了他在 20 世纪 90 年代末把微软的 Messenger Service(MMS)与 AOL Instant Messenger 打通时遭遇的一次缓冲区溢出。那时,想和亲友即时通信(IM),AOL Instant Messenger(AIM)是不二之选。微软想在这个市场站稳脚跟,就在 MMS 中设计了一个功能,让 MMS 用户能和他们的 AIM「好友」聊天。AOL 很不高兴,给服务器打了补丁,让 MMS 无法再连上。微软工程师想出办法让 MMS 客户端模仿 AIM 客户端发给 AOL 服务器的消息,使 AOL 难以区分消息来自 MMS 还是 AIM。AOL 的回应是改变 AIM 发送消息的方式,MMS 工程师则相应地修改客户端消息,使之再次与 AIM 的一致。这场「聊天大战」一直持续,直到 AOL 开始利用自家客户端里的一个缓冲区溢出错误来验证发来的消息是否来自 AIM 客户端。由于 MMS 客户端没有同样的漏洞,聊天大战就此结束,AOL 获胜。
AOL Chat Wars
David Auerbach5, a former Microsoft engineer, detailed his experience with a buffer overflow during his efforts to integrate Microsoft’s Messenger Service (MMS) with AOL Instant Messenger in the late 1990s. Back then, AOL Instant Messenger (AIM) was the service to use if you wanted to instant message (or IM) friends and family. Microsoft tried to gain a foothold in this market by designing a feature in MMS that enabled MMS users to talk to their AIM “buddies.” Displeased, AOL patched their servers so that MMS could no longer connect to them. Microsoft engineers figured out a way for MMS clients to mimic the messages sent by AIM clients to AOL servers, making it difficult for AOL to distinguish between messages received by MMS and AIM. AOL responded by changing the way AIM sent messages, and MMS engineers duly changed their client’s messages to once again match AIM’s. This “chat war” continued until AOL started using a buffer overflow error in their own client to verify that sent messages came from AIM clients. Since MMS clients did not have the same vulnerability, the chat wars ended, with AOL as the victor.
8.10.2. 初探:猜谜游戏
8.10.2. A First Look: The Guessing Game
为了帮助你理解缓冲区溢出攻击的机制,我们提供了一个简单程序的 32 位可执行文件,用户可以和它玩猜谜游戏。在这个链接下载 secret 可执行文件,并用 tar 命令解压:
To help you understand the mechanism of the buffer overflow attack, we provide a 32-bit executable of a simple program that enables the user to play a guessing game with the program. Download the
secretexecutable at this link and extract it using thetarcommand:
1 | $ tar -xzvf secret.tar.gz |
下面给出与该可执行文件对应的主文件 main.c(main.c)的副本:
Below, we provide a copy of
main.c(main.c), the main file associated with the executable:
1 | #include <stdio.h> |
这个游戏先提示用户输入一个秘密数字,再输入一个秘密字符串,两者都对才能赢。头文件 other.h 包含 getSecretCode 和 calculateValue 函数的定义,但我们拿不到它。那么用户怎样才能打败这个程序?暴力穷举会花太长时间。一种策略是在 GDB 中分析 secret 可执行文件,单步执行汇编代码,找出秘密数字和字符串。通过检查汇编代码来弄清它如何工作的过程,通常称为逆向工程(reverse engineering)。对 GDB 和阅读汇编足够熟练的读者,应该能用 GDB 逆向出秘密数字和秘密字符串。
This game prompts the user to enter first a secret number and then a secret string to win the guessing game. The header file
other.hcontains the definition of thegetSecretCodeandcalculateValuefunctions, but it is unavailable to us. How then can a user beat the program? Brute forcing the solution will take too long. One strategy is to analyze thesecretexecutable in GDB and step through the assembly to reveal the secret number and string. The process of examining assembly code to reveal knowledge of how it works is commonly referred to as reverse engineering. Readers comfortable enough with GDB and reading assembly should be able to use GDB to reverse engineer the secret number and the secret string.
不过,还有另一种更狡猾的取胜方法。
However, there is a different, sneakier way to win.
8.10.3. 仔细看看(C 之下)
8.10.3. Taking a Closer Look (Under the C)
程序在第一次调用 scanf 处有一个潜在的缓冲区越界漏洞。为了弄清发生了什么,我们用 GDB 查看 main 函数的汇编代码。我们还在地址 0x0804859f 处设一个断点,它是紧挨在调用 scanf 之前的那条指令的地址(如果把断点设在 scanf 的地址上,程序会停在 scanf 调用内部,而不是 main 中)。
The program contains a potential buffer overrun vulnerability at the first call to
scanf. To understand what is going on, let’s inspect the assembly code of themainfunction using GDB. Let’s also place a breakpoint at address 0x0804859f, which is the address of the instruction immediately before the call toscanf(placing the breakpoint at the address ofscanfcauses program execution to halt inside the call toscanf, not inmain).
1 | 0x08048582 <+0>: push %ebp |
图 1 描绘了调用 scanf 之前那一刻的栈。
Figure 1 depicts the stack immediately before the call to
scanf.

图 1. 调用 scanf 之前那一刻的调用栈
Figure 1. The call stack immediately before the call to scanf
调用 scanf 之前,它的参数被预先放到栈上:第一个参数在栈顶,第二个参数在它下面一个位置。位于 <main+21> 的 lea 指令生成了数组 buf 的引用(地址)。
Prior to the call to
scanf, the arguments forscanfare preloaded onto the stack, with the first argument at the top of the stack, and the second argument one address below. Theleainstruction at location<main+21>creates the reference for arraybuf.
现在,假设用户在提示符处输入 12345678。图 2 展示了 scanf 调用刚刚完成时栈的样子。
Now, suppose that the user enters
12345678at the prompt. [afterScanf] illustrates what the stack looks like immediately after the call toscanfcompletes.

图 2. 输入 12345678 时,scanf 调用刚完成那一刻的调用栈
Figure 2. The call stack immediately after the call to scanf with input 12345678
回忆一下,数字 0 到 9 的 ASCII 编码的十六进制值是 0x30 到 0x39,并且每个栈内存位置是四个字节长。帧指针距离栈指针 56 字节。跟着操作的读者可以用 GDB 打印 %ebp 的值(p $ebp)来确认。在这个例子中,%ebp 的值是 0xffffd428。下面的命令可以查看寄存器 %esp 之下的 64 个字节(以十六进制显示):
Recall that the hex values for the ASCII encodings of the digits 0 to 9 are 0x30 to 0x39, and that each stack memory location is four bytes long. The frame pointer is 56 bytes away from the stack pointer. Readers tracing along can confirm the value of
%ebpby using GDB to print its value (p $ebp). In the example shown, the value of%ebpis 0xffffd428. The following command allows the reader to inspect the 64 bytes (in hex) below register%esp:
1 | (gdb) x /64bx $esp |
这条 GDB 命令的输出类似这样:
This GDB command yields output that looks similar to the following:
1 | 0xffffd3f0: 0x1c 0x87 0x04 0x08 0x0c 0xd4 0xff 0xff |
每一行代表两个 32 位字。所以,第一行代表地址 0xffffd3f0 和 0xffffd3f4 处的两个字。从栈顶看起,可以看到与字符串 "%s" 关联的内存地址(即 0x0804871c),后面跟着 buf 的地址(即 0xffffd40c)。注意,在本节的图中,buf 的地址被简写为 0x40c。
Each line represents two 32-bit words. So, the first line represents the words at addresses 0xffffd3f0 and 0xffffd3f4. Looking at the top of the stack, we can see the memory address associated with the string
"%s"(or 0x0804871c) followed by the address ofbuf(or 0xffffd40c). Note that the address forbufis simply represented as 0x40c in the figures in this section.
原书注 · 多字节的值按小端序存储(Multibyte values are stored in little-endian order)
在前面的汇编片段中,地址 0xfffffd3f0 处的字节是 0x1c,地址 0xfffffd3f1 处的字节是 0x87,地址 0xfffffd3f2 处的字节是 0x04,地址 0xfffffd3f3 处的字节是 0x08。然而,地址 0xfffffd3f0 处的 32 位值(对应于字符串 "%s" 的内存地址)实际上是 0x0804871c。记住,由于 x86 是小端系统,地址这类多字节值的各个字节是按相反顺序存储的。同样,与数组 buf 的地址(0xffffd40c)对应的那些字节,也按相反顺序存放在地址 0xfffffd3f4 处。
In the preceding assembly segment, the byte at address 0xfffffd3f0 is 0x1c, the byte at address 0xfffffd3f1 is 0x87, the byte at address 0xfffffd3f2 is 0x04, and the byte at address 0xfffffd3f3 is 0x08. However, the 32-bit value (which corresponds to the memory address of the string
"%s") at address 0xfffffd3f0 is in fact 0x0804871c. Remember that because x86 is a little endian system, the bytes for multibyte values such as addresses are stored in reverse order. Similarly, the bytes corresponding to the address of arraybuf(0xffffd40c) are stored in reverse order at address 0xfffffd3f4.
译注 · 地址笔误
原文这几个地址多写了一个 f(0xfffffd3f0 是 9 位十六进制数),应为 0xffffd3f0~0xffffd3f4,对照上面的 GDB 输出即可。
与地址 0xffffd40c 关联的字节,和与地址 0xffffd408 关联的字节位于同一行,是那一行的第二个字。由于 buf 数组长 12 字节,buf 的元素占据从地址 0xffffd40c 到 0xffffd417 的 12 个字节。查看这些地址处的字节,得到:
The bytes associated with address 0xffffd40c are located on the same line as those associated with address 0xffffd408, and are the second word on that line. Since the
bufarray is 12 bytes long, the elements associated withbufspan the 12 bytes from address 0xffffd40c to 0xffffd417. Inspecting the bytes at those addresses yields:
1 | 0xffffd408: 0xcc 0xd4 0xff 0xff 0x31 0x32 0x33 0x34 |
在这些位置上,可以清楚地看到输入字符串 12345678 的十六进制表示。空字符 \0 出现在地址 0xffffd414 处那个字的最左边的字节位置。回想一下,scanf 会在所有字符串末尾加上一个空字节。
At these locations, we can clearly see the hex representation of the input string 12345678. The null termination byte
\0appears in the leftmost byte location at address 0xffffd414. Recall that scanf terminates all strings with a null byte.
当然,12345678 不是秘密数字。下面是用输入字符串 12345678 运行 secret 时的输出:
Of course, 12345678 is not the secret number. Here is the output when we try to run
secretwith input string 12345678:
1 | $ ./secret |
echo $? 命令打印 shell 中上一条命令的返回值。在这里,程序返回了 1,因为我们输入的秘密数字是错的。回想一下,按照惯例,程序在没有错误时返回 0。接下来我们的目标是骗程序以返回值 0 退出,表示我们赢了游戏。
The
echo $?command prints out the return value of the last executed command in the shell. In this case, the program returned 1, because the secret number we entered is wrong. Recall that by convention, programs return 0 when there are no errors. Our goal going forward is to trick the program to exit with a return value of 0, indicating that we won the game.
8.10.4. 缓冲区溢出:第一次尝试
8.10.4. Buffer Overflow: First Attempt
接下来,试着输入字符串 1234567890123456789012345678901234:
Next, let’s try typing in the string
1234567890123456789012345678901234:
1 | $ ./secret |
有意思!现在程序因段错误崩溃了,返回码是 139。图 3 展示了用这个新输入调用 scanf 刚完成时 main 的调用栈。
Interesting! Now the program crashes with a segmentation fault, with return code 139. Figure 3 shows what the call stack for
mainlooks like immediately after the call toscanfwith this new input.
译注 · 139 从哪里来
与第 7 章相同:进程被信号杀死时,shell 报告的退出状态是 128 + 信号编号,段错误 SIGSEGV 的编号是 11,所以是 139。

图 3. 输入 1234567890123456789012345678901234 时,scanf 调用刚完成那一刻的调用栈
Figure 3. The call stack immediately after the call to scanf with input 1234567890123456789012345678901234
输入字符串太长,不仅覆盖了存放在地址 0x428 处的值,还溢出到了 main 栈帧下方的返回地址。回想一下,函数返回时,程序会尝试从返回地址指定的位置继续执行。在这个例子中,程序退出 main 后试图从地址 0xf7003433 处继续执行,而这个地址并不存在,于是程序因段错误崩溃。
The input string is so long that it not only overwrote the value stored at address 0x428, but it spilled over into the return address below the stack frame for
main. Recall that when a function returns, the program tries to resume execution at the address specified by the return address. In this example, the program tries to resume execution at address 0xf7003433 after exitingmain, which does not exist. So the program crashes with a segmentation fault.
译注
下面的 GDB 示例中,命令顺序应当是先 run < input.txt 再 ni(程序还没运行时无法单步),断点地址也与前文的 0x0804859f 不同;照着操作时按实际情况调整即可。从输出最后一行可以验证:返回地址所在的 0xffffd42c 处字节为 33 34 00 f7,按小端序读出来正是 0xf7003433。
在 GDB 中重新运行程序(input.txt 中存放的是上面的输入字符串),可以看到这番破坏的实际过程:
Rerunning the program in GDB (
input.txtcontains the input string above) reveals this devilry in action:
1 | $ gdb secret |
注意,我们的输入字符串冲破了数组 buf 声明的边界,覆盖了栈上存储的所有其他值。换句话说,我们的字符串造成了缓冲区越界,破坏了调用栈,导致程序崩溃。这个过程也被称为栈粉碎(smashing the stack)。
Notice that our input string blew past the stated limits of the array
buf, overwriting all the other values stored on the stack. In other words, our string created a buffer overrun and corrupted the call stack, causing the program to crash. This process is also known as smashing the stack.
8.10.5. 更聪明的缓冲区溢出:第二次尝试
8.10.5. A Smarter Buffer Overflow: Second Attempt
第一个例子用垃圾数据覆盖了保存的 %ebp 和返回地址,粉碎了栈,导致程序崩溃。如果攻击者的目的只是让程序崩溃,到这一步就已经满意了。但我们的目标是骗猜谜游戏返回 0,表示我们赢了。为此,我们要用比垃圾值更有意义的数据填充调用栈。例如,可以覆盖栈,把返回地址替换成 endGame 的地址。这样,当程序试图从 main 返回时,它会去执行 endGame,而不是因段错误崩溃。
Our first example smashed the stack by overwriting the
%ebpregister and return address with junk, causing the program to crash. An attacker whose goal is to simply crash a program would be satisfied at this point. However, our goal is to trick the guessing game to return 0, indicating that we won the game. We accomplish this by filling the call stack with data more meaningful than junk values. For example, we could overwrite the stack so that the return address is replaced with the address ofendGame. Then, when the program attempts to return frommain, it will instead executeendGamerather than crashing with a segmentation fault.
为了找出 endGame 的地址,我们再次在 GDB 中查看 secret:
To find out the address of
endGame, let’s inspectsecretagain in GDB:
译注
与第 7 章一样,源码中的 printf("You win!\n") 在反汇编里变成了 puts:编译器把只输出以换行结尾的常量字符串的 printf 换成了更简单的 puts。
1 | $ gdb secret |
可以看到,endGame 从地址 0x08048564 开始。图 4 展示了一个迫使 secret 执行 endGame 函数的示例攻击字符串。
Observe that
endGamestarts at address 0x08048564. Figure 4 illustrates a sample exploit that forcessecretto run theendGamefunction.

图 4. 一个能迫使 secret 执行 endGame 函数的示例字符串
Figure 4. A sample string that can force secret to execute the endGame function
同样,由于 x86 是小端系统,并且栈向低地址方向增长,返回地址中的字节看起来是倒序的。
Again, since x86 is a little endian system in which the stack grows toward lower addresses, the bytes in the return address appear to be in reverse order.
译注 · 为什么是 32 字节
main 开头执行了 sub $0x38,%esp,所以 %esp = %ebp - 0x38;buf 位于 0x1c(%esp),也就是 %ebp - 0x1c。从 buf 起始处到保存的 %ebp 有 28 字节,再加上保存的 %ebp 本身 4 字节,共 32 字节,紧接着就是返回地址。这正是下面程序中 30 + 2 字节的垃圾值。
下面的程序演示了攻击者可以如何构造前面那个攻击字符串:
The following program illustrates how an attacker could construct the preceding exploit:
1 | #include <stdio.h> |
每个数字前面的 \x 表示该数字是一个字符的十六进制表示。定义了 ebuff[] 之后,main 函数只是逐个字符地把它打印出来。要得到对应的字节串,像下面这样编译并运行这个程序:
The
\xbefore each number indicates that the number is formatted as the hexadecimal representation of a character. After definingebuff[], themainfunction simply prints it out, character by character. To get the associated byte string, compile and run this program as follows:
译注
循环条件用的是 sizeof(ebuff),它包含字符串字面量末尾自动加上的 '\0',所以生成的 exploit 文件是 32 + 4 + 1 = 37 字节。scanf("%s", ...) 遇到空字节并不会停(它只在空白字符处停止),这个多出的空字节会被写到返回地址之后,不影响攻击。
1 | $ gcc -o genEx genEx.c |
要把文件 exploit 作为 scanf 的输入,只需像下面这样以 exploit 为输入运行 secret:
To use the file
exploitas input toscanfit suffices to runsecretwithexploitas follows:
1 | $ ./secret < exploit |
程序打印出「You are so wrong!」,因为 exploit 中的字符串不是秘密数字。但是,程序也打印出了「You win!」。不过回想一下,我们的目标是骗程序返回 0。在一个更大的系统中,「成功」与否由外部程序来跟踪,这时程序返回什么往往比它打印什么更重要。
The program prints out “You are so wrong!” because the string contained in
exploitis not the secret number. However, the program also prints out the string “You win!” Recall, though, that our goal is to trick the program to return 0. In a larger system, where the notion of “success” is tracked by an external program, it is often most important what a program returns, not what it prints out.
检查返回值,得到:
Checking the return value yields:
1 | $ echo $? |
攻击成功了!我们赢了游戏!
Our exploit works! We won the game!
8.10.6. 防御缓冲区溢出
8.10.6. Protecting Against Buffer Overflow
我们展示的例子改变了 secret 可执行文件的控制流,迫使它返回表示成功的零值。然而,这样的攻击可能造成真正的破坏。此外,一些较老的计算机系统会执行栈内存中的字节。如果攻击者把汇编指令对应的字节放到调用栈上,CPU 就会把这些字节当作真正的指令来解释,攻击者就能迫使 CPU 执行任意由他选定的代码。幸运的是,现代计算机系统采用了一些策略,让攻击者更难实施缓冲区溢出攻击:
The example we showed changed the control flow of the
secretexecutable, forcing it to return a zero value associated with success. However, an exploit like this could do some real damage. Furthermore, some older computer systems executed bytes from stack memory. If an attacker placed bytes associated with assembly instructions on the call stack, the CPU would interpret the bytes as real instructions, enabling the attacker to force the CPU to execute any arbitrary code of their choosing. Fortunately, there are strategies that modern computer systems employ to make it more difficult for attackers to run buffer overflow exploits:
- 栈随机化(stack randomization):操作系统把栈的起始地址分配在栈内存中的随机位置,使调用栈的位置/大小在程序的每次运行之间都不同。运行同一段代码的多台机器会有不同的栈地址。现代 Linux 系统把栈随机化作为标准做法。然而,执着的攻击者可以用不同的地址反复尝试,暴力破解。一个常见技巧是在真正的攻击代码前面放一个 NOP 滑板(NOP sled 或 NOP slide),即大量
nop指令。执行nop指令(0x90)除了让程序计数器递增到下一条指令以外没有任何效果。只要攻击者能让 CPU 从 NOP 滑板中的某处开始执行,NOP 滑板最终就会滑到紧随其后的攻击代码。Aleph One 的文章 Smashing the Stack for Fun and Profit6 详细介绍了这类攻击的机制。
- Stack Randomization: The OS allocates the starting address of the stack at a random location in stack memory, causing the position/size of the call stack to vary from one run of a program to another. Multiple machines running the same code would have different stack addresses. Modern Linux systems use stack randomization as a standard practice. However, a determined attacker can brute force the attack, by attempting to repeat attacks with different addresses. A common trick is to use a NOP sled (or slide), i.e., a large number of
nopinstructions, before the actual exploit code. Executing thenopinstruction (0x90) has no effect, other than causing the program counter to increment to the next instruction. As long as the attacker can get the CPU to execute somewhere in the NOP sled, the NOP sled will eventually lead to the exploit code that follows it. Aleph One’s writeup, Smashing the Stack for Fun and Profit6 details the mechanism of this type of attack.
译注
栈随机化是地址空间布局随机化(ASLR)的一部分;现代系统同样随机化堆和共享库的位置,若程序编译为位置无关可执行文件(PIE),代码段的位置也会随机化。
- 栈破坏检测(stack corruption detection):另一道防线是设法检测栈何时被破坏。较新版本的 GCC 使用一种叫作金丝雀(canary)的栈保护机制,它充当缓冲区与栈上其他元素之间的守卫。金丝雀是存放在不可写内存区域中的一个值,可以与放在栈上的值进行比较。如果金丝雀在程序执行期间「死掉了」,程序就知道自己受到了攻击,并以一条错误信息中止。不过,聪明的攻击者可以替换金丝雀,让程序检测不到栈的破坏。
- Stack corruption detection: Another line of defense is to try to detect when the stack is corrupted. Recent versions of GCC use a stack protector known as a canary that acts as a guard between the buffer and the other elements of the stack. A canary is a value stored in a nonwriteable section of memory that can be compared to a value put on the stack. If the canary “dies” during a program’s execution, the program knows that it is under attack and aborts with an error message. A clever attacker can, however, replace the canary to prevent the program from detecting stack corruption.
译注 · 金丝雀实际放在哪
在 32 位 x86 Linux 上,金丝雀的参考值存放在线程局部存储中,通过 %gs 段寄存器访问。译者用 clang -target i386-linux-gnu -O1 -fstack-protector-strong -S 编译一个带局部数组的函数,可以看到函数开头用 movl %gs:20, %eax 取出金丝雀放到栈上,返回前再与 %gs:20 比较,不一致就调用 __stack_chk_fail。(x86-64 上则是 %fs:40,见第 7 章。)
- 限制可执行区域:这道防线把可执行代码限制在内存中特定的区域。换句话说,调用栈不再是可执行的。然而,就连这种防御也可以被攻破。在利用面向返回编程(return-oriented programming,ROP)的攻击中,攻击者可以从可执行区域中「挑选」指令,从一条指令跳到另一条指令,拼凑出攻击代码。网上有一些著名的例子,尤其是在电子游戏中7。
- Limiting executable regions: In this line of defense, executable code is restricted to only particular regions of memory. In other words, the call stack is no longer executable. However, even this defense can be defeated. In an attack utilizing return-oriented programming (ROP), an attacker can “cherry-pick” instructions in executable regions and jump from instruction to instruction to build an exploit. There are some famous examples of this online, especially in video games7.
然而,最好的防线永远是程序员自己。要防止程序遭受缓冲区溢出攻击,尽可能使用带长度说明(length specifier)的 C 函数,并添加执行数组边界检查的代码。至关重要的是,定义的数组必须与选定的长度说明相匹配。表 1 列出了一些容易受缓冲区溢出影响的「坏」C 函数,以及对应应当使用的「好」函数(假设 buf 分配了 12 个字节)。
However, the best line of defense is always the programmer. To prevent buffer overflow attacks on your programs, use C functions with length specifiers whenever possible and add code that performs array bounds checking. It is crucial that any defined arrays match the chosen length specifiers. Table 1 lists some common “bad” C functions that are vulnerable to buffer overflow and the corresponding “good” function to use (assume that
bufis allocated 12 bytes).
表 1. 带长度说明的 C 函数
Table 1. C Functions with Length Specifiers
| 不要用: | 改用: |
|---|---|
gets(buf) |
fgets(buf, 12, stdin) |
scanf("%s", buf) |
scanf("%12s", buf) |
strcpy(buf2, buf) |
strncpy(buf2, buf, 12) |
strcat(buf2, buf) |
strncat(buf2, buf, 12) |
sprintf(buf, "%d", num) |
snprintf(buf, 12, "%d", num) |
Instead of: Use: gets(buf)fgets(buf, 12, stdin)scanf("%s", buf)scanf("%12s", buf)strcpy(buf2, buf)strncpy(buf2, buf, 12)strcat(buf2, buf)strncat(buf2, buf, 12)sprintf(buf, "%d", num)snprintf(buf, 12, "%d", num)
译注 · 表中有两处仍会溢出
- **
scanf("%12s", buf)应为%11s**:%s的宽度只限制读入的字符数,scanf还要在后面再写一个'\0',所以%12s最多写 13 字节,对 12 字节的buf正好越界 1 字节。译者用 clang 编译这一行,会得到警告:'scanf' may overflow; destination buffer in argument 2 has size 12, but the corresponding specifier may require size 13。fgets(buf, 12, stdin)和snprintf(buf, 12, ...)的 12 则是包含'\0'在内的缓冲区总大小,是对的。 strncat的第三个参数不是目标缓冲区的大小,而是最多从源串追加多少个字符;目标缓冲区至少要有strlen(dst) + strnlen(src, n) + 1字节(见 strncat(3))。若buf2中已有内容,strncat(buf2, buf, 12)照样会溢出,安全的上限应是sizeof(buf2) - strlen(buf2) - 1。strncpy(buf2, buf, 12)不会溢出,但当buf的长度不小于 12 时,它不会写入'\0',buf2将不是一个合法的字符串(参见第 2 章关于字符串函数的译注)。
secret2 二进制文件(secret2.tar.gz)不再有缓冲区溢出漏洞。这个新二进制文件的 main 函数(main2.c)如下:
The
secret2binary (secret2.tar.gz) no longer has the buffer overflow vulnerability. Here’s themainfunction of this new binary (main2.c):
1 | #include <stdio.h> |
注意,我们给所有 scanf 调用都加上了长度说明,使 scanf 函数在读入前 12 个字节之后就停止读取。攻击字符串再也无法破坏这个程序了:
Notice that we added a length specifier to all calls of
scanf, causing thescanffunction to stop reading from input after the first 12 bytes are read. The exploit string no longer breaks the program:
译注
按上面表格的译注,%12s 最多会写入 12 个字符加 1 个 '\0',仍可能越过 buf 末尾 1 字节。它挡住了本节这种长串攻击,但严格正确的写法应是 %11s。
1 | $ ./secret2 < exploit |
当然,任何具备基本逆向工程技能的读者,仍然可以通过分析汇编代码赢得这个猜谜游戏。如果你还没尝试过用逆向工程打败这个程序,我们鼓励你现在就试一试。
Of course, any reader with basic reverse-engineering skills can still win the guessing game by analyzing the assembly code. If you haven’t tried to beat the program yet with reverse engineering, we encourage you to do so now.
参考文献
References
Mohit Kumar. Critical Skype Bug Lets Hackers Remotely Execute Malicious Code. 2017.
Tamir Zahavi-Brunner. CVE-2017-13253: Buffer overflow in multiple Android DRM services. 2018.
Tom Spring. Google Patches ‘High Severity’ Browser Bug. 2017.
Christopher Kelty. The Morris Worm Limn Magazine, Issue 1. Issue 1, Systemic Risk. 2011.
David Auerbach. Chat Wars: Microsoft vs. AOL NplusOne Magazine, Issue 19. Spring 2014.
Aleph One. Smashing the Stack for Fun and Profit. 1996.
DotsAreCool. Super Mario World Credit Warp (Nintendo ROP example). 2015.