forked from SecuringWeb/BlackWidow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Classes.py
1554 lines (1257 loc) · 55.6 KB
/
Classes.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
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 selenium.webdriver.common.by import By
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
import logging
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
# 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
# Form data
# self.forms = []
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
return ret
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, Request):
return (self.url == other.url and
self.method == other.method)
return False
def __hash__(self):
return hash(self.url + self.method)
class Graph:
def __init__(self):
self.nodes = []
self.edges = []
self.data = {} # Meta data 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)
return edge
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 = {}
# 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, name, value):
self.itype = itype
self.name = name
self.value = value
def __repr__(self):
return str( (self.itype, self.name, self.value) )
def __eq__(self, other):
return (self.itype == other.itype) and (self.name == other.name)
def __hash__(self):
return hash(hash(self.itype) + hash(self.name))
class SubmitElement:
def __init__(self, itype, name, value, use):
self.itype = itype
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.name, self.value, self.use) )
def __eq__(self, other):
return ((self.itype == other.itype) and
(self.name == other.name) and
(self.use == other.use))
def __hash__(self):
return hash(hash(self.itype) + hash(self.name) + hash(self.use))
class RadioElement:
def __init__(self, itype, name, value):
self.itype = itype
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.name, self.value, self.override_value) )
def __eq__(self, other):
p1 = (self.itype == other.itype)
p2 = (self.name == other.name)
p3 = (self.value == other.value)
return (p1 and p2 and p3)
def __hash__(self):
return hash(hash(self.itype) + hash(self.name) + hash(self.value))
class SelectElement:
def __init__(self, itype, name):
self.itype = itype
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.name, self.options, self.selected, self.override_value) )
def __eq__(self, other):
return (self.itype == other.itype) and (self.name == other.name)
def __hash__(self):
return hash(hash(self.itype) + hash(self.name) )
class CheckboxElement:
def __init__(self, itype, name, value, checked):
self.itype = itype
self.name = name
self.value = value
self.checked = checked
self.override_value = ""
def __repr__(self):
return str( (self.itype, self.name, self.value, self.checked) )
def __eq__(self, other):
return (self.itype == other.itype) and (self.name == other.name) and (self.checked == other.checked)
def __hash__(self):
return hash(hash(self.itype) + hash(self.name) + hash(self.checked))
# <select>
def add_select(self, itype, name):
new_el = self.SelectElement(itype, name)
self.inputs[new_el] = new_el
return self.inputs[new_el]
# <input>
def add_input(self, itype, name, value, checked):
if itype == "radio":
new_el = self.RadioElement(itype, name, value)
key = self.RadioElement(itype, name, value)
elif itype == "checkbox":
new_el = self.CheckboxElement(itype, name, value, checked)
key = self.CheckboxElement(itype, name, value, None)
elif itype == "submit":
new_el = self.SubmitElement(itype, name, value, True)
key = self.SubmitElement(itype, name, value, None)
else:
new_el = self.Element(itype, name, value)
key = self.Element(itype, name, value)
self.inputs[key] = new_el
return self.inputs[key]
# <button>
def add_button(self, itype, name, value):
if itype == "submit":
new_el = self.SubmitElement(itype, name, value, True)
key = self.SubmitElement(itype, name, value, None)
else:
logging.error("Unknown button " + str((itype,name,value)))
new_el = self.Element(itype, name, value)
key = self.Element(itype, name, value)
self.inputs[key] = new_el
return self.inputs[key]
# <textarea>
def add_textarea(self, name, value):
# Textarea functions close enough to a normal text element
new_el = self.Element("textarea", 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(len(self.inputs))+", " + 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 Crawler:
def __init__(self, driver, url):
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
# Dont attack same form too many times
# hash -> number of attacks
self.attacked_forms = {}
# Dont submit same form too many times
self.done_form = {}
self.max_done_form = 5
logging.info("Init crawl on " + url)
def start(self, debug_mode=False, crawler_mode=False):
if(crawler_mode == False):
print("run both crawler module and attack module")
else:
print("only run the crawler module")
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) )
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")
self.graph.add(req)
self.graph.connect(self.root_req, req, CrawlEdge("get", None, None) )
self.graph.data['urls'] = {}
self.graph.data['form_urls'] = {}
open("run.flag", "w+").write("1")
open("queue.txt", "w+").write("")
open("command.txt", "w+").write("")
random.seed( 6 ) # chosen by fair dice roll
still_work = True
while still_work:
print("-"*50)
new_edges = len([edge for edge in self.graph.edges if edge.visited == False])
print("Edges left: %s" % str(new_edges))
try:
#f = open("graph.txt", "w")
#f.write( self.graph.toMathematica() )
if "0" in open("run.flag", "r").read():
logging.info("Run set to 0, stop crawling")
break
if "2" in open("run.flag", "r").read():
logging.info("Run set to 2, pause crawling")
input("Crawler paused, press enter to continue")
open("run.flag", "w+").write("3")
n_gets = 0
n_forms = 0
n_events = 0
for edge in self.graph.edges:
if edge.visited == False:
if edge.value.method == "get":
n_gets += 1
elif edge.value.method == "form":
n_forms += 1
elif edge.value.method == "event":
n_events += 1
print()
print("----------------------")
print("GETS | FROMS | EVENTS ")
print(str(n_gets).ljust(7), "|", str(n_forms).ljust(6), "|", n_events)
print("----------------------")
# for edge in self.graph.edges:
# if edge.visited == False and edge.value.method=="get":
# print(edge)
# input()
try:
still_work = self.rec_crawl()
except Exception as e:
still_work = n_gets + n_forms + n_events
print(e)
print(traceback.format_exc())
logging.error(e)
logging.error("Top level error while crawling")
#input("Enter to continue")
except KeyboardInterrupt:
print("CTRL-C, abort mission")
#print(self.graph.toMathematica())
break
print("Done crawling")
if(crawler_mode == False):
print("Start Attacking")
self.attack()
def extract_vectors(self):
print("Extracting urls")
vectors = []
added = set()
exploitable_events = ["input", "oninput", "onchange", "compositionstart"]
# GET
for node in self.graph.nodes:
if node.value.url != "ROOTREQ":
purl = urlparse(node.value.url)
if purl.scheme[:4] == "http" and not node.value.url in added:
vectors.append( ("get", node.value.url) )
added.add(node.value.url)
# FORMS and EVENTS
for edge in self.graph.edges:
method = edge.value.method
method_data = edge.value.method_data
if method == "form":
vectors.append( ("form", edge) )
if method == "event":
event = method_data
# check both for event and onevent, e.g input and oninput
print("ATTACK EVENT",event)
if ((event.event in exploitable_events) or
("on" + event.event in exploitable_events)):
if not event in added:
vectors.append( ("event", edge) )
added.add(event)
return vectors
def attack_404(self, driver, attack_lookup_table):
successful_xss = set()
# TODO make global somehow or better
# %RAND will be replaced, useful for tracking
alert_text = "jaekpot%RAND"
xss_payloads = ["<script>xss('"+alert_text+"')</script>",
'x" onerror="xss(\''+alert_text+'\')"']
for payload_template in xss_payloads:
random_id = random.randint(1,10000000)
random_id_padded = "[" + str(random_id) + "]"
payload = payload_template.replace("%RAND", random_id_padded)
lookup_id = alert_text.replace("%RAND", random_id_padded)
attack_lookup_table[lookup_id] = (self.url,"404",payload)
purl = urlparse(self.url)
parts = purl.path.split("/")
parts[-1] = payload
purl = purl._replace( path="/".join(parts) )
attack_vector = purl.geturl()
driver.get(attack_vector)
# Inspect
successful_xss = successful_xss.union( self.inspect_attack(url) )
return successful_xss
def attack_event(self, driver, vector_edge):
print("-"*50)
successful_xss = set()
xss_payloads = self.get_payloads()
print("Will try to attack vector", vector_edge)
for payload_template in xss_payloads:
(lookup_id, payload) = self.arm_payload(payload_template)
# Arm the payload
event = vector_edge.value.method_data
self.use_payload(lookup_id, (vector_edge,event.event,payload))
# Launch!
follow_edge(driver, self.graph, vector_edge)
try:
if event.event == "oninput" or event.event == "input":
el = driver.find_element(By.XPATH, event.addr)
el.clear()
el.send_keys(payload)
el.send_keys(Keys.RETURN)
logging.info("oninput %s" % driver.find_element(By.XPATH, event.addr) )
if event.event == "oncompositionstart" or event.event == "compositionstart":
el = driver.find_element(By.XPATH, event.addr)
el.click()
el.clear()
el.send_keys(payload)
el.send_keys(Keys.RETURN)
logging.info("oncompositionstart %s" % driver.find_element(By.XPATH, event.addr) )
else:
logging.error("Could not attack event.event %s" % event.event)
except:
print("PROBLEM ATTACKING EVENT: ", event)
logging.error("Can't attack event " + str(event))
# Inspect
inspect_result = self.inspect_attack(vector_edge)
if inspect_result:
successful_xss = successful_xss.union()
logging.info("Found injection, don't test all")
break
return successful_xss
def attack_get(self, driver, vector):
successful_xss = set()
xss_payloads = self.get_payloads()
purl = urlparse(vector)
print(purl)
for parameter in purl.query.split("&"):
if parameter:
for payload_template in xss_payloads:
(lookup_id, payload) = self.arm_payload(payload_template)
# Look for ?a=b&c=d
if "=" in parameter:
# Only split on first to allow ?a=b=C => (a, b=c)
(key,value) = parameter.split("=", 1)
# Singleton parameters ?x&y&z
else:
(key, value) = (parameter, "")
value = payload
self.use_payload(lookup_id, (vector,key,payload))
attack_query = purl.query.replace(parameter, key+"="+value)
#print("--Attack query: ", attack_query)
attack_vector = vector.replace(purl.query, attack_query)
print("--Attack vector: ", attack_vector)
driver.get(attack_vector)
# Inspect
inspect_result = self.inspect_attack(vector)
if inspect_result:
successful_xss = successful_xss.union()
logging.info("Found injection, don't test all")
break
return successful_xss
def xss_find_state(self, driver, edge):
graph = self.graph
path = rec_find_path(graph, edge)
for edge_in_path in path:
method = edge_in_path.value.method
method_data = edge_in_path.value.method_data
logging.info("find_state method %s" % method)
if method == "form":
form = method_data
try:
form_fill(driver, form)
except:
logging.error("NO FORM FILL IN xss_find_state")
def fix_form(self, form, payload_template, safe_attack):
alert_text = "%RAND"
# Optimization. If aggressive fuzzing doesn't add any new
# types of elements then skip it
only_aggressive = ["hidden", "radio", "checkbox", "select", "file"]
need_aggressive = False
for parameter in form.inputs:
if parameter.itype in only_aggressive:
need_aggressive = True
break
for parameter in form.inputs:
(lookup_id, payload) = self.arm_payload(payload_template)
if safe_attack:
# SAFE.
logging.debug("Starting SAFE attack")
# List all injectable input types text, textarea, etc.
if parameter.itype in ["text", "textarea", "password", "email"]:
# Arm the payload
form.inputs[parameter].value = payload
self.use_payload(lookup_id, (form,parameter,payload))
else:
logging.info("SAFE: Ignore parameter " + str(parameter))
elif need_aggressive:
# AGGRESSIVE
logging.debug("Starting AGGRESSIVE attack")
# List all injectable input types text, textarea, etc.
if parameter.itype in ["text", "textarea", "password", "email", "hidden"]:
# Arm the payload
form.inputs[parameter].value = payload
self.use_payload(lookup_id, (form,parameter,payload))
elif parameter.itype in ["radio", "checkbox", "select"]:
form.inputs[parameter].override_value = payload
self.use_payload(lookup_id, (form,parameter,payload))
elif parameter.itype == "file":
file_payload_template = "<img src=x onerror=xss(%RAND)>"
(lookup_id, payload) = self.arm_payload(file_payload_template)
form.inputs[parameter].value = payload
self.use_payload(lookup_id, (form,parameter,payload))
else:
logging.info("AGGRESSIVE: Ignore parameter " + str(parameter))
return form
def get_payloads(self):
payloads = []
# %RAND will be replaced, useful for tracking
alert_text = "%RAND"
xss_payloads = ["<script>xss("+alert_text+")</script>",
"\"'><script>xss("+alert_text+")</script>",
'<img src="x" onerror="xss('+alert_text+')">',
'<a href="" jaekpot-attribute="'+alert_text+'">jaekpot</a>',
'x" jaekpot-attribute="'+alert_text+'" fix=" ',
'x" onerror="xss('+alert_text+')"',
"</title></option><script>xss("+alert_text+")</script>",
]
# xss_payloads = ['<a href="" jaekpot-attribute="'+alert_text+'">jaekpot</a>']
return xss_payloads
def arm_payload(self, payload_template):
# IDs are strings to allow all strings as IDs in the attack table
lookup_id = str(random.randint(1,100000000))
payload = payload_template.replace("%RAND", lookup_id)
return (lookup_id, payload)
# Adds it to the attack table
def use_payload(self, lookup_id, vector_with_payload):
self.attack_lookup_table[str(lookup_id)] = {"injected": vector_with_payload,
"reflected": set()}
# Checks for successful injections
def inspect_attack(self, vector_edge):
successful_xss = set()
# attribute injections
attribute_injects = self.driver.find_elements(By.XPATH, "//*[@jaekpot-attribute]")
for attribute in attribute_injects:
lookup_id = attribute.get_attribute("jaekpot-attribute")
successful_xss.add(lookup_id)
self.reflected_payload(lookup_id, vector_edge)
xsses_json = self.driver.execute_script("return JSON.stringify(xss_array)")
lookup_ids = json.loads(xsses_json)
for lookup_id in lookup_ids:
successful_xss.add(lookup_id)
self.reflected_payload(lookup_id, vector_edge)
# Save successful attacks to file
if successful_xss:
f = open("successful_injections-"+self.session_id+".txt", "a+")
for xss in successful_xss:
attack_entry = self.get_table_entry(xss)
if attack_entry:
print("-"*50)
print("Found vulnerability: ", attack_entry)
print("-"*50)
#f.write( str(attack_entry) + "\n")
simple_entry = {'reflected': str(attack_entry['reflected']),
'injected': str(attack_entry['injected'])}
f.write( json.dumps(simple_entry) + "\n")
return successful_xss
def reflected_payload(self, lookup_id, location):
if str(lookup_id) in self.attack_lookup_table:
#self.attack_lookup_table[str(lookup_id)]["reflected"].append((self.driver.current_url, location))
self.attack_lookup_table[str(lookup_id)]["reflected"].add((self.driver.current_url, location))
else:
logging.warning("Could not find lookup_id %s, perhaps from an older attack session?" % lookup_id)
# Surprisingly tricky to get the string/int types right for numeric ids...
def get_table_entry(self, lookup_id):
if lookup_id in self.attack_lookup_table:
return self.attack_lookup_table[lookup_id]
if str(lookup_id) in self.attack_lookup_table:
return self.attack_lookup_table[str(lookup_id)]
logging.warning("Could not find lookup_id %s " % lookup_id)
return None
def execute_path(self, driver, path):
graph = self.graph
for edge_in_path in path:
method = edge_in_path.value.method
method_data = edge_in_path.value.method_data
logging.info("find_state method %s" % method)
if method == "get":
if allow_edge(graph, edge_in_path ):
driver.get(edge_in_path.n2.value.url)
self.inspect_attack(edge_in_path)
else:
logging.warning("Not allowed to get: " + str(edge_in_path.n2.value.url))
return False
elif method == "form":
form = method_data
try:
fill_result = form_fill(driver, form)
self.inspect_attack(edge_in_path)
if not fill_result:
logging.warning("Failed to fill form:" + str(form))
return False
except Exception as e:
print(e)
print(traceback.format_exc())
logging.error(e)
return False
elif method == "event":
event = method_data
execute_event(driver, event)
remove_alerts(driver)
self.inspect_attack(edge_in_path)
elif method == "iframe":
logging.info("iframe, do find_state")
if not find_state(driver, graph, edge_in_path):
logging.warning("Could not enter iframe" + str(edge_in_path))
return False
self.inspect_attack(edge_in_path)
elif method == "javascript":
# The javascript code is stored in the to-node
# "[11:]" gives everything after "javascript:"
js_code = edge_in_path.n2.value.url[11:]
try:
driver.execute_script(js_code)
self.inspect_attack(edge_in_path)
except Exception as e:
print(e)
print(traceback.format_exc())
logging.error(e)
return False
return True
def get_tracker(self):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(8))
def use_tracker(self, tracker, vector_with_payload):
self.io_graph[tracker] = {"injected": vector_with_payload,
"reflected": set()}
def inspect_tracker(self, vector_edge):
try:
body_text = self.driver.find_element(By.TAG_NAME, "body").text
for tracker in self.io_graph:
if tracker in body_text:
self.io_graph[tracker]['reflected'].add(vector_edge)
print("Found from tracker! " + str(vector_edge))
logging.info("Found from tracker! " + str(vector_edge))
#print(self.io_graph[tracker])
prev_edge = self.io_graph[tracker]['injected'][0]
attackable = prev_edge.value.method_data.attackable()
if attackable:
self.path_attack_form(self.driver, prev_edge, vector_edge)
except:
print("Failed to find tracker in body_text")
def track_form(self, driver, vector_edge):
successful_xss = set()
graph = self.graph
path = rec_find_path(graph, vector_edge)
form_edges = []
for edge in path:
if edge.value.method=="form":
form_edges.append(edge)
for form_edge in form_edges:
form = form_edge.value.method_data
tracker = self.get_tracker()
for parameter in form.inputs:
# List all injectable input types text, textarea, etc.
if parameter.itype == "text" or parameter.itype == "textarea":
# Arm the payload
form.inputs[parameter].value = tracker
self.use_tracker(tracker, (form_edge,parameter,tracker))
self.execute_path(driver, path)
# Inspect
inspect_tracker = self.inspect_tracker(vector_edge)
return successful_xss
def path_attack_form(self, driver, vector_edge, check_edge=None):