-
-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathconsole.py
1581 lines (1240 loc) · 61.5 KB
/
console.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
'''
@author: LoRexxar
@contact: [email protected]
@file: console.py
@time: 2020/8/25 11:32
@desc:
'''
import os
import sys
import ast
import glob
import time
import codecs
import atexit
import pprint
import traceback
import logging
from functools import wraps
from prettytable import PrettyTable
from django.db.models import Q, QuerySet
from django.db.models.aggregates import Max
from utils.log import logger, logger_console, log, log_add
from utils import readlineng as readline
from utils.utils import get_mainstr_from_filename, file_output_format, show_context
from utils.status import get_scan_id
from Kunlun_M.settings import HISTORY_FILE_PATH, MAX_HISTORY_LENGTH
from Kunlun_M.settings import RULES_PATH, PROJECT_DIRECTORY, LOGS_PATH
from Kunlun_M.const import VUL_LEVEL
from core.__version__ import __introduction__
from core import cli
from core.engine import Running
from web.index.models import ScanTask, ScanResultTask, Rules, Tampers, NewEvilFunc
from web.index.models import get_resultflow_class, get_dataflow_class
from web.index.models import get_and_check_scantask_project_id, get_and_check_scanresult, check_and_new_project_id
def readline_available():
"""
Check if the readline is available. By default
it is not in Python default installation on Windows
"""
return readline._readline is not None
def clear_history():
if not readline_available():
return
readline.clear_history()
def save_history():
if not readline_available():
return
history_path = HISTORY_FILE_PATH
try:
with open(history_path, "w+"):
pass
except Exception:
pass
readline.set_history_length(MAX_HISTORY_LENGTH)
try:
readline.write_history_file(history_path)
except IOError as msg:
warn_msg = "there was a problem writing the history file '{0}' ({1})".format(history_path, msg)
logger.warn(warn_msg)
def load_history():
if not readline_available():
return
clear_history()
history_path = HISTORY_FILE_PATH
if os.path.exists(history_path):
try:
readline.read_history_file(history_path)
except IOError as msg:
warn_msg = "there was a problem loading the history file '{0}' ({1})".format(history_path, msg)
logger.warn(warn_msg)
def auto_completion(completion=None, console=None):
if not readline_available():
return
readline.set_completer_delims(" ")
readline.set_completer(console)
readline.parse_and_bind("tab: complete")
load_history()
atexit.register(save_history)
def stop_after(space_number):
""" Decorator that determines when to stop tab-completion
Decorator that tells command specific complete function
(ex. "complete_use") when to stop tab-completion.
Decorator counts number of spaces (' ') in line in order
to determine when to stop.
ex. "use exploits/dlink/specific_module " -> stop complete after 2 spaces
"set rhost " -> stop completing after 2 spaces
"run " -> stop after 1 space
:param space_number: number of spaces (' ') after which tab-completion should stop
:return:
"""
def _outer_wrapper(wrapped_function):
@wraps(wrapped_function)
def _wrapper(self, *args, **kwargs):
try:
if args[1].count(" ") == space_number:
return []
except Exception as err:
logger.error(err)
return wrapped_function(self, *args, **kwargs)
return _wrapper
return _outer_wrapper
class BaseInterpreter(object):
global_help = ""
def __init__(self):
self.setup()
self.banner = ""
self.complete = None
self.subcommand_list = []
def setup(self):
""" Initialization of third-party libraries
Setting interpreter history.
Setting appropriate completer function.
:return:
"""
auto_completion(completion=4, console=self.complete)
def parse_line(self, line):
""" Split line into command and argument.
:param line: line to parse
:return: (command, argument)
"""
command, _, arg = line.strip().partition(" ")
return command, arg.strip()
@property
def prompt(self):
""" Returns prompt string """
return ">>>"
def get_command_handler(self, command):
""" Parsing command and returning appropriate handler.
:param command: command
:return: command_handler
"""
try:
command_handler = getattr(self, "command_{}".format(command))
except AttributeError:
logger.error("Unknown command: '{}'".format(command))
return False
return command_handler
def start(self):
""" Routersploit main entry point. Starting interpreter loop. """
logger_console.info(self.global_help)
while True:
try:
command, args = self.parse_line(input(self.prompt))
command = command.lower()
if not command:
continue
command_handler = self.get_command_handler(command)
command_handler(args)
except EOFError:
logger.info("KunLun-M Console mode stopped")
break
except KeyboardInterrupt:
logger.info("Console Exit")
break
except:
logger.error("[Console] {}".format(traceback.format_exc()))
def complete(self, text, state):
"""Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
"""
if state == 0:
original_line = readline.get_line_buffer()
line = original_line.lstrip()
stripped = len(original_line) - len(line)
start_index = readline.get_begidx() - stripped
end_index = readline.get_endidx() - stripped
if start_index > 0:
cmd, args = self.parse_line(line)
if cmd == "":
complete_function = self.default_completer
else:
try:
complete_function = getattr(self, "complete_" + cmd)
except AttributeError:
complete_function = self.default_completer
else:
complete_function = self.raw_command_completer
self.completion_matches = complete_function(text, line, start_index, end_index)
try:
return self.completion_matches[state]
except IndexError:
return None
def commands(self, *ignored):
""" Returns full list of interpreter commands.
:param ignored:
:return: full list of interpreter commands
"""
command_list = [command.rsplit("_").pop() for command in dir(self) if command.startswith("command_")]
# command_list.extend(self.subcommand_list)
return command_list
def raw_command_completer(self, text, line, start_index, end_index):
""" Complete command w/o any argument """
return [command for command in self.suggested_commands() if command.startswith(text)]
def default_completer(self, *ignored):
return []
def suggested_commands(self):
""" Entry point for intelligent tab completion.
Overwrite this method to suggest suitable commands.
:return: list of suitable commands
"""
return self.commands()
class KunlunInterpreter(BaseInterpreter):
"""
console mode for kunlun-m
"""
global_help = __introduction__.format(detail="""Global commands:
help Print this help menu
scan Enter the scan mode
load <scan_id> Load Scan task
showt Show all Scan task list
show [rule, tamper] <key> Show rules or tampers
search [vendor, ] <vendor_name> <vendor_version> Search Project which contains vendor
config [rule, tamper] <rule_id> | <tamper_name> Config mode for rule & tamper
exit Exit KunLun-M & save Config""")
config_rule_help = """Config Rule commands:
help Print this help menu
showit Show All config
set <option name> <value> Set Rule option
cancel Cancel last set
save Save option
back Back to the root list
"""
config_tamper_help = """Config Tamper commands:
help Print this help menu
showit Show All config
add <option name> <value> Add tamper option
cancel Cancel last set
save Save option
back Back to the root list
"""
scan_help = """Scan commands:
help Print this help menu
set <option name> <value> Set scan option
status Get Task status
run Run Task with the given options
back Back to the root list
"""
result_help = """Result Commands:
help Print this help menu
show [vuls, newevilfunc, options] <result_id> | <option_name> <option_value>
Show result vuls/new evil func with option or show display option
del [vuls, newevilfunc] <result_id> Del result id
set <option_name> <option_value> Config for show mode
check_log Open log file
back Back to the root list
"""
def __init__(self):
super(KunlunInterpreter, self).__init__()
self.prompt_hostname = "KunLun-M"
self.current_mode = 'root'
self.global_commands = ['help', 'scan', 'load ', 'showt', 'show ', 'search ', 'config ', 'exit']
self.config_commands = ['help', 'set ', 'save', 'back', 'showit']
self.scan_commands = ['help', 'set ', 'show ', 'run', 'status']
self.result_commands = ['help', 'show ', 'del ', 'set ', 'back']
self.subcommand_root_list = ['rule', 'tamper']
self.subcommand_result_list = ['options', 'vuls', 'newevilfunc']
self.subcommand_list = ['options', 'vuls', 'rule', 'tamper', 'newevilfunc']
self.show_index = 0
self.show_mode_list = ['showt', 'rule']
self.show_commands = ['n']
self.show_mode = ""
self.config_mode = ""
self.config_keyword = ""
self.config_dict = {}
self.config_obj = None
self.last_config = {}
self.rule_filecontent = ""
self.configurable_options = ['status', 'match_mode', 'match', 'match_name', 'black_list', 'keyword', 'unmatch', 'vul_function']
self.result_task_id = None
self.result_obj = None
self.result_options = {
"cvi_id": "all",
"language": "all",
"active_vul": True,
"get_unconfirm": True,
"result_type": "all",
}
self.result_option_list = {
"cvi_id": ["all", "<CVI_id>"],
"language": ["all", "<language>"],
"result_type": ["all", "<result_type>"],
"active_vul": [True, False, 'all'],
"get_unconfirm": [True, False, 'only'],
}
self.scan_options = {
"target": None,
"format": 'csv',
"output": None,
"rule_id": "all",
"tamper": None,
"log_name": None,
"language": None,
"black_path": None,
"is_debug": True,
"is_without_precom": False,
}
self.scan_option_list = {
"target": ["<target_path>"],
"format": ['csv', 'json', 'csv', 'xml'],
"output": ["<output>"],
"rule_id": ["all", "<CVI_ID>"],
"tamper": ['<tamper_name>'],
"log_name": ['<logfile_name>'],
"language": [None, 'php', 'javascript', 'solidity'],
"black_path": ['<black_path>'],
"is_debug": [False, True],
"is_without_precom": [False, True],
}
self.scan_option_help = {
"target": "file, folder",
"format": "vulnerability output format",
"output": "vulnerability output STREAM, FILE",
"rule_id": "specifies rules ",
"tamper": "tamper repair function",
"log_name": "log file name",
"language": "set target language",
"black_path": "black path list",
"is_debug": "open debug mode",
"is_without_precom": "without Precompiled. for quick only regex scan",
}
self.scan_short_options = {
"target": 't',
"format": 'f',
"output": 'o',
"rule_id": 'r',
"tamper": 'tp',
"log_name": 'l',
"language": 'lan',
"black_path": 'b',
"is_debug": 'd',
"is_without_precom": 'upc',
}
self.scan_required_options_list = ["target"]
self.__parse_prompt()
def __parse_prompt(self):
raw_prompt_default_template = "\001\033[4m\002{host}\001\033[0m\002 > "
self.raw_prompt_template = raw_prompt_default_template
module_prompt_default_template = "\001\033[4m\002{host}\001\033[0m\002 (\001\033[91m\002{module}\001\033[0m\002) > "
self.module_prompt_template = module_prompt_default_template
@property
def prompt(self):
""" Returns prompt string based on current_module attribute.
Adding module prefix (module.name) if current_module attribute is set.
:return: prompt string with appropriate module prefix.
"""
if self.current_mode:
try:
return self.module_prompt_template.format(host=self.prompt_hostname,
module=self.current_mode)
except (AttributeError, KeyError):
return self.module_prompt_template.format(host=self.prompt_hostname, module="UnnamedModule")
else:
return self.raw_prompt_template.format(host=self.prompt_hostname)
def clear_args(self, args):
new_arg_list = []
arg_list = args.split(" ")
temp_str = None
temp_sign = None
for arg in arg_list:
if arg:
# 如果temp_str 和 temp_sign
if temp_str and temp_sign:
if arg[-1] == temp_sign:
arg = temp_str + " " + arg[:-1]
temp_str = None
temp_sign = None
else:
temp_str += " "
temp_str += arg
continue
if arg[0] in ['"', "'"]:
temp_str = arg[1:]
temp_sign = arg[0]
# 如果剩下的字符里没有闭合该引号,那继续读取下一个
if temp_sign not in temp_str:
continue
else:
new_arg_list.append(temp_str[:-1])
else:
new_arg_list.append(arg)
return new_arg_list
def command_help(self, *args, **kwargs):
if self.current_mode == 'config':
if self.config_mode == 'rule':
logger_console.info(self.config_rule_help)
elif self.config_mode == 'tamper':
logger_console.info(self.config_tamper_help)
elif self.current_mode == 'scan':
logger_console.info(self.scan_help)
elif self.current_mode == 'result':
logger_console.info(self.result_help)
else:
self.current_mode = 'root'
logger_console.info(self.global_help)
def command_back(self, *args, **kwargs):
self.current_mode = 'root'
self.show_mode = ""
self.config_mode = ""
self.config_keyword = ""
self.last_config = {}
logger_console.info(self.global_help)
def command_scan(self, *args, **kwargs):
self.current_mode = 'scan'
os.chdir(PROJECT_DIRECTORY)
# set log
self.scan_options['log_name'] = self.check_scan_log_file()
logger_console.info(self.scan_help)
def command_exit(self, *args, **kwargs):
raise EOFError
def show_task(self, count=10):
sts = ScanTask.objects.all().order_by('-id')
# self.show_index = 0
index = 0
sts_table = PrettyTable(
['id', 'TaskName', 'Parameter', 'Scan_Time', 'Is_finished'])
sts_table.align = 'l'
if sts:
for st in sts:
if st:
if self.show_index <= index < count:
self.show_index += 1
parameter_config = " ".join(ast.literal_eval(st.parameter_config)).replace('\\', '/')
sts_table.add_row(
[st.id, st.task_name, parameter_config, str(st.last_scan_time)[:19], st.is_finished])
index += 1
logger.info("[Console] Show Scan Task list:\n{}".format(sts_table))
logger.warn("[Console] Now You can Enter N show Next 10 Tasks.")
else:
logger.warn("[Console] Now have no Scan Task.")
def command_showt(self, *args, **kwargs):
self.current_mode = 'showt'
self.show_index = 0
self.show_task(10)
def command_n(self, *args, **kwargs):
if self.current_mode not in self.show_mode_list:
logger.warn("[Console] Command N only for show mode.")
return
if self.current_mode == 'showt':
self.show_task(self.show_index + 10)
def show_rule_by_id(self, rule_id):
rule = Rules.objects.filter(svid=rule_id).first()
if rule:
template_file = codecs.open(os.path.join(RULES_PATH, 'rule.template'), 'rb+', encoding='utf-8',
errors='ignore')
template_file_content = template_file.read()
template_file.close()
rule_name = rule.rule_name
svid = rule.svid
language = rule.language
author = rule.author
description = rule.description
level = rule.level
status = "True" if rule.status else "False"
match_mode = rule.match_mode
match = file_output_format(rule.match)
match_name = file_output_format(rule.match_name)
black_list = file_output_format(rule.black_list)
keyword = file_output_format(rule.keyword)
unmatch = file_output_format(rule.unmatch)
vul_function = file_output_format(rule.vul_function)
main_function = rule.main_function
logger.info("[Console] Rule CVI_{} Detail:\n{}".format(svid, template_file_content.format(
rule_name=rule_name, svid=svid, language=language,
author=author, description=description, level=level, status=status,
match_mode=match_mode, match=match,
match_name=match_name,
black_list=black_list, keyword=keyword,
unmatch=unmatch,
vul_function=vul_function,
main_function=main_function)))
logger.warn("[Console] You can edit the Rule by command 'config rule <rule_id>'")
return
else:
logger.error("[Console] Please check Rule id or or use the command 'show rule' to view")
def load_rule_dict_by_id(self, rule_id):
rule = Rules.objects.filter(svid=rule_id).first()
# rule_dict = {}
if not rule:
logger.error("[Console] Please check Rule id or or use the command 'show rule' to view")
return False
return rule
def show_rule_by_dict(self, rule):
if rule:
template_file = codecs.open(os.path.join(RULES_PATH, 'rule.template'), 'rb+', encoding='utf-8',
errors='ignore')
template_file_content = template_file.read()
template_file.close()
# for rule
rule_dict = {}
rule_dict['rule_name'] = rule.rule_name
rule_dict['svid'] = rule.svid
rule_dict['language'] = rule.language
rule_dict['author'] = rule.author
rule_dict['description'] = rule.description
rule_dict['level'] = rule.level
rule_dict['status'] = "True" if rule.status else "False"
rule_dict['match_mode'] = rule.match_mode
rule_dict['match'] = file_output_format(rule.match)
rule_dict['match_name'] = file_output_format(rule.match_name)
rule_dict['black_list'] = file_output_format(rule.black_list)
rule_dict['keyword'] = file_output_format(rule.keyword)
rule_dict['unmatch'] = file_output_format(rule.unmatch)
rule_dict['vul_function'] = file_output_format(rule.vul_function)
rule_dict['main_function'] = rule.main_function
self.rule_filecontent = template_file_content.format(
rule_name=rule_dict['rule_name'], svid=rule_dict['svid'], language=rule_dict['language'],
author=rule_dict['author'], description=rule_dict['description'], level=rule_dict['level'], status=rule_dict['status'],
match_mode=rule_dict['match_mode'], match=rule_dict['match'],
match_name=rule_dict['match_name'],
black_list=rule_dict['black_list'], keyword=rule_dict['keyword'],
unmatch=rule_dict['unmatch'],
vul_function=rule_dict['vul_function'],
main_function=rule_dict['main_function'])
logger.info("[Console] Rule CVI_{} Detail:\n{}".format(rule_dict['svid'], self.rule_filecontent))
logger.warn("[Console] This is currently a temporary file, you must use Command 'save' to save")
return
else:
logger.error("[Console] Please check Rule id or or use the command 'show rule' to view")
def show_tamper_by_dict(self, tamper_dict):
if tamper_dict:
filter_func = self.config_dict['filter_func']
input_control = self.config_dict['input_control']
logger.info("""\nTamper Name:
{}
Filter Func:
{}
Input Control:
{}
""".format(self.config_keyword, pprint.pformat(filter_func, indent=4), pprint.pformat(input_control, indent=4)))
logger.warn("[Console] This is currently a temporary file, you must use Command 'save' to save")
return
else:
logger.error("[Console] Not Found Tampers, Please check command or execute config load.")
def save_rule_to_file(self):
"""
save rule content info rule file
:return:
"""
self.show_rule_by_dict(self.config_obj)
lan = self.config_obj.language
if not os.path.isdir(os.path.join(RULES_PATH, lan)):
os.mkdir(os.path.join(RULES_PATH, lan))
rule_lan_path = os.path.join(RULES_PATH, lan)
svid = self.config_obj.svid
rule_path = os.path.join(rule_lan_path, "CVI_{}.py".format(svid))
logger.info("[Console] new Rule file CVI_{}.py init.".format(svid))
rule_file = codecs.open(rule_path, "wb+", encoding='utf-8', errors='ignore')
rule_file.write(self.rule_filecontent)
rule_file.close()
return True
def get_scan_results_by_config(self):
project_id = get_and_check_scantask_project_id(self.result_task_id)
logger.info("Task {} belong Project {}.".format(self.result_task_id, project_id))
srs = get_and_check_scanresult(self.result_task_id).objects.filter(scan_project_id=project_id)
orm_limit = {}
if srs:
for option_name in self.result_options:
if option_name in ['language', 'result_type', 'active_vul', 'cvi_id']:
if self.result_options[option_name] == 'all':
continue
if option_name == 'active_vul':
orm_limit['is_active'] = self.result_options[option_name]
else:
orm_limit[option_name] = self.result_options[option_name]
elif option_name == 'get_unconfirm':
if self.result_options[option_name] == True:
continue
elif self.result_options[option_name] == 'only':
orm_limit['is_unconfirm'] = True
else:
orm_limit['is_unconfirm'] = False
q = Q()
for i in orm_limit:
q.add(Q(**{i: orm_limit[i]}), Q.AND)
# scan_task_id
q.add(Q(**{"scan_project_id": project_id}), Q.AND)
srs = get_and_check_scanresult(self.result_task_id).objects.filter(q).annotate(max_id=Max('id'))
return srs
else:
return False
def get_new_evil_func(self, option_name=None, option_value=None):
project_id = get_and_check_scantask_project_id(self.result_task_id)
logger.info("Task {} belong Project {}.".format(self.result_task_id, project_id))
nfs = NewEvilFunc.objects.filter(project_id=project_id)
orm_limit = {}
result_list = []
if nfs:
if self.result_options['active_vul'] != 'all':
orm_limit['is_active'] = self.result_options['active_vul']
q = Q()
for i in orm_limit:
q.add(Q(**{i: orm_limit[i]}), Q.AND)
# scan_task_id
q.add(Q(**{"project_id": project_id}), Q.AND)
nfs = NewEvilFunc.objects.filter(q).annotate(max_id=Max('id'))
if option_name and option_value:
for nf in nfs:
if option_value in str(getattr(nf, option_name)):
result_list.append(nf)
return result_list
else:
return nfs
else:
return False
def check_scan_options(self):
for option_name in self.scan_options:
if option_name in self.scan_required_options_list:
if not self.scan_options[option_name]:
logger.error("[Console] Option {} is a required option.You must set it before scanning.".format(option_name))
return False
if option_name == 'target':
target = self.scan_options[option_name]
if not os.path.exists(target):
logger.error("[Console] Target {} is not exist.".format(target))
return False
# all不需要专门限制
if self.scan_options[option_name] == "all":
self.scan_options[option_name] = None
return True
def check_scan_log_file(self):
last_scantask = ScanTask.objects.all().order_by('-id').first()
if last_scantask:
logfile_name = 'ScanTask_{}'.format(last_scantask.id+1)
else:
logfile_name = 'ScanTask_1'
i = 1
while os.path.exists(os.path.join(LOGS_PATH, logfile_name+'.log')):
if '-' not in logfile_name:
logfile_name += '-{}'.format(i)
else:
logfile_name = logfile_name[:-2] + '-{}'.format(i)
return logfile_name
def get_sacn_parameters(self):
parameter_config = ["./kunlun.py"]
for option_name in self.scan_options:
if self.scan_options[option_name] is None or self.scan_options[option_name] == 'all' or self.scan_options[option_name] is False:
continue
if self.scan_options[option_name] is True:
parameter_config.append(" -" + self.scan_short_options[option_name])
continue
parameter_config.append(" -" + self.scan_short_options[option_name])
parameter_config.append(" {}".format(self.scan_options[option_name]))
return parameter_config
def command_get(self, *args, **kwargs):
if self.show_mode not in self.show_mode_list:
logger.warn("[Console] Command Show only for show mode")
return
if self.show_mode == 'rule':
param = self.clear_args(args[0])
if param:
key = param[0]
self.show_rule_by_id(key)
else:
logger.error("[Console] You must specify the rule id. e.g.: get 1001")
def command_set(self, *args, **kwargs):
if self.current_mode not in ['config', 'result', 'scan']:
logger.warn("[Console] Command set only for config/result/scan mode")
return
if self.current_mode == 'config':
if self.config_mode == 'rule':
param = self.clear_args(args[0])
if len(param) < 2:
logger.error("[Console] you must set option name and value. e.g.: set status False")
return
option_name = param[0]
option_value = param[1]
option_value = ast.literal_eval(option_value) if option_value in ['True', 'False', 'None'] else option_value
if option_name not in self.configurable_options:
logger.warn("[Console] You can't edit option {}.".format(option_name))
return
# load last profile
if getattr(self.config_obj, option_name) == option_value:
logger.warn("[Console] The options you set have not been changed.")
return
self.last_config[option_name] = getattr(self.config_obj, option_name)
# self.config_dict[option_name] = option_value
setattr(self.config_obj, option_name, option_value)
logger.info("[Console] Update {}={}. Use 'showit' to view Detail.".format(option_name, option_value))
logger.warn("[Console] Use Command 'cancel' to cancel last set or Command 'save' to save rule." )
return
elif self.current_mode == 'result':
param = self.clear_args(args[0])
if len(param) < 2:
logger.error("[Console] you must set option name and value. e.g.: set active_vul all")
return
option_name = param[0]
option_value = param[1]
option_list = list(self.result_option_list)
if option_name not in option_list:
logger.error("[Console] you can only set option in {}.".format(option_list))
return
option_value = ast.literal_eval(option_value) if option_value in ['True', 'False'] else option_value
if option_value in self.result_option_list[option_name]:
self.result_options[option_name] = option_value
logger.info("[Console] Change Show options {}={}".format(option_name, option_value))
elif "<" in str(self.result_option_list[option_name]):
self.result_options[option_name] = option_value
logger.info("[Console] Change Show options {}={}".format(option_name, option_value))
else:
logger.info("[Console] Only accept option from {}".format(self.result_option_list[option_name]))
return
elif self.current_mode == 'scan':
param = self.clear_args(args[0])
if len(param) < 2:
logger.error("[Console] you must set option name and value. e.g.: set is_debug True")
return
option_name = param[0]
option_value = param[1]
if option_name not in list(self.scan_options):
logger.error("[Console] you can only set option in {}.".format(list(self.scan_options)))
return
option_value = ast.literal_eval(option_value) if option_value in ['True', 'False', 'None'] else option_value
if option_value in self.scan_option_list[option_name]:
self.scan_options[option_name] = option_value
logger.info("[Console] Change Show options {}={}".format(option_name, option_value))
elif "<" in str(self.scan_option_list[option_name]):
self.scan_options[option_name] = option_value
logger.info("[Console] Change Show options {}={}".format(option_name, option_value))
else:
logger.info("[Console] Only accept option from {}".format(self.scan_option_list[option_name]))
return
def command_add(self, *args, **kwargs):
if self.current_mode not in ['config']:
logger.warn("[Console] Command add only for config mode")
return
if self.current_mode == 'config':
if self.config_mode == 'tamper':
param = self.clear_args(args[0])
if len(param) < 2:
logger.error("[Console] you must set option name and value. e.g.: set status False")
return
option_name = param[0]
option_value = param[1]
# 如果option_name 和tamper_name相同,那么为Input-Control
# 如果不是,那么为Filter-Function
if option_name == self.config_keyword:
self.config_dict['input_control'].append(option_value)
self.last_config['input_control'].append(option_value)
logger.info("[Console] Add New Tamper for {} New Input-Control {}".format(self.config_keyword, option_value))
else:
if option_name in self.config_dict['filter_func']:
# check exist
if int(option_value) in self.config_dict['filter_func'][option_name]:
logger.error("[Console] New Tamper for {} New filter_function exists.".format(self.config_keyword))
return
else:
self.config_dict['filter_func'][option_name].append(int(option_value))
else:
self.config_dict['filter_func'][option_name] = [int(option_value)]
# record last change
if option_name in self.last_config['filter_func']:
self.last_config['filter_func'][option_name].append(int(option_value))
else:
self.last_config['filter_func'][option_name] = [int(option_value)]
logger.info("[Console] Add New Tamper for {} New filter_func {} for {}".format(self.config_keyword, option_name, option_value))
return
def command_cancel(self, *args, **kwargs):
if self.current_mode not in ['config']:
logger.warn("[Console] Command cancel only for config mode")
return
if self.current_mode == 'config':
if self.config_mode == 'rule':
if not self.last_config:
logger.error("[Console] No saved last configuration found.")
for option_name in self.last_config:
logger.info("[Console] Restore config {}={}".format(option_name, self.last_config[option_name]))
# self.config_dict[option_name] = self.last_config[option_name]
setattr(self.config_obj, option_name, self.last_config[option_name])
self.last_config = {}
return
elif self.config_mode == 'tamper':
if not self.last_config:
logger.error("[Console] No saved last configuration found.")
for option_name in self.last_config['filter_func']:
for option_value in self.last_config['filter_func'][option_name]:
logger.info("[Console] Restore filter_func tamper {} for {}".format(option_name, option_value))
self.config_dict['filter_func'][option_name].remove(int(option_value))
for option_value in self.last_config['input_control']:
logger.info("[Console] Restore Input-Control tamper {}".format(option_value))
self.config_dict['input_control'].remove(option_value)
self.last_config['filter_func'] = {}
self.last_config['input_control'] = []
return
def command_save(self, *args, **kwargs):
if self.current_mode not in ['config']:
logger.warn("[Console] Command set only for config mode")
return
if self.current_mode == 'config':
if self.config_mode == 'rule':
# rule = Rules.objects.filter(svid=self.config_dict['svid']).first()
#