forked from SecuringWeb/BlackWidow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClasses.py
More file actions
2363 lines (1933 loc) · 96.3 KB
/
Classes.py
File metadata and controls
2363 lines (1933 loc) · 96.3 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
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
from importlib.metadata import method_cache
from lib2to3.fixes.fix_input import context
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import (StaleElementReferenceException,
TimeoutException,
UnexpectedAlertPresentException,
NoSuchFrameException,
NoAlertPresentException,
WebDriverException,
InvalidElementStateException
)
from urllib.parse import urlparse, urljoin
import json
import pprint
import datetime
import tldextract
import math
import os
import traceback
import random
import re
import time
import itertools
import string
from Functions import *
from extractors.Events import extract_events
from extractors.Forms import extract_forms, parse_form
from extractors.Urls import extract_urls
from extractors.Iframes import extract_iframes
from extractors.Ui_forms import extract_ui_forms
from selenium.webdriver.common.by import By
import logging
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
from openai import OpenAI
log_file = os.path.join(os.getcwd(), 'logs', 'crawl-' + str(time.time()) + '.log')
logging.basicConfig(filename=log_file,
format='%(asctime)s\t%(name)s\t%(levelname)s\t[%(filename)s:%(lineno)d]\t%(message)s',
datefmt='%Y-%m-%d:%H:%M:%S', level=logging.DEBUG)
# Turn off all other loggers that we don't care about.
for v in logging.Logger.manager.loggerDict.values():
v.disabled = True
logging.getLogger('seleniumwire').setLevel(logging.WARNING)
logging.getLogger('hpack').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
# This should be the main class for nodes in the graph
# Should contain GET/POST, Form data, cookies,
# events too?
class Request:
def __init__(self, url, method):
self.url = url
# GET / POST
self.method = method
self.context = {}
self.before_resource_operation = None
self.after_resource_operation = None
# Form data
# self.forms = []
def add_context(self, context):
for key in context:
self.context[key] = context[key]
def set_before_resource_operation(self, resource_operation):
self.before_resource_operation = resource_operation
def set_after_resource_operation(self, resource_operation):
self.after_resource_operation = resource_operation
def __repr__(self):
if not self:
return "NO SELF IN REPR"
ret = ""
if not self.method:
ret = ret + "[NO METHOD?] "
else:
ret = ret + "[" + self.method + "] "
if not self.url:
ret = ret + "[NO URL?]"
else:
ret = ret + self.url
if self.after_resource_operation:
ret = ret + " " + str(self.after_resource_operation)
elif self.before_resource_operation:
ret = ret + " " + str(self.before_resource_operation)
if self.context:
ret = ret + " " + str(self.context)
return ret
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Request):
ori_equal = (self.url == other.url and
self.method == other.method)
if not ori_equal:
semantic_equal = False
method_equal = self.method == other.method
if (self.after_resource_operation and self.after_resource_operation != {}
and other.after_resource_operation and other.after_resource_operation != {}):
semantic_equal = method_equal and compare_resource_operation(self.after_resource_operation, other.after_resource_operation)
elif (self.before_resource_operation and self.before_resource_operation != {}
and other.before_resource_operation and other.before_resource_operation != {}):
semantic_equal = method_equal and compare_resource_operation(self.before_resource_operation, other.before_resource_operation)
else:
semantic_equal = method_equal and compare_url_structure(self.url, other.url)
return semantic_equal
return ori_equal
return False
def __hash__(self):
str_req = self.url + self.method
if self.after_resource_operation:
str_req += self.after_resource_operation
elif self.before_resource_operation:
str_req += self.before_resource_operation
return hash(str_req)
class Graph:
def __init__(self):
self.nodes = []
self.edges = []
self.data = {} # Metadata that can be used for anything
# Separate node class for storing meta data.
class Node:
def __init__(self, value):
self.value = value
# Meta data for algorithms
self.visited = False
def __repr__(self):
return str(self.value)
def __eq__(self, other):
return self.value == other.value
def __hash__(self):
return hash(self.value)
class Edge:
# Value can be anything
# For the crawler (type, data) is used,
# where type = {"get", "form", "event"}
# and data = {None, data about form, data about event}
def __init__(self, n1, n2, value, parent=None):
self.n1 = n1
self.n2 = n2
self.value = value
self.visited = False
self.parent = parent
def __eq__(self, other):
return self.n1 == other.n1 and self.n2 == other.n2 and self.value == other.value
def __hash__(self):
return hash(hash(self.n1) + hash(self.n2) + hash(self.value))
def __repr__(self):
return str(self.n1) + " -(" + str(self.value) + "[" + str(self.visited) + "])-> " + str(self.n2)
def add(self, value):
node = self.Node(value)
if not node in self.nodes:
self.nodes.append(node)
return True
logging.info("failed to add node %s, already added" % str(value))
return False
def create_edge(self, v1, v2, value, parent=None):
n1 = self.Node(v1)
n2 = self.Node(v2)
edge = self.Edge(n1, n2, value, parent)
exist = edge in self.edges
if exist:
logging.warning("Edge already exists %s" % str(edge))
return edge, exist
def connect(self, v1, v2, value, parent=None):
#print("[connect]",v1,v2,value)
n1 = self.Node(v1)
n2 = self.Node(v2)
edge = self.Edge(n1, n2, value, parent)
p1 = n1 in self.nodes
p2 = n2 in self.nodes
p3 = not (edge in self.edges)
#print(p1,p2,p3)
if p1 and p2 and p3:
self.edges.append(edge)
return True
logging.warning("Failed to connect edge, %s (%s %s %s)" % (str(value), p1, p2, p3))
return False
def visit_node(self, value):
node = self.Node(value)
if node in self.nodes:
target = self.nodes[self.nodes.index(node)]
target.visited = True
return True
return False
def visit_edge(self, edge):
if (edge in self.edges):
target = self.edges[self.edges.index(edge)]
target.visited = True
return True
return False
def unvisit_edge(self, edge):
if (edge in self.edges):
target = self.edges[self.edges.index(edge)]
target.visited = False
return True
return False
def get_parents(self, value):
node = self.Node(value)
return [edge.n1.value for edge in self.edges if node == edge.n2]
def __repr__(self):
res = "---GRAPH---\n"
for n in self.nodes:
res += str(n) + " "
res += "\n"
for edge in self.edges:
res += str(edge.n1) + " -(" + str(edge.value) + "[" + str(edge.visited) + "])-> " + str(edge.n2) + "\n"
res += "\n---/GRAPH---"
return res
# Generates strings that can be pasted into mathematica to draw a graph.
def toMathematica(self):
cons = [('"' + str(edge.n1) + '" -> "' + str(edge.n2) + '"') for edge in self.edges]
data = "{" + ",".join(cons) + "}"
edge_cons = [('("' + str(edge.n1) + '" -> "' + str(edge.n2) + '") -> "' + edge.value.method + "," + str(
edge.value.method_data) + '"') for edge in self.edges]
edge_data = "{" + ",".join(edge_cons) + "}"
vertex_labels = 'VertexLabels -> All'
edge_labels = 'EdgeLabels -> ' + edge_data
arrow_size = 'EdgeShapeFunction -> GraphElementData["FilledArrow", "ArrowSize" -> 0.005]'
vertex_size = 'VertexSize -> 0.1'
image_size = 'ImageSize->Scaled[3]'
settings = [vertex_labels, edge_labels, arrow_size, vertex_size, image_size]
res = "Graph[" + data + ", " + ','.join(settings) + " ]"
return res
class Form:
def __init__(self):
self.action = None
self.method = None
self.inputs = {}
self.a_tags = {}
# 新增验证码相关属性
self.captcha = {
'captcha_type': None, # 验证码类型
'captcha_img': None, # 验证码元素对象
'value': None # 验证码的值(后续可能通过OCR或其他方式获取)
}
self.html = None
def set_html(self, html):
self.html = html
def set_capcha_captcha_type(self, captcha_type):
self.captcha['captcha_type'] = captcha_type
def get_captcha_captcha_type(self):
return self.captcha['captcha_type']
def set_capcha_captcha_img(self, captcha_img):
self.captcha['captcha_img'] = captcha_img
def set_capcha_value(self, value):
self.captcha['value'] = value
def set_capcha_slide_location(self, x, y):
self.captcha['slide_location'] = (x, y)
def set_captcha(self, captcha_type, captcha_img, value):
"""设置验证码相关信息"""
self.captcha['captcha_type'] = captcha_type
self.captcha['captcha_img'] = captcha_img
self.captcha['value'] = value
# Can we attack this form?
def attackable(self):
for input_el in self.inputs:
if not input_el.itype:
return True
if input_el.itype in ["text", "password", "textarea"]:
return True
return False
class Element:
def __init__(self, itype, accessible_name, name, value):
self.itype = itype
self.accessible_name = accessible_name
self.name = name
self.value = value
def __repr__(self):
return str((self.itype, self.accessible_name, self.name, self.value))
def __eq__(self, other):
return (self.itype == other.itype) and (self.accessible_name == other.accessible_name)
def __hash__(self):
return hash(hash(self.itype) + hash(self.accessible_name))
class SubmitElement:
def __init__(self, itype, accessible_name, name, value, use):
self.itype = itype
self.accessible_name = accessible_name
self.name = name
self.value = value
# If many submit button are available, one must be picked.
self.use = use
def __repr__(self):
return str((self.itype, self.accessible_name, self.name, self.value, self.use))
def __eq__(self, other):
return ((self.itype == other.itype) and
(self.accessible_name == other.accessible_name) and
(self.use == other.use))
def __hash__(self):
return hash(hash(self.itype) + hash(self.accessible_name) + hash(self.use))
class RadioElement:
def __init__(self, itype, accessible_name, name, value):
self.itype = itype
self.accessible_name = accessible_name
self.name = name
self.value = value
# Click is used when filling out the form
self.click = False
# User for fuzzing
self.override_value = ""
def __repr__(self):
return str((self.itype, self.accessible_name, self.name, self.value, self.override_value))
def __eq__(self, other):
p1 = (self.itype == other.itype)
p2 = (self.accessible_name == other.accessible_name)
p3 = (self.value == other.value)
return (p1 and p2 and p3)
def __hash__(self):
return hash(hash(self.itype) + hash(self.accessible_name) + hash(self.value))
class SelectElement:
def __init__(self, itype, accessible_name, name):
self.itype = itype
self.accessible_name = accessible_name
self.name = name
self.options = []
self.selected = None
self.override_value = ""
def add_option(self, value):
self.options.append(value)
def __repr__(self):
return str((self.itype, self.accessible_name, self.name, self.options, self.selected, self.override_value))
def __eq__(self, other):
return (self.itype == other.itype) and (self.accessible_name == other.accessible_name)
def __hash__(self):
return hash(hash(self.itype) + hash(self.accessible_name))
class CheckboxElement:
def __init__(self, itype, accessible_name, name, value, checked):
self.itype = itype
self.accessible_name = accessible_name
self.name = name
self.value = value
self.checked = checked
self.override_value = ""
def __repr__(self):
return str((self.itype, self.accessible_name, self.name, self.value, self.checked))
def __eq__(self, other):
return (self.itype == other.itype) and (self.accessible_name == other.accessible_name) and (
self.checked == other.checked)
def __hash__(self):
return hash(hash(self.itype) + hash(self.accessible_name) + hash(self.checked))
# <select>
def add_select(self, itype, accessible_name, name):
new_el = self.SelectElement(itype, accessible_name, name)
self.inputs[new_el] = new_el
return self.inputs[new_el]
# <input>
def add_input(self, itype, accessible_name, name, value, checked):
if itype == "radio":
new_el = self.RadioElement(itype, accessible_name, name, value)
key = self.RadioElement(itype, accessible_name, name, value)
elif itype == "checkbox":
new_el = self.CheckboxElement(itype, accessible_name, name, value, checked)
key = self.CheckboxElement(itype, accessible_name, name, value, None)
elif itype == "submit":
new_el = self.SubmitElement(itype, accessible_name, name, value, True)
key = self.SubmitElement(itype, accessible_name, name, value, None)
else:
new_el = self.Element(itype, accessible_name, name, value)
key = self.Element(itype, accessible_name, name, value)
self.inputs[key] = new_el
return self.inputs[key]
# <button>
def add_button(self, itype, accessible_name, name, value):
if itype == "submit":
new_el = self.SubmitElement(itype, accessible_name, name, value, True)
key = self.SubmitElement(itype, accessible_name, name, value, None)
else:
# button
logging.error("Unknown button " + str((itype, accessible_name, name, value)))
new_el = self.Element(itype, accessible_name, name, value)
key = self.Element(itype, accessible_name, name, value)
self.inputs[key] = new_el
return self.inputs[key]
def add_a_tag(self, id_name, accessible_name):
self.a_tags[id_name] = accessible_name
return self.a_tags[id_name]
# <textarea>
def add_textarea(self, accessible_name, name, value):
# Textarea functions close enough to a normal text element
new_el = self.Element("textarea", accessible_name, name, value)
self.inputs[new_el] = new_el
return self.inputs[new_el]
# <iframe>
def add_iframe_body(self, id):
new_el = self.Element("iframe", '', id, "")
self.inputs[new_el] = new_el
return self.inputs[new_el]
def print(self):
print("[form", self.action, self.method)
for i in self.inputs:
print("--", i)
print("]")
# For entire Form
def __repr__(self):
s = "Form(" + str(self.inputs.keys()) + ", " + str(self.action) + ", " + str(self.method) + ")"
return s
def __eq__(self, other):
return (self.action == other.action
and self.method == other.method
and self.inputs == other.inputs)
def __hash__(self):
return hash(hash(self.action) + hash(self.method) + hash(frozenset(self.inputs)))
# JavaScript events, clicks, onmouse etc.
class Event:
def __init__(self, fid, event, i, tag, addr, c):
self.function_id = fid
self.event = event
self.id = i
self.tag = tag
self.addr = addr
self.event_class = c
def __repr__(self):
s = "Event(" + str(self.event) + ", " + self.addr + ")"
return s
def __eq__(self, other):
return (self.function_id == other.function_id and
self.id == other.id and
self.tag == other.tag and
self.addr == other.addr)
def __hash__(self):
if self.tag == {}:
logging.warning("Strange tag... %s " % str(self.tag))
self.tag = ""
return hash(hash(self.function_id) +
hash(self.id) +
hash(self.tag) +
hash(self.addr))
class Iframe:
def __init__(self, i, src):
self.id = i
self.src = src
def __repr__(self):
id_str = ""
src_str = ""
if self.id:
id_str = "id=" + str(self.id)
if self.src:
src_str = "src=" + str(self.src)
s = "Iframe(" + id_str + "," + src_str + ")"
return s
def __eq__(self, other):
return (self.id == other.id and
self.src == other.src
)
def __hash__(self):
return hash(hash(self.id) +
hash(self.src)
)
class Ui_form:
def __init__(self, sources, submit):
self.sources = sources
self.submit = submit
def __repr__(self):
return "Ui_form(" + str(self.sources) + ", " + str(self.submit) + ")"
def __eq__(self, other):
self_l = set([source['xpath'] for source in self.sources])
other_l = set([source['xpath'] for source in other.sources])
return self_l == other_l
def __hash__(self):
return hash(frozenset([source['xpath'] for source in self.sources]))
class RAGManager:
def __init__(self, index_file, reports_file=None):
self.model = SentenceTransformer('all-MiniLM-L6-v2')
self.index_file = index_file
self.metadata = {}
# 判断是否需要重新构建索引
if reports_file or not os.path.exists(self.index_file):
print("Building a new FAISS index...")
self.index, self.metadata = self.build_faiss_index(reports_file)
self.persist_index() # 将新构建的索引持久化
else:
print("Loading FAISS index from disk...")
self.index = faiss.read_index(self.index_file)
self.metadata = self.load_metadata()
def build_faiss_index(self, reports_file):
# 从文件中加载漏洞报告
reports = json.loads(open(reports_file).read())
# 将描述与资源类型拼接并转换为向量
embeddings = [self.model.encode(
report["app_context"] + " " + report["resource_type"] + " " + report["operation"]
) for report in reports]
embeddings = np.array(embeddings).astype("float32")
# 创建 FAISS 索引
dimension = embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(embeddings)
# 存储每个向量的元数据(漏洞报告的相关信息)
metadata = {i: report for i, report in enumerate(reports)}
return index, metadata
def retrieve_similar_reports(self, query_text, top_k=3):
# 将查询文本转换为嵌入向量
query_embedding = self.model.encode(query_text).astype("float32").reshape(1, -1)
# 在向量数据库中检索 top-k 相似报告
_, indices = self.index.search(query_embedding, top_k)
similar_reports = [self.metadata[idx] for idx in indices[0]]
return similar_reports
def persist_index(self):
# 保存索引文件
faiss.write_index(self.index, self.index_file)
# 保存元数据
metadata_file = self.index_file + ".meta"
with open(metadata_file, "w") as f:
for i, report in self.metadata.items():
f.write(f"{i}\t{report}\n")
def load_metadata(self):
# 加载元数据文件
metadata_file = self.index_file + ".meta"
metadata = {}
if os.path.exists(metadata_file):
with open(metadata_file, "r") as f:
for line in f:
i, report_str = line.strip().split("\t", 1)
metadata[int(i)] = eval(report_str) # 转回字典格式
return metadata
class LLMManager:
def __init__(self, api_key, base_url, context=None):
self.api_key = api_key
self.context = context or []
self.base_url = base_url
self.client = OpenAI(api_key=api_key, base_url=base_url)
def add_to_context(self, message):
self.context.append(message)
def clear_context(self):
self.context = []
def fill_forms(self, dom_context, action_url, key_fields, prompt):
system_prompt_template = """You are an assistant helping with form filling in a black-box testing tool.
There are some form contexts that help you understand the form structure and the form's action URL including DOM structure, form action URL, and key form fields.
The DOM structure of the form is as follows: {dom_context}.
The form's action URL is: {action_url}.
The key form fields are: {key_fields}.
The user will provide the accessible name of the form input field, and you will generate appropriate input values for the form.
Additionally, you will have access to contextual information, including the DOM structure of the form, the form’s action URL, and key form fields.
Please generate suitable input content for the form field based on the accessible name and any relevant contextual clues, outputting the result in JSON format.
For example, if user provides the accessible name "username" for a text field like this:
{{
"accessible_name": "username",
"type": "text"
}}
Your response should be:
{{
"value": "admin"
}}
Take note of any additional field types and information provided in the form context. Use realistic values for fields where applicable, such as a valid email for an email field or a standard name for a text field.
"""
system_prompt = system_prompt_template.format(dom_context=dom_context, action_url=action_url, key_fields=key_fields)
conversation = [{'role': 'system',
'content': system_prompt}, {'role': 'user', 'content': prompt}]
# conversation += self.context
try:
response = self.client.chat.completions.create(
model="deepseek-chat",
# model="llama3.2:1b",
messages=conversation,
response_format={
'type': 'json_object'
}
)
answer = response.choices[0].message.content
try:
answer = json.loads(answer)
if answer == {}:
logging.warning("Failed to fill forms: " + str(answer))
elif not 'value' in answer:
logging.error("Failed to fill forms: " + str(answer))
answer = {}
except:
logging.error("Failed to parse response: " + str(answer))
answer = {}
self.add_to_context({'role': 'assistant', 'content': answer})
except Exception as e:
logging.error(f"Failed to generate response: {str(e)}")
answer = {}
return answer
def identify_resource_operation_before_request(self, purpose, details, prompt):
system_prompt_template = """You are a penetration testing expert. Below is a description of a web application that you
need to analyze. The purpose and main functionalities of this application are {purpose}. The main features include {details}.
I will provide you with various requests from this web application. Your task is to analyze each request and
determine what operation will be performed on which resource. In addition, please categorize the operation into
one of the following CRUD types: create, read, update, delete, or unknown.
Please answer in the following JSON format: {{"operation": "action", "resource": "resource type", "CRUD_type": "CRUD category"}}.
For example, if the request is about deleting an order, the answer should be:
{{"operation": "delete", "resource": "order", "CRUD_type": "delete"}}.
Now, please analyze the provided request and determine the operation, resource, and CRUD type.
If you are unable to determine the operation or resource, please return {{}} or {{"operation": "unknown", "resource": "unknown", "CRUD_type": "unknown"}}.
"""
system_prompt = system_prompt_template.format(purpose=purpose, details=details)
# 组合对话内容,包括系统提示和用户的请求提示
conversation = [{'role': 'system', 'content': system_prompt}, {'role': 'user', 'content': prompt}]
# conversation += self.context
try:
# 调用LLM接口生成回答
response = self.client.chat.completions.create(
model="deepseek-chat",
# model="llama3.2:1b",
messages=conversation,
response_format={
'type': 'json_object'
}
)
# 提取并返回回答
answer = response.choices[0].message.content
try:
answer = json.loads(answer)
if answer == {}:
logging.warning("Failed to identify resource operation: " + str(answer))
elif not 'operation' in answer or not 'resource' in answer:
logging.error("Failed to generate resource operation: " + str(answer))
answer = {}
else:
if 'operation' in answer and 'resource' in answer and 'CRUD_type' in answer:
if answer['operation'] == "unknown" or answer['resource'] == "unknown":
logging.warning("Unknown resource operation: " + str(answer))
answer = {}
except:
logging.error("Failed to parse response: " + str(answer))
answer = {}
self.add_to_context({'role': 'assistant', 'content': answer})
except Exception as e:
logging.error(f"Failed to generate response: {str(e)}")
answer = {}
return answer
def identify_resource_operation_after_request(self, purpose, details, prompt):
system_prompt_template = """You are a penetration testing expert. Below is a description of a web application that you
need to analyze. The purpose and main functionalities of this application are {purpose}. The main features include {details}.
We have encountered a situation where it is not possible to identify specific resource operations based solely on
the contextual information available before the request is sent. Therefore, we need to compare the page state
before and after the request, as well as the request and response data, to determine the resource operation.
I will provide you with the page state before and after the request, as well as the request and response data.
Your task is to analyze this information and determine what operation will be performed on which resource. In addition,
please categorize the operation into one of the following CRUD types: create, read, update, delete, or unknown.
Please answer in the following JSON format: {{"operation": "action", "resource": "resource type", "CRUD_type": "CRUD category"}}.
For example, if the request is about deleting an order, the answer should be:
{{"operation": "delete", "resource": "order", "CRUD_type": "delete"}}.
Now, please analyze the provided information and determine the operation, resource, and CRUD type.
If you are unable to determine the operation or resource, please return {{}} or {{"operation": "unknown", "resource": "unknown", "CRUD_type": "unknown"}}.
"""
system_prompt = system_prompt_template.format(purpose=purpose, details=details)
conversation = [{'role': 'system', 'content': system_prompt}, {'role': 'user', 'content': prompt}]
try:
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=conversation,
response_format={
'type': 'json_object'
}
)
answer = response.choices[0].message.content
try:
answer = json.loads(answer)
if answer == {}:
logging.warning("Failed to identify resource operation: " + str(answer))
elif not 'operation' in answer or not 'resource' in answer:
logging.error("Failed to generate resource operation: " + str(answer))
answer = {}
else:
if 'operation' in answer and 'resource' in answer and 'CRUD_type' in answer:
if answer['operation'] == "unknown" or answer['resource'] == "unknown":
logging.warning("Unknown resource operation: " + str(answer))
answer = {}
except:
logging.error("Failed to parse response: " + str(answer))
answer = {}
self.add_to_context({'role': 'assistant', 'content': answer})
except Exception as e:
logging.error(f"Failed to generate response: {str(e)}")
answer = {}
return answer
def infer_resource_operation_sensitivity(self, purpose, details, prompt):
system_prompt_template = """You are a penetration testing expert. Below is a description of a web application that you
need to analyze. The purpose and main functionalities of this application are {purpose}. The main features include {details}.
Your task is to assess the access control policy of a specific resource operation within this application to determine whether it may have authorization vulnerabilities.
I will provide you with reference vulnerability reports that include both real and false reports to guide your analysis.
Based on these, evaluate the access control policy of the resource operation in question by considering the following aspects:
1. Privilege Operation Assessment: Does this operation require privileged access, such as access restricted to administrators or high-level users only?
2. User-Related Operation Assessment: Is this operation tied to a specific user? For example, is it an action that only the owner of the resource should be able to perform?
3. Sensitive Information Exposure Assessment: Does the resource contain sensitive information, and should this operation be limited to certain users or roles to prevent sensitive information exposure?
Please respond in the following JSON format: {{"Privilege Operation": "Yes or No", "User-Related Operation": "Yes or No", "Sensitive Information Exposure": "Yes or No"}}
For example, if the operation requires privileged access, the answer should be:
{{"Privilege Operation": "Yes", "User-Related Operation": "No", "Sensitive Information Exposure": "No"}}
Now, please evaluate the access control policy of the resource operation in question based on the provided information.
If you are unable to determine the sensitivity of the resource operation, please return {{}} or {{"Privilege Operation": "Unknown", "User-Related Operation": "Unknown", "Sensitive Information Exposure": "Unknown"}}.
"""
system_prompt = system_prompt_template.format(purpose=purpose, details=details)
conversation = [{'role': 'system', 'content': system_prompt}, {'role': 'user', 'content': prompt}]
try:
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=conversation,
response_format={
'type': 'json_object'
}
)
answer = response.choices[0].message.content
try:
answer = json.loads(answer)
if answer == {}:
logging.warning("Failed to infer resource operation sensitivity: " + str(answer))
elif (not 'Privilege Operation' in answer or not 'User-Related Operation' in answer
or not 'Sensitive Information Exposure' in answer):
logging.error("Failed to infer resource operation sensitivity: " + str(answer))
answer = {}
except:
logging.error("Failed to parse response: " + str(answer))
answer = {}
self.add_to_context({'role': 'assistant', 'content': answer})
except Exception as e:
logging.error(f"Failed to generate response: {str(e)}")
answer = {}
return answer
class NetworkTrafficLogger:
def __init__(self, driver):
self.driver = driver
self.logged_urls = set()
def log_traffic(self):
traffic_data = []
for request in self.driver.requests:
if request.response:
url = request.url
if url.endswith((".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico")):
if url in self.logged_urls:
continue
self.logged_urls.add(url)
request_data = {
"request_url": url,
"request_method": request.method,
"request_headers": dict(request.headers),
"request_body": request.body.decode('utf-8', errors='ignore'),
"response_status": request.response.status_code,
"response_headers": dict(request.response.headers),
}
# Add response body only for non-static files
if not url.endswith((".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico")):
try:
request_data["response_body"] = request.response.body.decode('utf-8', errors='ignore')
except Exception as e:
request_data["response_body_error"] = str(e)
traffic_data.append(request_data)
# Write to a JSON file
with open("network_traffic.json", "w", encoding="utf-8") as file:
json.dump(traffic_data, file, ensure_ascii=False, indent=4)
class Crawler:
def __init__(self, driver, url):
self.root_req = None
self.debug_mode = None
self.driver = driver
# Start url
self.url = url
self.graph = Graph()
self.session_id = str(time.time()) + "-" + str(random.randint(1, 10000000))
# Used to track injections. Each injection will have unique key.
self.attack_lookup_table = {}
# input / output graph
self.io_graph = {}
# Optimization to do multiple events in a row without
# page reloads.
self.events_in_row = 0
self.max_events_in_row = 15
# Start with gets
self.early_gets = 0
self.max_early_gets = 100
# Don't attack same form too many times
# hash -> number of attacks
self.attacked_forms = {}
# Don't submit same form too many times
self.done_form = {}
self.max_done_form = 1
self.max_crawl_time = float(os.getenv("MAX_CRAWL_TIME", 3 * 60 * 60)) # 3小时 = 3 * 60分钟 * 60秒
self.logger = NetworkTrafficLogger(driver)
self.llm_manager = LLMManager(os.getenv("API_KEY"), os.getenv("BASE_URL"))
self.rag_manager = RAGManager("faiss_index.index", os.getenv("REPORTS_FILE_PATH", None))
self.resource_operation = {}
self.link_urls = []
self.users = [os.getenv("USER_1"), os.getenv("USER_2")]
self.cookies = []
self.local_storages = []
self.session_storages = []
self.authorization_keys = []
self.login_url = ""
self.isRESTFUL = False
logging.info("Init crawl on " + url)
def start(self, debug_mode=False):
self.root_req = Request("ROOTREQ", "get")
req = Request(self.url, "get")
self.graph.add(self.root_req)
self.graph.add(req)
self.graph.connect(self.root_req, req, CrawlEdge("get", None, None, None))
self.debug_mode = debug_mode
# Path deconstruction
# TODO arg for this
if not debug_mode:
purl = urlparse(self.url)
if purl.path:
path_builder = ""
for d in purl.path.split("/")[:-1]:
if d:
path_builder += d + "/"
tmp_purl = purl._replace(path=path_builder)
req = Request(tmp_purl.geturl(), "get")