# S04_Buffer_Overflow.pptx：逐页可提取文字

> [原课件](../../../S04_Buffer_Overflow.pptx)；共51页。以下是文字提取，**未经逐句纠错**；图中文字、截图代码、公式对象及动画关系可能无法完整提取。阅读主题笔记后，可按页码回原文件查看。

## 第 1 页

````text
缓冲溢出攻击
Buffer Overflow Attack
````

## 第 2 页

````text
缓冲溢出攻击
当程序把超过缓冲区容量的数据写入内存时，超出的字节会覆盖相邻内存（如返回地址、帧指针、函数指针等），这就是缓冲区溢出
栈缓冲区（stack overflow）、堆缓冲区（heap overflow）、全局/静态缓冲区；相关漏洞还包括格式化字符串等内存操控类错误
长期以来是远程代码执行（RCE）与本地提权的主要起点。攻击链核心：
内存写入→覆盖控制流或数据结构→执行任意指令或调用已有函数（ret2libc/ROP）
````

## 第 3 页

````text
演化
1988–1990s：早期内存错误被利用（网络/本地崩溃、未必可控执行）
1996：公开教程（“Smashing the stack” 等）把栈溢出利用系统化，催生大量 exploit
2000s：ret2libc 技术出现（在 NX/DEP 存在时调用库函数）；同时 OS/编译器开始引入缓解措施（ASLR、NX、栈金丝雀、PIE、RELRO）
2007+：ROP（Return-Oriented Programming）成为主流绕过技术，利用已有代码片段拼链执行任意逻辑
2010s–至今：针对堆、内核、JIT、语言运行时的复杂内存利用持续出现；缓解与绕过呈“军备竞赛”。
````

## 第 4 页

````text
现状
依然高价值：即便缓解存在，实际系统中误配置、旧二进制、防护缺口仍使溢出利用可行
现代利用更依赖信息泄露、内存喷射、链式利用（ROP/SROP/Jump-Oriented Programming）
防御成熟但非万无一失：ASLR/NX/Canary/CFI 等显著降低简单溢出成功率，但实现细节、兼容性和回退路径常被利用
````

## 第 5 页

````text
缓冲区溢出:C 语言的“专属”吗？
C/C++ 是风险最高、漏洞最常见的语言。其他内存安全语言风险极低
C/C++ 代码中的内存安全漏洞占到所有安全漏洞的 60% - 70% 以上
美国 CISA/NSA： 明确发布安全指南，转向内存安全语言
Linux 内核社区也开始将 Rust 用到内核开发中
内存安全语言： Rust (系统级)、Go、Swift、Python 等
````

## 第 6 页

````text
大纲
了解堆栈布局 
含漏洞的代码 
漏洞利用方面的挑战 
Shellcode 
对策
````

## 第 7 页

````text
进程看到的虚拟内存布局
Text == code
Data == static variables
Heap == dynamic data
Stack == “scratch paper” 
动态局部变量
函数的参数
返回地址
静态/动态，只读/读写
所有进程看到的内存布局都一样
操作系统
用户栈
共享库地址区域
堆
读/写:.data已初始化；.bss未初始化
只读 .text: 程序机器指令；.rodata:只读常量；.init初始化代码
````

## 第 8 页

````text
程序							进程的栈
ptr points to the memory here
a,b, ptr
y
x
````

### 备注区文字

````text
Global variables are stored in Data segment.
Uninitialized static variables are stored in BSS.
Dynamic memory is allocated in heap.
Local variables are stored in Stack.
````

## 第 9 页

````text
栈
程序运行中，当前运行的函数的一些临时变量，放在栈里
多次函数的调用和返回，顺序是一致的
因此函数的栈帧在栈中是先进先出
基址寄存器*BP：栈基址，当前函数的栈的基址（坐标原点）
函数的参数、变量都可表示为与原点的距离
参数为正，变量为负
在 64-bit 调用约定中，前几个函数参数是通过通用寄存器传递
寄存器*SP:   栈顶，是最后一个被使用元素（最近压入的元素）所在的逻辑位置
函数的栈帧开始于其参数，结束于下一个函数的参数前
````

## 第 10 页

````text
堆栈中函数参数的顺序
````

### 备注区文字

````text
The local variables and function arguments are stored in the stack with reference to ebp.  The argument ‘b’ is stored at a higher address and hence is pushed into the stack before. The function arguments are pushed into the stack in reverse order.
````

## 第 11 页

````text
AT&T vs. Intel 汇编语言格式对比
语法方向：
AT&T：操作码 源, 目的;   像中文和英文的语序
Intel：操作码 目的, 源
寄存器表示：
AT&T：所有寄存器前加 %。例如：%eax
Intel：直接使用寄存器名。例如：eax
立即数表示：
AT&T：所有立即数前加 $。例如：$0x10
Intel：不加任何前缀。例如：0x10
内存访问：
AT&T：使用括号 ()，并采用段寄存器:偏移量(基址, 索引, 比例因子) 的复杂格式。例如：movl 8(%ebp), %eax
Intel：使用中括号 []，并采用[基址 + 索引 * 比例因子 + 偏移量] 的简单格式
用途：
AT&T：GCC 编译器默认使用的格式，在 Linux 环境下常见
Intel：在 Windows 和大多数 CPU 官方文档中更常见
````

## 第 12 页

````text
函数调用与栈
void f(int a, int b)
{
  int x;
}
void main()
{
  f(1,2);
  printf("hello world");
}

ebp并不是一个函数的栈帧的起始位置，提供了一个帧的坐标原点，函数的每个变量的地址都可以通过ebp的值得到：
Return address = ebp+4
&a == ebp+8
&b == ebp+12
&x == ebp – 4
…
````

### 备注区文字

````text
Main function calls f() with arguments a and b. f function stack frame is created below the main function stack. The returns address in the f() stack frame points to the next instruction address after the function is executed and returned. Here, it points to the printf() instruction.
````

## 第 13 页

````text
嵌套调用函数时的栈
	     main()

		
			  
  foo()

	
			  
  bar()

地址为ebp的单元存放的是上一个函数的epb，因此ebp形成了一个链表
````

### 备注区文字

````text
The figure shows how functions are pushed into the stack. The return address in every function stack points to the next instruction that will be executed after the return. The frame pointer (ebp) of the caller function is stored in the callee’s function stack, so when the callee returns, the ebp register can point to the caller’s function stack.
````

## 第 14 页

````text
函数调用与call、ret指令
call 指令和 ret 指令是 x86 汇编中用于实现函数调用和返回的指令
call 目标地址：调用一个子程序
压栈（Push）：将 call 指令的下一条指令的地址（即返回地址）压入栈中
跳转（Jump）：将控制权转移到子程序的入口点
ret：从子程序返回
出栈（Pop）：从栈顶弹出一个地址（即之前被 call 指令压入的返回地址），并将其存入指令指针寄存器（如 eip 或 rip）
跳转（Jump）：根据 eip/rip 中的新地址，将控制权转移回调用方。
````

## 第 15 页

````text
调用约定
函数调用时的一套规则，它规定了参数如何传递以及谁来清理栈。这是确保调用者和被调用者能够正确交互的基础。

参数传递 | 参数是放在寄存器里，还是栈里？如果是栈，是从左到右还是从右到左压栈？
栈清理 | 是调用者（caller）负责清理栈（pop 掉参数），还是被调用者（callee）负责？
返回值 | 返回值是如何传递的（通常在 eax/rax 寄存器中）？
````

## 第 16 页

````text
常见的调用约定

cdecl (C Declaration)
参数压栈：从右到左。
栈上参数清理：调用者负责。
优点：支持可变参数函数（如 printf），因为它保证第一个参数（format）总是在所有参数的最低地址。
应用：C 语言默认约定，广泛用于 Linux 和 Windows。
stdcall (Standard Call)
参数压栈：从右到左。
栈上参数清理：被调用者负责。
优点：栈由被调函数清理，代码更紧凑。
应用：Win32 API（如 MessageBox, CreateWindow）。
fastcall
参数压栈：优先使用寄存器（如 ecx, edx）传递前几个参数，剩下的才用栈。
栈上参数清理：取决于具体实现。
优点：减少了内存访问，显著提高性能。
应用：注重性能的代码，不同编译器有自己的实现。
````

## 第 17 页

````text
完整例子：
简单的函数：calculate(int a, int b)，它返回 a + b 的结果。然后，主函数 main 调用这个函数。

// cdecl_example.c
int calculate(int x, int y) {
    int sum = x + y;
    return sum;
}

int main() {
    int result = calculate(10, 20);
    return 0;
}
 GCC 编译器来生成汇编代码。为了让汇编代码更清晰，我们将禁用优化，并为 x86-64 架构生成 32 位汇编（-m32 选项），

gcc -S -m32 -fno-stack-protector -fno-pie cdecl_example.c
````

## 第 18 页

````text
汇编代码分析
关键部分
.LC0:
        .string "result: %d\n"
.globl  calculate
        .type   calculate, @function
calculate:
        pushl   %ebp             # 1. 压入旧的 ebp
        movl    %esp, %ebp       # 2. 将 esp 设为新的 ebp
        subl    $16, %esp        # 3. 为局部变量分配空间

        movl    8(%ebp), %eax    # 4. 从栈中取出第一个参数 x
        movl    12(%ebp), %edx   # 5. 从栈中取出第二个参数 y
        addl    %edx, %eax       # 6. 计算 x + y，结果放入 eax
        movl    %eax, -4(%ebp)   # 7. 将结果存入局部变量 sum

        movl    -4(%ebp), %eax   # 8. 将返回值放入 eax

        leave              # 9. 恢复栈：movl %ebp, %esp; popl %ebp
        ret                      # 10. 返回

.globl  main
        .type   main, @function
main:
        pushl   %ebp             # 1. 压入旧的 ebp
        movl    %esp, %ebp       # 2. 将 esp 设为新的 ebp
        subl    $16, %esp        # 3. 为局部变量 result 分配空间

        movl    $20, (%esp)      # 4. 参数 20 压入栈（从右到左）
        movl    $10, 4(%esp)     # 5. 参数 10 压入栈（从右到左）

        call    calculate        # 6. 调用 calculate，将返回地址压栈

        movl    %eax, -4(%ebp)   # 7. 将返回值从 eax 存入局部变量 result

        addl    $8, %esp         # 8. 调用者清理栈，移除 2 个参数 (2*4=8 字节)

        movl    $0, %eax         # 9. 返回值 0

        leave                    # 10. 恢复栈
        ret                      # 11. 返回
寄存器分类（调用前后是否允许改变）
是 caller-saved（volatile）：AX, CX, DX, 
否 SP，callee-saved（non-volatile）：BX, BP,
````

## 第 19 页

````text
含缓冲溢出漏洞的程序


从 badfile 读取 300 字节的数据。
将文件内容存储到大小为 400 字节的 str 数组中。
使用 str 作为参数调用 foo 函数。

注意：坏文件是由用户创建的，因此内容由用户控制。可以包含恶意代码。
````

## 第 20 页

````text
含缓冲溢出漏洞的程序
````

### 备注区文字

````text
Here we are copying str (300 bytes of data) into a buffer of size 100 bytes. This leads to buffer overflow. As seen in the foo() stack frame, this overflow leads to overwriting of some of the important contents of the stack like frame pointer, return address etc.
````

## 第 21 页

````text
缓冲区溢出的后果
用一些随机地址覆盖返回地址可以指向:

无效指令
不存在的地址
访问冲突
攻击者的代码 用于获取访问权限的恶意代码


buffer[108]

buffer[104]

buffer[100]





buffer[0]
````

## 第 22 页

````text
如何运行恶意代码
````

### 备注区文字

````text
To run malicious code, we need to find a place in the function stack which will point to our code, jump to it and execute it. As we had seen that, when a function is executed it jumps to the return address (the instruction after the function was called in the caller function) , we can modify the return address with the address of the malicious code so that it jumps to the code and executes it.
````

## 第 23 页

````text
实战环境设置
````

### 备注区文字

````text
To perform this attack, we need to switch off the countermeasures which are discussed in the next slides.
Address randomization is turned off so that the base address of the buffer remains. It makes the task simpler to guess the return address in the stack.
We set the stack as executable as we need to execute our own code on the stack. Also, we disabled stack guard protection (discussed later).
````

## 第 24 页

````text
Unix文件访问控制
12 个比特：一个文件的访问控制表
项，高3位: setuid, setgid, 粘连位

后9位：文件所有者U、组成员G和所有其他用户O，的读、写和执行权限

Figure 4.5 UNIX File Access Control



Chmod命令
chmod u-w file1
chmod u+w file1
chmod ugo+w file1
chmod 777 file1
777是8进制
chmod 4751
Setuid置1
````

## 第 25 页

````text
实例：普通用户可使用Passwd程序修改自己的密码，对passwd文件进行修改，但passwd属于root用户
Owner对可执行文件 e 有 s 权限，other用户对 f 有x权限，则用户A在执行e的过程中，用户有效id为owener的，拥有owner的权限
权限只在 e 执行过程中有效，命令执行完毕，权限也失效
其他setuid程序
find / -perm -4000 -o -perm -2000
加入setuid权限 chmod u+s file 或 chmod 4755 file
Setuid功能
````

## 第 26 页

````text
创建恶意输入 （badfile）
Task A ：找到放置返回地址位置：求缓冲区底部与返回地址之间的偏移距离
Task B :   找到放置 shellcode 的地址
````

### 备注区文字

````text
The two challenges faced when running the malicious code are :
Find the offset distance between the base of the buffer and return address so that we can modify the return with address of the code.
Find the address of the malicious code. If we don’t handle this, our malicious code will be stored in some random memory location to which we have control to. In that case we cannot modify the return address with the address of our code. Hence, we will put our malicious code in the function stack itself.

So,we need do the following on our badfile :

Write the malicious code (shellcode : discussed in later slides)
Place the malicious code in our stack ( At the lowest address above return address or at the end of the of the buffer)
Modify return address with address of the shell code
````

## 第 27 页

````text
Task A :缓冲区基地址和返回地址之间的距离
因此，距离是108 + 4 = 112
````

### 备注区文字

````text
To find the distance between the base of the buffer and the return address, we need to use a gdb debugging tool. given that we have access to the vulnerable code, we can use gdb to the base address of the buffer, address of the frame pointer (ebp) and return address ($ebp + 4)
````

## 第 28 页

````text
Task B :恶意代码地址
使用 gdb 进行跟踪

恶意代码写在坏文件中，该文件作为参数传递给易受攻击的函数

使用 gdb，我们可以找到函数参数的地址
````

## 第 29 页

````text
Task B :恶意代码地址
如果没有程序副本，只能猜测。但不难猜： 栈地址固定，栈深度浅


为了增加跳转到正确地址的机会，我们可以用 NOP 指令填充坏文件，并将恶意代码放在缓冲区的末尾。

只要返回地址处是nop指令，就会运行到恶意代码

注意：NOP- 什么都不做的指令。
````

## 第 30 页

````text
坏文件的结构
````

## 第 31 页

````text
坏文件构造 Python脚本
````

### 备注区文字

````text
- Initialize the entire buffer with NOP instructions.
- Obtain the results from Task A and Task B and place the malicious code address in return address.
- Place the malicious at the of the buffer.
````

## 第 32 页

````text
写入栈的返回地址
考虑：
函数堆栈 [0xbffff188 + nnn] 返回地址中的新地址不应在其任何字节中包含零，否则 badfile 将具有零，导致 strcpy（） 结束复制。
例如，0xbffff188 + 0x78 = 0xbffff200，最后一个字节包含零，导致结束复制。
````

## 第 33 页

````text
执行结果
在禁用所有防御措施的情况下编译带漏洞的代码。





执行漏洞利用代码和堆栈代码。
````

## 第 34 页

````text
关于防御措施的说明
在 Ubuntu16.04 上，/bin/sh 指向 /bin/dash，这有一个保护机制
 它在 setuid 进程中执行时，发现有效id和实际id不同，就会丢弃权限
为了演示攻击将 /bin/sh 指向另一个 shell
更改 shellcode（绕过此保护措施）

其他绕过保护机制的方法将在后面讨论
````

## 第 35 页

````text
Shellcode
恶意代码的目的：完全控制系统

解决 : Shell 程序






挑战 :
装载shell的系统调用						
内容中的 0
````

### 备注区文字

````text
The above C code gives the shell prompt to execute more commands. We can compile the above C code into binary and store it into the badfile with modified return address field to the address of main(). But there are issues with this solution :
Loader Issue : OS loader is responsible for setting up the memory, copying the program to the memory and invoking dynamic linker to link libraries etc to set up the running environment of the program.After the initializations steps are completed, main() is called. If any of the steps are missing, program won’t be loaded to the memory. In buffer flow program, we are copying the code using memory copy. Therefore all the initialization steps are missing and hence, our shell code won’t be executed.
Zeros in the code : strcpy() stops copying when a zero is found in the source string. When the C code is compiled ot binary, there will be zeros in the binary code which will stop copying the badfile further.
Refer to section 4.6
````

## 第 36 页

````text
int 0x80 系统调用
也是过程调用，但使用方式和目的与call指令不同
软中断指令，它触发的是一个内核定义好的中断处理程序
参数传递：通过 硬性规定 的特定寄存器来传递。系统调用号放在 eax，而参数则依次放在 ebx, ecx, edx, esi, edi, ebp。
灵活性：每个参数的位置都是预先定义好的。内核可以高效地从这些特定寄存器中读取参数，省去了访问栈内存的开销。
目的：它不是一个通用的函数调用机制，而是专门为了从用户空间进入内核空间而设计的一种接口。
返回地址等上下文压入内核栈
````

## 第 37 页

````text
Shellcode
用于启动 shell 的汇编代码（机器指令）

使用系统调用 execve(“/bin/sh”, argv, 0) 运行shell

在寄存器中为execve调用准备好参数:
eax = 0x0000000b (11) : execve()的系统调用编号
ebx = “/bin/sh”的地址
ecx =参数数组的地址
argv[0] = the address of “/bin/sh” 
argv[1] = 0 (i.e., no more arguments)
edx = 0 (不传递环境变量)
调用execve(): int 0x80
````

## 第 38 页

````text
Shellcode
%eax = 0 (avoid 0 in code)
set end of string “/bin/sh”
cdq指令：将eax的符号位复制到 edx 中的所有位
hs//
nib/
````

## 第 39 页

````text
Shellcode
````

### 备注区文字

````text
Refer to section 4.6.2 and 4.6.3
````

## 第 40 页

````text
保护机制
在程序设计中：
	使用更安全的函数，如 strncpy（）、strncat（） 等，更安全的动	态链接库，在复制之前检查数据的长度。
操作系统：
	ASLR（地址空间布局随机化）
编译器：
	堆栈防护
	硬件方法：
		不可执行堆栈
````

## 第 41 页

````text
ASLR原理
难以猜测恶意代码的%ebp地址和地址
很难猜出内存中的堆栈地址。
为了随机化堆栈的起始位置，即每次将代码加载到内存中时，堆栈地址都会更改。
````

## 第 42 页

````text
地址空间布局随机化
````

### 备注区文字

````text
When the ASLR is enabled in the Linux machine, we ran the above code to check how it affects the addresses of the local variables on stack as well as heap. ASLR changes the address of the code every time it is loaded.
````

## 第 43 页

````text
地址空间布局随机化：运行时

1
3
2
````

### 备注区文字

````text
1 : When set to 0, the address space is not randomized.
2 : When set to 1, only stack memory address is randomized.
3 : When set to 2, both stack and heap memory address is randomized.
````

## 第 44 页

````text
绕过ASLR 
打开地址随机化 (countermeasure)
          % sudo sysctl -w kernel.randomize_va_space=2

2. 编译 set-uid root 版本的 stack.c
  % gcc -o stack -z execstack -fno-stack-protector stack.c
  % sudo chown root stack
  % sudo chmod 4755 stack
````

## 第 45 页

````text
绕过ASLR 
3. 通过无限循环运行易受攻击的代码来击败它。
````

## 第 46 页

````text
绕过ASLR 
在 32 位 Linux 机器上运行脚本约 19 分钟后，我们获得了对 shell 的访问权限（执行了恶意代码）。
````

## 第 47 页

````text
堆栈防护
````

### 备注区文字

````text
Stackguard is a compiler approach to defeat buffer overflow.  A random secret value is generated and stored in a memory location (not on stack) and is assigned to a local variable of the function which gets stored in the stack. After the copy function is function, it is checked if the value of the local variable is changed. If yes, buffer overflow has taken place and the program exits without returning.
````

## 第 48 页

````text
使用 StackGuard 执行
由编译器插入金丝雀检查哨兵。
````

### 备注区文字

````text
Prog.c is a vulnerable program which takes input from the user and calls a function foo() which copies to a buffer. When the user passes a variable of longer length than buffer size, it changes the value of the local variable (guard) and hence, the program terminates with stack smashing message.
````

## 第 49 页

````text
在 bash & dash 中绕过保护机制
它们将 setuid 进程变成非 setuid 进程
 他们将有效用户 ID 设置为真实用户 ID，从而放弃权限
  想法：在运行它们之前，我们将真实用户 ID 设置为 0
 调用 setuid（0）
 我们可以在 shellcode 的开头执行此作
````

## 第 50 页

````text
不可执行堆栈
NX 位代表 CPU 中的 No-eXecute 功能，将代码与数据分开，将内存的某些区域标记为不可执行。

可以使用 Return-to-libc、Return Oriented Progamming 技术绕过此保护机制
````

## 第 51 页

````text
总结
缓冲区溢出是一个常见的安全漏洞
本节只关注基于堆栈的缓冲区溢出
基于堆的缓冲区溢出也会导致代码注入
利用缓冲区溢出来运行注入的代码
防御攻击
````
