protostar详细解析 heap2 解答

1源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>

struct auth {
char name[32];
int auth;
};

struct auth *auth;
char *service;

int main(int argc, char **argv)
{

char line[128];

while(1) {
printf("[ auth = %p, service = %p ]\n", auth, service);

if(fgets(line, sizeof(line), stdin) == NULL) break;

if(strncmp(line, "auth ", 5) == 0) {
auth = malloc(sizeof(auth));
memset(auth, 0, sizeof(auth));
if(strlen(line + 5) < 31) {
strcpy(auth->name, line + 5);
}
}
if(strncmp(line, "reset", 5) == 0) {
free(auth);
}
if(strncmp(line, "service", 6) == 0) {
service = strdup(line + 7);
}
if(strncmp(line, "login", 5) == 0) {
if(auth->auth) {
printf("you have logged in already!\n");
} else {
printf("please enter your password\n");
}
}
}
}

2 分析

1
user@protostar:/tmp$ ./bin/heap2 
[ auth = (nil), service = (nil) ]
auth 1
[ auth = 0x804c008, service = (nil) ]
reset
[ auth = 0x804c008, service = (nil) ]
serviceaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
[ auth = 0x804c008, service = 0x804c018 ]
login
you have logged in already!
[ auth = 0x804c008, service = 0x804c018 ]

​ heap2出问题的地方在于auth数据结构在被free之后,仍然有代码在使用被释放了的内存。

Image text

文章目录
  1. 1. 1源码
  2. 2. 2 分析
,