This repository was archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathjut_client.py
More file actions
412 lines (360 loc) · 14 KB
/
jut_client.py
File metadata and controls
412 lines (360 loc) · 14 KB
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
#!/usr/bin/python
import os
import sys
import string
import struct
import socket
import shutil
import argparse
import subprocess
def hexdump(data, indent=1, width=16):
i = 1
out = ""
outh = " " * indent + "0000: "
outa = ""
printable = string.printable.replace("\n", ".")
printable = printable.replace("\r", ".")
printable = printable.replace("\t", ".")
for c in data:
outh += "%02x " % ord(c)
if c in printable:
outa += c
else:
outa += "."
if (i % width) == 0:
out += "%-62s %-16s\n" % (outh, outa)
outh = " " * indent + "%04x: " % i
outa = ""
i += 1
if len(outa) > 0:
out += "%-62s %-16s\n" % (outh, outa)
return out[ : -1]
class Logger(object):
def __init__(self, debugMode):
self.debugMode = debugMode
def debug(self, msg):
if self.debugMode:
print "[debug] %s" % str(msg)
def log(self, msg):
print str(msg)
class SocketWrapper(object):
def recv(self, n):
raise NotImplemented
def send(self, data):
raise NotImplemented
def close(self):
raise NotImplemented
class NetworkSocket(SocketWrapper):
def __init__(self, log, sockfd):
self.fd = sockfd
self.log = log
def recv(self, n):
data = self.fd.recv(n)
log.debug("recv(%i) = %i\n%s" % (n, len(data), hexdump(data, indent=4)))
return data
def send(self, data):
log.debug("send()\n%s" % hexdump(data, indent=4))
self.fd.sendall(data)
def close(self):
self.fd.close()
class MixinSocket(SocketWrapper):
def __init__(self, log, stdin, stdout, p):
self.stdin = stdin
self.stdout = stdout
self.log = log
self.p = p
def recv(self, n):
data = self.stdout.read(n)
log.debug("recv(%i) = %i\n%s" % (n, len(data), hexdump(data, indent=4)))
return data
def send(self, data):
log.debug("send()\n%s" % hexdump(data, indent=4))
self.stdin.write(data)
self.stdin.flush()
def close(self):
self.stdin.close()
self.stdout.close()
self.p.kill()
class Pickle(object):
def __init__(self, sockfd):
self.fd = sockfd
def read(self, fmt):
data = self.fd.recv(struct.calcsize(fmt))
if len(data) == struct.calcsize(fmt):
return struct.unpack("<%s" % fmt, data)[0]
elif len(data) == 0:
return ""
else:
raise Exception
def write(self, fmt, val):
data = struct.pack("<%s" % fmt, val)
self.fd.send(data)
def readBlob(self):
size = self.read("H")
data = self.fd.recv(size)
return data
def writeBlob(self, data):
self.write("H", len(data))
self.fd.send(data)
class JUTClient(object):
def __init__(self, log, sockfd):
self.fd = sockfd
self.log = log
self.pickle = Pickle(self.fd)
self.sizeOfChar = self.pickle.read("I")
def __readHeader__(self):
status = True if self.pickle.read("I") == 1 else False
code = self.pickle.read("I")
return (status, code)
def __writeWSTR__(self, data):
self.pickle.writeBlob("".join(map(lambda c: c + "\x00", data + "\x00")))
def __writeSTR__(self, data):
self.pickle.writeBlob(data + "\x00")
def __writeTSTR__(self, data):
if self.sizeOfChar == 1:
self.__writeSTR__(data)
else:
self.__writeWSTR__(data)
def __readTSTR__(self):
data = self.pickle.readBlob()
if self.sizeOfChar == 2:
return data.replace("\x00", "")
return data[ : -1]
def readFile(self, path):
self.log.debug("Testing ReadFile on %s" % path)
self.pickle.write("B", 1)
self.__writeTSTR__(path)
hdr = self.__readHeader__()
if hdr[0]:
data = self.pickle.readBlob()
return (True, data)
else:
return hdr
def writeFile(self, path, data):
self.log.debug("Testing WriteFile by writing %i bytes to %s" % (len(data), path))
self.pickle.write("B", 2)
self.__writeTSTR__(path)
self.pickle.writeBlob(data)
hdr = self.__readHeader__()
return hdr
def queryDir(self, path):
self.log.debug("Testing QueryDirectory by enumerating %s" % path)
self.pickle.write("B", 3)
self.__writeTSTR__(path)
hdr = self.__readHeader__()
if not hdr[0]:
return hdr
items = []
while True:
fileAttr = self.pickle.read("I")
if fileAttr == 0xffffffff:
break
fileSizeHi = self.pickle.read("I")
fileSizeLo = self.pickle.read("I")
fileName = self.__readTSTR__()
items.append((fileName, fileAttr, fileSizeHi, fileSizeLo))
return (True, items)
def bindEchoServer(self, port):
self.log.debug("Testing BindEchoServer on port %i" % port)
self.pickle.write("B", 4)
self.pickle.write("H", port)
hdr = self.__readHeader__()
return hdr
def sendEchoClient(self, host, port):
self.log.debug("Testing SendEchoClient on %s:%i" % (host, port))
self.pickle.write("B", 5)
self.__writeSTR__("%s" % host)
self.__writeSTR__("%i" % port)
hdr = self.__readHeader__()
return hdr
def listProcesses(self):
self.log.debug("Testing ListProcess")
self.pickle.write("B", 6)
hdr = self.__readHeader__()
if hdr[0]:
processes = []
while True:
pid = self.pickle.read("I")
if pid == 0xffffffff:
break
name = self.__readTSTR__()
processes.append((pid, name))
return (True, processes)
else:
return hdr
def execShellcode(self, data):
self.log.debug("Executing shellcode")
self.pickle.write("B", 7)
self.pickle.writeBlob(data)
hdr = self.__readHeader__()
return hdr
def get_sockfd(log, isLocal, connectInfo):
if isLocal:
log.log("Starting unit test locally")
if connectInfo == "localhost:4444":
connectInfo = os.path.join("Debug", "JailUnitTest.exe")
log.debug("Making sure connectInfo is a valid path: \"%s\"" % connectInfo)
filePath = os.path.abspath(connectInfo)
log.debug("Calculated absolute path: %s\n" % filePath)
if not (os.path.exists(filePath) or os.path.isfile(filePath)):
log.log("%s either is not a file or doesn't exist" % filePath)
return None
try:
log.debug("Trying to launch %s" % filePath)
p = subprocess.Popen([filePath], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
log.debug("Process launched successfully!")
return MixinSocket(log, p.stdin, p.stdout, p)
except Exception, err:
log.debug("Exception: %s" % str(err))
log.log("Error has occurred trying to launch %s" % filePath)
return None
else:
log.log("Starting unit test over the network")
log.debug("Parsing connectInfo \"%s\"" % connectInfo)
p = connectInfo.find(":")
log.debug(" Checking for ':': %i" % p)
if p == -1:
log.log("Connection information does not appear to be in <host>:<port> format")
log.debug("Could not find ':' in connectInfo")
return None
host = connectInfo[0 : p]
try:
port = int(connectInfo[p + 1 : ])
except ValueError:
log.log("Port field does not appear to be a valid integer value")
return None
if port == 0 or port > 65535:
log.log("Port should be between 1 and 65535 (inclusive)")
return None
try:
log.debug("Creating TCP/IP socket")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
log.debug("Connecting to %s:%i..." % (host, port))
s.connect((host, port))
log.debug("Connection established...")
log.log("Connected to target at %s:%i" % (host, port))
return NetworkSocket(log, s)
except socket.error, err:
log.debug("socket.error: %s" % str(err))
log.log("Could not connect to %s:%i" % (host, port))
return None
def getParentDirectory():
return os.path.split(os.path.abspath(__file__))[0]
class UnitTest(object):
def __init__(self, log, client):
self.log = log
self.client = client
def makeTmpDirectory(self, name):
path = os.path.join(getParentDirectory(), "%s" % name)
self.log.debug("Make temporary directory at %s" % path)
os.mkdir(path)
self.log.debug("Temporary directory created")
return path
def delTmpDirectory(self, name):
path = os.path.join(getParentDirectory(), "%s" % name)
self.log.debug("Deleting entire temporary directory at %s" % path)
shutil.rmtree(path)
def writeFile(self, path, data):
fd = open(path, "wb")
fd.write(data)
fd.close()
def readFile(self, path):
fd = open(path, "rb")
data = fd.read()
fd.close()
return data
def testFileAccess(self):
self.log.log("Testing file access")
try:
path = self.makeTmpDirectory("tmpFileAccess")
tmpFile = os.path.join(path, "tmpFile")
tmpString = "*** testing 1 2 3 ***"
self.writeFile(tmpFile, tmpString)
self.log.debug("Temporary file written to %s" % tmpFile)
tmpNetFile = os.path.join(path, "tmpNetFile")
self.log.log("Can we write to %s?" % tmpNetFile)
status, code = self.client.writeFile(tmpNetFile, "DATA")
if status:
self.log.log(" [OK] Wrote a file to %s" % tmpNetFile)
self.log.log(" This should not happen in an AppContainered JailUnitTest")
else:
self.log.log(" [FAIL] Failed to write a file to %s" % tmpNetFile)
self.log.log(" Error Code: %08x" % code)
self.log.log(" This should happen in an AppContainered JailUnitTest")
self.log.log("Can we read %s?" % tmpFile)
status, data = self.client.readFile(tmpFile)
if status:
if data == tmpString:
self.log.log(" [OK] Successfully read contents of %s" % tmpFile)
self.log.log(" This should not happen in an AppContainered JailUnitTest")
else:
self.log.log(" [FAIL] String read back is not expected")
self.log.log(" Data: \"%s\"" % data)
else:
self.log.log(" [FAIL] Failed to read %s" % tmpFile)
self.log.log(" Error Code: %08x" % data)
self.log.log(" This should happen in an AppContainered JailUnitTest")
finally:
self.delTmpDirectory("tmpFileAccess")
def testListProcess(self):
self.log.log("Testing list process")
status, processes = self.client.listProcesses()
if status:
winSvcs = []
for pid, name in processes:
if name in ["csrss.exe", "explorer.exe", "smss.exe", "wininit.exe"] and \
not name in winSvcs:
winSvcs.append(name)
self.log.debug("winSvcs = %s" % str(winSvcs))
if len(winSvcs) == 4:
self.log.log("[FAIL] Found 4 Windows processes")
self.log.log(" This should not occur in an AppContainer")
else:
self.log.log("[OK] Found the following processes:")
self.log.log(" %s" % str(processes))
else:
self.log.log("[FAIL] Could not obtain process list")
self.log.log(" This should not occur. AppContainers can get a list of processes within the container")
def testNetworkAccess(self):
self.log.log("Testing network access")
srvPort = 8324
# FIXME: ignore this test for now
# self.log.debug("Attempting to bind to port %i" % srvPort)
# status, code = self.client.bindEchoServer(srvPort)
# if status:
# pass
# else:
# pass
host, port = ("www.yahoo.com", 80)
self.log.debug("Attempting to connect to %s:%i" % (host, port))
status, code = self.client.sendEchoClient(host, port)
if status:
self.log.log("[STATUS] Connected to %s:%i" % (host, port))
else:
self.log.log("[STATUS] Failed to connect to %s:%i" % (host, port))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("connect_info", type=str, nargs="?", help="connection information in the form of <host>:<port> for non-local or the path to JailUnitTest.exe binary", default="localhost:4444")
parser.add_argument("-l", "--local", help="instantiates JailUnitTest.exe locally", action="store_true")
parser.add_argument("-d", "--debug", help="enables debugging output", action="store_true")
args = parser.parse_args()
log = Logger(args.debug)
log.debug("Logger is initialized and awake")
log.debug("%s options:" % sys.argv[0])
log.debug(" local = %s" % args.local)
log.debug(" connect_info = %s" % args.connect_info)
log.debug("Getting access to a SocketWrapper object")
sockfd = get_sockfd(log, args.local, args.connect_info)
if sockfd is None:
log.debug("Exiting because of failure to get socket")
sys.exit(-1)
log.debug("SocketWrapper instance obtained")
rootPath = getParentDirectory()
log.debug("Parent directory is %s" % rootPath)
log.debug("Initializing JUTClient")
app = JUTClient(log, sockfd)
test = UnitTest(log, app)
test.testFileAccess()
test.testListProcess()
test.testNetworkAccess()
app.execShellcode("\xeb\xfe")