-
Notifications
You must be signed in to change notification settings - Fork 18
/
chik_hook.py
214 lines (171 loc) · 6.78 KB
/
chik_hook.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
#!/usr/bin/env python
"""
Copyright (c) 2013 muodov (muodov[monkey]gmail.com)
Hook sqlmap's I/O and redirect transparently to Kivy widgets.
This file must be imported before any sqlmap imports.
"""
import threading
import logging
import os
import re
import sys
from functools import partial
from kivy.app import App
from kivy.logger import Logger as kivy_logger
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from yesnopopup import YesNoPopup, YesNoQuitPopup, LogMessage
tlocal = threading.local()
tlocal.pending_question = 'If you see this, something went wrong'
# cProfile module seems to be currently unstable on iOS. After all, who needs --profile flag? ;D
import fake_profiling
sys.modules['lib.core.profiling'] = fake_profiling
# Hook version check
def customGetRevisionNumber():
"""
slightly patched getRevisionNumber() without trying to execute `git` command
"""
retVal = None
filePath = None
_ = os.path.join(os.path.dirname(__file__), 'sqlmap')
while True:
filePath = os.path.join(_, ".git", "HEAD")
if os.path.exists(filePath):
break
else:
filePath = None
if _ == os.path.dirname(_):
break
else:
_ = os.path.dirname(_)
while True:
if filePath and os.path.isfile(filePath):
with open(filePath, "r") as f:
content = f.read()
filePath = None
if content.startswith("ref: "):
filePath = os.path.join(_, ".git", content.replace("ref: ", "")).strip()
else:
match = re.match(r"(?i)[0-9a-f]{32}", content)
retVal = match.group(0) if match else None
break
else:
break
return retVal[:7] if retVal else None
import lib.core.revision
lib.core.revision.getRevisionNumber = customGetRevisionNumber
# Hook output
import lib.core.common
def print_on_ui_thread(value, color, dt):
App.get_running_app().root.scrolled_window.add_widget(LogMessage(text=value, color=color[0], bold=color[1]))
def print_on_widget(value, color=((1, 1, 1, 1), False)):
Clock.schedule_once(partial(print_on_ui_thread, value.replace('\r', ''), color), 0.2)
def output_wrapper(data, forceOutput=False, bold=False, content_type=None, status=None):
print_on_widget(data)
def clearConsoleLineStub(arg=None):
pass
lib.core.common.dataToStdout = output_wrapper
lib.core.common.clearConsoleLine = clearConsoleLineStub
lib.core.common.getConsoleWidth = lambda x=80: x
# Hook input
originalReadInput = lib.core.common.readInput
def readInputWrapper(message, default=None, checkBatch=True):
tlocal.pending_question = message
"""
possible question formats:
[Y/n]
[(S)kip current test/(e)nd detection phase/(n)ext parameter/(q)uit]
[y/N]
[(C)ontinue/(s)tring/(r)egex/(q)uit]
please enter value for parameter 'string':
[0] aalala
[1] dldld
[q] Quit
[Y/n/q]
Edit POST data [default: %s]%s:
Edit GET data [default: %s]:
orrect [%s (default)/%s]
document root locations [Enter for None]:
Please enter full target URL (-u):
number of threads? [Enter for %d (current)]
what is the back-end DBMS address? [%s]
functions now? [Y/n/q]
"""
res = originalReadInput(message, default, checkBatch)
tlocal.pending_question = 'If you see this, something went wrong'
print_on_widget('answer is %s' % res)
return res
lib.core.common.readInput = readInputWrapper
def create_yesnopopup(title, question, callback, *args, **kwargs):
popup = YesNoPopup(title, question, callback, auto_dismiss=False)
popup.open()
def create_yesnoquitpopup(title, question, callback, *args, **kwargs):
popup = YesNoQuitPopup(title, question, callback, auto_dismiss=False)
popup.open()
def create_stringpopup(callback, *args, **kwargs):
input_widget = BoxLayout(orientation='horizontal', size_hint=(1, 0.1))
text_input = TextInput(text_hint='type here', multiline=False)
input_widget.add_widget(text_input)
enter_button = Button(text='Enter', size_hint=(None, 1), width=100)
def close_input(instance):
callback(instance, text_input.text)
App.get_running_app().root.log_screen.remove_widget(input_widget)
enter_button.bind(on_press=close_input)
input_widget.add_widget(enter_button)
App.get_running_app().root.log_screen.add_widget(input_widget)
# Hook raw_input for fancy user interaction
def user_interact(msg=''):
lock = threading.Lock()
lock.acquire()
context = {}
def my_callback(instance, answer):
context['answer'] = answer
lock.release()
if 'pending_question' not in tlocal.__dict__:
Clock.schedule_once(partial(create_stringpopup, my_callback), 0)
elif '[y/n]' in tlocal.pending_question.lower():
Clock.schedule_once(partial(create_yesnopopup, 'What next?', tlocal.pending_question, my_callback), 0)
elif '[y/n/q]' in tlocal.pending_question.lower():
Clock.schedule_once(partial(create_yesnoquitpopup, 'What next?', tlocal.pending_question, my_callback), 0)
else:
Clock.schedule_once(partial(create_stringpopup, my_callback), 0)
lock.acquire()
return context['answer']
import __builtin__
__builtin__.raw_input = user_interact
# Hook logs
class WidgetHandler(logging.Handler):
# colors for logmessages (rgba, bold):
level_colors = {
'DEBUG': ((0.328125, 0.734375, 0.88671875, 1), False),
'INFO': ((0.17578125, 0.765625, 0.203125, 1), False),
'WARNING': ((0.8671875, 0.8046875, 0.29296875, 1), False),
'ERROR': ((0.99609375, 0.296875, 0.1328125, 1), False),
'CRITICAL': ((0.99609375, 0.296875, 0.1328125, 1), True),
'PAYLOAD': ((0,1,1,1),False),
'TRAFFIC OUT': ((1,0,1,1),False),
'TRAFFIC IN': ((1,0,1,1),True),
}
def emit(self, record):
try:
msg = self.format(record)
kivy_logger.debug(msg)
print_on_widget(msg, self.level_colors[record.levelname])
except:
self.handleError(record)
from lib.core.data import logger
widget_handler = WidgetHandler()
widget_handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s", "%H:%M:%S"))
# widget_handler.setLevel(logging.DEBUG)
logger.addHandler(widget_handler)
# disable os._exit to forbid exiting in multithreading mode
original_exit = os._exit
threading.current_thread().name = 'sqlmapchik_main_thread'
def exit_wrapper(status):
if threading.current_thread().name == 'sqlmapchik_main_thread':
original_exit(status)
else:
kivy_logger.warning('%s attempted to call os._exit(%d), ignoring' % (threading.current_thread().name, status))
os._exit = exit_wrapper