forked from flabbergastedbd/nightfury
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhack_actions.py
executable file
·295 lines (249 loc) · 10.5 KB
/
hack_actions.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
import os
import re
import md5
import json
import nf_shared
import subprocess
import numpy as np
from urlparse import urlparse
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
ACTIONS = []
class HackAction(object):
dependent_dims = {}
dependency_dims = []
reward = -1
def __init__(self, s):
self.string = s or ''
def hash_string(self, s):
m = md5.new()
m.update(s)
return(m.hexdigest())
def is_valid(self, s):
good_to_go = True
for dim_name, required_dim_value in self.dependent_dims.items():
state_dim_value = s[dim_name]
if state_dim_value == 0 or not re.search(required_dim_value, state_dim_value):
good_to_go = False
break
return good_to_go
def run(self, sink, taint, state):
injection_index = sink.index(taint)
sink = sink[:injection_index] + self.string + sink[injection_index:]
# nf_shared.browser.get("data:text/html," + sink.replace(taint, '<script>var popup = true;</script>'))
try:
nf_shared.browser.get("data:text/html,<script>var popup;</script>" + sink.replace(taint, ''))
r = nf_shared.browser.execute_script('return popup;');
alert = True if r == 1 else False
except WebDriverException:
alert = False
return(sink, alert)
def __str__(self):
return(self.string)
def __unicode__(self):
return(self.string)
class AttrParamAction(HackAction):
"""
Action representing a event handler
"""
dependent_dims = {'context': 'attr_param'}
def is_valid(self, s):
good_to_go = True if 0 in [s['1_tag_' + str(i) + '_ap'] for i in range(1, 3)] else False
for feature_name, feature_value in s.items():
if feature_name.endswith("_ap") and feature_value == self.string:
good_to_go = False
break
return(good_to_go and super(AttrParamAction, self).is_valid(s))
ATTR_PARAMS = ('onblur', 'onerror', 'src', 'onfocus', 'autofocus', 'onload', 'href', 'data', 'rel', 'srcset', 'open', 'ontoggle', 'onchange', 'onfocus', 'onclick', 'for', 'id', 'formaction')
for i in ATTR_PARAMS:
ACTIONS.append(AttrParamAction(i))
class AttrValueAction(HackAction):
"""
Action with attr value
"""
dependent_dims = {"context": "attr_value_start_delim|attr_value$"} # Either without delim or with delim
def is_valid(self, s):
good_to_go = True
if s['context_helper'] in ATTR_PARAMS: # If one attr value is already present then no other ATTR value is needed
for fname, fvalue in s.items():
if fname != 'context_helper' and fvalue == s['context_helper']:
if not s[fname.replace('ap', 'av')]:
good_to_go = True
else:
good_to_go = False
break
return(good_to_go and super(AttrValueAction, self).is_valid(s))
ATTR_VALUES = [
'x',
'popup=1;',
'data:text/html;base64,PHNjcmlwdD5wb3B1cD0xOzwvc2NyaXB0Pg==',
'data:svg/xml;base64,PHN2Zz48c2NyaXB0PnBvcHVwPTE7PC9zY3JpcHQ+PC9zdmc+',
'import']
for i in ATTR_VALUES:
ACTIONS.append(AttrValueAction(i))
class DataAction(HackAction):
"""
Action with data
"""
dependent_dims = {"context": "data"}
pass
# DATA_VALUES = ['popup=1;']
DATA_VALUES = []
for i in DATA_VALUES:
ACTIONS.append(DataAction(i))
def get_open_tags(s):
stack = []
for i in range(2, 0, -1):
fname = str(i) + "_tag"
fvalue = s[fname]
if fvalue and fvalue not in SELF_CLOSING_TAGS:
end_tag = False
for j in range(2, 0, -1):
param_fname = fname + "_" + str(j) + "_ap"
value_fname = fname + "_" + str(j) + "_av"
if s[param_fname] == "end" and s[value_fname] == 1:
end_tag = True
break
if not end_tag:
stack.append(fvalue)
elif end_tag:
if stack[-1] == fvalue:
stack.pop()
return(stack)
class TagAction(HackAction):
"""
Action representing a HTML tag
"""
dependent_dims = {'context': 'tag_name'}
def is_valid(self, s): # To support closing tag only when there is an open tag with same name
good_to_go = True if 0 in [s[str(i) + '_tag'] for i in range(1, 3)] else False
if s['context'] == 'end_tag_name':
good_to_go = False
if self.string in get_open_tags(s): # Don't use self closing tags with </
good_to_go = True
return(good_to_go and super(TagAction, self).is_valid(s))
# TAGS = ('a', 'abbr', 'acronym', 'address', 'applet', 'embed', 'object', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'colgroup', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'ul', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'input', 'legend', 'fieldset', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem')
TAGS = ('a', 'button', 'embed', 'object', 'body', 'canvas', 'embed', 'form', 'frameset', 'iframe', 'img', 'input', 'option', 'select', 'audio', 'video', 'source', 'track', 'svg', 'link', 'picture')
# TAGS = ['body', 'figcaption', 'aside', 'dialog', 'main', 'figure', 'mark', 'menuitem', 'rt', 'footer', 'rp', 'meter', 'article', 'bdi', 'details', 'section', 'ruby', 'header', 'wbr', 'time', 'summary', 'progress', 'nav']
# TAGS = ['div', 'input', 'img', 'audio', 'video', 'body', 'object']
SELF_CLOSING_TAGS = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
for i in TAGS:
a = TagAction(i)
ACTIONS.append(a)
class MasterControlAction(HackAction):
"""
Action representing a control character
"""
def is_valid(self, s):
if s['context'] == 'attr_value_start_delim' or (s['context'] == 'attr_value_end_delim' and s['1_cc'] == self.string):
return True
return False
MASTER_CONTROL_CHARS = ['"', "'"]
# MASTER_CONTROL_CHARS = []
for i in MASTER_CONTROL_CHARS:
a = MasterControlAction(i)
ACTIONS.append(a)
MASTER_COUNTER_CONTROL_CHARS = {
"'": "'",
'"': '"',
}
class ControlAction(HackAction):
"""
Action representing a control character
"""
pass
class ForwardSlashControlAction(ControlAction):
"""
Action representing a control character
"""
def is_valid(self, s):
good_to_go = True
# Check if there atleast one tag to be closed because '/' after a < will start a close tag state
if s['context'] == 'start_tag_name':
good_to_go = False
if len(get_open_tags(s)) > 0:
good_to_go = True
return(good_to_go and super(ForwardSlashControlAction, self).is_valid(s))
class SpaceControlAction(ControlAction):
"""
Action representing a control character
"""
def is_valid(self, s):
good_to_go = True
if s['context'] == 'attr_value_end_delim':
good_to_go = False
if s['1_cc'] not in MASTER_CONTROL_CHARS:
good_to_go = True
return(good_to_go and super(SpaceControlAction, self).is_valid(s))
class LessThanControlAction(ControlAction):
"""
Action representing a control character
"""
def is_valid(self, s):
good_to_go = True
if s['context'] in ['data'] and s['2_tag'] != 0: # If 2 tags are already there, no new tags
good_to_go = False
return(good_to_go and super(LessThanControlAction, self).is_valid(s))
CONTROL_CHARS = [' ', '(', ')', '*', '+', '-', ',', ';', '<', '>', '=', '[', ']', '{', '}', '`', '/']
CONTROL_CHARS = [' ', '<', '>', '/', '=']
CONTROL_CHARS = [' ', '<', '>', '/', '=']
for i in CONTROL_CHARS:
a = ControlAction(i)
if i == '>':
a.dependent_dims = {'context': 'start_tag_attr|end_tag_attr|attr_param|equal_dim|attr_delim'}
if i == '<':
a = LessThanControlAction(i)
a.dependent_dims = {'context': 'data'}
elif i in [' ']:
a = SpaceControlAction(i)
a.dependent_dims = {'context': 'start_tag_attr|attr_delim|attr_value_end_delim'}
elif i in ['/']:
a = ForwardSlashControlAction(i)
a.dependent_dims = {'context': 'start_tag_attr|start_tag_name'}
elif i == '=':
a.dependent_dims = {'context': 'equal_delim'}
ACTIONS.append(a)
COUNTER_CONTROL_CHARS = {
'(': ')',
'[': ']',
'{': '}',
'`': '`'
}
class MouseKeyboardAction(object):
reward = -30
def __init__(self, s, action='click'):
self.tag_num = s
self.action = action
def run(self, sink, taint, state):
tag = state[str(self.tag_num) + "_tag"]
previous_tags = [state[str(i) + "_tag"] for i in range(self.tag_num - 1, 1, -1)]
i = previous_tags.count(tag)
# nf_shared.browser.get("data:text/html," + sink.replace(taint, '<script>var popup = true;</script>'))
try:
nf_shared.browser.get("data:text/html,<script>var popup;</script>" + sink.replace(taint, ''))
elements = nf_shared.browser.find_elements_by_tag_name(tag)
e = elements[i]
# Perform action
if self.action == 'click':
e.click()
elif self.action == 'focus':
e.send_keys(Keys.NULL)
elif self.action == 'keyboard':
e.send_keys("1337")
r = nf_shared.browser.execute_script('return popup;');
alert = True if r == 1 else False
except WebDriverException:
alert = False
except IndexError: # IndexError when selenium cannot find element
alert = False
return(sink, alert)
def is_valid(self, s):
good_to_go = False
if s[str(self.tag_num) + "_tag"] != 0 and s[str(self.tag_num) + "_tag"] not in ['div', 'link', 'body']:
good_to_go = True
if self.tag_num == 1 and s['context'] != 'data': # Or else click will happen when sink is incomplete i.e <button abcdef
good_to_go = False
return(good_to_go)
for a in ['click', 'focus', 'keyboard']:
for i in range(1, 3):
ACTIONS.append(MouseKeyboardAction(i, action=a))