summaryrefslogtreecommitdiff
path: root/suspicious
blob: 3a4d0568c3938bdb213810e5736d4d5e65e31647 (plain)
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
#!/usr/bin/python3

# Copyright 2014, 2016 Software Freedom Law Center (www.softwarefreedom.org)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Authors: Marc Jones <mjones@softwarefreedom.org>, 
#          Daniel Gnoutcheff <gnoutchd@softwarefreedom.org>
# Date: October 2017
# Version 0.4.0
# Use YAML for summary files

##TODO
#need to verify that word score counts each instance, not just 0 or 1
#need to discount found words if they are substrings of common strings in text
 
from optparse import OptionParser
import os
import os.path
import re
import sys
import datetime
import string
import subprocess
import chardet

from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

import avfs

report = {}
wordscore = {}
filescore = {}
filelist = list()
skipped = 0
opened = 0
datasize = 0
progresstext = "" 



fsencoding = sys.getfilesystemencoding()
def fsdecode_display(bytestring):
	return str(bytestring, encoding=fsencoding, errors='replace')


_def_file_encoding = sys.getdefaultencoding()

def decode_file(filename):
	"""
	Return the contents of the file at the given path as a (Unicode) string.
	Return None if the file appears to be a binary.
	"""

	with avfs.open(filename, 'rb') as filehandle:
		contents_raw = filehandle.read()
	
	try:
		return str(contents_raw, encoding=_def_file_encoding)
	except UnicodeDecodeError:
		pass
	
	guessed_encoding = chardet.detect(contents_raw)['encoding']
	if not guessed_encoding:
		return None
	
	try:
		return str(contents_raw, encoding=guessed_encoding)
	except UnicodeDecodeError:
		return None
	
def sortscore(score, reverse=True):
	sortedscore = sorted(score.items(), key=lambda score: score[1], reverse=reverse)
	returnscore = []
	for s in sortedscore:
		if s[1] > 0:
			returnscore.append(s)
	
	return returnscore

def printscore(report):
	for filename, filescore in report:
		print(filename + ':' + str(filescore))

def scorewords(report):
	for file in report.keys():
		for word in report[file].keys():
			if not word in wordscore:
				wordscore[word] = 0
			if not file in filescore:
				filescore[file] = 0
			wordscore[word] += report[file][word]
	return wordscore

def weightreport(report, commonwords):
	notsuspiciousfiles = []
	weightedout = 0
	for file in report:
		suspicious = False
		filescore = 0
		for word in report[file]:
		        filescore += report[file][word]
		if filescore > 0:
		        for word in report[file]:
		                if report[file][word] > 0 and not word in commonwords:
			                suspicious = True
		if not suspicious and filescore > 0:
		        notsuspiciousfiles.append(file)

	for file in notsuspiciousfiles:
		report.pop(file)
		weightedout +=1

	return report, weightedout

def scorefile(report):
	for file in report.keys():
		for word in report[file].keys():
			if not word in wordscore:
				wordscore[word] = 0
			if not file in filescore:
				filescore[file] = 0
			filescore[file] += report[file][word]
	return filescore

def summary(report):
	filescore = scorefile(report)
	text = ""
	for filename, filescore in sortscore(filescore):
		text += filename + '(' + str(filescore) + '):'
		for word, wordfreq in report[filename].items():
			if wordfreq > 0:
				text += word + '(' + str(wordfreq) + ');' 
		text += '\n'
	return text

def wholeword(word, string):
	re.purge()
	matches = []
	
	if word.isdigit():
		int(word)
		regexNum = r'([^0-9]|\b)(' + word + r')([^0-9]|\b)'
		mN = re.search(regexNum, string)
		if "groups" in dir(mN):
			matches.append(mN.groups())
	
	else:
		regexU = r'([A-Z]|[^a-zA-Z]|\b)(' + word.lower() + r')([A-Z]|[^a-zA-Z]|\b)'
		regexL = r'([a-z]|[^a-zA-Z]|\b)(' + word.upper() + r')([a-z]|[^a-zA-Z]|\b)'
		mU = re.search(regexU, string)
		if "groups" in dir(mU):
			matches.append(mU.groups())
		re.purge()
		mL = re.search(regexL, string)
		if "groups" in dir(mL):
			matches.append(mL.groups())
	return matches

def skipfile(filename,skippedexts):
	if not isinstance(skippedexts, list):
		return False
	for skip in skippedexts:
		if filename.endswith(skip):
			return True
	return False

def scoretext(wordlist, text, maxwholewordlen = -1):
	score = {}
	ltext = text.lower()
	for word in wordlist:
		wordreg = word.replace('-', ' ')
		wordreg = wordreg.replace(' ', '['+string.punctuation+' ]?')
		if int(len(word)) > int(maxwholewordlen):
			matches = [] 
			m = re.search(wordreg.lower(),ltext)
			if "groups" in dir(m):
				matches.append(m.groups())
			score[word] = len(matches)			
		else:
			score[word] = len(wholeword(wordreg,text))
	return score

usage = "%prog [options] DIRECTORY ... DIRECTORYN"
epilog = "example: ./suspicious ../gitcheckout -s .tar -s .gz -s .bmp -s .zip -s .ppt -s .docx -s .pdf -s .xls -s .xlsx -s .gif -s .png -s .jpg -s .css -r fw -w cryptology.txt -c -p -l 3"
parser = OptionParser(usage = usage, epilog = epilog)
parser.add_option("-w", "--wordlist", 
		dest="wordlistfilename", 
		help="file containing all of the words to look for")
parser.add_option("-s", "--skip", 
		dest="skipfileextensions", 
		help="file extensions to skip", 
		action="append")
parser.add_option("-v", "--verbose", 
		dest="verbose", 
		help="print verberose information", 
		default=False, 
		action="store_true")
parser.add_option("-r", "--report", 
		dest="printreport", 
		default="wf", 
		help="print score")
parser.add_option("--show-wordlist", 
		dest="show_wordlist", 
		default=False, 
		help="print list of words to detect", 
		action="store_true")
parser.add_option("-c", "--display-counts", 
		dest="display_counts", 
		default=False, 
		help="Show the number of files processed", 
		action="store_true")
parser.add_option("-p", "--display_progress", 
		dest="display_progress", 
		default=False, 
		help="show percentage complete", 
		action="store_true")
parser.add_option("-l", "--max-wholeword-length", 
		dest="maxwholewordlength", 
		type="int", 
		default=-1, 
		help="maximun length of a word allowed to only find matches on whole word")
parser.add_option("-o", "--summary-file", 
		dest="summaryfile", 
		help="name of the file to store the summary in")
parser.add_option("-x", "--display-summary", 
		dest="displaysummary", 
		default=False, 
		help="Display a summary from the summary file", 
		action="store_true")
parser.add_option("-X", "--dont-display-summary", 
		dest="dontdisplaysummary", 
		default=False, 
		help="Dont Display a summary after running a scan", 
		action="store_true")
parser.add_option("-k", "--commonwords", 
		dest="commonwordfilename", 
		help="file containing commmon words that allow do not indicate a suspicious file")
parser.add_option("-t", "--test", 
		dest="test", 
		default=False, 
		help="Run internal tests on pattern matching", 
		action="store_true")
parser.add_option("--donotoptimizewordlist",
                dest="optimizewordlist",
                default=True,
                help="Reduce the number of words to look for by removing words from the wordlist that contain other words on the list as substrings",
                action="store_false")
parser.add_option("--dontweightreport",
                dest="dontweightreport",
                default=False,
                help="If the only suspicious words in a file are common words, remove the file from the report",
                action="store_true")

(options, args) = parser.parse_args()

if options.wordlistfilename:
	wordlist = list(set(open(options.wordlistfilename).read().lower().strip().split('\n')))

if options.commonwordfilename:
	commonwords = list(set(open(options.commonwordfilename).read().lower().strip().split('\n')))
	
if options.optimizewordlist and options.wordlistfilename:
    for word in wordlist:
        if len(word) > options.maxwholewordlength:
            for check_word in wordlist:
                if check_word.find(word)> 0:
#                    print word + " in " + check_word
                    wordlist.remove(check_word)
                    break

if options.show_wordlist: print(wordlist); exit()

if options.displaysummary and options.summaryfile:
	report = dict()
	try:
		summaryfile = open(options.summaryfile)
	except:
		print("no summary file: " + options.summaryfile)
		exit()
	report = load(summaryfile, Loader=Loader)

	if options.commonwordfilename and not(options.dontweightreport):
		report, weightedfiles = weightreport(report, commonwords)

	if options.printreport:
		if options.printreport == "f":
			printscore(sortscore(scorefile(report)))
		elif options.printreport == "w":
			printscore(sortscore(scorewords(report)))
		elif options.printreport == "wf" or options.printreport == "fw":
			print(summary(report))			
	else:
		print(summary(report))
	
	exit()

#Run a search if not displaying a existing report
prunedirs = {b'CVS', b'.git', b'.bzr', b'.hg', b'.svn'}
if len(args) > 0:
	for a in args:
		filelist.extend(avfs.find(os.fsencode(a), prunedirs))

start = datetime.datetime.now()
for filename_bytes in filelist:
	file = fsdecode_display(filename_bytes)
	if skipfile(file, options.skipfileextensions):
		skipped += 1
		continue
	try:
		filecontents = decode_file(filename_bytes)
	except OSError:
		print("failed to open: " + file)
		continue
	if filecontents is None:
		print("possible binary: " + file)
		continue
	opened +=1
	now = datetime.datetime.now()
	if options.display_progress: 
		frac_done = (opened + skipped)*1.0/len(filelist)
		est = ((now - start) / (opened + skipped)) * len(filelist)
		est_hr, est_rem = divmod(est.total_seconds(), 3600)
		est_min, est_sec = divmod(est_rem, 60)
		if len(file)> 52:
			prog_file = file.split('/')[0] + "/.../" + file.split('/')[-1]
			if len(prog_file) > 52:
				prog_file = prog_file[0:52]
		else:
			prog_file = file
		progresstext = \
			"{:6.1%}  time left: {:02.0f}:{:02.0f}:{:02.0f} {:52s}\r" \
			.format(frac_done, est_hr, est_min, est_sec, prog_file)
		print(progresstext, end='', file=sys.stderr)
	sys.stdout.flush()
	datasize += len(filecontents)		
	filenamescore = scoretext(wordlist, file, options.maxwholewordlength)
	filecontentsscore = scoretext(wordlist, filecontents, options.maxwholewordlength)
	report[file] = {}
	for k in filecontentsscore.keys():
		report[file][k] = filenamescore[k] + filecontentsscore[k]

#Clear screen of proggress text now that finished scoring file
if options.display_progress: 
	print('\r' + " " * len(progresstext) + '\r', end='', file=sys.stderr)

#Save summary as a file, but if the filename exists do not overwrite, append a number
if options.summaryfile and len(filelist) > 0 and not options.displaysummary:
	summaryfilename = options.summaryfile	
	counter = 0
	while os.path.isfile(summaryfilename):
		counter +=1
		summaryfilename = options.summaryfile + '.' + str(counter)
	try:
		if counter > 1: print("saving as " + summaryfilename + "....")
		summaryfile = open(summaryfilename, 'w+')

		summaryfile.write(dump(report, Dumper=Dumper))
		summaryfile.close()		
	except:
		print(report)
		print("error saving summary as " + summaryfilename)

if options.commonwordfilename and not(options.dontweightreport):
	report, weightedfiles = weightreport(report, commonwords)
        
if options.printreport and not options.dontdisplaysummary:
	if options.printreport == "f":
		printscore(sortscore(scorefile(report)))
	elif options.printreport == "wf" or options.printreport == "fw":
		print(summary(report))
	else:
		printscore(sortscore(scorewords(report)))

if options.display_counts:
	print("total files:" + str(len(filelist)))
	print("suspicious files:" + str(len(sortscore(scorefile(report)))))
	print("skipped files:" + str(skipped))
	if options.commonwordfilename and not(options.dontweightreport):
		print("removed weighted files:" + str(weightedfiles))
	print("searched:" + str(datasize) + 'B')
	print("time:" + str(datetime.datetime.now() - start).split('.')[0])