This repository has been archived by the owner on Jun 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
bruteforcescan.py
2394 lines (2173 loc) · 79.8 KB
/
bruteforcescan.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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
## Binary Analysis Tool
## Copyright 2009-2016 Armijn Hemel for Tjaldur Software Governance Solutions
## Licensed under Apache 2.0, see LICENSE file for details
'''
This script tries to analyse binary blobs, using a "brute force" approach
The script has a few separate scanning phases:
1. marker scanning phase, to search for specific markers (compression, file
systems, media formats), if available. This information is later used to filter
scans and to find the start/end of embedded files and carve them out from a
larger binary blob.
2. prerun phase for tagging files. This is a first big rough sweep to determine
what files are to prevent spending too much time on useless scanning in the
following phases. Some things that tagged in this phase (by some of the BAT
default scans) are text files, XML files, various graphics formats and some
other files.
3. unpack phase for unpacking files. In this phase several methods for
unpacking files are run, using the information from the marker scanning phase
if applicable. Also some simple metadata about files is recorded in this phase.
This method runs recursively: if a file system was found and unpacked all the
scans from steps 1, 2, 3 are run on the files that were unpacked.
4. individual file scanning phase. In this phase each file will be inspected
individually. There are many different scans in BAT, like extraction of
markers, and so on.
5. aggregate file scanning phase. In this phase all files are inspected in
context, because some information only makes sense in context, for example
ELF dynamic linking analysis.
6. postrun phase. In this phase methods that just process results of earlier
scans, but which do not modify the results or add to the results are run, such
as generating pictures or creating reports.
7. packing phase. In this phase several datafiles, plus the state of the
running program, are packed in a tar file.
'''
## import a few standard Python modules
import sys, os, os.path, hashlib, subprocess, tempfile, shutil, stat, multiprocessing
import platform, cPickle, glob, tarfile, copy, gzip, Queue
from optparse import OptionParser
import datetime, re, struct, ConfigParser
from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
## import the Python magic module
## NOTE: there are various incompatible python-magic modules
import magic
## import the PostgreSQL connection module
import psycopg2
## finally import a few BAT specific modules
import extractor, prerun, fsmagic
## load the magic library. Some versions of libmagic are too old
## to have the NO_CHECK_CDF magic flag, which might be problematic
## with some files.
try:
ms = magic.open(magic.MAGIC_NO_CHECK_CDF|magic.MAGIC_NONE)
except:
ms = magic.open(magic.MAGIC_NONE)
ms.load()
## Try to load the TLSH module if available, else disable TLSH
## scanning, as TLSH is not standard on every Linux distribution.
try:
import tlsh
tlshscan = True
except Exception, e:
tlshscan = False
## Method to run a setup scan. Returns the result of the setup
## scan, which is in the form of a tuple (boolean, environment).
## The environment returned is always a dictionary, like os.environ
def runSetup(setupscan, usedatabase, cursor, conn, debug=False):
module = setupscan['module']
method = setupscan['setup']
if debug:
print >>sys.stderr, module, method
sys.stderr.flush()
if setupscan['needsdatabase'] and not usedatabase:
return (False, {})
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
return (False, {})
scanres = locals()["bat_%s" % method](setupscan['environment'], cursor, conn, debug=debug)
return scanres
## convenience method to run the genericMarkerSearch in parallel chunks if needed
def paralleloffsetsearch((filedir, filename, magicscans, optmagicscans, offset, length)):
return prerun.genericMarkerSearch(os.path.join(filedir, filename), magicscans, optmagicscans, offset, length)
## method to filter scans, based on the tags that were found for a
## file, plus a list of tags that the scan should skip.
## This is done to avoid scans running unnecessarily.
def filterScans(scans, tags):
filteredscans = []
for scan in scans:
if scan['scanonly'] != None:
scanonly = scan['scanonly'].split(':')
if set(tags).intersection(set(scanonly)) == set():
continue
if scan['noscan'] != None:
noscans = scan['noscan'].split(':')
if set(noscans).intersection(set(tags)) != set():
continue
else:
filteredscans.append(scan)
else:
filteredscans.append(scan)
return filteredscans
## compute a SHA256, and possibly other hashes as well. This is done in chunks
## to prevent a big file from being read in its entirety at once, slowing down
## the machine.
def gethash(filepath, filename, hashtypes, tlshmaxsize):
hashestocompute = set()
## always compute SHA256
hashestocompute.add('sha256')
for hashtype in hashtypes:
hashestocompute.add(hashtype)
hashresults = {}
## initiate new hashing objects, except for CRC32
## and TLSH, which need to be treated slightly differently
hashdict = {}
for h in hashestocompute:
if h == 'crc32' or h == 'tlsh':
continue
hashdict[h] = hashlib.new(h)
scanfile = open(os.path.join(filepath, filename), 'rb')
scanfile.seek(0)
hashdata = scanfile.read(10000000)
while hashdata != '':
for h in hashestocompute:
## CRC32 is not yet supported, TLSH is
## processed later
if h == 'crc32' or h == 'tlsh':
continue
hashdict[h].update(hashdata)
hashdata = scanfile.read(10000000)
scanfile.close()
for h in hashestocompute:
if h == 'crc32' or h == 'tlsh':
continue
hashresults[h] = hashdict[h].hexdigest()
filesize = os.stat(os.path.join(filepath, filename)).st_size
## compute TLSH, as long as it is not too big (determined by tlshmaxsize)
if 'tlsh' in hashestocompute:
if tlshscan:
if filesize >= 256 and filesize <= tlshmaxsize:
scanfile = open(os.path.join(filepath, filename), 'rb')
scanfile.seek(0)
hashdata = scanfile.read()
scanfile.close()
hashresults['tlsh'] = tlsh.hash(hashdata)
else:
hashresults['tlsh'] = None
return hashresults
## continuously grab tasks (files) from a queue, tag ('prerun phase'), possibly unpack
## and recurse ('unpack'). Then run different scans per file ('leaf').
def scan(scanqueue, reportqueue, scans, leafscans, prerunscans, prerunignore, prerunmagic, magicscans, optmagicscans, processid, hashdict, llock, template, unpacktempdir, topleveldir, tempdir, outputhash, cursor, conn, scansourcecode, dumpoffsets, offsetdir, compressed, timeout, scan_binary_basename, tlshmaxsize):
lentempdir = len(tempdir)
sourcecodequery = "select checksum from processed_file where checksum=%s limit 1"
## import all methods defined in the scans, once per thread
## ignore all scans that cannot be loaded successfully
blacklistscans = set()
for prerunscan in prerunscans:
module = prerunscan['module']
method = prerunscan['method']
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
blacklistscans.add((module, method))
continue
for unpackscan in scans:
module = unpackscan['module']
method = unpackscan['method']
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
blacklistscans.add((module, method))
continue
for leafscan in leafscans:
module = leafscan['module']
method = leafscan['method']
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
blacklistscans.add((module, method))
continue
## grab tasks from the queue continuously until there are no more tasks left
while True:
## reset the reports, blacklist, offsets and tags for each new scan
blacklist = []
(dirname, filename, lenscandir, debug, tags, scanhints, offsets) = scanqueue.get(timeout=timeout)
if debug:
## record the time when processing of the file started
## in case debugging is enabled.
starttime = datetime.datetime.utcnow().isoformat()
## absolute path of the file in the file system (so including temporary dir)
filetoscan = os.path.join(dirname, filename)
## path of the file relative to the temporary dir
relfiletoscan = filetoscan[lentempdir:]
if relfiletoscan.startswith('/'):
relfiletoscan = relfiletoscan[1:]
## initialize the result dictionary
unpackreports = {}
unpackreports['name'] = filename
## use libmagic to find out the 'magic' of the file for reporting
## It cannot properly handle file names with 'exotic' encodings,
## so wrap it in a try statement and provide a default value of
## 'data'.
magic = 'data'
try:
magic = ms.file(filetoscan)
except Exception, e:
## libmagic could not handle it, likely because of an encoding
## issue (name with 'weird' characters, so try to workaround the
## problem. In case of a regular file (anything but a link) copy
## the file to a temporary location with a file name that libmagic
## will be able to handle.
if not os.path.islink(filetoscan):
tmpmagic = tempfile.mkstemp()
os.fdopen(tmpmagic[0]).close()
shutil.copy(filetoscan, tmpmagic[1])
magic = ms.file(tmpmagic[1])
os.unlink(tmpmagic[1])
else:
## TODO: create a better value for 'magic'
magic = 'symbolic link'
unpackreports['magic'] = magic
## Add both the path to indicate the position inside the file sytem
## or file that was unpacked, as well as the position of the files as unpacked
## by BAT, convenient for later analysis of binaries.
## In case of squashfs remove the "squashfs-root" part of the temporary
## directory too, if it is present (not always).
## TODO: validate if this is stil needed
storepath = dirname[lenscandir:].replace("/squashfs-root", "")
unpackreports['path'] = storepath
unpackreports['realpath'] = dirname
unpackreports['relativename'] = relfiletoscan
## if the file is a symbolic link, then there is not much
## to report about it, so continue.
if os.path.islink(filetoscan):
tags.append('symlink')
unpackreports['tags'] = tags
reportqueue.put({relfiletoscan: unpackreports})
scanqueue.task_done()
continue
## no use to further check pipes, sockets, device files, etcetera
if not os.path.isfile(filetoscan) and not os.path.isdir(filetoscan):
reportqueue.put({relfiletoscan: unpackreports})
scanqueue.task_done()
continue
## store the size of the file
filesize = os.lstat(filetoscan).st_size
unpackreports['size'] = filesize
## empty file, not interested in further scanning
if filesize == 0:
tags.append('empty')
unpackreports['tags'] = tags
reportqueue.put({relfiletoscan: unpackreports})
scanqueue.task_done()
continue
## Store the hash of the file for identification and for possibly
## querying the knowledgebase later on.
filehashresults = gethash(dirname, filename, [outputhash, 'sha1', 'md5', 'tlsh'], tlshmaxsize)
unpackreports['checksum'] = filehashresults[outputhash]
for u in filehashresults:
unpackreports[u] = filehashresults[u]
filehash = filehashresults[outputhash]
exactmatches = []
seenbefore = False
if cursor != None:
cursor.execute("select pathname, parentname, parentchecksum from batresult where checksum=%s", (filehash,))
res = cursor.fetchall()
if res != []:
seenbefore = True
for r in res:
exactmatches.append(res)
blacklistedfiles = []
if cursor != None:
pass
## blacklisted file, not interested in further scanning
if filehash in blacklistedfiles:
tags.append('blacklisted')
unpackreports['tags'] = tags
reportqueue.put({relfiletoscan: unpackreports})
scanqueue.task_done()
continue
## acquire the lock for the shared dictionary to see if this file was already
## scanned, or is in the process of being scanned.
llock.acquire()
if filehash in hashdict:
llock.release()
## if the hash is already there mark it as a
## duplicate and stop scanning.
unpackreports['tags'] = ['duplicate']
reportqueue.put({relfiletoscan: unpackreports})
scanqueue.task_done()
continue
else:
## add the file to the shared dictionary
hashdict[filehash] = relfiletoscan
llock.release()
## look up the file in the BAT database to see if it is
## a known source code file.
if scansourcecode:
cursor.execute(sourcecodequery, (filehash,))
fetchres = cursor.fetchone()
if fetchres != None:
tags.append('inbatdb')
tags.append('sourcecode')
## first see if a shortcut can be taken to unpack the file
## directly based on its extension.
unpacked = False
knownfile = False
if 'knownfile' in scanhints:
knownfile = scanhints['knownfile']
unpacked = True
else:
blacklistignorescans = set()
if "blacklistignorescans" in scanhints:
blacklistignorescans = scanhints['blacklistignorescans']
for unpackscan in scans:
if not 'knownfilemethod' in unpackscan:
continue
fileextensions = filename.lower().rsplit('.', 1)
if len(fileextensions) != 2:
continue
fileextension = fileextensions[1]
if not fileextension in unpackscan['extensions']:
continue
module = unpackscan['module']
method = unpackscan['knownfilemethod']
if 'minimumsize' in unpackscan:
if filesize < unpackscan['minimumsize']:
continue
if debug:
print >>sys.stderr, module, method, filetoscan, datetime.datetime.utcnow().isoformat()
sys.stderr.flush()
## make a copy before changing the environment
newenv = copy.deepcopy(unpackscan['environment'])
if template != None:
templen = len(re.findall('%s', template))
if templen == 2:
newenv['TEMPLATE'] = template % (os.path.basename(filetoscan), unpackscan['name'])
elif templen == 1:
newenv['TEMPLATE'] = template % unpackscan['name']
else:
newenv['TEMPLATE'] = template
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
continue
## run the known unpack method
scanres = eval("bat_%s(filetoscan, tempdir, newenv, debug=debug)" % (method))
if scanres == ([], [], [], {}):
## no result, so move on to the next scan
continue
(diroffsets, blacklist, scantags, hints) = scanres
newblacklist = []
for b in blacklist:
if len(b) == 2:
b = b + (unpackscan['name'],)
newblacklist.append(b)
blacklist = newblacklist
tags = list(set(tags + scantags))
knownfile = True
unpacked = True
unpackreports['scans'] = []
## special case: the whole file was unpacked and blacklisted
## but 'blacklistignorescans' was set. Resubmitting into the queue is
## not a possibility
if len(diroffsets) == 0:
if filetoscan in hints:
if 'blacklistignorescans' in hints[filetoscan]:
blacklistignorescans = hints[filetoscan]['blacklistignorescans']
## Add all the files found to the scan queue
## each diroffset is a (path, offset) tuple
for diroffset in diroffsets:
if diroffset == None:
continue
report = {}
scandir = diroffset[0]
## recursively scan all files in the directory
osgen = os.walk(scandir)
scanreports = []
try:
while True:
i = osgen.next()
## make sure all directories can be accessed
for d in i[1]:
directoryname = os.path.join(i[0], d)
if not os.path.islink(directoryname):
os.chmod(directoryname, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
for p in i[2]:
leaftags = []
filepathname = os.path.join(i[0], p)
try:
if not os.path.islink(filepathname):
os.chmod(filepathname, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
scannerhints = {}
if filepathname in hints:
if 'tags' in hints[filepathname]:
leaftags = list(set(leaftags + hints[filepathname]['tags']))
if 'scanned' in hints[filepathname]:
if hints[filepathname]['scanned']:
scannerhints['knownfile'] = True
for sc in hints[filepathname]:
scannerhints[sc] = copy.deepcopy(hints[filepathname][sc])
if "temporary" in tags and diroffset[1] == 0 and diroffset[2] == filesize:
leaftags.append('temporary')
scantask = (i[0], p, len(scandir), debug, leaftags, scannerhints, {})
scanqueue.put(scantask)
relscanpath = "%s/%s" % (i[0][lentempdir:], p)
if relscanpath.startswith('/'):
relscanpath = relscanpath[1:]
scanreports.append(relscanpath)
except Exception, e:
pass
except StopIteration:
pass
unpackreports['scans'].append({'scanname': unpackscan['name'], 'scanreports': scanreports, 'offset': diroffset[1], 'size': diroffset[2]})
break
if not knownfile or 'blacklistignorescans' in scanhints:
## scan for markers in case they are not already known
if offsets == {}:
(offsets, offsetkeys, isascii) = prerun.genericMarkerSearch(filetoscan, magicscans, optmagicscans)
if isascii:
tags.append('text')
else:
tags.append('binary')
if dumpoffsets:
## write pickles with offsets to disk
offsetpicklename = os.path.join(offsetdir, '%s-offsets.pickle' % filehash)
if compressed:
checkoffsetpicklename = "%s.gz" % offsetpicklename
else:
checkoffsetpicklename = offsetpicklename
try:
os.stat(checkoffsetpicklename)
except:
picklefile = open(offsetpicklename, 'wb')
cPickle.dump(offsets, picklefile)
picklefile.close()
## optionally compress the pickle files to save space
if compressed:
fin = open(offsetpicklename, 'rb')
fout = gzip.open("%s.gz" % offsetpicklename, 'wb')
fout.write(fin.read())
fout.close()
fin.close()
os.unlink(fin.name)
if "encrypted" in tags:
knownfile = True
blacklisted = False
if not knownfile or 'blacklistignorescans' in scanhints:
## all offsets are known now, so scans that are not needed can
## be filtered out. Also keep track of the "most promising" scans
## (offset 0) to try them first.
filterscans = set()
zerooffsets = set()
for magictype in offsets:
if offsets[magictype] != []:
filterscans.add(magictype)
if offsets[magictype][0] - fsmagic.correction.get(magictype, 0) == 0:
zerooffsets.add(magictype)
## prerun scans should be run before any of the other scans
for prerunscan in prerunscans:
ignore = False
if 'extensionsignore' in prerunscan:
extensionsignore = prerunscan['extensionsignore'].split(':')
for e in extensionsignore:
if filetoscan.endswith(e):
ignore = True
break
if ignore:
continue
if prerunscan['name'] in prerunignore:
if set(tags).intersection(set(prerunignore[prerunscan['name']])) != set():
continue
if prerunscan['name'] in prerunmagic:
if set(prerunmagic[prerunscan['name']]).intersection(filterscans) == set():
continue
module = prerunscan['module']
method = prerunscan['method']
if (module, method) in blacklistscans:
continue
if debug:
print >>sys.stderr, module, method, filetoscan, datetime.datetime.utcnow().isoformat()
sys.stderr.flush()
scantags = locals()['bat_%s' % method](filetoscan, cursor, conn, tempdir, tags, offsets, prerunscan['environment'], debug=debug, unpacktempdir=unpacktempdir, filehashes=filehashresults)
## append the tag results. These will be used later to be able to specifically filter
## out files
if scantags != []:
tags = tags + scantags
## Reorder the scans based on information about offsets. If one scan has a
## match for offset 0 (after correction of the offset, like for tar, gzip,
## iso9660, etc.) make sure it is run first (not enabled now, unsafe in some
## cases).
unpackscans = []
scanfirst = []
## Filter scans
filteredscans = filterScans(scans, tags)
for unpackscan in filteredscans:
## filter the scan again as the tags might have changed
if unpackscan['noscan'] != None:
noscans = unpackscan['noscan'].split(':')
if set(noscans).intersection(set(tags)) != set():
continue
if unpackscan['magic'] != None:
scanmagic = unpackscan['magic'].split(':')
if set(scanmagic).intersection(filterscans) != set():
if set(scanmagic).intersection(zerooffsets) != set():
if unpackscan['name'] != 'lzma':
scanfirst.append(unpackscan)
else:
unpackscans.append(unpackscan)
else:
unpackscans.append(unpackscan)
else:
unpackscans.append(unpackscan)
## sort 'unpackscans' in decreasing priority, so highest
## priority scans are run first.
unpackscans = sorted(unpackscans, key=lambda x: x['priority'], reverse=True)
## prepend the most promising scans at offset 0 (if any)
scanfirst = sorted(scanfirst, key=lambda x: x['priority'], reverse=True)
unpackscans = scanfirst + unpackscans
unpackreports['scans'] = []
blacklistignorescans = set()
if "blacklistignorescans" in scanhints:
blacklistignorescans = scanhints['blacklistignorescans']
unpacked = False
for unpackscan in unpackscans:
blacklistignored = False
if extractor.inblacklist(0, blacklist) == filesize:
## the whole file has already been scanned by other scans, so
## continue with the leaf scans.
blacklisted = True
if len(blacklistignorescans) == 0:
break
if not unpackscan['name'] in blacklistignorescans:
continue
## store a copy of the old blacklist
blacklistignored = True
oldblacklist = copy.deepcopy(blacklist)
blacklist = []
if 'minimumsize' in unpackscan:
if filesize < unpackscan['minimumsize']:
continue
if unpackscan['noscan'] != None:
noscans = unpackscan['noscan'].split(':')
if list(set(tags).intersection(set(noscans))) != []:
continue
ignore = False
if 'extensionsignore' in unpackscan:
extensionsignore = unpackscan['extensionsignore'].split(':')
for e in extensionsignore:
if filetoscan.endswith(e):
ignore = True
break
if ignore:
continue
module = unpackscan['module']
method = unpackscan['method']
if (module, method) in blacklistscans:
continue
if debug:
print >>sys.stderr, module, method, filetoscan, datetime.datetime.utcnow().isoformat()
sys.stderr.flush()
## make a copy before changing the environment
newenv = copy.deepcopy(unpackscan['environment'])
newenv['BAT_UNPACKED'] = unpacked
if template != None:
templen = len(re.findall('%s', template))
if templen == 2:
newenv['TEMPLATE'] = template % (os.path.basename(filetoscan), unpackscan['name'])
elif templen == 1:
newenv['TEMPLATE'] = template % unpackscan['name']
else:
newenv['TEMPLATE'] = template
## return value is the temporary dir, plus offset in the parent file
## plus a blacklist containing blacklisted ranges for the *original*
## file and a hash with offsets for each marker.
scanres = locals()["bat_%s" % method](filetoscan, tempdir, blacklist, offsets, newenv, debug=debug)
## result is either empty, or contains offsets, blacklist, tags and hints
if len(scanres) == 0:
continue
if len(scanres) != 4:
continue
(diroffsets, blacklist, scantags, hints) = scanres
tags = list(set(tags + scantags))
if extractor.inblacklist(0, blacklist) == filesize:
blacklisted = True
## special case: the whole file was unpacked and blacklisted
## but 'blacklistignorescans' was set. Resubmitting into the queue is
## not a possibility
if len(diroffsets) == 0:
if filetoscan in hints:
if 'blacklistignorescans' in hints[filetoscan]:
blacklistignorescans = hints[filetoscan]['blacklistignorescans']
for diroffset in diroffsets:
if diroffset == None:
continue
unpacked = True
report = {}
scandir = diroffset[0]
## recursively scan all files in the directory
osgen = os.walk(scandir)
scanreports = []
try:
while True:
i = osgen.next()
## make sure all directories can be accessed
for d in i[1]:
directoryname = os.path.join(i[0], d)
if not os.path.islink(directoryname):
os.chmod(directoryname, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
for p in i[2]:
filepathname = os.path.join(i[0], p)
try:
leaftags = []
scannerhints = {}
if not os.path.islink(filepathname):
os.chmod(filepathname, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
if filepathname in hints:
if 'tags' in hints[filepathname]:
leaftags = list(set(leaftags + hints[filepathname]['tags']))
if 'scanned' in hints[filepathname]:
if hints[filepathname]['scanned']:
scannerhints['knownfile'] = True
## TODO: add offsets if available
for sc in hints[filepathname]:
scannerhints[sc] = copy.deepcopy(hints[filepathname][sc])
if "temporary" in tags and diroffset[1] == 0 and diroffset[2] == filesize:
leaftags.append('temporary')
scantask = (i[0], p, len(scandir), debug, leaftags, scannerhints, {})
scanqueue.put(scantask)
relscanpath = "%s/%s" % (i[0][lentempdir:], p)
if relscanpath.startswith('/'):
relscanpath = relscanpath[1:]
scanreports.append(relscanpath)
except Exception, e:
pass
except StopIteration:
pass
unpackreports['scans'].append({'scanname': unpackscan['name'], 'scanreports': scanreports, 'offset': diroffset[1], 'size': diroffset[2]})
newblacklist = []
for b in blacklist:
if len(b) == 2:
b = b + (unpackscan['name'],)
newblacklist.append(b)
blacklist = newblacklist
if blacklistignored:
## restore the old blacklist
blacklist = copy.deepcopy(oldblacklist)
## add anything new
for b in newblacklist:
blacklist.append(b)
blacklist.sort()
carveout = False
if carveout and not (blacklisted or knownfile):
if blacklist != []:
## TODO: make configurable
if not 'elf' in tags:
counter = 1
byteoffset = 0
prevblacklist = (0,0)
origfile = open(filetoscan, 'r')
for r in range(0, len(blacklist)):
b = blacklist[r]
if byteoffset == b[0]:
byteoffset = b[1]
prevblacklist = b
continue
origfile.seek(prevblacklist[1])
try:
tmpdir = "%s/%s-%s-%s" % (os.path.dirname(filetoscan), os.path.basename(filetoscan), "carveout", counter)
os.makedirs(tmpdir)
carveoutfile = open(os.path.join(tmpdir, "carveout"), 'w')
carveoutfile.write(origfile.read(b[0] - prevblacklist[1]))
carveoutfile.close()
## now write the data
counter += 1
except Exception, e:
break
byteoffset = b[1]
prevblacklist = b
if filesize > byteoffset:
try:
origfile.seek(prevblacklist[1])
tmpdir = "%s/%s-%s-%s" % (os.path.dirname(filetoscan), os.path.basename(filetoscan), "carveout", counter)
os.makedirs(tmpdir)
carveoutfile = open(os.path.join(tmpdir, "carveout"), 'w')
carveoutfile.write(origfile.read(filesize - prevblacklist[1]))
carveoutfile.close()
## now write the data
counter += 1
except Exception, e:
pass
origfile.close()
unpackreports['tags'] = tags
if not unpacked and 'temporary' in tags:
os.unlink(filetoscan)
reportqueue.put({relfiletoscan: unpackreports})
else:
reports = {}
## First compute the closest
## a threshold for TLSH for the files to be considered similar.
## TODO: make configurable
tlshthreshold = 60
closestfile = None
if cursor != None:
if tlshscan and not seenbefore:
if 'tlsh' in filehashresults:
if filehashresults['tlsh'] != None:
tlshminimum = sys.maxint
decoded = False
for i in ['utf-8','ascii','latin-1','euc_jp', 'euc_jis_2004', 'jisx0213', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr','shift_jis','shift_jis_2004','shift_jisx0213']:
try:
decodefilename = u.decode(i)
decoded = True
break
except Exception, e:
pass
if decoded:
cursor.execute("select tlsh, pathname, parentname, parentchecksum from batresult where filename=%s", (decodefilename,))
else:
cursor.execute("select tlsh, pathname, parentname, parentchecksum from batresult where filename=%s", (filename,))
res = cursor.fetchall()
for r in res:
(tlshchecksum, tlshpathname, parentname, parentchecksum) = r
if tlshchecksum == None:
continue
tlshdistance = tlsh.diff(filehashresults['tlsh'], tlshchecksum)
if tlshdistance < tlshminimum:
tlshminimum = tlshdistance
if tlshminimum < tlshthreshold:
closestfile = (tlshpathname, parentname, tlshdistance)
if closestfile != None:
reports['closematch'] = closestfile
tags.append('closematch')
if seenbefore:
reports['exactbinarymatches'] = exactmatches
tags.append('exactbinarymatch')
## run the leaf scans for the file
for leafscan in filterScans(leafscans, tags):
## filter the scan again as the tags might have changed
if leafscan['noscan'] != None:
noscans = leafscan['noscan'].split(':')
if set(noscans).intersection(set(tags)) != set():
continue
ignore = False
if 'extensionsignore' in leafscan:
extensionsignore = leafscan['extensionsignore'].split(':')
for e in extensionsignore:
if filetoscan.endswith(e):
ignore = True
break
if ignore:
continue
report = {}
module = leafscan['module']
method = leafscan['method']
if (module, method) in blacklistscans:
continue
scandebug = False
if 'debug' in leafscan:
scandebug = True
debug = True
if debug:
print >>sys.stderr, module, method, filetoscan, datetime.datetime.utcnow().isoformat()
sys.stderr.flush()
scandebug = True
res = eval("bat_%s(filetoscan, tags, cursor, conn, filehashresults, blacklist, leafscan['environment'], scandebug=scandebug, unpacktempdir=unpacktempdir)" % (method))
if res != None:
(nt, leafres) = res
reports[leafscan['name']] = leafres
tags += list(set(tags + nt))
reports['tags'] = list(set(tags))
unpackreports['tags'] = list(set(unpackreports['tags'] + reports['tags']))
## write pickles with information to disk here to reduce memory usage
try:
os.stat('%s/filereports/%s-filereport.pickle' % (topleveldir,filehash))
except Exception, e:
picklefile = open('%s/filereports/%s-filereport.pickle' % (topleveldir,filehash), 'wb')
cPickle.dump(reports, picklefile)
picklefile.close()
reportqueue.put({relfiletoscan: unpackreports})
if debug:
print >>sys.stderr, "DONE", filetoscan, starttime, datetime.datetime.utcnow().isoformat()
sys.stderr.flush()
scanqueue.task_done()
def aggregatescan(unpackreports, aggregatescans, processors, scantempdir, topleveldir, scan_binary, scandate, batcursors, batcons, debug, unpacktempdir):
## aggregate scans look at the entire result and possibly modify it.
## The best example is JAR files: individual .class files will not be
## very significant (or even insignificant), but combined results are.
## Because aggregate scans have to look at everything as a whole, these
## cannot be run in parallel.
statistics = {}
for aggregatescan in aggregatescans:
module = aggregatescan['module']
method = aggregatescan['method']
scandebug = False
if 'debug' in aggregatescan:
scandebug = True
debug = True
starttime = datetime.datetime.utcnow()
if debug:
print >>sys.stderr, "AGGREGATE BEGIN", module, method, starttime.isoformat()
sys.stderr.flush()
scandebug = True
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
continue
res = eval("bat_%s(unpackreports, scantempdir, topleveldir, processors, aggregatescan['environment'], batcursors, batcons, scandebug=scandebug, unpacktempdir=unpacktempdir)" % (method))
if res != None:
if res.keys() != []:
filehash = unpackreports[scan_binary]['checksum']
leaf_file_path = os.path.join(topleveldir, "filereports", "%s-filereport.pickle" % filehash)
leaf_file = open(leaf_file_path, 'rb')
leafreports = cPickle.load(leaf_file)
leaf_file.close()
for reskey in set(res.keys()):
leafreports[reskey] = res[reskey]
unpackreports[scan_binary]['tags'].append(reskey)
leafreports['tags'].append(reskey)
leaf_file = open(leaf_file_path, 'wb')
leafreports = cPickle.dump(leafreports, leaf_file)
leaf_file.close()
endtime = datetime.datetime.utcnow()
if debug:
print >>sys.stderr, "AGGREGATE END", method, endtime.isoformat()
statistics[method] = endtime - starttime
return statistics
## continuously grab tasks (files) from a queue and process
def postrunscan(scanqueue, postrunscans, topleveldir, scantempdir, cursor, conn, debug, timeout):
## import all methods defined in the scans
blacklistscans = set()
extensionsignore = []
for postrunscan in postrunscans:
module = postrunscan['module']
method = postrunscan['method']
try:
exec "from %s import %s as bat_%s" % (module, method, method)
except Exception, e:
blacklistscans.add((module, method))
continue
ignore = False
if 'extensionsignore' in postrunscan:
extensionsignore = postrunscan['extensionsignore'].split(':')
## grab tasks from the queue continuously until there are no more tasks
while True:
(filetoscan, unpackreports) = scanqueue.get(timeout=timeout)
ignore = False
for e in extensionsignore:
if filetoscan.endswith(e):
ignore = True
break
if ignore:
scanqueue.task_done()
continue
for postrunscan in postrunscans:
module = postrunscan['module']
method = postrunscan['method']
res = eval("bat_%s(filetoscan, unpackreports, scantempdir, topleveldir, postrunscan['environment'], cursor, conn, debug=debug)" % (method))
## TODO: find out what to do with this
if res != None:
pass
scanqueue.task_done()
## process a single configuration section
def scanconfigsection(config, section, scanenv, batconf):
if config.has_option(section, 'type'):
debug = False
mandatory = False
## some scans are mandatory
if not config.has_option(section, 'mandatory'):
if config.get(section, 'enabled') == 'yes':
mandatory = True
## scans have to be explicitely enabled
if not config.has_option(section, 'enabled'):
return
if config.get(section, 'enabled') == 'no':
if not mandatory:
return
else:
## TODO: figure out the cleanest way to
## handle this, probably passing some
## error message back
return
conf = {}
try:
conf['module'] = config.get(section, 'module')
conf['method'] = config.get(section, 'method')
except Exception, e:
return
## some scans might, or might not, have these defined
try:
conf['name'] = config.get(section, 'name')