[SEEDLab]格式化字符串漏洞(Format String Vulnerability)
Introduction
格式化字符串漏洞是一个经典的漏洞,也是Pwn里面一个基础吧。他是由于C语言中的printf
相关的函数导致的。printf
想必大家都已熟悉,对于下面这个语句:
printf("%d%d%d", a, b, c);
系统会将"%d%d%d"
和后面的a, b, c
三个int
变量一起压入栈中。在执行时,系统会扫描第一个字符串,统计其一共有多少个格式化字符串,然后向高地址依次读取,最后输出。在实践中,有时候会有人写出这样的代码:
s = gets();
printf(s);
这时,一旦我们输入%8x
,系统便会将字符串s
之上的栈中的内容打印出来。此外,printf
中还定义了一个不常用的%n
,可以对一个特定地址实现写入目前输出的字符数目的操作。这样便造成了严重的格式化字符串漏洞。
Task 1: The Vulnerable Program
实验指导中给出了一个具有格式化字符串漏洞的程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#define PORT 9090
char *secret = "A secret message\n";
unsigned int target = 0x11223344;
void myprintf(char *msg){
printf("The address of the ’msg’ argument: 0x%.8x\n", (unsigned) &msg);
printf(msg);// This line has a format-string vulnerability
printf("The value of the ’target’ variable (after): 0x%.8x\n", target);
}
// This function provides some helpful information. It is meant to
// simplify the lab task. In practice, attackers need to figure
// out the information by themselves.
void helper(){
printf("The address of the secret: 0x%.8x\n", (unsigned) secret);
printf("The address of the ’target’ variable: 0x%.8x\n",(unsigned) &target);
printf("The value of the ’target’ variable (before): 0x%.8x\n", target