-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrashitoooo.py
94 lines (83 loc) · 1.93 KB
/
crashitoooo.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import tempfile
import os
import sys
INCLUDES = """
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
"""
RAND_HEADER = """
static bool RANDOM_IS_SET = 0;
#define FAIL_PROBA 0.5
"""
RAND_CODE = """
if (!RANDOM_IS_SET)
srand(time(NULL));
RANDOM_IS_SET = 1;
if (((double)rand() / (double)RAND_MAX) < FAIL_PROBA)
return NULL;
"""
MALLOC_BEGIN = """
void *malloc(size_t s)
{
void *ptr;
"""
MALLOC_FAIL = """
return NULL;
}
"""
MALLOC_GOOD = """
ptr = sbrk(0);
if ((intptr_t)(sbrk(s)) < 0)
return NULL;
return (uint8_t *)ptr + s;
}
"""
FREE = "void free(void *) { return; }\n"
BINARY = "crashito.so"
def generate(rand = None, n = None):
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
print(tmp.name)
x = tmp.name + ".c"
os.rename(tmp.name, x)
tmp.name = x
tmp.write(INCLUDES.encode())
if rand is True:
tmp.write(RAND_HEADER.format(n / 100).encode())
tmp.write(MALLOC_BEGIN.encode())
if rand is True:
tmp.write(RAND_CODE.encode())
if rand is True:
tmp.write(MALLOC_GOOD.encode())
else:
tmp.write(MALLOC_FAIL.encode())
tmp.write(FREE.encode())
tmp.flush()
os.system(f"gcc -shared -fPIC {tmp.name} -o {os.getcwd()}/{BINARY}")
finally:
tmp.close()
os.unlink(tmp.name)
def main():
if (len(sys.argv) == 1):
print("all mallocs will fail !")
generate()
return 0
rand = sys.argv[1].endswith("%")
n = 0
try:
n = int(sys.argv[1].removesuffix("%"))
except:
return 84
if rand:
print(f"there will be a {n}% chance that the malloc fails !")
generate(True, n)
else:
print(f"crashes after {n} mallocs")
print("soon")
return 0
if __name__ == "__main__":
exit(main())