-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpsexec2.py
More file actions
1272 lines (1118 loc) · 66.4 KB
/
Copy pathpsexec2.py
File metadata and controls
1272 lines (1118 loc) · 66.4 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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description:
# PSEXEC like functionality example using RemComSvc (https://github.com/kavika13/RemCom)
#
# Author:
# beto (@agsolino)
#
# Reference for:
# DCE/RPC and SMB.
#
import sys
import os
import re
import cmd
import logging
from threading import Thread, Lock
import argparse
import random
import string
import time
from six import PY3
from impacket.examples import logger
from impacket import version, smb, LOG
from impacket.smbconnection import SMBConnection
from impacket.dcerpc.v5 import transport, scmr
from impacket.structure import Structure
from impacket.examples import remcomsvc, serviceinstall, servicechange
from impacket.examples.utils import parse_target
from impacket.krb5.keytab import Keytab
CODEC = sys.stdout.encoding
# 输出字符报错处理
class RemComMessage(Structure):
structure = (
('Command','4096s=""'),
('WorkingDir','260s=""'),
('Priority','<L=0x20'),
('ProcessID','<L=0x01'),
('Machine','260s=""'),
('NoWait','<L=0'),
)
# 一个结构类体
# Structure:这是 Impacket 提供的基类,可以定义 C 风格的二进制结构体。
# structure:一个元组,里面定义了字段名、数据类型、默认值。
# 远程命令消息的“封装格式”。
class RemComResponse(Structure):
structure = (
('ErrorCode','<L=0'),
('ReturnCode','<L=0'),
)
# 响应结构体
RemComSTDOUT = "RemCom_stdout"
RemComSTDIN = "RemCom_stdin"
RemComSTDERR = "RemCom_stderr"
# RemComSTDOUT → 远程进程的 标准输出 管道。
# RemComSTDIN → 远程进程的 标准输入 管道。
# RemComSTDERR → 远程进程的 标准错误 管道。
lock = Lock()
# 线程锁对象。防止多个进程同时改写数据
class PSEXEC:
def __init__(self, command, path, exeFile, copyFile, port=445,
username='', password='', domain='', hashes=None, aesKey=None, doKerberos=False, kdcHost=None, serviceName=None,
remoteBinaryName=None, service_list=False, service_change=None):
self.__username = username
self.__password = password
self.__port = port
self.__command = command
self.__path = path
self.__domain = domain
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = aesKey
self.__exeFile = exeFile
self.__copyFile = copyFile
self.__doKerberos = doKerberos
self.__kdcHost = kdcHost
self.__serviceName = serviceName
self.__remoteBinaryName = remoteBinaryName
self.__service_list = service_list
self.__service_change = service_change
if hashes is not None:
self.__lmhash, self.__nthash = hashes.split(':')
# 定义了psexec类 吸收了参数并存入对象方便后续方法使用
def run(self, remoteName, remoteHost):
# Handle service list functionality
if self.__service_list:
return self.listServices(remoteName, remoteHost)
# Handle service hijacking functionality
if self.__service_change is not None:
return self.executeViaServiceHijacking(remoteName, remoteHost)
# Original psexec functionality
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
logging.debug('StringBinding %s'%stringbinding)
# 先传入远程主机名称或者ip等,之后定义通过smb命名管道连接此机器的服务控制管理器
rpctransport = transport.DCERPCTransportFactory(stringbinding)
# 根据上面的绑定字符串返回合适的dce/rpc传输对象
rpctransport.set_dport(self.__port)
# 设置目标端口
rpctransport.setRemoteHost(remoteHost)
# 指定实际要连接的远程主机ip
if hasattr(rpctransport, 'set_credentials'):
# This method exists only for selected protocol sequences.
rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,
self.__nthash, self.__aesKey)
#检查是否存在set_credentials方法,如果支持需要认证,则将所有凭据传入
rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
# 如果self.__doKerberos=True,则使用kerbores认证
self.doStuff(rpctransport)
# 这里交给类里的另一个方法 doStuff,把准备好的传输对象传进去
def openPipe(self, s, tid, pipe, accessMask):
# s → 已经建立的 SMBConnection 对象。
# tid → 共享资源的 ID(Tree ID),由 SMB 打开共享返回。
# pipe → 命名管道名称,例如 "\\pipe\\RemCom_stdout"。
# accessMask → 文件/管道的访问权限(读、写、读写)
pipeReady = False
tries = 50
while pipeReady is False and tries > 0:
try:
s.waitNamedPipe(tid,pipe)
pipeReady = True
except:
tries -= 1
time.sleep(2)
pass
# s.waitNamedPipe(tid, pipe) → 阻塞调用,等待远程管道就绪。尝试连接至多50次,每次失败后等待两秒
if tries == 0:
raise Exception('Pipe not ready, aborting')
# 如果 50 次都没成功,抛出异常,中止操作。
fid = s.openFile(tid,pipe,accessMask, creationOption = 0x40, fileAttributes = 0x80)
# s.openFile → SMB 文件/管道操作,返回 文件句柄 (FID, File ID)。
# 参数说明:
# creationOption = 0x40 → FILE_OPEN_IF:如果存在就打开,否则报错。
# fileAttributes = 0x80 → FILE_ATTRIBUTE_NORMAL:普通文件属性。
return fid
# 返回可以用于后续 读/写管道数据 的文件句柄。
def listServices(self, remoteName, remoteHost):
"""List all services and mark suitable ones for hijacking"""
LOG.info("Listing services on %s" % remoteHost)
try:
# Create SMB connection
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
rpctransport.setRemoteHost(remoteHost)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(self.__username, self.__password, self.__domain,
self.__lmhash, self.__nthash, self.__aesKey)
rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
# Create SMB connection for service changer
dce = rpctransport.get_dce_rpc()
dce.connect()
smb_connection = rpctransport.get_smb_connection()
# Create service changer
service_changer = servicechange.ServiceChanger(smb_connection, remoteHost)
# Get all services
services = service_changer.listAllServices()
# Filter only suitable services
suitable_services = [s for s in services if s.is_suitable]
if not suitable_services:
print("\n" + "="*120)
print("NO SUITABLE SERVICES FOUND FOR HIJACKING")
print("="*120)
return True
# Print header
print("\n" + "="*120)
print("SUITABLE SERVICES FOR HIJACKING - %s" % remoteHost)
print("="*120)
print("%-30s %-15s %-15s %-15s %-20s" %
("SERVICE NAME", "START TYPE", "STATUS", "ACCOUNT", "PRIORITY"))
print("-"*120)
# Sort services by priority (lower number = higher priority)
suitable_services.sort(key=lambda x: x.priority)
# Print only suitable services
for service in suitable_services:
start_type_map = {
1: "BOOT",
2: "SYSTEM",
3: "MANUAL",
4: "DISABLED"
}
start_type_str = start_type_map.get(service.start_type, "UNKNOWN")
print("%-30s %-15s %-15s %-15s %-20s" %
(service.service_name[:30], start_type_str, "STOPPED",
service.start_name[:15] if service.start_name else "N/A",
str(service.priority)))
print("="*120)
print("Total suitable services: %d" % len(suitable_services))
print("="*120)
return True
except Exception as e:
LOG.critical("Error listing services: %s" % str(e))
return False
def executeViaServiceHijacking(self, remoteName, remoteHost):
"""Execute command via service hijacking"""
LOG.info("Executing command via service hijacking: %s" % self.__command)
try:
# Create SMB connection
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
rpctransport.setRemoteHost(remoteHost)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(self.__username, self.__password, self.__domain,
self.__lmhash, self.__nthash, self.__aesKey)
rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
# Create SMB connection for service changer
dce = rpctransport.get_dce_rpc()
dce.connect()
smb_connection = rpctransport.get_smb_connection()
# Create service changer
service_changer = servicechange.ServiceChanger(smb_connection, remoteHost)
# Find suitable service or use specified one
if self.__service_change:
# Use specified service
LOG.info("Using specified service: %s" % self.__service_change)
service_name = self.__service_change
# Verify service exists and is suitable
scm_handle = service_changer.openSvcManager()
service_info = service_changer.getServiceInfo(service_name, scm_handle)
scmr.hRCloseServiceHandle(service_changer.rpcsvc, scm_handle)
if not service_info.service_name:
LOG.critical("Service %s not found" % service_name)
return False
if not service_changer.isServiceSuitable(service_info):
LOG.critical("Service %s is not suitable: %s" % (service_name, service_info.reason))
return False
else:
# Find a suitable service automatically
LOG.info("Looking for suitable service...")
service_info = service_changer.findSuitableService()
if not service_info:
LOG.critical("No suitable service found for hijacking")
return False
service_name = service_info.service_name
LOG.info("Selected service for hijacking: %s" % service_name)
# Step 1: Prepare service hijacking (restore original config first, then backup)
LOG.info("Preparing service hijacking...")
# First, try to restore service to original state if it was previously hijacked
LOG.info("Checking if service needs restoration to original state...")
try:
# Get current service info to check if it's been hijacked
scm_handle = service_changer.openSvcManager()
current_info = service_changer.getServiceInfo(service_name, scm_handle)
scmr.hRCloseServiceHandle(service_changer.rpcsvc, scm_handle)
if current_info.binary_path_name and ('RemCom' in current_info.binary_path_name or not current_info.binary_path_name.endswith('.exe') or 'alg.exe' not in current_info.binary_path_name.lower()):
LOG.info("Service appears to be hijacked, attempting to restore original configuration...")
# Try to restore using a default configuration
from impacket.examples.servicechange import ServiceInfo
default_config = ServiceInfo()
default_config.binary_path_name = "C:\\Windows\\System32\\alg.exe" if service_name == "ALG" else "C:\\Windows\\system32\\ntfrs.exe" if service_name == "NtFrs" else "C:\\Windows\\system32\\vssvc.exe" if service_name == "VSS" else "C:\\Windows\\system32\\SearchIndexer.exe" if service_name == "WSearch" else "C:\\Windows\\System32\\snmptrap.exe" if service_name == "SNMPTRAP" else "C:\\Windows\\system32\\locator.exe" if service_name == "RpcLocator" else ""
default_config.start_type = 3 # MANUAL
default_config.start_name = "NT AUTHORITY\\LocalService" if service_name in ["ALG", "SNMPTRAP"] else "LocalSystem"
service_changer.restoreServiceConfig(service_name, default_config)
LOG.info("Service restored to default configuration")
except Exception as e:
LOG.debug("Could not restore service to original state: %s" % str(e))
# Now backup the (hopefully) original configuration
original_config = service_changer.backupServiceConfig(service_name)
# Upload RemComSvc file (use custom file if specified)
from impacket.examples import serviceinstall
# Determine which executable to use
if self.__exeFile is not None:
# Use custom file specified with -file parameter
LOG.info("Using custom executable: %s" % self.__exeFile)
try:
exe_file = open(self.__exeFile, 'rb')
except Exception as e:
LOG.critical("Error opening custom executable %s: %s" % (self.__exeFile, str(e)))
return False
installService = serviceinstall.ServiceInstall(service_changer.connection, exe_file, service_name, self.__remoteBinaryName)
remcom_filename = installService.binaryServiceName
service_changer.uploadFile(exe_file, "System32\\" + remcom_filename)
else:
# Use default RemComSvc
LOG.info("Using default RemComSvc executable")
installService = serviceinstall.ServiceInstall(service_changer.connection, remcomsvc.RemComSvc(), service_name, self.__remoteBinaryName)
remcom_svc = remcomsvc.RemComSvc()
remcom_filename = installService.binaryServiceName
service_changer.uploadFile(remcom_svc, "System32\\" + remcom_filename)
# Handle -c parameter (copy file and modify command)
if self.__copyFile is not None:
LOG.info("Copying file for execution: %s" % self.__copyFile)
try:
# Copy the file to target
service_changer.uploadFile(open(self.__copyFile, 'rb'), "System32\\" + os.path.basename(self.__copyFile))
# Modify command to use the copied file
self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command
LOG.info("Modified command to: %s" % self.__command)
except Exception as e:
LOG.critical("Error copying file %s: %s" % (self.__copyFile, str(e)))
return False
# Hijack service with RemComSvc
full_remcom_path = "C:\\Windows\\System32\\" + remcom_filename
if not service_changer.hijackService(service_name, full_remcom_path):
LOG.critical("Failed to hijack service")
return False
LOG.info("Service hijacked successfully, now executing command...")
# Step 2: Execute command through hijacked service
# The service is already hijacked with RemComSvc, now we need to communicate with it
LOG.info("Executing command through hijacked service...")
# Create SMB connection for communication
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.set_dport(self.__port)
rpctransport.setRemoteHost(remoteHost)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,
self.__nthash, self.__aesKey)
rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
# Execute command through the hijacked service using doStuff logic
# but skip the service installation part since we already hijacked a service
self.executeCommandViaHijackedService(rpctransport, service_changer, service_name)
# Step 3: Restore original service configuration
LOG.info("Restoring original service configuration...")
LOG.info("Original config - Binary Path: %s" % original_config.binary_path_name)
LOG.info("Original config - Start Type: %d" % original_config.start_type)
LOG.info("Original config - Start Name: %s" % original_config.start_name)
if not service_changer.restoreServiceConfig(service_name, original_config):
LOG.warning("Failed to restore service configuration")
else:
LOG.info("Service configuration restored successfully")
# Cleanup uploaded files
service_changer.cleanupFiles()
# Cleanup -c parameter file if used
if self.__copyFile is not None:
try:
LOG.info("Cleaning up copied file: %s" % os.path.basename(self.__copyFile))
service_changer.connection.deleteFile("ADMIN$", "System32\\" + os.path.basename(self.__copyFile))
except Exception as e:
LOG.warning("Failed to cleanup copied file: %s" % str(e))
return True
except Exception as e:
LOG.critical("Error executing via service hijacking: %s" % str(e))
return False
def executeCommandViaHijackedService(self, rpctransport, service_changer, service_name):
"""Execute command through already hijacked service"""
dce = rpctransport.get_dce_rpc()
try:
dce.connect()
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.critical(str(e))
sys.exit(1)
global dialect
dialect = rpctransport.get_smb_connection().getDialect()
try:
s = rpctransport.get_smb_connection()
s.setTimeout(100000)
# Connect to IPC$ and open communication pipe
tid = s.connectTree('IPC$')
fid_main = self.openPipe(s, tid, r'\RemCom_communicaton', 0x12019f)
# Create command message
packet = RemComMessage()
pid = os.getpid()
packet['Machine'] = ''.join([random.choice(string.ascii_letters) for _ in range(4)])
if self.__path is not None:
packet['WorkingDir'] = self.__path
packet['Command'] = self.__command
packet['ProcessID'] = pid
# Send command to hijacked service
s.writeNamedPipe(tid, fid_main, packet.getData())
global LastDataSent
LastDataSent = ''
# Start communication pipes
stdin_pipe = RemoteStdInPipe(rpctransport,
r'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, None)
stdin_pipe.start()
stdout_pipe = RemoteStdOutPipe(rpctransport,
r'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stdout_pipe.start()
stderr_pipe = RemoteStdErrPipe(rpctransport,
r'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stderr_pipe.start()
# Wait for response
ans = s.readNamedPipe(tid, fid_main, 8)
if len(ans):
retCode = RemComResponse(ans)
logging.info("Process %s finished with ErrorCode: %d, ReturnCode: %d" % (
self.__command, retCode['ErrorCode'], retCode['ReturnCode']))
# Stop the hijacked service after command execution
logging.info("Stopping hijacked service after command execution...")
if not service_changer.stopService(service_name):
logging.warning("Failed to stop hijacked service")
sys.exit(retCode['ErrorCode'])
except SystemExit:
raise
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.debug(str(e))
sys.stdout.flush()
sys.exit(1)
def doStuff(self, rpctransport):
dce = rpctransport.get_dce_rpc()
# 获取一个 DCE/RPC 对象,用来和目标 Windows 服务进行 RPC 调用。
try:
dce.connect()
# 发起连接尝试,如果目标不可达或者管道出错,会抛异常。
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.critical(str(e))
sys.exit(1)
# 这一步就是建立与远程 SCM 的 RPC 通道,如果连不上就直接失败退出。
global dialect
dialect = rpctransport.get_smb_connection().getDialect()
# get_smb_connection() → 从 DCE/RPC 传输对象中获取底层 SMB 连接对象。
# getDialect() → 获取 SMB 协议版本(例如 SMB1、SMB2、SMB3)。
# 存到全局变量 dialect,后续在写管道或文件操作时可能会根据 SMB 协议做兼容处理
try:
unInstalled = False
# unInstalled → 标记安装的服务是否已经卸载,用于异常处理时清理。
s = rpctransport.get_smb_connection()
# s → 获取 SMB 连接对象,用于后续文件操作、管道操作。
s.setTimeout(100000)
# s.setTimeout(100000) → 将 SMB 操作超时设置成很大,避免网络延迟导致操作中断。
if self.__exeFile is None:
installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), remcomsvc.RemComSvc(), self.__serviceName, self.__remoteBinaryName)
# 如果 self.__exeFile参数为空,则默认使用内置 remcomsvc.exe。注册服务
else:
try:
f = open(self.__exeFile, 'rb')
# 如果传入了self.__exeFile参数则尝试打开
except Exception as e:
logging.critical(str(e))
sys.exit(1)
# 打不开记录错误并退出
installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), f, self.__serviceName, self.__remoteBinaryName)
# 打的开则直接使用传入的exe进行注册服务
if installService.install() is False:
return
# 如果安装失败,直接返回,不继续执行命令。
if self.__exeFile is not None:
f.close()
# 如果使用了自定义 exe 文件,记得关闭本地文件句柄,防止资源泄露。
# 检查是否需要复制文件以供执行
if self.__copyFile is not None:
installService.copy_file(self.__copyFile, installService.getShare(), os.path.basename(self.__copyFile))
# 我们将要执行的命令更改为此文件名
self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command
# 如果用户指定了额外的文件需要上传执行:
# copy_file → 上传到远程共享(通常是 C$ 或服务安装的共享目录)。
# 把 self.__command 改成只执行上传的文件(保证远程执行时可以找到文件)。
tid = s.connectTree('IPC$')
fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)
# openPipe → 前面解释过的方法,打开主通信管道 \RemCom_communicaton,返回文件句柄。
# 访问掩码 0x12019f:表示SMB 文件权限,表示可读、可写、可执行操作。
packet = RemComMessage()
pid = os.getpid()
# 新建请求消息对象
packet['Machine'] = ''.join([random.choice(string.ascii_letters) for _ in range(4)])
# Machine → 随机 4 个字母,用于命名管道区分不同进程。
if self.__path is not None:
packet['WorkingDir'] = self.__path
# WorkingDir → 如果用户指定,设置工作目录。
packet['Command'] = self.__command
# Command → 要执行的命令。
packet['ProcessID'] = pid
# 本地进程 PID,用于命名管道标识(保证唯一性)
s.writeNamedPipe(tid, fid_main, packet.getData())
# 将打包好的 RemComMessage 二进制数据写入管道,发送到远程服务。
global LastDataSent
LastDataSent = ''
# 用于存储命令输入,防止在 stdout/stderr 中重复打印自己输入的命令。这里是清空初始化。
stdin_pipe = RemoteStdInPipe(rpctransport,
r'\%s%s%d' % (RemComSTDIN, packet['Machine'], packet['ProcessID']),
smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, installService.getShare())
stdin_pipe.start()
stdout_pipe = RemoteStdOutPipe(rpctransport,
r'\%s%s%d' % (RemComSTDOUT, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stdout_pipe.start()
stderr_pipe = RemoteStdErrPipe(rpctransport,
r'\%s%s%d' % (RemComSTDERR, packet['Machine'], packet['ProcessID']),
smb.FILE_READ_DATA)
stderr_pipe.start()
# 分别启动 标准输入、输出、错误 的线程。,每个线程负责异步读取/写入对应管道,保证命令交互实时。
ans = s.readNamedPipe(tid,fid_main,8)
if len(ans):
retCode = RemComResponse(ans)
logging.info("Process %s finished with ErrorCode: %d, ReturnCode: %d" % (
self.__command, retCode['ErrorCode'], retCode['ReturnCode']))
# readNamedPipe → 阻塞读取远程管道,等待 8 字节响应。
# 使用 RemComResponse 解包:
# ErrorCode → 服务执行状态
# ReturnCode → 命令退出码
# 输出日志,显示命令执行结果。
installService.uninstall()
if self.__copyFile is not None:
# We copied a file for execution, let's remove it
s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))
unInstalled = True
sys.exit(retCode['ErrorCode'])
# 卸载刚才安装的临时服务。
# 如果上传了执行文件,删除它。
# 标记 unInstalled = True → 异常处理时就不用重复卸载
# 退出程序并返回 ErrorCode。
except SystemExit:
raise
except Exception as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.debug(str(e))
if unInstalled is False:
installService.uninstall()
if self.__copyFile is not None:
s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile))
sys.stdout.flush()
sys.exit(1)
#区分 SystemExit → 直接重新抛出,保留退出行为。
# 捕获其他异常:
# 打印 DEBUG traceback(如果调试等级开启)
# 卸载服务并删除临时文件(保证清理,不留痕迹)
# 刷新 stdout
# 退出程序,返回错误码 1
# 总结 doStuff 执行流程
# 建立 RPC 连接 → 远程 SCM
# 获取 SMB 协议版本
# 准备远程服务(内置 remcomsvc 或自定义 exe)
# 上传 exe 并安装服务
# 上传额外执行文件(可选)
# 打开 IPC$ 树与主通信管道
# 构建 RemComMessage(命令 + 工作目录 + 随机机器 ID)
# 发送消息到管道
# 启动 stdin/stdout/stderr 管道线程
# 阻塞等待 RemComResponse(获取 ErrorCode 和 ReturnCode)
# 卸载服务并删除临时文件
# 异常捕获 → 清理资源 → 程序退出
class Pipes(Thread):
# Pipes 继承自 Python 的 Thread
# 说明每个 Pipes 实例都是一个线程,可以并行运行
# 用于异步处理管道通信,不会阻塞主线程
def __init__(self, transport, pipe, permissions, share=None):
# transport → DCE/RPC 传输对象,用于获取 SMB 连接和认证信息
# pipe → 要操作的命名管道名称,例如 \RemCom_stdoutXXXXpid
# permissions → 管道访问权限(读/写/追加等)
# share → 可选的远程共享(默认 None),在某些操作中用到
Thread.__init__(self)
# 调用父类初始化方法,确保线程能正确启动
self.server = 0
self.transport = transport
self.credentials = transport.get_credentials()
self.tid = 0
self.fid = 0
self.share = share
self.port = transport.get_dport()
self.pipe = pipe
self.permissions = permissions
self.daemon = True
# server 初始为 0,可能后续存放远程服务对象或 SMB 连接对象
# transport 保存传入的 DCE/RPC 传输对象
# credentials 从 transport 获取凭据(用户名、hash、AES key 等)
# tid Tree ID,打开远程共享返回的 ID,初始为 0
# fid 文件/管道句柄(File ID),初始为 0
# share 远程共享名称,可选,用于某些文件操作
# port 远程端口号(默认 445)
# pipe 管道名称
# permissions 管道访问权限,例如读取/写入/追加
# daemon True → 线程是守护线程,主程序退出时自动结束线程
def connectPipe(self):
# 负责在客户端与远程服务之间建立 SMB 命名管道连接
# 线程启动后通常会首先调用这个方法
try:
lock.acquire()
# lock 是全局锁
# 避免多个管道线程同时创建 SMB 连接导致竞争条件
# 例如多个线程同时尝试登录同一个远程主机
global dialect
#self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(), sess_port = self.port, preferredDialect = SMB_DIALECT)
self.server = SMBConnection(self.transport.get_smb_connection().getRemoteName(), self.transport.get_smb_connection().getRemoteHost(),
sess_port=self.port, preferredDialect=dialect)
# 新建一个 SMB 连接对象 self.server参数:
# getRemoteName() → 远程主机 NetBIOS 名称
# getRemoteHost() → 远程 IP 地址
# sess_port → SMB 端口(默认为 445)
# preferredDialect → 使用全局 SMB 协议版本(dialect)
# 注释掉的代码是以前的占位方式 '*SMBSERVER',现在改成用远程实际名字
user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials
if self.transport.get_kerberos() is True:
self.server.kerberosLogin(user, passwd, domain, lm, nt, aesKey, kdcHost=self.transport.get_kdcHost(), TGT=TGT, TGS=TGS)
else:
self.server.login(user, passwd, domain, lm, nt)
# 从 self.credentials 解包用户认证信息
#支持两种认证方式:
# Kerberos → kerberosLogin()
# NTLM/普通 SMB → login()
lock.release()
# SMB 连接完成后释放全局锁
self.tid = self.server.connectTree('IPC$')
# IPC$ 是 Windows 内置管理共享
self.server.waitNamedPipe(self.tid, self.pipe)
# 阻塞等待管道被创建
# 例如 \RemCom_stdoutXXXXpid 或 \RemCom_stdinXXXXpid
# 如果管道还没创建,会阻塞直到可用
self.fid = self.server.openFile(self.tid,self.pipe,self.permissions, creationOption = 0x40, fileAttributes = 0x80)
# 打开管道并返回文件句柄(fid)参数:
# creationOption=0x40 → FILE_OPEN_IF
# fileAttributes=0x80 → FILE_ATTRIBUTE_NORMAL
self.server.setTimeout(1000000)
# 设置 SMB 操作超时为非常大防止网络超时
except:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.error("Something wen't wrong connecting the pipes(%s), try again" % self.__class__)
# 捕获所有异常
# DEBUG 模式打印详细 tracebac
# 记录日志错误,但 不会抛异常退出线程
# 线程可能会在后续循环尝试重连管道
#总结connectPipe 做了以下事情:
# 获取线程锁,避免 SMB 登录竞争
# 建立 SMB 连接并登录(NTLM 或 Kerberos)
# 连接 IPC$ 树
# 等待并打开指定管道
# 设置超大超时保证读写稳定
# 异常时记录日志,线程可重试
class RemoteStdOutPipe(Pipes):
def __init__(self, transport, pipe, permisssions):
Pipes.__init__(self, transport, pipe, permisssions)
def run(self):
self.connectPipe()
# RemoteStdOutPipe 继承自前面你给的 Pipes 基类,Pipes.connectPipe() 会:
# 用全局 lock 建立一个新的 SMBConnection(登录/kerberos),
# connectTree('IPC$') 获取 tid,waitNamedPipe 等待命名管道就绪,openFile 获取 fid,
# 并把 self.server、self.tid、self.fid 等准备好。
# 所以 self.connectPipe() 结束后,这个线程已经有了可读的管道文件句柄 self.fid,可以调用 self.server.readFile(self.tid, self.fid, ...) 去读远端 stdout。
global LastDataSent
# LastDataSent 是一个 全局变量(主线程/RemoteShell 中设置)。作用:避免把自己发送给远端(即 send_data() 写入管道的数据)再原样回显到本地终端(防止把命令两次显示)。
if PY3:
__stdoutOutputBuffer, __stdoutData = b"", b""
# __stdoutOutputBuffer:用来累计从管道读到的原始 bytes(可能是半行)
# __stdoutData:待输出(经判断后要打印的完整行或 prompt)
while True:
try:
stdout_ans = self.server.readFile(self.tid, self.fid, 0, 1024)
except:
pass
else:
try:
if stdout_ans != LastDataSent:
if len(stdout_ans) != 0:
# Append new data to the buffer while there is data to read
__stdoutOutputBuffer += stdout_ans
# 限循环,持续读取管道:
# readFile(..., 1024):尝试读取最多 1024 bytes(这取决于远端写入的块大小)。如果没有数据,会抛异常或返回空(实现依赖于 Impacket 的 readFile 实现及超时),异常被吞掉(except: pass),线程继续循环 —— 这样能在远端没有输出时保持存活。
# if stdout_ans != LastDataSent::关键:如果刚好读到的是刚刚写入到 stdin 的那批字节(避免把自己输入再次回显),就跳过;否则把数据累加到 __stdoutOutputBuffer
promptRegex = rb'([a-zA-Z]:[\\\/])((([a-zA-Z0-9 -\.]*)[\\\/]?)+(([a-zA-Z0-9 -\.]+))?)?>$'
endsWithPrompt = bool(re.match(promptRegex, __stdoutOutputBuffer) is not None)
if endsWithPrompt == True:
# All data, we shouldn't have encoding errors
# Adding a space after the prompt because it's beautiful
__stdoutData = __stdoutOutputBuffer + b" "
# Remainder data for next iteration
__stdoutOutputBuffer = b""
# 尝试识别 Windows 命令提示符(例如 C:\Users\Admin> 或 C:\>)作为“本次输出已经完整”的标志。
# print("[+] endsWithPrompt")
# print(" | __stdoutData:",__stdoutData)
# print(" | __stdoutOutputBuffer:",__stdoutOutputBuffer)
elif b'\n' in __stdoutOutputBuffer:
# We have read a line, print buffer if it is not empty
lines = __stdoutOutputBuffer.split(b"\n")
# All lines, we shouldn't have encoding errors
__stdoutData = b"\n".join(lines[:-1]) + b"\n"
# Remainder data for next iteration
__stdoutOutputBuffer = lines[-1]
# print("[+] newline in __stdoutOutputBuffer")
# print(" | __stdoutData:",__stdoutData)
# print(" | __stdoutOutputBuffer:",__stdoutOutputBuffer)
# 如果缓冲区包含换行符,说明至少有一行完整行可输出:
if len(__stdoutData) != 0:
# There is data to print
try:
sys.stdout.write(__stdoutData.decode(CODEC))
sys.stdout.flush()
__stdoutData = b""
except UnicodeDecodeError:
logging.error('Decoding error detected, consider running chcp.com at the target,\nmap the result with '
'https://docs.python.org/3/library/codecs.html#standard-encodings\nand then execute smbexec.py '
'again with -codec and the corresponding codec')
print(__stdoutData.decode(CODEC, errors='replace'))
__stdoutData = b""
# 使用 __stdoutData.decode(CODEC) 把 bytes 解为 Python 字符串(文本),然后写入主进程的 sys.stdout
else:
# Don't echo the command that was sent, and clear it up
LastDataSent = b""
# 没有输出要打印时,把 LastDataSent 清空。意思是下一轮再收到与之前发送的数据相同的字节就不会被忽略(避免死等)。这是用于“不回显自己输入”的逻辑清理。
# Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,
# it will give false positives tho.. we should find a better way to handle this.
# if LastDataSent > 10:
# LastDataSent = ''
except:
pass
# 捕获并吞掉处理阶段的任何异常(例如正则异常、索引越界、decode 中未预见的异常),让线程保持存活并继续循环。
else:
__stdoutOutputBuffer, __stdoutData = "", ""
while True:
try:
stdout_ans = self.server.readFile(self.tid, self.fid, 0, 1024)
except:
pass
else:
try:
if stdout_ans != LastDataSent:
if len(stdout_ans) != 0:
# Append new data to the buffer while there is data to read
__stdoutOutputBuffer += stdout_ans
promptRegex = r'([a-zA-Z]:[\\\/])((([a-zA-Z0-9 -\.]*)[\\\/]?)+(([a-zA-Z0-9 -\.]+))?)?>$'
endsWithPrompt = bool(re.match(promptRegex, __stdoutOutputBuffer) is not None)
if endsWithPrompt:
# All data, we shouldn't have encoding errors
# Adding a space after the prompt because it's beautiful
__stdoutData = __stdoutOutputBuffer + " "
# Remainder data for next iteration
__stdoutOutputBuffer = ""
elif '\n' in __stdoutOutputBuffer:
# We have read a line, print buffer if it is not empty
lines = __stdoutOutputBuffer.split("\n")
# All lines, we shouldn't have encoding errors
__stdoutData = "\n".join(lines[:-1]) + "\n"
# Remainder data for next iteration
__stdoutOutputBuffer = lines[-1]
if len(__stdoutData) != 0:
# There is data to print
sys.stdout.write(__stdoutData.decode(CODEC))
sys.stdout.flush()
__stdoutData = ""
else:
# Don't echo the command that was sent, and clear it up
LastDataSent = ""
# Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,
# it will give false positives tho.. we should find a better way to handle this.
# if LastDataSent > 10:
# LastDataSent = ''
except Exception as e:
pass
# 这段代码就是 “远程 stdout 管道输出的清洗器 + 交互模拟器”。
class RemoteStdErrPipe(Pipes):
def __init__(self, transport, pipe, permisssions):
Pipes.__init__(self, transport, pipe, permisssions)
def run(self):
self.connectPipe()
# 建立和远程进程的 stderr 命名管道 的连接。
if PY3:
__stderrOutputBuffer, __stderrData = b'', b''
# __stderrOutputBuffer:用于拼接未完整的一行错误输出。
while True:
try:
stderr_ans = self.server.readFile(self.tid, self.fid, 0, 1024)
except:
pass
else:
try:
if len(stderr_ans) != 0:
# Append new data to the buffer while there is data to read
__stderrOutputBuffer += stderr_ans
# 无限循环持续读取管道(守护线程模式)。
# readFile(..., 1024):尝试读取最多 1024 bytes。可能的返回:
# 非空 bytes:新数据
# 空 bytes:可能表示无内容(实现依赖 impacket),但代码只在 len(stderr_ans) != 0 时 append
# readFile 抛异常(如网络问题、文件句柄失效):except 捕获并 pass —— 循环继续(线程不会崩溃)
# 把非空读取结果追加到 __stderrOutputBuffer。
if b'\n' in __stderrOutputBuffer:
# We have read a line, print buffer if it is not empty
lines = __stderrOutputBuffer.split(b"\n")
# All lines, we shouldn't have encoding errors
__stderrData = b"\n".join(lines[:-1]) + b"\n"
# Remainder data for next iteration
__stderrOutputBuffer = lines[-1]
# 如果缓冲中出现 \n 则说明至少有一整行(或多行)可输出。
# lines[:-1] 是所有完整行(最后一项可能为不完整的尾部),通过 b"\n".join(...) + b"\n" 恢复原来的换行格式放入 __stderrData。
# 将最后一个片段(不完整行或空)留回 __stderrOutputBuffer 以便下一次继续拼接。
if len(__stderrData) != 0:
# There is data to print
try:
sys.stdout.write(__stderrData.decode(CODEC))
sys.stdout.flush()
__stderrData = b""
except UnicodeDecodeError:
logging.error('Decoding error detected, consider running chcp.com at the target,\nmap the result with '
'https://docs.python.org/3/library/codecs.html#standard-encodings\nand then execute smbexec.py '
'again with -codec and the corresponding codec')
print(__stderrData.decode(CODEC, errors='replace'))
__stderrData = b""
# 使用 CODEC(来自脚本顶部 CODEC = sys.stdout.encoding 或 -codec 参数覆盖)对 bytes 调用 .decode(CODEC),得到 str 并写到 sys.stdout。
# sys.stdout.flush() 确保即时输出。
# 成功后把 __stderrData 清空。
else:
# Don't echo the command that was sent, and clear it up
LastDataSent = b""
# Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,
# it will give false positives tho.. we should find a better way to handle this.
# if LastDataSent > 10:
# LastDataSent = ''
except Exception as e:
pass
# 处理解析/输出过程中的任意异常并忽略,保持线程存活
else:
__stderrOutputBuffer, __stderrData = '', ''
while True:
try:
stderr_ans = self.server.readFile(self.tid, self.fid, 0, 1024)
except:
pass
else:
try:
if len(stderr_ans) != 0:
# Append new data to the buffer while there is data to read
__stderrOutputBuffer += stderr_ans
if '\n' in __stderrOutputBuffer:
# We have read a line, print buffer if it is not empty
lines = __stderrOutputBuffer.split("\n")
# All lines, we shouldn't have encoding errors
__stderrData = "\n".join(lines[:-1]) + "\n"
# Remainder data for next iteration
__stderrOutputBuffer = lines[-1]
if len(__stderrData) != 0:
# There is data to print
sys.stdout.write(__stderrData.decode(CODEC))
sys.stdout.flush()
__stderrData = ""
else:
# Don't echo the command that was sent, and clear it up
LastDataSent = ""
# Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars,
# it will give false positives tho.. we should find a better way to handle this.
# if LastDataSent > 10:
# LastDataSent = ''
except:
pass
# 意图
# 获并显示远程进程的错误输出。
# 在远程执行命令时,不仅有正常结果(stdout),还有可能产生错误(stderr)。
# 如果不处理 stderr,用户在交互式 shell 中就看不到报错信息,体验会失真。
# 保证 stderr 的输出格式和 stdout 一致。
# 通过缓冲区、按行输出、编码解码,确保报错信息在本地终端正确显示。
class RemoteShell(cmd.Cmd):
# 继承 Python 标准库的 cmd.Cmd,这个类就是用来构建交互式命令行解释器的。
def __init__(self, server, port, credentials, tid, fid, share, transport):
cmd.Cmd.__init__(self, False)
# 初始化父类 cmd.Cmd,参数 False 的含义是禁用 command completion(命令自动补全功能)。
self.prompt = '\x08'
# 设置交互式提示符为 \x08(ASCII 退格符)。
# 这是个技巧:
# 通过这种特殊字符,用户在交互时几乎看不到传统的提示符符号(比如 $、>)。
# 目的是:避免提示符和远程回显的命令输出混淆。
self.server = server
# 保存远程 SMB/RPC 服务的连接句柄或对象
self.transferClient = None
# 占位符,未来可能会初始化为一个文件传输客户端对象。
self.tid = tid
# tid(Tree ID):表示 SMB 协议中的一个树连接(对应一个共享目录,比如 C$)。
self.fid = fid
# fid(File ID):文件句柄 ID,通常是一个 已打开的远程管道(例如 \\PIPE\\RemCom_Communicate)。
self.credentials = credentials
# 保存用于连接目标的凭据对象。
self.share = share
# 目标共享名称(例如 ADMIN$ 或 C$)
self.port = port
# 保存远程目标 SMB 服务端口。
self.transport = transport
# 传输层对象,封装 SMB 连接、I/O 操作。
self.intro = '[!] Press help for extra shell commands'
# 当进入这个 shell 时,会自动显示这段提示信息。
def connect_transferClient(self):