-
Notifications
You must be signed in to change notification settings - Fork 4
/
osx.py
executable file
·531 lines (471 loc) · 18.2 KB
/
osx.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import sys
import re
import time
import signal
from Peach.agent import Monitor
class CrashReporter(Monitor):
"""
Monitor crash reporter for log files.
"""
def __init__(self, args):
"""
Arguments are supplied via the Peach XML file.
:param args: dict of parameters
:type args: dict
"""
Monitor.__init__(self, args)
self._name = "CrashReporter"
if args.has_key('ProcessName'):
self.process_name = str(args['ProcessName']).replace("'''", "")
self.process_name = os.path.basename(self.process_name)
else:
self.process_name = None
if args.has_key('LogFolder'):
self.log_folder = str(args['LogFolder']).replace("'''", "")
else:
self.logFolder = os.path.join(os.environ['HOME'], "Library/Logs/DiagnosticReports")
if args.has_key('LookoutTime'):
self.lookout_time = float(args['LookoutTime']).replace("''", "")
else:
self.lookout_time = None
self.data = None
self.starting_files = None
def OnTestStarting(self):
# The monitor folder does not exist on a fresh installed system.
if not os.path.isdir(self.log_folder):
os.mkdir(self.log_folder)
self.starting_files = os.listdir(self.log_folder)
def GetMonitorData(self):
if not self.data:
return None
return {"CrashReport.txt": self.data}
def DetectedFault(self):
try:
# Give crash reporter time to find the crash. Only explicit from
# now on, since we have enough time during the re-launch of the
# process. We do not need to wait 0.50 seconds on each testcase
# to check for crashes if we monitor a single process.
if self.lookout_time:
time.sleep(self.lookout_time)
self.data = None
for f in os.listdir(self.log_folder):
if f not in self.starting_files and \
f.endswith(".crash") and \
(self.process_name is None or f.find(self.process_name) > -1):
fd = open(os.path.join(self.log_folder, f), "r")
self.data = fd.read()
fd.close()
return True
return False
except:
print(sys.exc_info())
return False
class CrashWrangler(Monitor):
"""
Use Apple Crash Wrangler to detect and sort crashes.
"""
def __init__(self, args):
"""
Arguments are supplied via the Peach XML file.
:param args: dict of parameters
:type args: dict
"""
Monitor.__init__(self, args)
if args.has_key('EnvironmentCommand'):
self.EnvCommand = str(args['EnvironmentCommand']).replace("'''", "")
try:
self.EnvCommand = os.environ[self.EnvCommand]
except KeyError:
self.EnvCommand = None
else:
self.EnvCommand = None
if args.has_key('EnvironmentArguments'):
self.EnvArguments = str(args['EnvironmentArguments']).replace("'''", "")
try:
self.EnvArguments = os.environ[self.EnvArguments]
except KeyError:
self.EnvArguments = ""
else:
self.EnvArguments = ""
if not self.EnvCommand:
if args.has_key('Command'):
self.Command = str(args['Command']).replace("'''", "")
else:
self.Command = None
else:
self.Command = self.EnvCommand
if not self.EnvArguments:
if args.has_key('Arguments'):
self.Arguments = str(args['Arguments']).replace("'''", "")
else:
self.Arguments = ""
else:
self.Arguments = self.EnvArguments
if args.has_key('StartOnCall'):
self.StartOnCall = str(args['StartOnCall']).replace("'''", "")
else:
self.StartOnCall = None
if args.has_key('UseDebugMalloc'):
self.UseDebugMalloc = str(args['UseDebugMalloc']).replace("'''", "").lower() == 'true'
else:
self.UseDebugMalloc = False
if args.has_key('EnvironmentExecHandler'):
self.EnvExecHandler = str(args['EnvironmentExecHandler']).replace("'''", "")
try:
self.EnvExecHandler = os.environ[self.EnvExecHandler]
except KeyError:
self.EnvExecHandler = ""
else:
self.EnvExecHandler = ""
if not self.EnvExecHandler:
if args.has_key('ExecHandler'):
self.ExecHandler = str(args['ExecHandler']).replace("'''", "")
else:
raise PeachException("Error, CrashWrangler monitor requires 'ExecHandler' parameter.")
else:
self.ExecHandler = self.EnvExecHandler
if args.has_key('ExploitableReads') and str(args['ExploitableReads']).replace("'''", "").lower() == "false":
self.ExploitableReads = False
else:
self.ExploitableReads = True
if args.has_key("NoCpuKill"):
self.NoCpuKill = True
else:
self.NoCpuKill = False
if args.has_key('CwLogFile'):
self.CwLogFile = str(args['CwLogFile']).replace("'''", "")
else:
self.CwLogFile = "cw.log"
if args.has_key('CwLockFile'):
self.CwLockFile = str(args['CwLockFile']).replace("'''", "")
else:
self.CwLockFile = "cw.lck"
if args.has_key('CwPidFile'):
self.CwPidFile = str(args['CwPidFile']).replace("'''", "")
else:
self.CwPidFile = "cw.pid"
# Our name for this monitor
self._name = "CrashWrangler"
self.pid = None
self.pid2 = None
self.currentCount = 0
self.restartFinger = 1000
def OnTestStarting(self):
if not self.StartOnCall:
if not self._IsRunning():
self._StartProcess()
def OnTestFinished(self):
if self.StartOnCall and self._IsRunning():
self._StopProcess()
def GetMonitorData(self):
if os.path.exists(self.CwLogFile):
fd = open(self.CwLogFile, "rb")
data = fd.read()
fd.close()
bucket = "Unknown"
if re.match(r".*:is_exploitable=\s*no\s*:.*", data):
bucket = "NotExploitable"
elif re.match(r".*:is_exploitable=\s*yes\s*:.*", data):
bucket = "Exploitable"
if data.find("exception=EXC_BAD_ACCESS:") > -1:
bucket += "_BadAccess"
if data.find(":access_type=read:") > -1:
bucket += "_Read"
elif data.find(":access_type=write:") > -1:
bucket += "_Write"
elif data.find(":access_type=exec:") > -1:
bucket += "_Exec"
elif data.find(":access_type=recursion:") > -1:
bucket += "_Recursion"
elif data.find(":access_type=unknown:") > -1:
bucket += "_Unknown"
elif data.find("exception=EXC_BAD_INSTRUCTION:") > -1:
bucket += "_BadInstruction"
elif data.find("exception=EXC_ARITHMETIC:") > -1:
bucket += "_Arithmetic"
elif data.find("exception=EXC_CRASH:") > -1:
bucket += "_Crash"
# Locate crashing address to help bucket duplicates
try:
threadId = re.search(r"Crashed Thread:\s+(\d+)", data).group(1)
threadPos = data.find("Thread " + threadId + " Crashed:")
crashAddress = re.search(r"(0x[0-9a-fA-F]+)", data[threadPos:]).group(1)
bucket += "_" + crashAddress
except:
print(sys.exc_info())
try:
os.unlink(self.CwLogFile)
os.unlink(self.CwLockFile)
except:
pass
if self.pid is not None:
return {"CrashWrangler" + str(self.pid) + ".txt": data, "Bucket": bucket}
else:
return {"CrashWrangler.txt": data, "Bucket": bucket}
return None
def DetectedFault(self):
try:
# Give crash wrangler time to find the crash
time.sleep(0.25)
time.sleep(0.25)
return os.path.exists(self.CwLogFile)
except:
print(sys.exc_info())
return False
def OnShutdown(self):
self._StopProcess()
def PublisherCall(self, method):
if self.StartOnCall:
if self.StartOnCall == method:
self._StartProcess()
elif self.StartOnCall + "_isrunning" == method:
if self._IsRunning():
if not self.NoCpuKill:
cpu = None
try:
os.system("ps -o pcpu %d > .cpu" % self.pid2)
fd = open(".cpu", "rb")
data = fd.read()
fd.close()
os.unlink(".cpu")
cpu = re.search(r"\s*(\d+\.\d+)", data).group(1)
if cpu.startswith("0.") and not os.path.exists("cw.lck"):
time.sleep(1.5)
# Check and see if crashwrangler is going
if os.path.exists(self.CwLockFile):
return True
print("CrashWrangler: PCPU is low (%s), stopping process" % cpu)
self._StopProcess()
return False
except:
print(sys.exc_info())
return True
else:
return False
return None
def unlink(self, file):
try:
os.unlink(file)
except:
pass
def _StartProcess(self):
if self._IsRunning():
return
self.currentCount += 1
# OS X can get very unstable during testing. This will hopefully
# allow for longer fuzzing runs by killing off some processes
# that seem to get "stuck".
if self.currentCount % self.restartFinger == 0:
os.system('killall -KILL Finder')
os.system('killall -KILL Dock')
os.system('killall -KILL SystemUIServer')
# Clean up any files
self.unlink(self.CwLockFile)
self.unlink(self.CwLogFile)
self.unlink(self.CwPidFile)
# If no command is specified, assume we are running exc_handler some
# other way.
if self.Command is None:
return
args = ["/usr/bin/env",
"CW_LOG_PATH=" + self.CwLogFile,
"CW_PID_FILE=" + self.CwPidFile,
"CW_LOCK_FILE=" + self.CwLockFile]
if self.UseDebugMalloc:
args.append("CW_USE_GMAL=1")
if self.ExploitableReads:
args.append("CW_EXPLOITABLE_READS=1")
args.append(self.ExecHandler)
args.append(self.Command)
splitArgs = self.Arguments.split(" ")
for i in range(len(splitArgs)):
if i > 0 and splitArgs[i - 1][-1] == '\\':
args[-1] = args[-1][:-1] + " " + splitArgs[i]
else:
args.append(splitArgs[i])
print("CrashWrangler._StartProcess():" % args)
self.pid = os.spawnv(os.P_NOWAIT, "/usr/bin/env", args)
while not os.path.exists(self.CwPidFile):
time.sleep(0.15)
fd = open(self.CwPidFile, "rb")
self.pid2 = int(fd.read())
fd.close()
self.unlink(self.CwPidFile)
print("_StartProcess(): Pid2: %d" % self.pid2)
def _StopProcess(self):
if self.pid is not None:
try:
# Verify if process is still running
(pid1, ret) = os.waitpid(self.pid, os.WNOHANG)
if not (pid1 == 0 and ret == 0):
self.pid = None
return
# Check for cw.lck before killing
while os.path.exists("cw.lck"):
time.sleep(0.25)
(pid1, ret) = os.waitpid(self.pid, os.WNOHANG)
if not (pid1 == 0 and ret == 0):
self.pid = None
return
except:
return
try:
# Kill process with signal
os.kill(self.pid2, signal.SIGTERM)
time.sleep(0.25)
os.kill(self.pid2, signal.SIGKILL)
except:
pass
try:
# Kill process with signal
os.kill(self.pid, signal.SIGTERM)
time.sleep(0.25)
os.kill(self.pid, signal.SIGKILL)
except:
pass
# Prevent Zombies!
os.wait()
self.pid = None
def _IsRunning(self):
if self.pid:
try:
(pid1, ret) = os.waitpid(self.pid, os.WNOHANG)
if pid1 == 0 and ret == 0:
print("_IsRunning: True")
return True
except:
pass
print("_IsRunning: False")
return False
class Process(Monitor):
"""
Start a process and kill it based on CPU usage.
"""
def __init__(self, args):
"""
Arguments are supplied via the Peach XML file.
:param args: dict of parameters
:type args: dict
"""
Monitor.__init__(self, args)
if args.has_key('Command'):
self.Command = str(args['Command']).replace("'''", "")
else:
self.Command = None
if args.has_key('Arguments'):
self.Arguments = str(args['Arguments']).replace("'''", "")
else:
self.Arguments = ""
if args.has_key('StartOnCall'):
self.StartOnCall = str(args['StartOnCall']).replace("'''", "")
else:
self.StartOnCall = None
if args.has_key("NoCpuKill"):
self.NoCpuKill = True
else:
self.NoCpuKill = False
self._name = "OsxProcess"
self.pid = None
self.currentCount = 0
self.restartFinger = 1000
def OnTestStarting(self):
if not self.StartOnCall:
if not self._IsRunning():
self._StartProcess()
def OnTestFinished(self):
if self.StartOnCall and self._IsRunning():
self._StopProcess()
def OnShutdown(self):
self._StopProcess()
def PublisherCall(self, method):
if self.StartOnCall:
if self.StartOnCall == method:
self._StartProcess()
elif self.StartOnCall + "_isrunning" == method:
if self._IsRunning():
if not self.NoCpuKill:
cpu = None
try:
os.system("ps -o pcpu %d > .cpu" % self.pid)
fd = open(".cpu", "rb")
data = fd.read()
fd.close()
self.unlink(".cpu")
cpu = re.search(r"\s*(\d+\.\d+)", data).group(1)
if cpu.startswith("0."):
time.sleep(1)
print("osx.Process: PCPU is low (%s), stopping process" % cpu)
self._StopProcess()
return False
except:
print(sys.exc_info())
return True
else:
return False
return None
def unlink(self, file):
try:
os.unlink(file)
except:
pass
def _StartProcess(self):
if self._isRunning():
return
self.currentCount += 1
# OS X can get very unstable during testing. This will hopefully
# allow for longer fuzzing runs by killing off some processes
# that seem to get "stuck"
if self.currentCount % self.restartFinger == 0:
os.system('killall -KILL Finder')
os.system('killall -KILL Dock')
os.system('killall -KILL SystemUIServer')
# If no command is specified, assume we are running
# exc_handler some other way.
if self.Command is None:
return
args = [self.Command]
splitArgs = self.Arguments.split(" ")
for i in range(len(splitArgs)):
if i > 0 and splitArgs[i - 1][-1] == '\\':
args[-1] = args[-1][:-1] + " " + splitArgs[i]
else:
args.append(splitArgs[i])
print("osx.Process._StartProcess(): %s" % args)
self.pid = os.spawnv(os.P_NOWAIT, self.Command, args)
time.sleep(1.5)
print("osx.Process: pid: %d" % self.pid)
def _StopProcess(self):
if self.pid is not None:
try:
# Verify if process is still running
(pid1, ret) = os.waitpid(self.pid, os.WNOHANG)
if not (pid1 == 0 and ret == 0):
self.pid = None
return
except:
return
try:
# Kill process with signal
os.kill(self.pid, signal.SIGTERM)
time.sleep(0.25)
os.kill(self.pid, signal.SIGKILL)
except:
pass
# Prevent Zombies!
os.wait()
self.pid = None
def _IsRunning(self):
if self.pid is not None:
try:
(pid1, ret) = os.waitpid(self.pid, os.WNOHANG)
if pid1 == 0 and ret == 0:
print("osx.Process._IsRunning: True")
return True
except:
pass
print("osx.Process._IsRunning: False")
return False