说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C7-x86_64/buffer_overflow.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
7.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.
7.10.1. 著名的缓冲区溢出案例
7.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.
7.10.2. 初探:猜谜游戏
7.10.2. A First Look: The Guessing Game
为了帮助你理解缓冲区溢出攻击的机制,我们提供了一个简单程序的可执行文件,用户可以和它玩猜谜游戏。在这个链接下载 secret 可执行文件,并用 tar 命令解压:
To help you understand the mechanism of the buffer overflow attack, we provide the 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 secretx86-64.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 assembly. Readers comfortable enough with their GDB and assembly reading skills should be able to figure out what the secret number and the secret string should be by using GDB to reverse engineer their values.
不过,还有另一种更狡猾的取胜方法。
However, there is a different, sneakier way to win.
7.10.3. 仔细看看(C 之下)
7.10.3. Taking a Closer Look (Under the C)
程序在第一次调用 scanf 处有一个潜在的缓冲区越界漏洞。为了弄清发生了什么,我们用 GDB 查看 main 函数的汇编代码。我们还在地址 0x0000000000400717 处设一个断点,它是调用 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 0x0000000000400717, which is the address of the instruction right before the call toscanf(note that placing the breakpoint at the address ofscanfcauses program execution to halt inside the call toscanf, not inmain).
1 | 0x00000000004006f2 <+0>: push %rbp |
图 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 之前,它的前两个参数被分别预先加载到寄存器 %edi 和 %rsi 中。位于 <main+25> 的 lea 指令生成了数组 buf 的引用(地址)。
Prior to the call to
scanf, the first two arguments forscanfare preloaded into registers%ediand%rsi, respectively. Theleainstruction at location<main+25>creates the reference for arraybuf.
现在,假设用户在提示符处输入 1234567890。图 2 展示了 scanf 调用刚刚完成时栈的样子。
Now, suppose the user enters
1234567890at the prompt. Figure 2 illustrates what the stack looks like immediately after the call toscanfcompletes.

图 2. 输入 1234567890 时,scanf 调用刚完成那一刻的调用栈
Figure 2. The call stack immediately after the call to scanf with input 1234567890
回忆一下,数字 0 到 9 的 ASCII 编码的十六进制值是 0x30 到 0x39,并且每个栈内存位置是 8 字节长。帧指针距离栈指针 32 字节。跟着操作的读者可以用 GDB 打印 %rbp 的值(p $rbp)来确认。在这个例子中,%rbp 的值是 0x7fffffffdd10。下面的命令可以查看寄存器 %rsp 之下的 48 个字节(以十六进制显示):
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 eight bytes long. The frame pointer is 32 bytes away from the stack pointer. Readers tracing along can confirm the value of
%rbpby using GDB to print its value (p $rbp). In the example shown, the value of%rbpis 0x7fffffffdd10. The following command allows the reader to inspect the 48 bytes (in hex) below register%rsp:
1 | (gdb) x /48bx $rsp |
这条 GDB 命令的输出类似这样:
This GDB command yields output that looks similar to the following:
1 | (gdb) x /48bx $rsp |
每一行代表一个 64 位地址,或者说两个 32 位地址。所以,与 32 位地址 0x7fffffffdd0c 对应的值,位于显示 0x7fffffffdd08 的那一行最右边的四个字节。
Each line represents one 64-bit address, or two 32-bit addresses. So, the value associated with the 32-bit address 0x7fffffffdd0c is located at the rightmost four bytes of the line showing 0x7fffffffdd08.
原书注 · 多字节的值按小端序存储(Multibyte values are stored in little-endian order)
在前面的汇编片段中,地址 0xf7ffffffdd00 处的字节是 0xf0,地址 0xf7ffffffdd01 处的字节是 0xdd,地址 0xf7ffffffdd02 处的字节是 0xff,地址 0xf7ffffffdd03 处的字节是 0xff,地址 0xf7ffffffdd04 处的字节是 0xff,地址 0xf7ffffffdd05 处的字节是 0x7f。然而,地址 0x7fffffffdd00 处的 64 位值实际上是 0x7fffffffddf0。记住,由于 x86-64 是小端系统,地址这类多字节值的各个字节是按相反顺序存储的。
In the preceding assembly segment, the byte at address 0xf7ffffffdd00 is 0xf0, the byte at address 0xf7ffffffdd01 is 0xdd, the byte at address 0xf7ffffffdd02 is 0xff, the byte at address 0xf7ffffffdd03 is 0xff, the byte at address 0xf7ffffffdd04 is 0xff, and the byte at address 0xf7ffffffdd05 is 0x7f. However, the 64-bit value at address 0x7fffffffdd00 is in fact 0x7fffffffddf0. Remember that since x86-64 is a little-endian system, the bytes for multibyte values such as addresses are stored in reverse order.
译注 · 地址笔误
原文把这几个地址写成了 0xf7ffffffdd00~0xf7ffffffdd05,应为 0x7fffffffdd00~0x7fffffffdd05(对照上面的 GDB 输出)。
在这个例子中,buf 的地址位于栈顶。因此,前两个地址存放的是输入字符串 1234567890 对应的字节:
In this example, the address for
bufis located at the top of the stack. Therefore, the first two addresses hold the inputted bytes associated with input the string 1234567890:
1 | 0x7fffffffdcf0: 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 |
空字符 \0 出现在地址 0x7fffffffdcf8 那一行的第三个字节位置(即地址 0x7fffffffdcfa)。回想一下,scanf 会在所有字符串末尾加上一个空字节。
The null termination byte
\0appears in the third most significant byte location at address 0x7fffffffdcf8 (i.e., at address 0x7fffffffdcfa). Recall thatscanfterminates all strings with a null byte.
译注
原文说这是该 8 字节单元中「第三高位」(third most significant)的字节。按小端序,GDB 每行最左边的字节地址最低、权重也最低,所以 0x7fffffffdcfa 其实是这个 64 位值中从低位数起的第三个字节。不影响理解,知道它的地址是 0x7fffffffdcfa 就行。
当然,1234567890 不是秘密数字。下面是用输入字符串 1234567890 运行 secret 时的输出:
Of course, 1234567890 is not the secret number. Here is the output when we try to run
secretwith input string 1234567890:
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, since 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 into exiting with a return value of 0, indicating that we won the game.
7.10.4. 缓冲区溢出:第一次尝试
7.10.4. Buffer Overflow: First Attempt
接下来,试着输入字符串 1234567890123456789012345678901234567890123:
Next, let’s try typing in the string
1234567890123456789012345678901234567890123:
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 从哪里来
进程被信号杀死时,shell 报告的退出状态是 128 + 信号编号。段错误对应的信号 SIGSEGV 编号为 11,所以是 128 + 11 = 139。译者在本机让一个程序解引用空指针,bash 里 echo $? 同样输出 139。

图 3. 输入 1234567890123456789012345678901234567890123 时,scanf 调用刚完成那一刻的调用栈
Figure 3. The call stack immediately after the call to scanf with input 1234567890123456789012345678901234567890123
输入字符串太长,不仅覆盖了存放在 0xd08 和 0xd10 处的值,还溢出到了 main 栈帧下方的返回地址。回想一下,函数返回时,程序会尝试从返回地址指定的位置继续执行。在这个例子中,程序退出 main 后试图从地址 0xf7ff00333231 处继续执行,而这个地址看起来并不存在,于是程序因段错误崩溃。
The input string is so long that it not only overwrote the values stored at 0xd08 and 0xd10, 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 0xf7ff00333231 after exitingmain, which does not appear to exist. So the program crashes with a segmentation fault.
译注 · 地址笔误
原文的 0xf7ff00333231 应为 0x7fff00333231:返回地址所在的 0x7fffffffdd18 处的 8 个字节是 31 32 33 00 ff 7f 00 00,按小端序读出来是 0x00007fff00333231,与下面 GDB 输出中的 0x00007fff00333231 in ?? () 一致。
在 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.
7.10.5. 更聪明的缓冲区溢出:第二次尝试
7.10.5. A Smarter Buffer Overflow: Second Attempt
第一个例子用垃圾数据覆盖了保存的 %rbp 和返回地址,粉碎了栈,导致程序崩溃。如果攻击者的目的只是让程序崩溃,到这一步就已经满意了。但我们的目标是骗猜谜游戏返回 0,表示我们赢了。为此,我们要用比垃圾值更有意义的数据填充调用栈。例如,可以覆盖栈,把返回地址替换成 endGame 的地址。这样,当程序试图从 main 返回时,它会去执行 endGame,而不是因段错误崩溃。
Our first example smashed the stack by overwriting the
%rbpregister 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:
译注 · printf 变成了 puts
源码里 endGame 调用的是 printf("You win!\n"),反汇编中却是 puts@plt:对于只输出一个以换行结尾的常量字符串的 printf,编译器会把它换成等价而更简单的 puts。译者用 clang 以 -O1 为 x86-64 Linux 生成汇编,也看到了同样的替换(-O0 时 clang 保留 printf;原书的 GCC 输出说明它在这里也做了替换)。
1 | $ gdb secret |
可以看到,endGame 从地址 0x00000000004006da 开始。图 4 展示了一个迫使 secret 执行 endGame 函数的示例攻击字符串。
Observe that
endGamestarts at address 0x00000000004006da. 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
本质上就是 40 字节的垃圾值,后面跟着返回地址。同样,由于 x86-64 是小端系统,返回地址中的字节看起来是倒序的。
Essentially, there are 40 bytes of junk values followed by the return address. Again, since x86-64 is a little-endian system the bytes in the return address appear to be in reverse order.
译注 · 为什么是 40 字节
buf 位于 %rbp-0x20(见上面 lea -0x20(%rbp),%rax),从 buf 起始处到保存的 %rbp 有 32 字节,再加上保存的 %rbp 本身 8 字节,共 40 字节,紧接着就是返回地址。
另外,这个攻击能直接写入 0x4006da 这样的固定地址,是因为 secret 不是位置无关可执行文件(PIE),代码段总加载在固定地址(0x400000 一带是非 PIE 的 x86-64 程序的传统加载地址)。如果程序编译为 PIE,下文提到的地址随机化也会作用于代码段,攻击者事先就不知道 endGame 的确切地址了。
下面的程序演示了攻击者可以如何构造前面那个攻击字符串:
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 文件一共 49 字节,最后多一个空字节。scanf("%s", ...) 读到空字节并不会停下(它只在空白字符处停止),这个空字节随后又被 scanf 自己加的终止符覆盖,所以不影响攻击。
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!” since 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!
7.10.6. 防御缓冲区溢出
7.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指令)。执行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 (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,Address Space Layout Randomization)的一部分:现代系统同样会随机化堆、共享库的位置,若程序编译为位置无关可执行文件(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.
译注 · 金丝雀实际放在哪
在 x86-64 Linux 上,金丝雀的参考值存放在线程局部存储中,用 %fs 段寄存器访问。译者用 clang -target x86_64-linux-gnu -O1 -fstack-protector-strong -S 编译一个带局部数组的函数,可以看到函数开头 movq %fs:40, %rax 取出金丝雀并放到栈上,返回前再与 %fs:40 比较,不一致就调用 __stack_chk_fail 中止程序。GCC 的 -fstack-protector、-fstack-protector-strong、-fstack-protector-all 选项控制哪些函数插入这种检查。
- 限制可执行区域:这道防线把可执行代码限制在内存中特定的区域。换句话说,调用栈不再是可执行的。然而,就连这种防御也可以被攻破。在利用面向返回编程(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.
现代更新(截至 2026-11)· 硬件影子栈
针对覆盖返回地址和 ROP 这类攻击,x86 处理器的 CET(Control-flow Enforcement Technology,控制流强制技术)提供了影子栈(shadow stack):执行 call 时,处理器把返回地址同时压入普通栈和一个应用程序无法直接修改的影子栈;函数返回时比较两份副本,不一致就触发异常。本节那种改写栈上返回地址的攻击,在启用影子栈的程序里会被硬件直接拦下。Linux 内核在 6.6 版(2023 年 10 月)加入了对用户态 x86 影子栈的支持,程序需要由工具链和加载器(如 glibc)配合启用。Linux 内核文档:CET Shadow Stack;Kernel Newbies:Linux 6.6
然而,最好的防线永远是程序员自己。要防止程序遭受缓冲区溢出攻击,尽可能使用带长度说明(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 章关于字符串函数的译注)。
现代更新(截至 2026-11)· gets 已被移出标准
表中第一行的 gets 无法安全使用,C99 的第三号技术勘误将其弃用,C11 标准把它彻底删除了;替代品是 fgets,或 C11 可选附录 K 中的 gets_s。新代码里不应再出现 gets。cppreference:gets, gets_s
secret2 二进制文件(secret2x86-64.tar.gz)不再有缓冲区溢出漏洞。这个新二进制文件的 main 函数(main2.c)如下:
The
secret2binary (secret2x86-64.tar.gz) no longer has the buffer overflow vulnerability. Themainfunction of this new binary (main2.c) appears below:
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 字节(写到 %rbp-0x14)。它挡住了本节这种长串攻击,但严格正确的写法应是 %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: 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.