-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
656 lines (626 loc) · 21.9 KB
/
Copy pathserver.py
File metadata and controls
656 lines (626 loc) · 21.9 KB
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
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse,FileResponse, Response
from fastapi.staticfiles import StaticFiles
# import fastapi_cdn_host
from io import StringIO
import sys
import os
import uvicorn
from time import sleep
import zipfile
import json
import utils.PE_analyse
from hashlib import sha256, md5
from main import process_upload_asm, exe2asm, detect_virus, getfeaturenum, VERSION, get_n, get_description
from shutil import rmtree
from random import randint
def Generate_tag(args_list:list):
tag = ''
for args in args_list:
tag += args + '.'
while True:
if tag.endswith('.'):
tag = tag[:-1]
else:
return tag
def NumberOfBytesHumanRepresentation(value):
if value <= 1024:
return '%s bytes' % value
elif value < 1024 * 1024:
return '%.1f KB' % (float(value) / 1024.0)
elif value < 1024 * 1024 * 1024:
return '%.1f MB' % (float(value) / 1024.0 / 1024.0)
else:
return '%.1f GB' % (float(value) / 1024.0 / 1024.0 / 1024.0)
ida_PATH = input('your IDA path: >>> ')
if not ida_PATH.endswith('/') or not ida_PATH.endswith('\\'):
ida_PATH += '/'
if not os.path.exists(ida_PATH):
print('[-] Path not found')
exit()
if not os.path.isdir(ida_PATH):
print('[-] Input your install dir, ex: D:/IDApro/')
exit()
if not 'idat64.exe' in os.listdir(ida_PATH):
print('[-] idat64.exe missing')
exit()
app = FastAPI()
# fastapi_cdn_host.patch_docs(app, favicon_url='./static/logo.svg')
# 定义上传文件的目标目录
os.makedirs("./upload", exist_ok=True)
os.makedirs("./download", exist_ok=True)
# 静态文件目录
app.mount("/static", StaticFiles(directory="./static"), name="static")
app.mount("/js", StaticFiles(directory="./js"), name="js")
# app.mount("/css", StaticFiles(directory="./css"), name="css")
# app.mount("/download", StaticFiles(directory="./download"), name="download")
app.mount("/fonts", StaticFiles(directory="./fonts"), name="fonts")
@app.get('/favicon.ico', include_in_schema=False)
async def favicon():
return FileResponse('./static/favicon.ico')
@app.get("/downloadfile")
async def download(file_name:str):
# 需要下载文件名,从服务器保存文件地址拼接
file_path = "./download/"+file_name
return FileResponse(file_path, filename='analyze detail.zip', media_type="application/octet-stream")
# 根路由,返回上传页面
@app.get("/", response_class=HTMLResponse)
async def get_upload_page():
return """
<!DOCTYPE html>
<html lang="en">
<head>
<link id="favicon" rel="icon" type="image/x-icon" href="static/favicon.ico">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MalPro """+VERSION+"""</title>
<style>
@font-face {
font-family: 'good_font';
src: url('/fonts/good_font.ttf') format('truetype');
}
.text_display {
flex: left;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: 'good_font', Arial, sans-serif;
}
.container{
overflow: hiddden;
display: flex;
background-color: #eaeaea;
}
.box {
float: left;
width: 100%;
height: 50%;
margin-right: 10px;
}
.fire{
flex: right;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
#logo {
width: 300px;
height: auto;png
margin-top: 20px;
}
h1 {
font-size: 24px;
color: black;
}
.animbox {
margin: 50px auto;
width: 200px;
text-align: center;
}
.enter-x-left {
z-index: 9;
opacity: 0;
animation: enter-x-left 0.4s ease-in-out 0.3s;
animation-fill-mode: forwards;
transform: translateX(-50px);
}
.enter-x-right {
z-index: 9;
opacity: 0;
animation: enter-x-right 0.4s ease-in-out 0.3s;
animation-fill-mode: forwards;
transform: translateX(50px);
}
.enter-x-left:nth-child(1),
.enter-x-right:nth-child(1) {
animation-delay: 0.1s;
}
.enter-x-left:nth-child(2),
.enter-x-right:nth-child(2) {
animation-delay: 0.2s;
}
.enter-x-left:nth-child(3),
.enter-x-right:nth-child(3) {
animation-delay: 0.3s;
}
.enter-x-left:nth-child(4),
.enter-x-right:nth-child(4) {
animation-delay: 0.4s;
}
@keyframes enter-x-left {
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes enter-x-right {
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes exit-x-right {
from {
opacity: 1;
transform: translateX(0);
}
to {
opacity: 0;
transform: translateX(50px);
}
}
@keyframes exit-x-left {
from {
opacity: 1;
transform: translateX(0);
}
to {
opacity: 0;
transform: translateX(-50px);
}
}
.exit-x-right {
z-index: 9;
opacity: 1;
animation: exit-x-right 0.4s ease-in-out;
animation-fill-mode: forwards;
}
.exit-x-left {
z-index: 9;
opacity: 1;
animation: exit-x-left 0.4s ease-in-out;
animation-fill-mode: forwards;
}
.exit-x-right:nth-child(1),
.exit-x-left:nth-child(1) {
animation-delay: 0.1s;
}
.exit-x-right:nth-child(2),
.exit-x-left:nth-child(2) {
animation-delay: 0.2s;
}
.exit-x-right:nth-child(3),
.exit-x-left:nth-child(3) {
animation-delay: 0.3s;
}
.exit-x-right:nth-child(4),
.exit-x-left:nth-child(4) {
animation-delay: 0.4s;
}
form {
margin-top: 20px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
border-radius: 4px;
font-size: 16px;
transition: background-color 0.3s;
}
.loading{
text-align: center;
}
button:hover {
background-color: #45a049;
}
button:active {
background-color: #367b36;
}
.message {
margin-top: 20px;
font-size: 18px;
color: blue;
font-family: 'good_font', Arial, sans-serif;
justify-content: top;
}
</style>
</head>
<body>
<div class="container">
<div class="box enter-x-left">
<div class="text_display" id="box1">
<img id="logo" src="/static/logo.png" alt="Logo">
<h1>MalPro """+VERSION+"""</h1>
<p>Upload your file here (only PE & ≤8MB files allowed).</p>
<form action="/uploadfile/" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" id="fileupload">Upload File</button>
</form>
<p></p>
<div>
<a href="https://github.com/BSDFZ-programming-team/MalPro" class="message">Need Help?</a>
</div>
</div>
</div>
<div class="box enter-x-right">
<div class="fire" id="box2">
<svg class="flameSVG" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg">
<defs>
<rect class="flame" x="400" y="310" width="5" height="5" rx="0.5" ry="0.5" fill="#FFDD02"/>
<circle class="spark" cx="400" cy="300" r="0.05" fill="#FFDD02"/>
<filter id="shadow" x="-100%" y="-100%" width="250%" height="250%">
<feOffset in="SourceAlpha" dx="4" dy="4" result="offsetOut"></feOffset>
<feGaussianBlur stdDeviation="3" in="offsetOut" result="drop" />
<feOffset dx="0" dy="0" result="offsetblur"></feOffset>
<feFlood id="glowAlpha" flood-color="#0F1217" flood-opacity="0.42"></feFlood>
<feComposite in2="offsetblur" operator="in"></feComposite>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"></feMergeNode>
</feMerge>
</filter>
</defs>
<g class="whole">
<g class="flameContainer" />
<g class="sparksContainer" />
<g class="logs" opacity="1">
<path d="M446.68,299.63l-91.46,29.22a3,3,0,0,1-3.68-2.12L349.2,318a3,3,0,0,1,2.12-3.68l91.46-29.22a3,3,0,0,1,3.68,2.12L448.8,296A3,3,0,0,1,446.68,299.63Z" fill="#612e25"/>
<path filter="url(#shadow)" d="M349.2,296l2.34-8.69a3,3,0,0,1,3.68-2.12l91.46,29.22A3,3,0,0,1,448.8,318l-2.34,8.69a3,3,0,0,1-3.68,2.12l-91.46-29.22A3,3,0,0,1,349.2,296Z" fill="#70392f"/>
</g>
</g>
<rect class="hit" width="200" height="260" x="300" y="230" fill="transparent">
</rect>
</svg>
<script>
const fadeInButton = document.getElementById('fileupload');
const fadeInBox1 = document.getElementById('box1');
const fadeInBox2 = document.getElementById('box2');
const Loading = document.getElementById('loading');
fadeInButton.addEventListener('click', () => {
fadeInBox1.classList.add('exit-x-left');
fadeInBox2.classList.add('exit-x-right');
Loading.classList.add('animbox');
});
</script>
<script src='js/TweenMax.min.js'></script>
<script src='js/CustomEase.min.js'></script>
<script src="js/index.js"></script>
</div></div>
</div>
</body>
</html>
"""
@app.post("/uploadfile/", response_class=HTMLResponse)
async def upload(file: UploadFile = File(...)):
sleep(0.5) # For the animation XD
data = await file.read()
random_name = str(randint(100000, 999999))
is_same = False
file_size = file.size
data_md5 = sha256(data).hexdigest()
if file_size > 8*1024*1024:
result=[[[f'FILE TOO LARGE ({NumberOfBytesHumanRepresentation(file_size)})', ''], 'red'], random_name]
else:
fn = random_name+'.exe'
if not os.path.exists('./upload/'):
os.mkdir('./upload/')
save_file = os.path.join('./upload/', fn)
f = open(save_file, 'wb')
f.write(data)
f.close()
del f
def judge_file(random_name):
if not os.path.exists('MD5_record_list.json'):
open('MD5_record_list.json', 'w').close()
# RETURN: [[[RESULT, PLATFORM], COLOR], RANDOM_NAME]
f_md5_json = open('MD5_record_list.json', 'r+')
try:
md5dict = json.load(f_md5_json)
except json.decoder.JSONDecodeError:
md5dict = {}
if data_md5 in md5dict:
# print(1)
return md5dict[data_md5]
# Caculate some basic informations
analyze_result = utils.PE_analyse.check_avaliable(save_file)
if analyze_result == 'Header broken':
result = 'UNAVALIABLE PE FILE (header broken)'
platform = ''
color = 'red'
elif analyze_result == 'Load failed':
result = 'UNAVALIABLE PE FILE (failed to load)'
platform = ''
color = 'red'
elif analyze_result == 'failed to load the DOS Header magic':
result = 'UNAVALIABLE PE FILE (failed to load the DOS Header magic)'
platform = ''
color = 'red'
else:
pe = analyze_result
buffer = StringIO()
sys.stdout = buffer
print(pe)
with open(f'./upload/{random_name}_exe_details.txt', 'w+') as f:
f.write(buffer.getvalue())
sys.stdout = sys.__stdout__
del f
try:
platform = utils.PE_analyse.analyze_machine(pe)
pe.close()
except:
platform = ''
if detect_virus(save_file): #TODO: detect virus
asm_file = exe2asm(save_file, ida_PATH)
n = get_n('./model/ngramfeature_fitting_use.csv')
result = process_upload_asm(asm_file, n)
color = 'red'
else:
result = 'NON-VIRUS'
color = 'green'
md5dict[data_md5] = [[[result, platform], color], random_name]
f_md5_json.seek(0)
f_md5_json.truncate()
f_md5_json.flush()
json.dump(md5dict, f_md5_json)
f_md5_json.close()
if result != 'UNAVALIABLE PE FILE (failed to load)' and result != 'UNAVALIABLE PE FILE (header broken)' and result != f'FILE TOO LARGE ({NumberOfBytesHumanRepresentation(file_size)})':
with zipfile.ZipFile(f'./download/{random_name}.zip', 'w') as zip_file:
zip_file.write(f'./upload/{random_name}_exe_details.txt', random_name+'PE_details.txt')
if result != 'NON-VIRUS':
zip_file.write(f'./upload/'+random_name+'.exe.asm_ngramfeature.csv', './features/'+random_name+'_ngramfeature.csv')
zip_file.write(f'./upload/'+random_name+'.exe.asm_imgfeature.csv', './features/'+random_name+'_imgfeature.csv')
rmtree('./upload')
return [[[result, platform], color], random_name]
result = judge_file(random_name)
color = result[0][-1]
if random_name != result[-1]:
is_same = True
random_name = result[-1]
result = result[0][0]
tag = Generate_tag(result)
if result[0].startswith('UNAVALIABLE PE FILE') or result[0] == f'FILE TOO LARGE ({NumberOfBytesHumanRepresentation(file_size)})':
error = True
else:
error = False
html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<link id="favicon" rel="icon" type="image/x-icon" href="static/favicon.ico">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>'''+VERSION+'''</title>
<style>
@font-face {
font-family: 'good_font';
src: url('/fonts/good_font.ttf') format('truetype');
}
.green{
color:green;
font-size:20px;
}
.red{
color:red;
font-size:20px;
}
.text_display {
flex: left;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: 'good_font', Arial, sans-serif;
}
.enter-x-left {
z-index: 9;
opacity: 0;
animation: enter-x-left 0.4s ease-in-out 0.3s;
animation-fill-mode: forwards;
transform: translateX(-50px);
}
.enter-x-right {
z-index: 9;
opacity: 0;
animation: enter-x-right 0.4s ease-in-out 0.3s;
animation-fill-mode: forwards;
transform: translateX(50px);
}
.enter-x-left:nth-child(1),
.enter-x-right:nth-child(1) {
animation-delay: 0.1s;
}
.enter-x-left:nth-child(2),
.enter-x-right:nth-child(2) {
animation-delay: 0.2s;
}
.enter-x-left:nth-child(3),
.enter-x-right:nth-child(3) {
animation-delay: 0.3s;
}
.enter-x-left:nth-child(4),
.enter-x-right:nth-child(4) {
animation-delay: 0.4s;
}
@keyframes enter-x-left {
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes enter-x-right {
to {
opacity: 1;
transform: translateY(0);
}
}
.details_display {
flex: left;
display: flex;
flex-direction: column;
align-items: left;
justify-content: left;
height: 100vh;
margin: 0;
font-family: 'good_font', Arial, sans-serif;
}
.container{
overflow: hiddden;
display: flex;
background-color: #eaeaea;
}
.box {
float: left;
width: 100%;
height: 100%;
margin-right: 10px;
}
.fire{
flex: right;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
#logo {
width: 300px;
height: auto;png
margin-top: 20px;
}
h1 {
font-size: 24px;
color: black;
}
form {
margin-top: 20px;
}
.message {
margin-top: 20px;
font-size: 18px;
color: blue;
font-family: 'good_font', Arial, sans-serif;
justify-content: top;
}
</style>
</head>
<body>
<div class="container">
<div class="box enter-x-left">
<div class="text_display">
<img id="logo" src="/static/logo.png" alt="Logo">
<h1>MalPro '''+VERSION+'''</h1>
<h3 class="'''+color+''' larger">predict type: '''+tag+'''</h3> '''
if not error:
html += '''
<small><h5 description="'''+color+'''">'''+get_description(result[0])+'''</h5></small> '''
html += '''
<svg class="flameSVG" viewBox="0 0 800 600" xmlns="http://www.w3.org/2000/svg">
<defs>
<rect class="flame" x="400" y="310" width="5" height="5" rx="0.5" ry="0.5" fill="#FFDD02"/>
<circle class="spark" cx="400" cy="300" r="0.05" fill="#FFDD02"/>
<filter id="shadow" x="-100%" y="-100%" width="250%" height="250%">
<feOffset in="SourceAlpha" dx="4" dy="4" result="offsetOut"></feOffset>
<feGaussianBlur stdDeviation="3" in="offsetOut" result="drop" />
<feOffset dx="0" dy="0" result="offsetblur"></feOffset>
<feFlood id="glowAlpha" flood-color="#0F1217" flood-opacity="0.42"></feFlood>
<feComposite in2="offsetblur" operator="in"></feComposite>
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic"></feMergeNode>
</feMerge>
</filter>
</defs>
<g class="whole">
<g class="flameContainer" />
<g class="sparksContainer" />
<g class="logs" opacity="1">
<path d="M446.68,299.63l-91.46,29.22a3,3,0,0,1-3.68-2.12L349.2,318a3,3,0,0,1,2.12-3.68l91.46-29.22a3,3,0,0,1,3.68,2.12L448.8,296A3,3,0,0,1,446.68,299.63Z" fill="#612e25"/>
<path filter="url(#shadow)" d="M349.2,296l2.34-8.69a3,3,0,0,1,3.68-2.12l91.46,29.22A3,3,0,0,1,448.8,318l-2.34,8.69a3,3,0,0,1-3.68,2.12l-91.46-29.22A3,3,0,0,1,349.2,296Z" fill="#70392f"/>
</g>
</g>
<rect class="hit" width="200" height="260" x="300" y="230" fill="transparent">
</rect>
</svg>
<div>
<a href="https://github.com/BSDFZ-programming-team/MalPro" class="message">Need Help?</a>
</div>
</body>
</html>
<script src='../js/TweenMax.min.js'></script>
<script src='../js/CustomEase.min.js'></script>
<script src="../js/index.js"></script>
</div>
</div>
<div class="box enter-x-right">
<div class="details_display">
'''
if os.path.exists('./download/'+random_name+'.zip'):
html += '''
<h2>FILE INFO</h2>
<p> Size: '''+NumberOfBytesHumanRepresentation(file_size)+'''</p>
<p> ID: '''+random_name+'''</p>
<p> Filename: '''+file.filename+'''</p>
<p> Sha256: '''+data_md5+'''</p>
<p> MD5: '''+md5(data).hexdigest()+'''</p>
<h2>ANALYZE DETAILS</h2>
<div>
<a href="/downloadfile/?file_name='''+random_name+'''.zip" download>Download PE & feature details</a>
</div>
<h2>MODEL INFO</h2>
<h5> Asmimage features</h5>
<p>  Deprecated</p>
<h5> Opcode-ngram features</h5>
<p>  n: '''+str(get_n('./model/ngramfeature_fitting_use.csv'))+'''</p>
<p>  loaded features: '''+str(getfeaturenum())+'''</p>
'''
elif error:
pass
if is_same:
if not error:
html +=f'''
<div>
<small><p class="red">This file has already been uploaded(ID {random_name})</p></small>
</div>
'''
html += f'''</div>
</div>
</div>
</body>
</html>
'''
# html += f'''
# <div>
# <a href="https://github.com/BSDFZ-programming-team/MalPro" class="message">Need Help?</a>
# </div>
# </div></div>
# </div>
# </body>
# </html>
# '''
return html
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=7777)