-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathrefServer.py
327 lines (289 loc) · 10.6 KB
/
refServer.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
# REQUIRED: PyCrypto 2.6.1
# To install: pip install pycrypto
# Homepage: https://www.dlitz.net/software/pycrypto/
import argparse
import SocketServer
import socket
import time
import sys
import json
import logging
from io import BytesIO
from base64 import b64encode, b64decode
from struct import pack, unpack
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Hash import SHA256
################################
# BEGIN SERVER SECRET DATA
serverKey = b64decode("zfAjjf1mNH3HStxAOR0Q+w==")
authDb = \
[
{ "user": "admin", "password": "BLTL-INCC-6GPM-N6S7", "groups": [ "admin" ] },
{ "user": "guest", "password": "Z29S-L47Z-9R8N-D76J", "groups": [ "guests" ] }
]
# END SERVER SECRET DATA
################################
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def pad(data):
result = data
nPadBytes = AES.block_size - len(data) % AES.block_size
for i in range(0, nPadBytes):
result += chr(nPadBytes)
return result
def unpad(data):
if len(data) == 0:
raise ValueError("Incorrect padding")
padLength = ord(data[-1])
if padLength == 0 or padLength > AES.block_size:
raise ValueError("Incorrect padding")
if padLength > len(data):
raise ValueError("Incorrect padding")
for i in range(-padLength, -2):
if ord(data[i]) != padLength:
raise ValueError("Incorrect padding")
return data[0:-padLength]
def encrypt(plaintext, key):
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintextPadded = pad(plaintext)
return iv + cipher.encrypt(plaintextPadded)
def decrypt(ciphertext, key):
if len(ciphertext) < AES.block_size:
raise ValueError("Ciphertext is invalid - too short to contain IV")
iv = ciphertext[0:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintextPadded = cipher.decrypt(ciphertext[AES.block_size:])
return unpad(plaintextPadded)
def getCurrentTimestamp():
return time.time() * 1000
def readNullTerminatedString(f):
buf = b''
while True:
if len(buf) > 1 << 20:
logger.warning("Overly long input string encountered")
raise Exception("Overly long input")
c = f.read(1)
if len(c) == 0:
logger.info("Unexpected end of stream encountered while reading a null-terminated string")
raise Exception("End of stream encountered")
if ord(c[0]) == 0: # Indicates NULL termination of a UTF-8 string.
break
buf += c
return unicode(buf, encoding="utf-8", errors="strict")
def readBytes(f, nBytes):
result = f.read(nBytes)
if len(result) != nBytes:
logger.warning("Unexpected end of stream encountered while reading a null-terminated string")
raise Exception("End of stream encountered")
return result
def toNullTerminatedUtf8(s):
return unicode(s).encode("utf-8") + "\x00"
def stringEquals_dataIndependentTime(a, b):
if len(a) != len(b):
return False
error = 0
for i in range(0, len(a)):
error |= ord(a[i]) ^ ord(b[i])
return error == 0
class MyTCPHandler(SocketServer.StreamRequestHandler):
nonceLengthInBytes = 8
def __init__(self, *a, **k):
logger.info("Instantiating MyTCPHandler")
self._terminateConnection = False
SocketServer.StreamRequestHandler.__init__(self, *a, **k)
def handle(self):
logger.debug("In MyTCPHandler.handle")
try:
while not self._terminateConnection:
messageTypeByte = self.rfile.read(1)
if len(messageTypeByte) == 0:
# Client has disconnected.
logger.info("Client has disconnected")
self._terminateConnection = True
else:
messageType = ord(messageTypeByte)
if messageType == 0x01:
self._processMessage_LogonRequest()
elif messageType == 0x03:
self._processMessage_LogonResponse()
elif messageType == 0x06:
self._processMessage_Command()
else:
raise Exception("Unknown message type received")
except:
# All malformed requests caught here.
# Send AUTHX_FAILURE and terminate connection.
exceptionInfo = sys.exc_info()
try:
logger.info("Exception: %s", exceptionInfo[1])
self._sendMessage_AuthxFailure(terminateConnection = True)
except:
pass
raise exceptionInfo[0], exceptionInfo[1], exceptionInfo[2]
def _isAdmin(self, identity):
for group in identity["groups"]:
if group == "admin":
return True
return False
def _processMessage_LogonRequest(self):
logger.info("Processing message: LOGON_REQUEST")
userName = readNullTerminatedString(self.rfile)
nonce = Random.new().read(self.nonceLengthInBytes)
timestamp = getCurrentTimestamp()
challengeCookie = b64encode(encrypt( \
nonce + \
toNullTerminatedUtf8(userName) + \
pack("<q", timestamp), \
serverKey))
self._sendMessage_LogonChallenge(nonce, challengeCookie)
def _sendMessage_LogonChallenge(self, nonce, challengeCookie):
logger.info("Sending message: LOGON_CHALLENGE")
self.wfile.write(
"\x02" + \
nonce + \
toNullTerminatedUtf8(challengeCookie))
self.wfile.flush()
def _sendMessage_AuthxFailure(self, terminateConnection = False):
logger.info("Sending message: AUTHX_FAILURE")
self.wfile.write("\x05")
self.wfile.flush()
if terminateConnection:
logger.info("Connection will be terminated")
self._terminateConnection = True
def _processMessage_LogonResponse(self):
logger.info("Processing message: LOGON_RESPONSE")
r = self._readBytes(SHA256.digest_size)
challengeCookie = readNullTerminatedString(self.rfile)
logger.debug("Challenge cookie received: %s", challengeCookie)
d = BytesIO(decrypt(b64decode(challengeCookie), serverKey))
nonce = readBytes(d, self.nonceLengthInBytes)
username = readNullTerminatedString(d)
timestamp = unpack("<q", readBytes(d, 8))[0]
if len(d.read(1)) != 0: # Not at end of string
logger.warn("Challenge cookie received does not have proper format")
raise Exception("Challenge cookie received does not have proper format")
currentTime = getCurrentTimestamp()
logger.debug("Cookie timestamp: %d. Current time: %d", timestamp, currentTime)
if timestamp < currentTime - 5 * 60 * 1000 or timestamp > currentTime:
logger.info("Challenge cookie is expired")
self._sendMessage_AuthxFailure()
return
userRecord = None
for element in authDb:
if element["user"] == username:
userRecord = element
break
if not userRecord:
logger.info("User does not exist in database: %s", username)
self._sendMessage_AuthxFailure()
return
correctResponse = SHA256.new(nonce + userRecord["password"]).digest()
logger.debug("Correct response to challenge : %s", correctResponse.__repr__())
logger.debug("Received response to challenge: %s", r.__repr__())
if not stringEquals_dataIndependentTime(r, correctResponse):
logger.info("Response to authentication challenge is not correct. User: %s", username)
self._sendMessage_AuthxFailure()
return
ticketTimestamp = getCurrentTimestamp()
identity = json.dumps( \
{ "user" : userRecord["user"], "groups": userRecord["groups"] }, \
ensure_ascii = False)
ticket = b64encode(encrypt( \
toNullTerminatedUtf8(identity) + \
pack("<q", ticketTimestamp), \
serverKey))
logger.info("Authentication succeeded. User: %s", username)
self._sendMessage_LogonSuccess(ticket)
def _sendMessage_LogonSuccess(self, ticket):
logger.info("Sending message: LOGON_SUCCESS")
self.wfile.write(
"\x04" + \
toNullTerminatedUtf8(ticket))
self.wfile.flush()
def _processMessage_Command(self):
logger.info("Processing message: COMMAND")
ticket = readNullTerminatedString(self.rfile)
(identity, error) = self._validateTicket(ticket)
if error == "EXPIRED":
logger.info("Ticket expired")
self._sendMessage_AuthxFailure()
return
elif error or not identity:
logger.info("Ticket invalid")
self._sendMessage_AuthxFailure(terminateConnection = True)
return
command = readNullTerminatedString(self.rfile)
logger.info("Command: %s. User: %s", command, identity["user"])
if command == "whoami":
result = json.dumps(identity, ensure_ascii = False)
elif command == "getflag":
if not self._isAdmin(identity):
logger.info("Unauthorized")
self._sendMessage_AuthxFailure()
return
else:
result = "GETFLAG AUTHORIZED BUT THIS SERVER DOES NOT CONTAIN A REAL FLAG"
else:
logger.info("Unrecognized command")
self._sendMessage_AuthxFailure()
return
self._sendMessage_CommandResult(result)
# Validates ticket and returns a tuple (identity, error).
# On success, identity is an identity object and error is None.
# On failure, identity is None and error is a string indicating the type of error
def _validateTicket(self, ticket):
try:
logger.debug("Ticket: %s", ticket)
d = BytesIO(decrypt(b64decode(ticket), serverKey))
identityFromTicket = json.loads(readNullTerminatedString(d))
timestamp = unpack("<q", readBytes(d, 8))[0]
if len(d.read(1)) != 0: # Not at end of string
raise Exception("Ticket is not well formed")
currentTime = getCurrentTimestamp()
logger.debug("Ticket timestamp: %d. Current time: %d", timestamp, currentTime)
if timestamp < currentTime - 1 * 60 * 60 * 1000 or timestamp > currentTime:
return (None, "EXPIRED")
username = identityFromTicket["user"]
if not (isinstance(username, str) or isinstance(username, unicode)):
raise Exception("Ticket is not well formed: username is not a string")
groups = []
for group in identityFromTicket["groups"]:
if not (isinstance(group, str) or isinstance(group, unicode)):
raise Exception("Ticket is not well formed: group name not a string")
groups.append(group)
identity = { "user": username, "groups": groups }
return (identity, None)
except:
logger.info("Ticket is not well formed", exc_info=True)
return (None, "INVALID")
def _sendMessage_CommandResult(self, commandResult):
self.wfile.write(
"\x07" + \
toNullTerminatedUtf8(commandResult))
self.wfile.flush()
def _readBytes(self, nBytes):
result = self.rfile.read(nBytes)
if len(result) != nBytes:
raise Exception("Connection was closed")
return result
class MyThreadingTCPServer(SocketServer.ThreadingTCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--serverBindAddress", required=False, default="127.0.0.1")
parser.add_argument("port", type=int, nargs="?", default="8888")
args = parser.parse_args()
server = MyThreadingTCPServer((args.serverBindAddress, args.port), MyTCPHandler)
try:
logger.warn("Listing on interface '%s', port %d", args.serverBindAddress, args.port)
server.serve_forever()
except KeyboardInterrupt:
pass
logger.warn("")
logger.warn("Shutting down...")
server.shutdown()
logger.warn("Exiting")