forked from kholia/checksec
/
checksec.py
executable file
·314 lines (264 loc) · 11.6 KB
/
checksec.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python
from __future__ import print_function
import sys
import re
from six.moves import cStringIO
import six
try:
from elftools.common.exceptions import ELFError
from elftools.elf.elffile import ELFFile
from elftools.elf.sections import SymbolTableSection
from elftools.common.py3compat import bytes2str
from elftools.elf.constants import P_FLAGS
from elftools.elf.dynamic import DynamicSection
except ImportError as exc:
print(str(exc), file=sys.stderr)
print("""\n[-] Please install pyelftools, run "pip install pyelftools" """,
file=sys.stderr)
sys.exit(-1)
# http://people.redhat.com/sgrubb/security/find-elf4tmp
TMP_FUNCTIONS = ["^mkstemp", "^tempnam", "^tmpfile"]
# XXX add more APR and other common patterns
LOCAL_PATTERNS = ["^connect$", "^listen$", "^accept$", "^accept4$",
"^apr_socket_accept$", "PR_Accept", "PR_Listen",
"^getpeername", "^SSL_accept"]
IP_PATTERNS = ["getaddrinfo", "getnameinfo", "getservent", "getservbyname",
"getservbyport", "gethostbyname", "gethostbyname2",
"gethostbyaddr", "gethostbyaddr2", "apr_getnameinfo",
"PR_GetAddrInfoByName"]
# FORTIFY_SOURCE checklist
UNSAFE_FUNCTIONS = ["asprintf", "mbsnrtowcs", "snprintf",
"vsyslog", "confstr", "mbsrtowcs",
"sprintf", "vwprintf", "dprint",
"mbstowcs", "stpcpy", "wcpcpy",
"fgets", "memcpy", "stpncpy",
"wcpncpy", "fgets_unlocked", "memmove",
"strcat", "wcrtomb", "fgetws",
"mempcpy", "strcpy", "wcscat",
"fgetws_unlocked", "memset", "strncat",
"wcscpy", "fprintf", "obstack_printf",
"strncpy", "wcsncat", "fread",
"obstack_vprintf", "swprintf", "wcsncpy",
"fread_unlocked", "pread", "syslog",
"wcsnrtombs", "fwprintf", "pread64",
"ttyname_r", "wcsrtombs", "getcwd",
"printf", "vasprintf", "wcstombs",
"getdomainname", "ptsname_r", "vdprintf",
"wctomb", "getgroups", "read",
"vfprintf", "wmemcpy", "gethostname",
"readlink", "vfwprintf", "wmemmove",
"getlogin_r", "readlinkati", "vprintf",
"wmempcpy", "gets", "realpath",
"vsnprintf", "wmemset", "getwd",
"recv", "vsprintf", "wprintf"
"longjmp", "recvfrom", "vswprintf"]
STACK_CHK = "__stack_chk_fail"
class Elf(object):
def __init__(self, fileobj):
self.elffile = ELFFile(fileobj)
self.output = sys.stdout
# our code starts here :-)
def network(self):
ret = "None"
for section in self.elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
print("\nSymbol table '%s' has a sh_entsize " \
"of zero!" % (bytes2str(section.name)), file=sys.stderr)
continue
for _, symbol in enumerate(section.iter_symbols()):
# first match IP_PATTERNS
for pattern in IP_PATTERNS:
if re.match(pattern, bytes2str(symbol.name)):
return "network-ip"
# then match LOCAL_PATTERNS
for pattern in LOCAL_PATTERNS:
if re.match(pattern, bytes2str(symbol.name)):
ret = "network-local"
break
return ret
def _strings(self):
stream = self.elffile.stream
epos = stream.tell()
stream.seek(0, 0)
data = stream.read()
stream.seek(epos, 0)
ret = []
# XXX avoid calling eu-strings
import subprocess
p = subprocess.Popen("eu-strings", shell=True, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
out = p.communicate(input=data)[0]
for line in out.splitlines():
if re.match("^/tmp/.+", line) and "XXX" not in line:
ret.append(line)
return ret
def tempstuff(self):
tmp_strings = self._strings()
# if there are no /tmp references, just return
if len(tmp_strings) == 0:
return "None"
for section in self.elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
print("\nSymbol table '%s' has a sh_entsize " \
"of zero!" % (bytes2str(section.name)), file=sys.stderr)
continue
for _, symbol in enumerate(section.iter_symbols()):
for pattern in TMP_FUNCTIONS:
if re.match(pattern, bytes2str(symbol.name)):
return "None"
return "$".join(tmp_strings)
# XXX implement this
def chroot_without_chdir(self):
"""
This functions looks for apps that use chroot(2) without using chdir(2).
Inspired by http://people.redhat.com/sgrubb/security/find-chroot
"""
pass
def fortify(self):
""" NA : FORTIFY_SOURCE was not applicable
Enabled : unsafe and _chk functions were found
Disabled : only unsafe functions were found
(_chk functions missing)"""
ret = "NA"
for section in self.elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
print("\nSymbol table '%s' has a sh_entsize " \
"of zero!" % (bytes2str(section.name)), file=sys.stderr)
continue
for _, symbol in enumerate(section.iter_symbols()):
for pattern in UNSAFE_FUNCTIONS:
if re.match(pattern, bytes2str(symbol.name)):
if ret == "NA":
ret = "Disabled"
break
if ret == "Disabled":
# afename = "__" + bytes2str(symbol.name) + "_chk"
for _, symbol in enumerate(section.iter_symbols()):
# first look for corresponding _chk symbol
symbolstr = bytes2str(symbol.name)
if (symbolstr.startswith("__") and
symbolstr.endswith("_chk")) or \
symbolstr.endswith(" __chk_fail"):
ret = "Enabled"
break
return ret
def canary(self):
for section in self.elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
print ("\nSymbol table '%s' has a sh_entsize " \
"of zero!" % (bytes2str(section.name)), file=sys.stderr)
continue
for _, symbol in enumerate(section.iter_symbols()):
if re.match(STACK_CHK, bytes2str(symbol.name)):
return "Enabled"
return "Disabled"
def dynamic_tags(self, key="DT_RPATH"):
for section in self.elffile.iter_sections():
if not isinstance(section, DynamicSection):
continue
for tag in section.iter_tags():
if tag.entry.d_tag == key:
return "Enabled"
return "Disabled"
def program_headers(self):
pflags = P_FLAGS()
if self.elffile.num_segments() == 0:
# print('There are no program headers in this file.', \
# file=sys.stderr)
return
for segment in self.elffile.iter_segments():
if re.search("GNU_STACK", segment['p_type']):
if segment['p_flags'] & pflags.PF_X:
return "Disabled"
return "Enabled"
def relro(self):
if self.elffile.num_segments() == 0:
# print('There are no program headers in this file.', \
# file=sys.stderr)
return
have_relro = False
for segment in self.elffile.iter_segments():
if re.search("GNU_RELRO", segment['p_type']):
have_relro = True
break
if self.dynamic_tags("DT_BIND_NOW") == "Enabled" and have_relro:
return "Enabled"
if have_relro:
return "Partial"
return "Disabled"
def pie(self):
header = self.elffile.header
if self.dynamic_tags("EXEC") == "Enabled":
return "Disabled"
if "ET_DYN" in header['e_type']:
if self.dynamic_tags("DT_DEBUG") == "Enabled":
return "Enabled"
else:
return "DSO"
return "Disabled"
def getdeps(self):
deps=[]
if self.elffile.num_segments() == 0:
return deps
for segment in self.elffile.iter_segments():
if re.search("PT_DYNAMIC", segment['p_type']):
# this file uses dynamic linking, so read the dynamic section
# and find DT_SONAME tag
for section in self.elffile.iter_sections():
if not isinstance(section, DynamicSection):
continue
for tag in section.iter_tags():
if tag.entry.d_tag == 'DT_NEEDED':
deps.append(bytes2str(tag.needed))
break
return deps
def process_file(elfo, deps=True):
output = "NX=%s,CANARY=%s,RELRO=%s,PIE=%s,RPATH=%s,RUNPATH=%s," \
"FORTIFY=%s,CATEGORY=%s,TEMPPATHS=%s" \
% (elfo.program_headers(), elfo.canary(), elfo.relro(), elfo.pie(),
elfo.dynamic_tags("DT_RPATH"), elfo.dynamic_tags("DT_RUNPATH"),
elfo.fortify(), elfo.network(), elfo.tempstuff())
if deps:
output = output + (",DEPS=%s" % '$'.join(elfo.getdeps()))
return output
if __name__ == "__main__":
if len(sys.argv) < 2:
try:
if six.PY3:
import io
sys.stdin = sys.stdin.detach()
fh = io.BytesIO(sys.stdin.read())
else:
fh = cStringIO(sys.stdin.read())
elf = Elf(fh)
except ELFError as exc:
print("%s,Not an ELF binary" % \
str(exc), file=sys.stderr)
sys.exit(-1)
except IOError as exc:
print("%s,Not an ELF binary" % \
str(exc), file=sys.stderr)
sys.exit(-1)
print(process_file(elf))
else:
for i in range(1, len(sys.argv)):
try:
filename = sys.argv[i]
elf = Elf(open(filename, "rb"))
except ELFError as exc:
print("%s,%s,Not an ELF binary" % \
(filename, str(exc)), file=sys.stderr)
continue
except IOError as exc:
print("%s,%s,Not an ELF binary" % \
(filename, str(exc)), file=sys.stderr)
continue
print("%s,%s" % (filename, process_file(elf)))