-
Notifications
You must be signed in to change notification settings - Fork 0
/
startweb.py
executable file
·1232 lines (1023 loc) · 32.9 KB
/
startweb.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/env python
# -*- coding: UTF-8 -*-
# coding=utf-8
from flask import Flask, render_template, request, url_for, Response, redirect, send_from_directory, abort, jsonify
import flask.ext.login as flask_login
import os
from werkzeug import secure_filename
from bson import json_util
import pymongo, json
from peewee import *
from playhouse.pool import MySQLDatabase
import threading
import sys
from dateutil.parser import parse as dateParser
from datetime import datetime
import time
import pytz
# sys.path.insert(0, '/home/ikko/repo/mdpdp/')
import importer
from reversediff import findCommon
connection=pymongo.MongoClient("localhost",27017,tz_aware=True)
MDPMongoDB=connection.MDPDP
col_behavior=MDPMongoDB.behavior_PE
col_enginediff=MDPMongoDB.enginediff_PE
login_manager=flask_login.LoginManager()
count=0
database = MySQLDatabase('MEDDB', **{'password': 'qwe123', 'user': 'asduser03'})
users={'foo@bar.tld':{'pw':'secret'}}
app=Flask(__name__)
# print "my path:",
# app.config['MDPDP_BASEDIR']='/home/ikko/repo/mdpdp'
MDPDP_BASEDIR=os.path.dirname(os.path.realpath(__file__))
# print "my path:",MDPDP_BASEDIR
app.config['ZIP_UPLOAD_DIR']=os.path.join(MDPDP_BASEDIR,'upload/zip/')
app.config['CSV_UPLOAD_DIR']=os.path.join(MDPDP_BASEDIR,'upload/csv/')
application=app
login_manager.init_app(app)
# with app.request_context(environ):
# assert request.method == 'POST'
class UnknownField(object):
pass
class BaseModel(Model):
class Meta:
database = database
class MedFile(BaseModel):
av_scan = TextField(db_column='AV_Scan')
ctime = DateTimeField(db_column='CTIME')
file_name = TextField(db_column='File_Name')
file_tag = CharField(db_column='File_Tag')
md5_key = CharField(db_column='MD5_Key', index=True)
mdp_rule = TextField(db_column='MDP_Rule')
report_pc_count = IntegerField(db_column='REPORT_PC_Count')
result_number = TextField(db_column='Result_Number')
saved_size = IntegerField(db_column='Saved_Size')
sign_credit = IntegerField(db_column='Sign_Credit')
virus_name = TextField(db_column='Virus_Name')
idx = PrimaryKeyField()
class Meta:
db_table = 'med_file'
class User(flask_login.UserMixin):
pass
@login_manager.user_loader
def user_loader(email):
if email not in users:
return
user = User()
user.id = email
return user
@login_manager.request_loader
def request_loader(request):
email = request.form.get('email')
if email not in users:
return
user = User()
user.id = email
# DO NOT ever store passwords in plaintext and always compare password
# hashes using constant-time comparison!
user.is_authenticated = request.form['pw'] == users[email]['pw']
return user
def medfileSearch(md5sumlist, search, sort, order, limit, offset):
database.get_conn().ping(True)
# print "md5sumlist:", ', '.join(md5sumlist)[0:67], "...", ', '.join(md5sumlist)[-68:]
# print "md5sumlist count:", len(md5sumlist)
# print "search:", search
# print "sort:", sort
# print "order:", order
# print "limit:", limit
# print "offset:", offset
if len(md5sumlist) == 0 :
retval={'total':0, 'rows':[]}
else:
if search!=None:
queryResult=MedFile.select().where(MedFile.md5_key.in_(md5sumlist) & \
(\
MedFile.md5_key.contains(search) | \
MedFile.file_name.contains(search) | \
MedFile.virus_name.contains(search) | \
MedFile.file_tag.contains(search)
)\
)
else:
queryResult=MedFile.select().where(MedFile.md5_key.in_(md5sumlist))
if sort:
if sort=="MD5_KEY":
queryColumn=MedFile.md5_key
if sort=="FILE_NAME":
queryColumn=MedFile.file_name
if sort=="RESULT_NUMBER":
queryColumn=MedFile.result_number
if sort=="VIRUS_NAME":
queryColumn=MedFile.virus_name
if sort=="SIGN_CREDIT":
queryColumn=MedFile.sign_credit
if sort=="REPORT_PC_COUNT":
queryColumn=MedFile.report_pc_count
if sort=="SAVED_SIZE":
queryColumn=MedFile.saved_size
if sort=="FILE_TAG":
queryColumn=MedFile.file_tag
if sort=="CTIME":
queryColumn=MedFile.ctime
if order=="desc":
queryResult=queryResult.order_by(queryColumn.desc())
else:
queryResult=queryResult.order_by(queryColumn.asc())
# queryResult=MedFile.select().where(MedFile.md5_key.in_(md5sumlist)).limit(limit).offset(offset).order_by(order)
rows=[]
for row in queryResult.limit(limit).offset(offset):
# print "row.report_pc_count:", row.report_pc_count
# Inject Tick Count from MongoDB Collection
docs=col_behavior.find({'md5sum':row.md5_key},{'mdpLog.behavior.behaviorData.@tick':1})
tickCount=None
for doc in docs:
tickCount=len(doc["mdpLog"]["behavior"]["behaviorData"])
# print row.md5_key, tickCount
rows.append(\
{"MD5_KEY":row.md5_key, \
"FILE_NAME": row.file_name, \
"RESULT_NUMBER":row.result_number, \
"VIRUS_NAME":row.virus_name,\
"SIGN_CREDIT":str(row.sign_credit), \
"REPORT_PC_COUNT":str(row.report_pc_count), \
"SAVED_SIZE":str(row.saved_size), \
"FILE_TAG":row.file_tag, \
"CTIME":str(row.ctime), \
"TICKCOUNT": tickCount \
})
total=queryResult.count()
retval={'total':total, 'rows':rows}
return json.dumps(retval, default=json_util.default)
def allowed_file(filename):
ALLOWED_EXTENSIONS = set(['zip'])
return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
def postprocessor(value):
import HTMLParser
try:
return int(value)
except (ValueError, TypeError):
# print "not num: escaped value", value
if (value.lower()=="true"):
return True
elif (value.lower()=="false"):
return False
return HTMLParser.HTMLParser().unescape(value)
def getDaterange(input_daterange):
# print ("input_daterange: %s" % input_daterange)
strStartDate, strEndDate = input_daterange.split(" - ")
intCompensationSec=float(32400)
# print ("strStartDate: %s, strEndDate:%s" % (strStartDate,strEndDate))
# startDate=datetime.fromtimestamp(float(dateParser(strStartDate).strftime('%s'))+intCompensationSec)
startDate=datetime.fromtimestamp(float(dateParser(strStartDate).strftime('%s')))
# endDate =datetime.fromtimestamp(float(dateParser(strEndDate ).strftime('%s'))+intCompensationSec)
endDate =datetime.fromtimestamp(float(dateParser(strEndDate ).strftime('%s')))
# print ("startDate:%s, endDate: %s" %(startDate, endDate))
return startDate, endDate
def getTotalPerDay(daterange):
startDate, endDate = getDaterange(daterange)
records=col_enginediff.distinct('Date',{'Date':{'$gte':startDate, '$lte':endDate}})
# sort is not available after distinct.
# print "before Sort:", records
records.sort()
# print "after Sort:", records
dateList=set()
for r in records:
dateList.add(r)
# print "after Uniq :", dateList
# dateList=list(dateList)
chartCount=[]
for date in dateList:
cnt=col_enginediff.distinct('File.MD5', {'Date':date})
size=len(cnt)
chartNsec=time.mktime(date.timetuple())*1000
chartCount.append([chartNsec, size])
return chartCount
def sortList(seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
def getArrayPerDay(query, daterange):
startDate, endDate = getDaterange(daterange)
qr={'$and':
[
query,
{'Date':
{'$gte':startDate, '$lte':endDate}
}
]
}
records=col_enginediff.find(qr).sort('Date',1)
dateList=[]
for r in records:
dateList.append(r['Date'])
dateList=sortList(dateList)
chartCount=[]
for date in dateList:
count=len(col_enginediff.distinct('File.MD5', {'$and':[query, {'Date':date}]}))
timestamp=(int(time.mktime(date.timetuple()))+32400)*1000
chartCount.append([timestamp, count])
return chartCount
def getTotalMaliciousCountArrayPerDay(query, daterange=None):
startDate, endDate = getDaterange(daterange)
records=col_enginediff.find(
{'$and':[
query,
{'Date':{'$gte':startDate, '$lte':endDate}}
]}
).sort('Date',1)
dateList=[]
for r in records:
dateList.append(r['Date'])
dateList=sortList(dateList)
chartCount=[]
for date in dateList:
count=len(col_enginediff.distinct('File.MD5', {'$and':[query, {'Date':date}]}))
timestamp=(int(time.mktime(date.timetuple()))+32400)*1000
chartCount.append([timestamp, count])
return chartCount
def getTotalMaliciousCount(daterange):
startDate, endDate = getDaterange(daterange)
totalMal=len(
col_enginediff.distinct(
'File.MD5',
{
'$or':
[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.V3.Result':'MALICIOUS'},
{'Results.Heimdal.Result':'MALICIOUS'},
{'Results.VirusTotal.Result':'MALICIOUS'},
{'Results.MDP_VM.Result':'MALICIOUS'}
],
'Date':{'$gte':startDate, '$lte':endDate}
}
)
)
return totalMal
def getTotalInputCount(daterange):
totalIn=0
for countAndTime in getTotalPerDay(daterange):
cnt=countAndTime[1]
totalIn+=cnt
return totalIn
def getDetectionEngineCount(engineName, daterange):
startDate, endDate = getDaterange(daterange)
key="Results."+engineName+".Result"
qr={
key:'MALICIOUS',
'Date':{'$gte':startDate, '$lte':endDate}
}
# print qr
engineCount=col_enginediff.distinct('File.MD5',qr)
return len(engineCount)
def returnDICAVersions(daterange):
DICA_4_1_2_1 = getArrayPerDay({'$and':[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.DICA.Version':'4.1.2.1'}
]}, daterange)
DICA_5_0_0_54= getArrayPerDay({'$and':[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.DICA.Version':'5.0.0.54'}
]}, daterange)
DICA_5_0_1_39 = getArrayPerDay({'$and':[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.DICA.Version':'5.0.1.39'}
]}, daterange)
DICA_New = getArrayPerDay({'$and':[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.DICA.Version':{'$ne':'4.1.2.1'}},
{'Results.DICA.Version':{'$ne':'5.0.0.54'}},
{'Results.DICA.Version':{'$ne':'5.0.1.39'}}
]}, daterange)
retval={
'v4_1_2_1':DICA_4_1_2_1,
'v5_0_0_54':DICA_5_0_0_54,
'v5_0_1_39':DICA_5_0_1_39,
'Recent':DICA_New
}
return retval
def returnEngineRate(engineName, daterange):
totalMal=getTotalMaliciousCount(daterange)
totalEngine=getDetectionEngineCount(engineName, daterange)
engineVsMalPercent=round(float(totalEngine)/float(totalMal)*100,2)
# print ("totalMal: %.1f, totalEngine: %.1f, engineVsMalPercent: %.1f" % (totalMal, totalEngine, engineVsMalPercent))
retval={
engineName:{
'percent': engineVsMalPercent,
'count' : totalEngine,
'total' : totalMal
}
}
return retval
def returnOverall(daterange):
return {'Malicious': getTotalMaliciousCount(daterange), 'Input': getTotalInputCount(daterange) }
def returnAllRate(daterange):
retval={}
# print "returnAllRate: daterange: %s" % daterange
totalMal=getTotalMaliciousCount(daterange)
for engineName in ['DICA', 'V3', 'Heimdal', 'VirusTotal', 'MDP_VM']:
totalEngine = getDetectionEngineCount(engineName, daterange)
percent=0
# print "totalEngine: %.1f" % totalEngine
percent=0
if totalEngine!=0:
percent=float(totalEngine)/float(totalMal)*100
# print "percent: %.1f" % percent
# array_merge
retval.update({
engineName: {
'percent': percent,
'count' : totalEngine,
'total' : totalMal
}
})
# print retval
return retval
def calculateDailyPercent(numerator, denominator):
retval=[]
for dt, dv in denominator:
for nt, nv in numerator:
if dt==nt:
nv=float(nv)
dv=float(dv)
percent=nv/dv*100
retval.append([dt, percent])
break
return retval
def returnEngineDiff(fetchDate):
# print "fetchDate", fetchDate
TotalData=getTotalPerDay(fetchDate)
DICAData=getArrayPerDay(
{'$and':
[
{'Results.DICA.Result': "MALICIOUS"},
{'Results.DICA.Version': {'$ne':'4.1.2.1' }},
{'Results.DICA.Version': {'$ne':'5.0.0.54'}},
{'Results.DICA.Version': {'$ne':'5.0.1.39'}}
]
}
, fetchDate)
V3Data=getArrayPerDay({'Results.V3.Result':'MALICIOUS'}, fetchDate)
VirusTotalData=getArrayPerDay({'Results.VirusTotal.Result':'MALICIOUS'}, fetchDate)
HeimdalData=getArrayPerDay({'Results.Heimdal.Result':'MALICIOUS'}, fetchDate)
MDP_VMData=getArrayPerDay({'Results.MDP_VM.Result':'MALICIOUS'}, fetchDate)
TotalMalwareData=getTotalMaliciousCountArrayPerDay(
{
'$or':
[
{'Results.DICA.Result':'MALICIOUS'},
{'Results.V3.Result':'MALICIOUS'},
{'Results.Heimdal.Result':'MALICIOUS'},
{'Results.VirusTotal.Result':'MALICIOUS'},
{'Results.MDP_VM.Result':'MALICIOUS'}
]
}
, fetchDate)
DICAPercent = calculateDailyPercent(DICAData, TotalMalwareData)
V3Percent = calculateDailyPercent(V3Data, TotalMalwareData)
VirusTotalPercent = calculateDailyPercent(VirusTotalData, TotalMalwareData)
HeimdalPercent = calculateDailyPercent(HeimdalData, TotalMalwareData)
MDP_VMPercent = calculateDailyPercent(MDP_VMData, TotalMalwareData)
retval={
'Total':TotalData,
'TotalMalicious':TotalMalwareData,
'DICA':DICAData,
'DICA_percent':DICAPercent,
'V3':V3Data,
'V3_percent':V3Percent,
'VirusTotal':VirusTotalData,
'VirusTotal_percent':VirusTotalPercent,
'Heimdal':HeimdalData,
'Heimdal_percent':HeimdalPercent,
'MDP_VM':MDP_VMData,
'MDP_VM_percent':MDP_VMPercent
}
# print "retval", retval
return retval
def returnResultTable(fetchDate=None, fetchEngine=None, daterange=None):
if fetchDate is not None:
# print "here?"
fetchdate=float(fetchDate)/1000
# print "here!"
fetchDate=datetime.fromtimestamp(fetchdate)
# print fetchDate
query=[
{
'$match': {
'$and':[
{'Date':fetchDate}
]
}
},
{
'$group':
{
'_id':'$File.MD5',
'Date':{'$push':'$Date'},
'File':{'$push':'$File'},
'Threat':{'$push':'$Threat'},
'Results':{'$push':'$Results'},
}
},
{
'$sort':
{
'Date':-1
}
},
{
'$limit':10000
}
]
documents=col_enginediff.aggregate(query, allowDiskUse=True)
else:
startDate, endDate=getDaterange(daterange)
query=[
{'$match': {'$and':[{'Date':{'$gte':startDate, '$lte':endDate}}]}},
{'$group': {
'_id':'$File.MD5',
'Date':{'$push':'$Date'},
'File':{'$push':'$File'},
'Threat':{'$push':'$Threat'},
'Results':{'$push':'$Results'},
}
},
{'$sort':{'Date':-1}},
{'$limit':10000},
]
documents=col_enginediff.aggregate(query, allowDiskUse=True)
retval=[]
if documents is not None:
# print "t: %s" % t
for document in documents:
# print "============ document: %s" % document
# results={}
threat_name="None"
if document['Threat'][0].has_key('Name'):
threat_name=document['Threat'][0]['Name']
behavior_count="None"
if document['Threat'][0].has_key('behaviorCount'):
behavior_count=int(document['Threat'][0]['behaviorCount'])
crc64="None"
if document['File'][0].has_key('CRC64'):
crc64=document['File'][0]['CRC64']
info={
"Date":document['Date'][0].strftime('%Y-%m-%d'),
"Name":document['File'][0]['Name'],
"Type":document['File'][0]['Type'],
"MD5":document['File'][0]['MD5'],
"CRC64":crc64,
"Size":document['File'][0]['Size'],
"Severity":document['Threat'][0]['Severity'],
"Threat_Name":threat_name,
"Behavior_Count":behavior_count,
}
results={}
for Results in document['Results']:
if Results.has_key('MDP_VM'):
elementVal=Results['MDP_VM']
elementKey="MDP_VM"
results.update({elementKey+'_Result':elementVal['Result'], elementKey+'_Reason':elementVal['Reason']})
# m=1
if Results.has_key('V3'):
elementVal=Results['V3']
elementKey="V3"
results.update({elementKey+'_Result':elementVal['Result'], elementKey+'_Reason':elementVal['Reason']})
# print elementKey, elementVal
# v=1
if Results.has_key('Heimdal'):
elementVal=Results['Heimdal']
elementKey="Heimdal"
results.update({elementKey+'_Result':elementVal['Result'], elementKey+'_Reason':elementVal['Reason']})
if Results.has_key('DICA'):
elementVal=Results['DICA']
if elementVal['Version'] in ['4.1.2.1', '5.0.0.54', '5.0.1.39']:
# skip above version
raise KeyError
elementKey="VirusTotal"
results.update({elementKey+'_Result':elementVal['Result'], elementKey+'_Reason':elementVal['Reason']})
info.update(results)
# if m==1 and v==1:
# print results
# pass
# info.update(results)
retval.append(info)
# print "appending info: %s" % info
# print "=-"*40
# print info
# info.update(retval) # print retval
# print retval
return retval
def csvToJson(csvString):
keys=[]
for key in csvString[0].split(","):
key=key.strip()
keys.append(key)
retval=[]
for data in csvString[1:]:
cols={}
row=data.split(",")
for key, val in zip(keys, row):
if key=="":
pass
cols[key]=val.strip()
retval.append(cols)
return retval
def csvToMongo(csvString):
Seoul=pytz.timezone('Asia/Seoul')
data=csvToJson(csvString)
# print data
# data=json.dumps(jsonData)
mongoRetval=[]
# print "data", data
for elem in data:
# PreProcessing Rule
# print "elem: %s" % elem
# print type(elem)
# print "+="*40
elem['Size']=int(elem['Size'])
print elem['Date']
elem['Date']=elem['Date']+" 09:01:00"
print elem['Date']
elem['Date']=dateParser(elem['Date'])
elem['Severity']=int(elem['Severity'])
if elem['Threat_Name'].lower()=="none" or elem['Threat_Name']=="":
elem['Threat_Name']=None
if elem.has_key("CRC64") is not True:
elem['CRC64']=None
try:
elem.pop('Unnamed: 0')
except:
pass
# Processing From here.
Date=Seoul.localize(elem['Date'])
elem.pop('Date')
File={
"Name": elem['FileName'],
"Type": elem['Type'],
"MD5" : elem['MD5'],
"CRC64":elem['CRC64'],
"Size": elem['Size']
}
elem.pop('FileName')
elem.pop('Type')
elem.pop('MD5')
elem.pop('CRC64')
elem.pop('Size')
behaviorCount=0
if elem['BeaviorCount']:
behaviorCount=elem['BeaviorCount']
elem.pop('BeaviorCount')
elif elem['BehaviorCount']:
behaviorCount=elem['BehaviorCount']
elem.pop('BehaviorCount')
Threat={
"Severity":elem['Severity'],
"Name": elem['Threat_Name'],
"VM_Severity":elem['Result'],
"behaviorCount":behaviorCount,
}
elem.pop('Severity')
elem.pop('Result')
Results={}
for key, val in elem.items():
# result(BENIGN|MALICIOUS|SUSPICIOUS) categorization
if key=='':
pass
else:
if val=="MALICOUS":
val="MALICIOUS"
if val in ['not found', 'Not found', 'None', 'none', 'Clean', 'BENIGN', '', None]:
result="BENIGN"
reason=val
else:
result=val
reason=val
if key.find("DICA") >= 0:
Engine="DICA"
EngineVersion=key.replace("DICA_","")
Result=result
Reason=reason
elif key.find("VM_Threat_Name") >= 0:
Engine="MDP_VM"
if val.find("/") >= 0 :
EngineVersion=0
Reason=reason
if reason!="None":
Result="MALICIOUS"
else:
Result="BENIGN"
Reason=None
else:
EngineVersion=0
Result="BENIGN"
Reason=None
elif key.find("AhnLab-V3") >= 0 or key.find("Threat_Name")>=0:
Engine="V3"
EngineVersion="AhnLab-V3"
Reason=reason
if result!="BENIGN":
Result="MALICIOUS"
else:
Result=result
elif key.find("Heimdal")>=0:
Engine="Heimdal"
EngineVersion=key
Result=result
Reason=reason
if reason.find("/") >=0:
Result=result.split("/")[0]
Reason=result.split("/")[1]
elif key.find("VirusTotal") >= 0:
Engine="VirusTotal"
if val.find("/") >= 0:
EngineVersion=int(reason.split("/")[1])
Reason=int(reason.split("/")[0])
if int(reason.split("/")[0])>0:
Result="MALICIOUS"
else:
Result="BENIGN"
else:
EngineVersion=0
Result="BENIGN"
Reason=0
else:
Engine=key
EngineVersion=key
Result=result
Reason=reason
# print "Engine: %s" % Engine
Results.update({
Engine: {
"Version":EngineVersion,
"Result":Result,
"Reason":Reason,
}
})
# print Results
# elem.pop(key)
retval={
"Date": Date,
"File": File,
"Threat": Threat,
"Results": Results
}
# ret.append(retval)
# print "Insert: %s" % retval
mongoRetval.append(col_enginediff.insert(retval))
return mongoRetval
def escapeHtml(s, quote=None):
'''Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.'''
# if type(s) == type(str()):
try:
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
s = s.replace("'", "'")
return s
except:
return s
def queryToDict(query):
try:
Query=query
if query.startswith(" "):
Query=query[1:]
# if key starts with { it means it's json type.
if Query.startswith("{"):
key, val=json.loads(query.replace("'","\"")).items()[0]
else:
# otherwise it means it's aaa.bb.cc=ccc type
idx=Query.find("=")
key=Query[:idx]
val=postprocessor(Query[idx+1:])
retval={key:val}
print "retval",retval
return retval
except:
# if query includes regex
return query
@login_manager.unauthorized_handler
def unauthorized_handler():
return 'Unauthorized'
@app.route("/fetch/enginerate/<engineName>")
def fetchEngineRate(engineName):
return Response(json.dumps(returnEngineRate(engineName)), mimetype='application/json')
@app.route("/fetch/DICAVersions/")
def fetchDicaVersions():
fetchDate = request.args.get('daterange')
return Response(json.dumps(returnDICAVersions(fetchDate)), mimetype='application/json')
@app.route("/fetch/Overall/")
def fetchOverAll():
fetchDate = request.args.get('daterange')
return Response(json.dumps(returnOverall(fetchDate)), mimetype='application/json')
@app.route("/fetch/AllRate/")
def fetchAllRate():
fetchDate = request.args.get('daterange')
return Response(json.dumps(returnAllRate(fetchDate)), mimetype='application/json')
@app.route("/fetch/ResultTable/")
def fetchResultTable():
fetchDate = request.args.get('date')
fetchEngine = request.args.get('engine')
daterange = request.args.get('daterange')
return Response(json.dumps(returnResultTable(fetchDate, fetchEngine, daterange)), mimetype='application/json')
@app.route("/fetch/EngineDiff/")
def fetchEngineDiff():
fetchDate = request.args.get('daterange')
# print "+="*40
# print fetchDate
return Response(json.dumps(returnEngineDiff(fetchDate)), mimetype='application/json')
@app.route("/login", methods=['POST', 'GET'])
def login():
if request.method == 'GET':
return '''
<form action='login' method='POST'>
<input type='text' name='email' id='email' placeholder='email'></input>
<input type='password' name='pw' id='pw' placeholder='password'></input>
<input type='submit' name='submit'></input>
</form>
'''
email = request.form['email']
if request.form['pw'] == users[email]['pw']:
user = User()
user.id = email
flask_login.login_user(user)
return redirect(url_for('protected'))
return 'Bad login'
@app.route('/protected')
@flask_login.login_required
def protected():
return 'Logged in as: ' + flask_login.current_user.id
@app.route('/logout')
def logout():
flask_login.logout_user()
return 'Logged out'
@app.route("/analysis/")
def mainpage():
return render_template('analysis.html')
@app.route("/query/<query>/")
def startpage(query):
return render_template('analysis.html', query=query)
@app.route("/analysis/md5list/", methods=['POST'])
def md5list():
query=request.form.getlist('md5list[]')
return render_template('analysis.html', md5list=";".join(query))
@app.route("/count/", methods=['POST'])
def count():
query=request.form.get('query')
# print query
dQuery=queryToDict(query)
print "dQuery",dQuery
try:
data=col_behavior.find(dQuery).distinct("md5sum")
except:
data=col_behavior.find(dQuery)
return json.dumps(len(data), default=json_util.default)
@app.route("/count/and/", methods=['POST'])
def count_and():
query=request.form.getlist('query[]')
queryList=[]
print "queries: %s" % query
for keyval in query:
queryList.append(queryToDict(keyval))
data=col_behavior.find({"$and":queryList}).distinct("md5sum")
# print "DistinctCount: %s" % len(data)
# print "DistinctList: %s" % col_behavior.find({"$and":queryList}).distinct("md5sum")
print "DistinctCount: %s" % len(data)
print "UniqueCount :%s" %len(set(data))
# data=col_behavior.find({"$and":queryList}).distinct("md5sum")
return json.dumps(len(data), default=json_util.default)
@app.route("/detail_one/", methods=['POST'])
def detail_one():
query=request.form.get('query')
# print request.form
data=json_util.dumps(col_behavior.find(queryToDict(query)).sort('mdpLog.behavior.behaviorData.@tick',1))
return json_util.dumps(data)
@app.route("/detail_one/and/", methods=['POST'])
def detail_one_and():
query=request.form.getlist('query[]')
queryList=[]
for keyval in query:
queryList.append(queryToDict(keyval))
data=col_behavior.find({"$and":queryList}).sort({'mdpLog.behavior.behaviorData.@tick':1})
return json.dumps(data, default=json_util.default)
@app.route("/list/", methods=['GET','POST'])
def list():
if request.method=="POST":
# print "POST", request.form
query = request.form.get('query')
limit = request.form.get('limit')
offset= request.form.get('offset')
sort = request.form.get('sort')