forked from shad0w008/Scanver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.py
2212 lines (2003 loc) · 74.2 KB
/
webserver.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
# encoding=utf-8
#codeby 道长且阻
#email @ydhcui/QQ664284092
#https://github.com/ydhcui/Scanver
from __future__ import division
from functools import reduce
from urllib import parse
import os
import sys
import re
import signal
import time
import datetime
import json
import uuid
import traceback
import hashlib
import binascii
from tornado import web,gen
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import xlrd
import redis
import settings
import models
from service import TaskManage
from core.reportlib import ReportParse,ReportGenerate
from core.nmapscan import PortScan
DEBUG = settings.DEBUG
def generateid():
return str(uuid.uuid4().hex)
def ormstr(s,sv=False):
s = str(s)
if s and s != 'None':
if sv:
s = s.replace('&','&')
s = s.replace('<','<')
s = s.replace('>','>')
else:
s = ''
return s.strip()
class MemorySession(object):
'''会话管理器
基于内存存储,每次服务器重启都要重新登录一次,
以后要拓展再加入本地存储或者上redis
初始化:session = MemorySession(token)
设置值:value = session['key']
取值: session['key'] = value
'''
_session_data = {
'userid':'@',
'group':3,
'projectid':'@'
} if DEBUG else {}
def __init__(self, token,options=None):
self.session = token
'''
self.redis = redis.StrictRedis(
host = options['rhost'],
port = options['rport'],
password = options['rpass']) if options else None
'''
def __setitem__(self, key, value):
if self.session not in self._session_data.keys():
self.session = self.generate()
self._session_data[self.session] = {}
self._session_data[self.session][key] = value
def __getitem__(self, key):
info = self._session_data.get(self.session,{})
if info:return info.get(key, None)
def __repr__(self):
return self.session
@classmethod
def generate(self):
return str(uuid.uuid4().hex)
def heartbeat(self):
session = self.session
self.session = self.generate()
if session in self._session_data.keys():
self._session_data[self.session] = self._session_data[session]
del self._session_data[session]
return str(self.session)
class Route(object):
'''路由管理器
使用负载均衡时,后端同时启用多路进程,管理器自动匹配主机
注册:@Route(urlpattern)
使用:Route.routes()
'''
_routes = {}
def __init__(self, pattern, kwargs={}, name=None, host='.*$'):
self.pattern = pattern #'/api' + pattern
self.kwargs = {}
self.name = name
self.host = host
def __call__(self, handler_class):
spec = web.url(self.pattern, handler_class, self.kwargs, name=self.name)
self._routes.setdefault(self.host, []).append(spec)
return handler_class
@classmethod
def routes(cls, application=None):
if application:
for host, handlers in cls._routes.items():
application.add_handlers(host, handlers)
else:
return reduce(lambda x,y:x+y, cls._routes.values()) if cls._routes else []
class Authenticated(object):
'''权限管理器'''
def __init__(self,group=0):
self.group = group
def __call__(self,f):
def F(cls,d):
#简单判断当前权限,后续再拓展
if cls.session['group']:
if int(cls.session['group']) >= int(self.group):
return f(cls,d)
else:
cls.json['code'] = 401
cls.json['error'] = '权限不足'
else:
cls.json['code'] = 401
cls.json['error'] = '您已退出登录'
#cls.session.heartbeat()
return F
class ApiAction(object):
@Authenticated(2)
def _bugdatabymouth_action(self,data):
'''获取月统计数据'''
projectid = data.get('projectid',None)
M = models.BugResult
MU = models.User
MP = models.Project
MT = models.ScanTask
MV = models.Vulnerable
RU = MU.get(MU.uid == self.session['userid'])
sw = MP.project_user == RU
if projectid:
sw &= (MP.project_id == projectid)
query = MP.select().where(sw).order_by(-MP.finishdate).limit(5)
ret ={}
ret_day = {}
ret_mouth = {}
ret_rank = {}
mouthlist = set()
daylist = set()
for p in query:
sw = (M.projectid == p)
ret_mouth[str(p.project_name)] = {}
query_mouth = (M
.select(
models.orm.fn.substr(M.updatedate,1,7).alias('mouth'),
models.orm.fn.Count(M.bug_id).alias('count'))
.where(sw)
.group_by(models.orm.fn.substr(M.updatedate,1,7))
.order_by(-M.updatedate)
.limit(12))
for q in query_mouth:
mouthlist.add(str(q.mouth))
ret_mouth[str(p.project_name)].update({str(q.mouth):str(q.count)})
#ret['mouthvalue'] = ret_mouth
ret_day[str(p.project_name)] = {}
query_mouth = (M
.select(
models.orm.fn.substr(M.updatedate,1,10).alias('daym'),
models.orm.fn.Count(M.bug_id).alias('count'))
.where(sw)
.group_by(models.orm.fn.substr(M.updatedate,1,10))
.order_by(-M.updatedate)
.limit(30))
for q in query_mouth:
daylist.add(str(q.daym)[:10])
ret_day[str(p.project_name)].update({str(q.daym)[:10]:str(q.count)})
#ret['dayvalue'] = ret_day
'''
for m in mouthlist:
for p,v in ret_mouth.items():
if m not in ret_mouth[p].keys():
ret_mouth[p][m] = 0
for m in daylist:
for p,v in ret_day.items():
if m not in ret_day[p].keys():
ret_day[p][m] = 0
'''
ret['mouthvalue'] = ret_mouth
ret['dayvalue'] = ret_day
return ret
@Authenticated(2)
def _bugdatabypid_action(self,data):
'''获取按漏洞名称统计数据'''
projectid = data.get('projectid',None)
M = models.BugResult
MU = models.User
MP = models.Project
MT = models.ScanTask
MV = models.Vulnerable
RU = MU.get(MU.uid == self.session['userid'])
sw = MP.project_user == RU
if projectid:
sw &= (MP.project_id == projectid)
ret = {}
#漏洞状态
query_state = (M
.select(M.bug_state,models.orm.fn.Count(M.bug_id).alias('count'))
.switch(M)
.join(MP)
.where(sw)
.group_by(M.bug_state))
ret_state = {}
for q in query_state:
ret_state[str(q.bug_state)] = str(q.count)
ret['statevalue'] = ret_state
sw &= M.bug_state != '已修复'
sw &= M.bug_state != '已忽略'
#漏洞名称
query_name = (M
.select(MV.vul_name,models.orm.fn.Count(M.bug_id).alias('count'))
.join(MV)
.group_by(MV.vul_name)
.switch(M)
.join(MP)
.where(sw)
.order_by(MV.vul_name)
.limit(8))
ret_name = {}
for qn in query_name:
ret_name[str(qn.vulid.vul_name)] = str(qn.count)
ret['namevalue'] = ret_name
#漏洞等级
query_rank = (M
.select(MV.vul_rank,models.orm.fn.Count(M.bug_id).alias('count'))
.join(MV)
.group_by(MV.vul_rank)
.switch(M)
.join(MP)
.where(sw)
.order_by(MV.vul_rank))
ret_rank = {}
for q in query_rank:
ret_rank[str(q.vulid.vul_rank)] = str(q.count)
ret['rankvalue'] = ret_rank
return ret
@Authenticated(2)
def _portdatabypid_action(self,data):
'''端口服务分布'''
projectid = data.get('projectid')
MU = models.User
MP = models.Project
MT = models.ScanTask
MH = models.HostResult
MR = models.PortResult
RU = MU.get(MU.uid == self.session['userid'])
sw = MP.project_user == RU
if projectid:
sw &= (MP.project_id == projectid)
ret = {}
ret['port'] = {}
query_port = (MR
.select(MR.port,models.orm.fn.Count(MR.port))
.group_by(MR.port)
.join(MH)
.switch(MP)
.join(MP)
.where(sw)
)
for q in query_port:
ret['port'][port] = str(q.count)
return ret
@Authenticated(2)
def _taskdiff_action(self,data):
'''任务对比'''
class Bug(dict):
def order(self):
return (self['bugname'],self['bugaddr'])
def __eq__(self,bug):
return self.order() == bug.order()
def __hash__(self):
return hash(self.order())
tida = data.get('tida')
tidb = data.get('tidb')
MB = models.BugResult
MV = models.Vulnerable
MT = models.ScanTask
R1 = MT.get(MT.task_id == tida)
R2 = MT.get(MT.task_id == tidb)
querya = [Bug({
"bugid":str(R.bug_id),
"bugname":str(R.vulid.vul_name),
"bugrank":str(R.vulid.vul_rank),
"bugaddr":str(R.bug_addr),
"bugstate":str(R.bug_state),
"createdate":str(R.createdate)
}) for R in MB.select().where(MB.taskid==R1).order_by(-MB.createdate)]
queryb = [Bug({
"bugid":str(R.bug_id),
"bugname":str(R.vulid.vul_name),
"bugrank":str(R.vulid.vul_rank),
"bugaddr":str(R.bug_addr),
"bugstate":str(R.bug_state),
"createdate":str(R.createdate)
}) for R in MB.select().where(MB.taskid==R2).order_by(-MB.createdate)]
ret = {}
inter = [] #交集
union = [] #差集
if querya and queryb:
for R1 in querya:
for R2 in queryb:
if(R1 == R2):
R2["bugstate"] = R1["bugstate"]
inter.append(R2)
elif R2 not in union and R2 not in querya:
union.append(R2)
elif queryb:
union = queryb
ret["inter"] = inter
ret["union"] = union
return ret
def _userlogin_action(self,data):
'''用户登录,验证码还没有写'''
username = data.get('u')
password = data.get('p')
verifycode = data.get('v')
M = models.User
try:
R = M.get(M.username == username)#, M.password == M._create_password(password))
if R._check_password(password):
R.lastlogin = datetime.datetime.now()
R.save()
self.session['userid'] = str(R.uid)
self.session['group'] = str(R.group)
self.session['projectid'] = str(R.projectid)
return {
'username' :str(R.username),
'token' :str(self.session),
'group' :str(R.group),
'projectid' :self.session['projectid']
}
else:
self.json['code'] = 401
self.json['error'] = ' 用户名或密码错误'
except M.DoesNotExist:
self.json['code'] = 401
self.json['error'] = '用户名或密码错误 '
####################项目管理####################################
@Authenticated(1)
def _projectselect_action(self,data):
'''选择默认项目'''
projectid = data.get('projectid')
MP = models.Project
MU = models.User
if projectid:
RP = MP.get(MP.project_id == projectid)
RP.finishdate = datetime.datetime.now()
RP.save()
RU = MU.update(
projectid = str(RP.project_id)
).where(
MU.uid == self.session['userid']
).execute()
self.session['projectid'] = str(RP.project_id)
return {
'projectid' :str(RP.project_id),
'projectname' :str(RP.project_name)
}
@Authenticated(2)
def _projectfinish_action(self,data):
'''删除/禁用项目'''
projectid = data.get('selectlist',[])
M = models.Project
MT = models.ScanTask
for pid in projectid:
M.update(
finishdate = '0000-00-00 00:00:00'
).where(
M.project_id == pid
).execute()
#停止该项目所在的任务
for Q in MT.select().join(M).where((M.project_id == pid)&((MT.task_code == 'PENDING')|(MT.task_code == 'waiting'))):
TaskManage.stoptask(str(Q.task_pid))
@Authenticated(2)
def _projectadd_action(self,data):
'''增加项目'''
project_name = data.get('project_name')
project_desc = data.get('project_desc')
MP = models.Project
MU = models.User
R = MP.create(
project_name = project_name,
project_desc = project_desc,
project_user = MU.get(MU.uid == self.session['userid'])
)
return {
'project_id' :str(R.project_id),
'project_name' :str(R.project_name),
'project_desc' :str(R.project_desc),
'createdate' :str(R.createdate),
'createuser' :str(R.project_user.realname),
}
@Authenticated(1)
def _projectget_action(self,data):
'''获取用户项目列表
emmm 一个请求33333ms 搞毛啊
'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',10)
MP = models.Project
MS = models.ScanTask
MB = models.BugResult
MU = models.User
MM = models.Member
createuser = MU.get(MU.uid == self.session['userid'])
sw = MP.project_user == createuser
pidlist = [str(p.projectid.project_id) for p in MM.select().where(MM.userid == createuser)]
if pidlist:
sw |= MP.project_id << pidlist
sw &= (MP.finishdate != '0000-00-00 00:00:00')
if keyword:
sw &= (MP.project_name.contains(keyword)|MP.project_desc.contains(keyword))
query = (MP.select()
.where(sw)
.order_by(-MP.finishdate))
ret = []
for R in query.paginate(page, size):
task = []
for r in MS.select().where((MS.projectid == R)&(MS.finishdate != '0000-00-00 00:00:00')):
task.append({
'desc':str(r.tasktype.task_desc),
'load':str(r.task_code)
})
bug = []
bug += [v for v in MB.select().where(MB.projectid == R)]
ret.append({
'project_id' :str(R.project_id),
'project_name' :str(R.project_name),
'project_desc' :str(R.project_desc),
'createuser' :str(R.project_user.realname),
'member' :[str(Q.userid.realname) for Q in MM.select().where(MM.projectid == R)],
'createdate' :str(R.createdate),
'scanvul' :len(bug),
'scantask' :len(task),
'tasklist' :list(set([d['desc'] for d in task])),
'project_load' :round((len([d for d in task if d['load']=='finish'])/len(task))*100,2) if task else 0
})
return ret
@Authenticated(3)
def _projectsget_action(self,data):
'''获取所有项目列表'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',10)
MP = models.Project
MS = models.ScanTask
MB = models.BugResult
MU = models.User
MM = models.Member
sw = MP.project_id
if keyword:
sw &= (MP.project_name.contains(keyword)|MP.project_desc.contains(keyword))
query = (MP.select()
.where(sw)
.order_by(-MP.finishdate))
ret = []
for R in query.paginate(page, size):
task = []
for r in MS.select().where((MS.projectid == R)&(MS.finishdate != '0000-00-00 00:00:00')):
task.append({
'desc':str(r.tasktype.task_desc),
'load':str(r.task_code)
})
bug = []
bug += [v for v in MB.select().where(MB.projectid == R)]
ret.append({
'project_id' :str(R.project_id),
'project_name' :str(R.project_name),
'project_desc' :str(R.project_desc),
'createuser' :str(R.project_user.realname),
'member' :[str(Q.userid.realname) for Q in MM.select().where(MM.projectid == R)],
'createdate' :str(R.createdate),
'scanvul' :len(bug),
'scantask' :len(task),
'tasklist' :list(set([d['desc'] for d in task])),
'project_load' :round((len([d for d in task if d['load']=='finish'])/len(task))*100,2) if task else 0
})
return ret
@Authenticated(2)
def _projectinfo_action(self,data):
'''项目详情'''
projectid = data.get('projectid')
MP = models.Project
MS = models.ScanTask
MV = models.VulResult
R = MP.get(MP.project_id == projectid)
task = []
query = (MS.select().where((MS.projectid ==R)&(MS.finishdate != '0000-00-00 00:00:00')))
for r in query:
task.append({
'taskid' :str(r.task_id),
'taskcode' :str(r.task_code),
'taskhost' :str(r.task_host),
'taskargs' :str(r.task_args),
'tasknote' :str(r.task_note),
'tasklevel' :str(r.task_level),
'taskname' :str(r.tasktype.task_desc),
'createdate':str(r.createdate),
'finishdate':str(r.finishdate),
})
return {
'projectid' :str(R.project_id),
'project_name' :str(R.project_name),
'project_desc' :str(R.project_desc),
'createuser' :str(R.project_user.realname),
'createdate' :str(R.createdate),
'finishdate' :str(R.finishdate),
'scantask' :task,
}
@Authenticated(1)
def _projectsearchbyname_action(self,data):
'''根据项目名称搜索'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',10)
MP = models.Project
MU = models.User
MM = models.Member
createuser = MU.get(MU.uid == self.session['userid'])
sw = MP.project_user == createuser
pidlist = [str(p.projectid.project_id) for p in MM.select().where(MM.userid == createuser)]
if pidlist:
sw |= MP.project_id << pidlist
sw &= MP.finishdate != '0000-00-00 00:00:00'
if keyword:
sw &= MP.project_name.contains(keyword)
query = (MP.select()
.where(sw)
.order_by(MP.createdate))
ret = []
for Q in query.paginate(page, size):
ret.append({
'id' :str(Q.project_id),
'name' :str(Q.project_name),
})
return ret
@Authenticated(2)
def _psettingedit_action(self,data):
'''项目设置'''
editd = data.get('editd')
pid = data.get('pid')
pname = data.get('pname')
pdesc = data.get('pdesc')
pmembers = data.get('pmembers',[])
pusers = data.get('pusers',[])
ppwds = data.get('ppwds',[])
MU = models.User
MP = models.Project
MD = models.DictResult
MM = models.Member
RU = MU.get(MU.uid==self.session['userid'])
RP = MP.get((MP.project_user==RU)&(MP.project_id == pid))
if pname or editd:
RP.project_name = pname
if pdesc or editd:
RP.project_desc = pdesc
RP.save()
if editd:
MD.delete().where((MD.projectid==RP)&(MD.dict_key == 'user')).execute()
MD.delete().where((MD.projectid==RP)&(MD.dict_key == 'pwd')).execute()
MM.delete().where(MM.projectid ==RP).execute()
for user in pusers:
MD.get_or_create(projectid=RP,dict_key='user',dict_value=user)
for pwd in ppwds:
MD.get_or_create(projectid=RP,dict_key='pwd',dict_value=pwd)
for member in pmembers:
MM.get_or_create(projectid=RP,userid=MU.get(MU.uid==member['uid']))
pusers = [str(Q.dict_value) for Q in MD.select().where((MD.projectid==RP)&(MD.dict_key == 'user'))]
pwds = [str(Q.dict_value) for Q in MD.select().where((MD.projectid==RP)&(MD.dict_key == 'pwd'))]
pmembers = [{
'uid':str(Q.userid.uid),
'username':str(Q.userid.username),
'realname':str(Q.userid.realname)
} for Q in MM.select().where(MM.projectid==RP)]
ret = {}
ret['pusers'] = pusers
ret['ppwds'] = pwds
ret['pmembers'] = pmembers
ret['pname'] = str(RP.project_name)
ret['pdesc'] = str(RP.project_desc)
return ret
######################任务管理##################################################
@Authenticated(3)
def _tasktypeget_action(self,data):
'''获取任务类型'''
tasktype = data.get('type','')
page = data.get('page',1)
size = data.get('size',100)
M = models.TaskType
sw = M.task_type != '-1'
if tasktype:
sw &= M.task_type == tasktype
query = M.select().where(sw)
ret = []
for R in query:
ret.append({
'task_name':str(R.task_name),
'task_desc':str(R.task_desc),
'task_type':str(R.task_type),
})
return ret
@Authenticated(3)
def _tasknodeget_action(self,data):
'''获取任务节点'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',100)
M = models.ClientNode
sw = M.node_stat == '200'
if keyword:
sw &= M.node_id.contains(keyword)
query = M.select().where(sw)
ret = []
for R in query:
ret.append({
'nodeid':str(R.node_id),
'nodestat':str(R.node_stat),
'nodeauth':str(R.node_auth),
})
return ret
@Authenticated(2)
def _scantasksearch_action(self,data):
'''本项目任务列表'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',50)
MS = models.ScanTask
MP = models.Project
sw = (MP.project_id==self.session['projectid'])
sw &= (MS.task_code != 'stop' )
if keyword:
sw &= (MS.task_id.contains(keyword))|(MS.task_host.contains(keyword))|(MS.task_note.contains(keyword))
query = (MS.select()
.join(MP)
.where(sw)
.order_by(-MS.createdate)
)
result = {}
result['current'] = page
result['total'] = query.count()
ret = []
for R in query.paginate(page, size):
ret.append({
'task_id' :str(R.task_id),
'task_code':str(R.task_code),
'task_host':str(R.task_host),
'task_name':str(R.tasktype.task_desc),
'task_args':str(R.task_args),
'createdate':str(R.createdate)[:10],
})
result['ret'] = ret
return result
@Authenticated(2)
def _scantaskadd_action(self,data):
'''新建任务'''
task_host = data.get('task_host')
task_name = data.get('task_name',[])
task_level = data.get('task_level',3)
task_args = json.dumps(data.get('task_args',{}))
task_note = data.get('task_note')
task_node = data.get('task_node',[])
MS = models.ScanTask
MP = models.Project
MT = models.TaskType
MC = models.ClientNode
RP = MP.get(MP.project_id == self.session['projectid'])
for name in task_name:
try:
RT = MT.get(MT.task_name == name)
except:
continue
for host in task_host.split():
if task_node and task_node[0]: #emmm 出现[""]这种情况识别为真
for node in task_node:
RC = MC.get(MC.node_id == task_node)
R = MS.create(
projectid = RP,
tasktype = RT,
tasknode = RC,
task_host = host,
task_args = task_args,
task_note = task_note,
task_level = task_level)
TaskManage.addtask(R)
else:
R = MS.create(
projectid = RP,
tasktype = RT,
task_host = host,
task_args = task_args,
task_note = task_note,
task_level = task_level)
TaskManage.addtask(R)
@Authenticated(2)
def _scantaskfinish_action(self,data):
'''删除任务'''
tasklist = data.get('selectlist',[])
M = models.ScanTask
MB = models.BugResult
for tid in tasklist:
R1 = M.get(M.task_id == tid)
task_pid = str(R1.task_pid)
R2 = MB.delete().where(MB.taskid==R1).execute()
R1.delete_instance()
TaskManage.stoptask(task_pid)
@Authenticated(2)
def _scanntaskinfo_action(self,data):
'''任务详情'''
taskid = data.get('taskid')
page = data.get('page',1)
size = data.get('size',50)
MS = models.ScanTask
MB = models.BugResult
MT = models.ScanHostPortTemp
R = MS.get(MS.task_id == taskid)
buglist = [{
'bugid':str(bug.bug_id),
'bugname':str(bug.vulid.vul_name),
'bugrank':str(bug.vulid.vul_rank)} \
for bug in (MB
.select()
.where(MB.taskid == R)
.order_by(MB.updatedate))]
hostlist = [{
'hostid' :str(h.host_id),
'host' :str(h.host),
'port' :str(h.port),
'status' :str(h.status),
'service' :str(h.service_name),
'softver' :''.join(str(h.soft_ver).split(',')),} \
for h in (MT.select()
.where(MT.taskid == R)
.order_by(MT.updatedate))]
return {'buglist' :buglist,
'hostlist' :hostlist,
'taskid' :str(R.task_id),
'taskcode' :str(R.task_code),
'taskhost' :str(R.task_host),
'taskargs' :str(R.task_args),
'tasknote' :str(R.task_note),
'taskpid' :str(R.task_pid),
'tasklevel' :str(R.task_level),
'taskname' :str(R.tasktype.task_desc),
'tasktype' :str(R.tasktype.task_name),
'tasknode' :str(R.tasknode.node_id if R.tasknode else ''),
'createdate':str(R.createdate),
'finishdate':str(R.finishdate),
}
@Authenticated(2)
def _taskinfoverify_action(self,data):
'''任务结果审核'''
hostids = data.get('hostids',[])
MT = models.ScanHostPortTemp
MH = models.HostResult
MP = models.PortResult
for hostid in hostids:
try:
Q = MT.get(MT.host_id == hostid)
RH,created = MH.get_or_create(projectid = Q.taskid.projectid, host_ip=Q.host)
RH.userid = Q.taskid.projectid.project_user
RH.host_name = Q.host_name
RH.mac_addr = Q.mac_addr
RH.os_type = Q.os_type
RH.updatedate = datetime.datetime.now()
RH.save()
if Q.status == 'delete':
MP.delete().where(MP.hostid==RH,MP.host==Q.host,MP.port==Q.port).execute()
else:
RP,created = MP.get_or_create(hostid=RH,host=RH.host_ip,port=Q.port)
RP.port_type = Q.port_type
RP.port_state = Q.port_state
RP.service_name = Q.service_name
RP.soft_name = Q.soft_name
RP.soft_type = Q.soft_type
RP.soft_ver = Q.soft_ver
RP.response = Q.response
RP.updatedate = datetime.datetime.now()
RP.save()
Q.delete_instance()
except MT.DoesNotExist:
continue
@Authenticated(2)
def _taskinfofinish_action(self,data):
'''任务结果审核'''
hostids = data.get('hostids',[])
MT = models.ScanHostPortTemp
for hostid in hostids:
MT.delete().where(MT.host_id == hostid).execute()
#####################漏洞管理########################################
@Authenticated(1)
def _buginfoget_action(self,data):
'''获取漏洞详情'''
bugid = data.get('bugid')
M = models.BugResult
R = M.get(M.bug_id == bugid)
return {
'projectid': str(R.projectid.project_id),
'projectname': str(R.projectid.project_name),
'createuser': str(R.userid.realname),
#'taskid': str(R.taskid.task_id),
'bugid': str(R.bug_id),
'bugaddr': str(R.bug_addr),
'bugstate': str(R.bug_state),
'bugtag': [v for v in str(R.bug_tag).split('|')],
'bugreq': str(R.request).replace('on','0n'),
'bugres': str(R.response),
'createdate': str(R.createdate),
'updatedate': str(R.createdate),
'vulinfo':{
'vulid': str(R.vulid.vul_id),
'vulrank': str(R.vulid.vul_rank),
'vulname': str(R.vulid.vul_name),
'vulreal': str(R.vulid.vul_real),
'vulowasp': str(R.vulid.vul_owasp),
'vulno': [v for v in str(R.vulid.vul_number).split('|')],
'vuldesc': str(R.vulid.vul_desc),
'vulplan': str(R.vulid.vul_plan),
}
}
@Authenticated(1)
def _stepinfoget_action(self,data):
'''获取漏洞处理进度'''
bugid = data.get('bugid')
MF = models.BugFlow
MB = models.BugResult
query = MF.select().where(
MF.flowid == MB.get(MB.bug_id == bugid)
).order_by(MF.createdate)
ret=[]
for R in query:
ret.append({
'flowid' : str(R.fid),
'flowname' : str(R.flowname.realname),
'updatedate': str(R.createdate),
'flownote' : str(R.flownote),
})
return ret
@Authenticated(1)
def _stepsave_action(self,data):
'''编辑漏洞进度'''
bugid = data.get('bugid')
note = data.get('note')
MF = models.BugFlow
MB = models.BugResult
MU = models.User
R = MF.create(
flowid = MB.get(
MB.bug_id == bugid),
flowname = MU.get(
MU.uid == self.session['userid']),
flownote = note
)
return {
'flowid' : str(R.fid),
'flowname' : str(R.flowname.realname),
'updatedate': str(R.createdate),
'flownote' : str(R.flownote),
}
@Authenticated(1)
def _bugsearch_action(self,data):
'''搜索漏洞'''
keyword = data.get('keyword')
page = data.get('page',1)
size = data.get('size',30)
history = data.get('history',False)
MB = models.BugResult
MV = models.Vulnerable
MP = models.Project
sw = MB.id
if history:
sw = ((MB.bug_state == '已修复')|(MB.bug_state == '已忽略'))
else:
sw &= (MB.bug_state != '已修复')
sw &= (MB.bug_state != '已忽略')
if keyword:
sw &= (MV.vul_name.contains(keyword) \
| MV.vul_real.contains(keyword) \
| MB.bug_id.contains(keyword) \
| MB.bug_addr.contains(keyword))
query = (MB
.select()
.join(MP)
.where(MP.project_id == self.session['projectid'])
.switch(MB)
.join(MV)
.where(sw)
.order_by(-MB.updatedate))
result = {}
result['current'] = page
result['total'] = query.count()
ret = []
for Q in query.paginate(page, size):
ret.append({
'bugid':str(Q.bug_id),
'bugrank':str(Q.vulid.vul_rank),
'bugname':str(Q.vulid.vul_name),
'bugaddr':str(Q.bug_addr),
'bugstate':str(Q.bug_state),
'updatedate':str(Q.updatedate),
})
result['ret'] = ret
return result