Class: Rex::Post::Meterpreter::Ui::Console::CommandDispatcher::Core

Inherits:
Object
  • Object
show all
Includes:
Rex::Post::Meterpreter::Ui::Console::CommandDispatcher
Defined in:
lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb

Overview

Core meterpreter client commands that provide only the required set of commands for having a functional meterpreter client<->server instance.

Constant Summary collapse

CommDispatcher =
Console::CommandDispatcher
@@irb_opts =
Rex::Parser::Arguments.new(
  '-h' => [false, 'Help menu.'             ],
  '-e' => [true,  'Expression to evaluate.']
)
@@load_opts =
Rex::Parser::Arguments.new(
  '-h' => [false, 'Help menu.'                    ],
  '-l' => [false, 'List all available extensions.']
)
@@pivot_opts =
Rex::Parser::Arguments.new(
  '-t' => [true, 'Pivot listener type'],
  '-i' => [true, 'Identifier of the pivot to remove'],
  '-l' => [true, 'Host address to bind to (if applicable)'],
  '-n' => [true, 'Name of the listener entity (if applicable)'],
  '-a' => [true, 'Architecture of the stage to generate'],
  '-p' => [true, 'Platform of the stage to generate'],
  '-h' => [false, 'View help']
)
@@pivot_supported_archs =
[Rex::Arch::ARCH_X64, Rex::Arch::ARCH_X86]
@@pivot_supported_platforms =
['windows']
@@channel_opts =

Displays information about active channels

Rex::Parser::Arguments.new(
'-c' => [ true,  'Close the given channel.' ],
'-k' => [ true,  'Close the given channel.' ],
'-K' => [ false, 'Close all channels.' ],
'-i' => [ true,  'Interact with the given channel.' ],
'-l' => [ false, 'List active channels.' ],
'-r' => [ true,  'Read from the given channel.' ],
'-w' => [ true,  'Write to the given channel.' ],
'-h' => [ false, 'Help menu.' ])
@@set_timeouts_opts =
Rex::Parser::Arguments.new(
'-c' => [true, 'Comms timeout (seconds)'],
'-x' => [true, 'Expiration timout (seconds)'],
'-t' => [true, 'Retry total time (seconds)'],
'-w' => [true, 'Retry wait time (seconds)'],
'-h' => [false, 'Help menu'])
@@ssl_verify_opts =

Arguments for ssl verification

Rex::Parser::Arguments.new(
'-e' => [ false, 'Enable SSL certificate verification' ],
'-d' => [ false, 'Disable SSL certificate verification' ],
'-q' => [ false, 'Query the status of SSL certificate verification' ],
'-h' => [ false, 'Help menu' ])
@@transport_opts =

Arguments for transport switching

Rex::Parser::Arguments.new(
'-t' => [true, "Transport type: #{Rex::Post::Meterpreter::ClientCore::VALID_TRANSPORTS.keys.join(', ')}"],
'-l' => [true, 'LHOST parameter (for reverse transports)'],
'-p' => [true, 'LPORT parameter'],
'-i' => [true, 'Specify transport by index (currently supported: remove)'],
'-u' => [true, 'Local URI for HTTP/S transports (used when adding/changing transports with a custom LURI)'],
'-c' => [true, 'SSL certificate path for https transport verification (optional)'],
'-A' => [true, 'User agent for HTTP/S transports (optional)'],
'-H' => [true, 'Proxy host for HTTP/S transports (optional)'],
'-P' => [true, 'Proxy port for HTTP/S transports (optional)'],
'-U' => [true, 'Proxy username for HTTP/S transports (optional)'],
'-N' => [true, 'Proxy password for HTTP/S transports (optional)'],
'-B' => [true, 'Proxy type for HTTP/S transports (optional: http, socks; default: http)'],
'-C' => [true, 'Comms timeout (seconds) (default: same as current session)'],
'-X' => [true, 'Expiration timout (seconds) (default: same as current session)'],
'-T' => [true, 'Retry total time (seconds) (default: same as current session)'],
'-W' => [true, 'Retry wait time (seconds) (default: same as current session)'],
'-v' => [false, 'Show the verbose format of the transport list'],
'-h' => [false, 'Help menu'])
@@migrate_opts =
Rex::Parser::Arguments.new(
  '-P' => [true, 'PID to migrate to.'],
  '-N' => [true, 'Process name to migrate to.'],
  '-p' => [true, 'Writable path - Linux only (eg. /tmp).'],
  '-t' => [true, 'The number of seconds to wait for migration to finish (default: 60).'],
  '-h' => [false, 'Help menu.']
)
@@write_opts =

Writes data to a channel.

Rex::Parser::Arguments.new(
'-f' => [true, 'Write the contents of a file on disk'],
'-h' => [false, 'Help menu.'])
@@client_extension_search_paths =
[::File.join(Rex::Root, 'post', 'meterpreter', 'ui', 'console', 'command_dispatcher')]

Instance Attribute Summary collapse

Attributes included from Ui::Text::DispatcherShell::CommandDispatcher

#shell, #tab_complete_items

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Rex::Post::Meterpreter::Ui::Console::CommandDispatcher

check_hash, #client, #docs_dir, #filter_commands, #log_error, #msf_loaded?, set_hash

Methods included from Ui::Text::DispatcherShell::CommandDispatcher

#cmd_help, #cmd_help_help, #cmd_help_tabs, #deprecated_cmd, #deprecated_commands, #deprecated_help, #docs_dir, #help_to_s, included, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #tab_complete_directory, #tab_complete_filenames, #tab_complete_generic, #tab_complete_source_address, #update_prompt

Constructor Details

#initialize(shell) ⇒ Core

Initializes an instance of the core command set using the supplied shell for interactivity.



25
26
27
28
29
30
31
32
33
34
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 25

def initialize(shell)
  super

  self.extensions = []
  self.bgjobs     = []
  self.bgjob_id   = 0

  # keep a lookup table to refer to transports by index
  @transport_map = {}
end

Instance Attribute Details

#bgjob_idObject (protected)

:nodoc:



1848
1849
1850
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1848

def bgjob_id
  @bgjob_id
end

#bgjobsObject (protected)

:nodoc:



1848
1849
1850
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1848

def bgjobs
  @bgjobs
end

#extensionsObject (protected)

:nodoc:



1847
1848
1849
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1847

def extensions
  @extensions
end

Class Method Details

.add_client_extension_search_path(path) ⇒ Object



1816
1817
1818
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1816

def self.add_client_extension_search_path(path)
  @@client_extension_search_paths << path unless @@client_extension_search_paths.include?(path)
end

.client_extension_search_pathsObject



1820
1821
1822
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1820

def self.client_extension_search_paths
  @@client_extension_search_paths
end

Instance Method Details

#add_extension_client(mod) ⇒ Object (protected)

Loads the client extension specified in mod



1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1855

def add_extension_client(mod)
  klass = get_extension_client_class(mod)

  if klass.nil?
    print_error("Failed to load client portion of #{mod}.")
    return false
  end

  # Enstack the dispatcher
  self.shell.enstack_dispatcher(klass)

  # Insert the module into the list of extensions
  self.extensions << mod
end

#cmd_backgroundObject Also known as: cmd_bg



339
340
341
342
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 339

def cmd_background
  print_status("Backgrounding session #{client.name}...")
  client.interacting = false
end

#cmd_background_helpObject Also known as: cmd_bg_help



332
333
334
335
336
337
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 332

def cmd_background_help
  print_line('Usage: background')
  print_line
  print_line('Stop interacting with this session and return to the parent prompt')
  print_line
end

#cmd_bgkill(*args) ⇒ Object

Kill a background job



1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1577

def cmd_bgkill(*args)
  if args.empty? || args.include?('-h')
    print_line('Usage: bgkill [id]')
    return
  end

  args.each do |jid|
    jid = jid.to_i
    if self.bgjobs[jid]
      print_status("Killing background job #{jid}...")
      self.bgjobs[jid].kill
      self.bgjobs[jid] = nil
    else
      print_error("Job #{jid} was not running")
    end
  end
end

#cmd_bglist(*args) ⇒ Object

List background jobs



1598
1599
1600
1601
1602
1603
1604
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1598

def cmd_bglist(*args)
  self.bgjobs.each_index do |jid|
    if self.bgjobs[jid]
      print_status("Job #{jid}: #{self.bgjobs[jid][:args].inspect}")
    end
  end
end

#cmd_bgrun(*args) ⇒ Object

Executes a script in the context of the meterpreter session in the background



1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1536

def cmd_bgrun(*args)
  if args.empty? || args.first == '-h'
    print_line('Usage: bgrun <script> [arguments]')
    print_line
    print_line('Executes a ruby script in the context of the meterpreter session.')
    print_line

    return true
  end

  jid = self.bgjob_id
  self.bgjob_id += 1

  # Get the script name
  self.bgjobs[jid] = Rex::ThreadFactory.spawn("MeterpreterBGRun(#{args[0]})-#{jid}", false, jid, args) do |myjid,xargs|
    ::Thread.current[:args] = xargs.dup
    begin
      # the rest of the arguments get passed in through the binding
      script_name = args.shift
      client.execute_script(script_name, args)
    rescue ::Exception => e
      print_error("Error in script: #{script_name}")
      elog("Error in script: #{script_name}", error: e)
    end
    self.bgjobs[myjid] = nil
    print_status("Background script with Job ID #{myjid} has completed (#{::Thread.current[:args].inspect})")
  end

  print_status("Executed Meterpreter with Job ID #{jid}")
end

#cmd_bgrun_tabs(*args) ⇒ Object

Map this to the normal run command tab completion



1570
1571
1572
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1570

def cmd_bgrun_tabs(*args)
  cmd_run_tabs(*args)
end

#cmd_channel(*args) ⇒ Object

Performs operations on the supplied channel.



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
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 370

def cmd_channel(*args)
  if args.empty? || args.include?('-h')
    cmd_channel_help
    return
  end

  mode = nil
  chan = nil

  # Parse options
  @@channel_opts.parse(args) { |opt, idx, val|
    case opt
    when '-l'
      mode = :list
    when '-c', '-k'
      mode = :close
      chan = val
    when '-i'
      mode = :interact
      chan = val
    when '-r'
      mode = :read
      chan = val
    when '-w'
      mode = :write
      chan = val
    when '-K'
      mode = :kill_all
    end

    if @@channel_opts.arg_required?(opt)
      unless chan
        print_error('Channel ID required')
        return
      end
    end
  }

  case mode
  when :list
    tbl = Rex::Text::Table.new(
      'Indent'  => 4,
      'Columns' => ['Id', 'Class', 'Type'])
    items = 0

    client.channels.each_pair { |cid, channel|
      tbl << [ cid, channel.class.cls, channel.type ]
      items += 1
    }

    if (items == 0)
      print_line('No active channels.')
    else
      print("\n" + tbl.to_s + "\n")
    end
  when :close
    cmd_close(chan)
  when :interact
    cmd_interact(chan)
  when :read
    cmd_read(chan)
  when :write
    cmd_write(chan)
  when :kill_all
    if client.channels.empty?
      print_line('No active channels.')
      return
    end

    print_line('Killing all channels...')
    client.channels.each_pair do |id, channel|
      channel._close
    rescue ::StandardError
      print_error("Failed when trying to kill channel: #{id}")
    end
    print_line('Killed all channels.')
  else
    # No mode, no service.
    return true
  end
end

#cmd_channel_helpObject



360
361
362
363
364
365
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 360

def cmd_channel_help
  print_line('Usage: channel [options]')
  print_line
  print_line('Displays information about active channels.')
  print_line(@@channel_opts.usage)
end

#cmd_channel_tabs(str, words) ⇒ Object



452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 452

def cmd_channel_tabs(str, words)
  case words.length
  when 1
    @@channel_opts.option_keys
  when 2
    case words[1]
    when '-k', '-c', '-i', '-r', '-w'
      tab_complete_channels
    else
      []
    end
  else
    []
  end
end

#cmd_close(*args) ⇒ Object

Closes a supplied channel.



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 478

def cmd_close(*args)
  if args.empty? || args.include?('-h')
    cmd_close_help
    return true
  end

  cid = args[0].to_i
  channel = client.find_channel(cid)

  unless channel
    print_error('Invalid channel identifier specified.')
    return true
  end

  channel._close # Issue #410

  print_status("Closed channel #{cid}.")
end

#cmd_close_helpObject



468
469
470
471
472
473
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 468

def cmd_close_help
  print_line('Usage: close <channel_id>')
  print_line
  print_line('Closes the supplied channel.')
  print_line
end

#cmd_close_tabs(str, words) ⇒ Object Also known as: cmd_interact_tabs, cmd_read_tabs



497
498
499
500
501
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 497

def cmd_close_tabs(str, words)
  return [] if words.length > 1

  return tab_complete_channels
end

#cmd_detach(*args) ⇒ Object

Disconnects the session



529
530
531
532
533
534
535
536
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 529

def cmd_detach(*args)
  unless client.passive_service
    print_error('The detach command is not applicable with the current transport')
    return
  end
  client.shutdown_passive_dispatcher
  shell.stop
end

#cmd_detach_helpObject



515
516
517
518
519
520
521
522
523
524
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 515

def cmd_detach_help
  print_line('Detach from the victim. Only possible for non-stream sessions (http/https)')
  print_line
  print_line('The victim will continue to attempt to call back to the handler until it')
  print_line('successfully connects (which may happen immediately if you have a handler')
  print_line('running in the background), or reaches its expiration.')
  print_line
  print_line("This session may #{client.passive_service ? "" : "NOT"} be detached.")
  print_line
end

#cmd_disable_unicode_encodingObject



1809
1810
1811
1812
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1809

def cmd_disable_unicode_encoding
  client.encode_unicode = false
  print_status('Unicode encoding is disabled')
end

#cmd_enable_unicode_encodingObject



1804
1805
1806
1807
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1804

def cmd_enable_unicode_encoding
  client.encode_unicode = true
  print_status('Unicode encoding is enabled')
end

#cmd_exit(*args) ⇒ Object Also known as: cmd_quit

Terminates the meterpreter session.



506
507
508
509
510
511
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 506

def cmd_exit(*args)
  print_status('Shutting down Meterpreter...')
  client.core.shutdown rescue nil
  client.shutdown_passive_dispatcher
  shell.stop
end

#cmd_get_timeouts(*args) ⇒ Object



696
697
698
699
700
701
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 696

def cmd_get_timeouts(*args)
  # Calling set without passing values is the same as
  # getting all the current timeouts
  timeouts = client.core.set_transport_timeouts
  print_timeouts(timeouts)
end

#cmd_guid(*args) ⇒ Object

Get the session GUID



729
730
731
732
733
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 729

def cmd_guid(*args)
  parts = client.session_guid.unpack('H*')[0]
  guid = [parts[0, 8], parts[8, 4], parts[12, 4], parts[16, 4], parts[20, 12]].join('-')
  print_good("Session GUID: #{guid}")
end

#cmd_info(*args) ⇒ Object

Show info for a given Post module.

See also cmd_info in lib/msf/ui/console/command_dispatcher/core.rb



1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1618

def cmd_info(*args)
  return unless msf_loaded?

  if args.length != 1 or args.include?('-h')
    cmd_info_help
    return
  end

  module_name = args.shift
  mod = client.framework.modules.create(module_name);

  if mod.nil?
    print_error("Invalid module: #{module_name}")
  end

  if (mod)
    print_line(::Msf::Serializer::ReadableText.dump_module(mod))
    mod_opt = ::Msf::Serializer::ReadableText.dump_options(mod, '   ')
    print_line("\nModule options (#{mod.fullname}):\n\n#{mod_opt}") if (mod_opt and mod_opt.length > 0)
  end
end

#cmd_info_helpObject



1606
1607
1608
1609
1610
1611
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1606

def cmd_info_help
  print_line('Usage: info <module>')
  print_line
  print_line('Prints information about a post-exploitation module')
  print_line
end

#cmd_info_tabs(str, words) ⇒ Object



1640
1641
1642
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1640

def cmd_info_tabs(str, words)
  tab_complete_modules(str, words) if msf_loaded?
end

#cmd_interact(*args) ⇒ Object

Interacts with a channel.



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 548

def cmd_interact(*args)
  if args.empty? || args.include?('-h')
    cmd_info_help
    return true
  end

  cid = args[0].to_i
  channel = client.find_channel(cid)

  if channel
    print_line("Interacting with channel #{cid}...\n")

    shell.interact_with_channel(channel)
  else
    print_error('Invalid channel identifier specified.')
  end
end

#cmd_interact_helpObject



538
539
540
541
542
543
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 538

def cmd_interact_help
  print_line('Usage: interact <channel_id>')
  print_line
  print_line('Interacts with the supplied channel.')
  print_line
end

#cmd_irb(*args) ⇒ Object

Open an interactive Ruby shell on the current session



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 583

def cmd_irb(*args)
  expressions = []

  # Parse the command options
  @@irb_opts.parse(args) do |opt, idx, val|
    case opt
    when '-e'
      expressions << val
    when '-h'
      return cmd_irb_help
    end
  end

  session = client
  framework = client.framework

  if expressions.empty?
    print_status('Starting IRB shell...')
    print_status("You are in the \"client\" (session) object\n")
    framework.history_manager.with_context(name: :irb) do
      Rex::Ui::Text::IrbShell.new(client).run
    end
  else
    # XXX: No vprint_status here
    if framework.datastore['VERBOSE'].to_s == 'true'
      print_status("You are executing expressions in #{binding.receiver}")
    end

    expressions.each { |expression| eval(expression, binding) }
  end
end

#cmd_irb_helpObject



568
569
570
571
572
573
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 568

def cmd_irb_help
  print_line('Usage: irb')
  print_line
  print_line('Open an interactive Ruby shell on the current session.')
  print @@irb_opts.usage
end

#cmd_irb_tabs(str, words) ⇒ Object



575
576
577
578
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 575

def cmd_irb_tabs(str, words)
  return [] if words.length > 1
  @@irb_opts.option_keys
end

#cmd_load(*args) ⇒ Object

Loads one or more meterpreter extensions.



1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1281

def cmd_load(*args)
  if args.length == 0
    args.unshift('-h')
  end

  @@load_opts.parse(args) { |opt, idx, val|
    case opt
    when '-l'
      exts = Set.new
      if extensions.include?('stdapi') && !client.sys.config.sysinfo['BuildTuple'].blank?
        # Use API to get list of extensions from the gem
        exts.merge(MetasploitPayloads::Mettle.available_extensions(client.sys.config.sysinfo['BuildTuple']))
      else
        exts.merge(client.binary_suffix.map { |suffix| MetasploitPayloads.list_meterpreter_extensions(suffix) }.flatten)
      end
      exts = exts.sort.uniq
      print(exts.to_a.join("\n") + "\n")

      return true
    when '-h'
      cmd_load_help
      return true
    end
  }

  # Load each of the modules
  args.each { |m|
    md = m.downcase

    # Temporary hack to pivot mimikatz over to kiwi until
    # everyone remembers to do it themselves
    if md == 'mimikatz'
      print_warning('The "mimikatz" extension has been replaced by "kiwi". Please use this in future.')
      md = 'kiwi'
    end

    modulenameprovided = md

    if client.binary_suffix and client.binary_suffix.size > 1
      client.binary_suffix.each { |s|
        if (md =~ /(.*)\.#{s}/ )
          md = $1
          break
        end
      }
    end

    if (extensions.include?(md))
      print_warning("The \"#{md}\" extension has already been loaded.")
      next
    end

    print("Loading extension #{md}...")

    begin
      # Use the remote side, then load the client-side
      if (client.core.use(modulenameprovided) == true)
        add_extension_client(md)

        if md == 'stdapi' && (client.exploit_datastore && !client.exploit_datastore['AutoLoadStdapi'] && client.exploit_datastore['AutoSystemInfo'])
          client.load_session_info
        end
      end
    rescue => ex
      print_line
      log_error("Failed to load extension: #{ex.message}")
      elog(ex)
      if ex.kind_of?(ExtensionLoadError) && ex.name
        # MetasploitPayloads and MetasploitPayloads::Mettle do things completely differently, build an array of
        # suggestion keys (binary_suffixes and Mettle build-tuples)
        suggestion_keys = MetasploitPayloads.list_meterpreter_extension_suffixes(ex.name) + MetasploitPayloads::Mettle.available_platforms(ex.name)
        suggestion_map = {
          # Extension Suffixes
          'jar' => 'java',
          'php' => 'php',
          'py' => 'python',
          'x64.dll' => 'windows/x64',
          'x86.dll' => 'windows',
          # Mettle Platforms
          'aarch64-iphone-darwin' => 'apple_ios/aarch64',
          'aarch64-linux-musl' => 'linux/aarch64',
          'arm-iphone-darwin' => 'apple_ios/armle',
          'armv5b-linux-musleabi' => 'linux/armbe',
          'armv5l-linux-musleabi' => 'linux/armle',
          'i486-linux-musl' => 'linux/x86',
          'mips64-linux-muslsf' => 'linux/mips64',
          'mipsel-linux-muslsf' => 'linux/mipsle',
          'mips-linux-muslsf' => 'linux/mipsbe',
          'powerpc64le-linux-musl' => 'linux/ppc64le',
          'powerpc-e500v2-linux-musl' => 'linux/ppce500v2',
          'powerpc-linux-muslsf' => 'linux/ppc',
          's390x-linux-musl' => 'linux/zarch',
          'x86_64-apple-darwin' => 'osx/x64',
          'x86_64-linux-musl' => 'linux/x64',
        }
        suggestions = suggestion_map.select { |k,_v| suggestion_keys.include?(k) }.values
        unless suggestions.empty?
          log_error("The \"#{ex.name}\" extension is supported by the following Meterpreter payloads:")
          suggestions.each do |suggestion|
            log_error("  - #{suggestion}/meterpreter*")
          end
        end
      end

      next
    end

    print_line('Success.')
  }

  return true
end

#cmd_load_helpObject Also known as: cmd_use_help



1271
1272
1273
1274
1275
1276
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1271

def cmd_load_help
  print_line('Usage: load ext1 ext2 ext3 ...')
  print_line
  print_line('Loads a meterpreter extension module or modules.')
  print_line(@@load_opts.usage)
end

#cmd_load_tabs(str, words) ⇒ Object Also known as: cmd_use_tabs



1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1394

def cmd_load_tabs(str, words)
  tabs = Set.new
  if extensions.include?('stdapi') && !client.sys.config.sysinfo['BuildTuple'].blank?
    tabs.merge(MetasploitPayloads::Mettle.available_extensions(client.sys.config.sysinfo['BuildTuple']))
  else
    tabs.merge(client.binary_suffix.map { |suffix| MetasploitPayloads.list_meterpreter_extensions(suffix) }.flatten)
  end
  tabs = tabs.sort.uniq
  return tabs.to_a
end

#cmd_machine_id(*args) ⇒ Object

Get the machine ID of the target



721
722
723
724
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 721

def cmd_machine_id(*args)
  client.machine_id = client.core.machine_id unless client.machine_id
  print_good("Machine ID: #{client.machine_id}")
end

#cmd_migrate(*args) ⇒ void

This method returns an undefined value.

Migrates the server to the supplied process identifier.

Parameters:

  • args (Array<String>)

    Commandline arguments, -h or a pid. On linux platforms a path for the unix domain socket used for IPC.



1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1153

def cmd_migrate(*args)
  if args.length == 0 || args.any? { |arg| %w(-h --pid --name).include? arg }
    cmd_migrate_help
    return true
  end

  pid = nil
  writable_dir = nil
  opts = {
    timeout: nil
  }

  @@migrate_opts.parse(args) do |opt, idx, val|
    case opt
    when '-t'
      opts[:timeout] = val.to_i
    when '-p'
      writable_dir = val
    when '-P'
      unless val =~ /^\d+$/
        print_error("Not a PID: #{val}")
        return
      end
      pid = val.to_i
    when '-N'
      if val.to_s.empty?
        print_error('No process name provided')
        return
      end
      # this will migrate to the first process with a matching name
      unless (process = client.sys.process.processes.find { |p| p['name'] == val })
        print_error("Could not find process name #{val}")
        return
      end
      pid = process['pid']
    end
  end

  # we cannot migrate to another process until loaded stdapi
  unless extensions.include?('stdapi')
    print_error('Stdapi extension must be loaded.')
    return
  end

  unless pid
    unless (pid = args.first)
      print_error('A process ID or name argument must be provided')
      return
    end
    unless pid =~ /^\d+$/
      print_error("Not a PID: #{pid}")
      return
    end
    pid = pid.to_i
  end

  begin
    server = client.sys.process.open
  rescue Rex::TimeoutError, ::Timeout::Error => e
    elog('Server Timeout', error: e)
  rescue RequestError => e
    elog('Request Error', error: e)
  end

  service = client.pfservice

  # If we have any open port forwards, we need to close them down
  # otherwise we'll end up with local listeners which aren't connected
  # to valid channels in the migrated meterpreter instance.
  existing_relays = []

  if service
    service.each_tcp_relay do |lhost, lport, rhost, rport, opts|
      next unless opts['MeterpreterRelay']
      if existing_relays.empty?
        print_status('Removing existing TCP relays...')
      end
      if (service.stop_tcp_relay(lport, lhost))
        print_status("Successfully stopped TCP relay on #{lhost || '0.0.0.0'}:#{lport}")
        existing_relays << {
          :lport => lport,
          :opts => opts
        }
      else
        print_error("Failed to stop TCP relay on #{lhost || '0.0.0.0'}:#{lport}")
        next
      end
    end
    unless existing_relays.empty?
      print_status("#{existing_relays.length} TCP relay(s) removed.")
    end
  end

  if pid == server.pid
    print_error("Process already running at PID #{pid}")
    return
  end

  server ? print_status("Migrating from #{server.pid} to #{pid}...") : print_status("Migrating to #{pid}")

  # Do this thang.
  client.core.migrate(pid, writable_dir, opts)

  print_status('Migration completed successfully.')

  # Update session info (we may have a new username)
  client.update_session_info

  unless existing_relays.empty?
    print_status('Recreating TCP relay(s)...')
    existing_relays.each do |r|
      client.pfservice.start_tcp_relay(r[:lport], r[:opts])
      print_status("Local TCP relay recreated: #{r[:opts]['LocalHost'] || '0.0.0.0'}:#{r[:lport]} <-> #{r[:opts]['PeerHost']}:#{r[:opts]['PeerPort']}")
    end
  end

end

#cmd_migrate_helpObject



1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1135

def cmd_migrate_help
  if client.platform == 'linux'
    print_line('Usage: migrate <<pid> | -P <pid> | -N <name>> [-p writable_path] [-t timeout]')
  else
    print_line('Usage: migrate <<pid> | -P <pid> | -N <name>> [-t timeout]')
  end
  print_line
  print_line('Migrates the server instance to another process.')
  print_line('NOTE: Any open channels or other dynamic state will be lost.')
  print_line
end

#cmd_pivot(*args) ⇒ Object



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
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 189

def cmd_pivot(*args)
  if args.length == 0 || args.include?('-h')
    cmd_pivot_help
    return true
  end

  opts = {}
  @@pivot_opts.parse(args) { |opt, idx, val|
    case opt
    when '-t'
      opts[:type] = val
    when '-i'
      opts[:guid] = val
    when '-l'
      opts[:lhost] = val
    when '-n'
      opts[:name] = val
    when '-a'
      opts[:arch] = val
    when '-p'
      opts[:platform] = val
    end
  }

  # first parameter is the command
  case args[0]
  when 'remove', 'del', 'delete', 'rm'
    unless opts[:guid]
      print_error('Pivot listener ID must be specified (-i)')
      return false
    end

    unless opts[:guid] =~ /^[0-9a-f]{32}/i && opts[:guid].length == 32
      print_error("Invalid pivot listener ID: #{opts[:guid]}")
      return false
    end

    listener_id = [opts[:guid]].pack('H*')
    unless client.find_pivot_listener(listener_id)
      print_error("Unknown pivot listener ID: #{opts[:guid]}")
      return false
    end

    Pivot.remove_listener(client, listener_id)
    print_good("Successfully removed pivot: #{opts[:guid]}")
  when 'list', 'show', 'print'
    if client.pivot_listeners.length > 0
      tbl = Rex::Text::Table.new(
        'Header'  => 'Currently active pivot listeners',
        'Indent'  => 4,
        'Columns' => ['Id', 'URL', 'Stage'])

      client.pivot_listeners.each do |k, v|
        tbl << v.to_row
      end
      print_line
      print_line(tbl.to_s)
    else
      print_status('There are no active pivot listeners')
    end
  when 'add'
    unless opts[:type]
      print_error('Pivot type must be specified (-t)')
      return false
    end

    unless opts[:arch]
      print_error('Architecture must be specified (-a)')
      return false
    end
    unless @@pivot_supported_archs.include?(opts[:arch])
      print_error("Unknown or unsupported architecture: #{opts[:arch]}")
      return false
    end

    unless opts[:platform]
      print_error('Platform must be specified (-p)')
      return false
    end
    unless @@pivot_supported_platforms.include?(opts[:platform])
      print_error("Unknown or unsupported platform: #{opts[:platform]}")
      return false
    end

    # currently only one pivot type supported, more to come we hope
    case opts[:type]
    when 'pipe'
      pivot_add_named_pipe(opts)
    else
      print_error("Unknown pivot type: #{opts[:type]}")
      return false
    end
  else
    print_error("Unknown command: #{args[0]}")
  end
end

#cmd_pivot_helpObject



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 146

def cmd_pivot_help
  print_line('Usage: pivot <list|add|remove> [options]')
  print_line
  print_line('Manage pivot listeners on the target.')
  print_line
  print_line(@@pivot_opts.usage)
  print_line
  print_line('Supported pivot types:')
  print_line('     - pipe (using named pipes over SMB)')
  print_line('Supported architectures:')
  @@pivot_supported_archs.each do |a|
    print_line('     - ' + a)
  end
  print_line('Supported platforms:')
  print_line('     - windows')
  print_line
  print_line("eg.    pivot add -t pipe -l 192.168.0.1 -n msf-pipe -a #{@@pivot_supported_archs.first} -p windows")
  print_line("       pivot list")
  print_line("       pivot remove -i 1")
  print_line
end

#cmd_pivot_tabs(str, words) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 168

def cmd_pivot_tabs(str, words)
  return %w[list add remove] + @@pivot_opts.option_keys if words.length == 1

  case words[-1]
  when '-a'
    return @@pivot_supported_archs
  when '-i'
    matches = []
    client.pivot_listeners.each_value { |v| matches << v.id.unpack('H*')[0] }
    return matches
  when '-p'
    return @@pivot_supported_platforms
  when '-t'
    return ['pipe']
  when 'add', 'remove'
    return @@pivot_opts.option_keys
  end

  []
end

#cmd_pry(*args) ⇒ Object

Open the Pry debugger on the current session



625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 625

def cmd_pry(*args)
  if args.include?('-h')
    cmd_pry_help
    return
  end

  begin
    require 'pry'
  rescue LoadError
    print_error('Failed to load Pry, try "gem install pry"')
    return
  end

  print_status('Starting Pry shell...')
  print_status("You are in the \"client\" (session) object\n")

  Pry.config.history_load = false
  client.framework.history_manager.with_context(history_file: Msf::Config.pry_history, name: :pry) do
    client.pry
  end
end

#cmd_pry_helpObject



615
616
617
618
619
620
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 615

def cmd_pry_help
  print_line 'Usage: pry'
  print_line
  print_line 'Open the Pry debugger on the current session.'
  print_line
end

#cmd_read(*args) ⇒ Object

Reads data from a channel.



1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1422

def cmd_read(*args)
  if args.empty? || args.include?('-h')
    cmd_read_help
    return true
  end

  cid     = args[0].to_i
  length  = (args.length >= 2) ? args[1].to_i : 16384
  channel = client.find_channel(cid)

  unless channel
    print_error("Channel #{cid} is not valid.")
    return true
  end

  data = channel.read(length)

  if data && data.length
    print("Read #{data.length} bytes from #{cid}:\n\n#{data}\n")
  else
    print_error('No data was returned.')
  end

  return true
end

#cmd_read_helpObject



1412
1413
1414
1415
1416
1417
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1412

def cmd_read_help
  print_line('Usage: read <channel_id> [length]')
  print_line
  print_line('Reads data from the supplied channel.')
  print_line
end

#cmd_resource(*args) ⇒ Object



1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1742

def cmd_resource(*args)
  if args.empty?
    cmd_resource_help
    return false
  end

  args.each do |res|
    good_res = nil
    if res == '-'
      good_res = res
    elsif ::File.exist?(res)
      good_res = res
    elsif
      # let's check to see if it's in the scripts/resource dir (like when tab completed)
      [
        ::Msf::Config.script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter',
        ::Msf::Config.user_script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter'
      ].each do |dir|
        res_path = dir + ::File::SEPARATOR + res
        if ::File.exist?(res_path)
          good_res = res_path
          break
        end
      end
    end
    if good_res
      client.console.load_resource(good_res)
    else
      print_error("#{res} is not a valid resource file")
      next
    end
  end
end

#cmd_resource_helpObject



1734
1735
1736
1737
1738
1739
1740
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1734

def cmd_resource_help
  print_line "Usage: resource path1 [path2 ...]"
  print_line
  print_line "Run the commands stored in the supplied files. (- for stdin, press CTRL+D to end input from stdin)"
  print_line "Resource files may also contain ERB or Ruby code between <ruby></ruby> tags."
  print_line
end

#cmd_resource_tabs(str, words) ⇒ Object



1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1776

def cmd_resource_tabs(str, words)
  tabs = []
  #return tabs if words.length > 1
  if ( str and str =~ /^#{Regexp.escape(::File::SEPARATOR)}/ )
    # then you are probably specifying a full path so let's just use normal file completion
    return tab_complete_filenames(str,words)
  elsif (not words[1] or not words[1].match(/^\//))
    # then let's start tab completion in the scripts/resource directories
    begin
      [
        ::Msf::Config.script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter',
        ::Msf::Config.user_script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter',
        '.'
      ].each do |dir|
        next if not ::File.exist? dir
        tabs += ::Dir.new(dir).find_all { |e|
          path = dir + ::File::SEPARATOR + e
          ::File.file?(path) and ::File.readable?(path)
        }
      end
    rescue Exception
    end
  else
    tabs += tab_complete_filenames(str,words)
  end
  return tabs
end

#cmd_run(*args) ⇒ Object

Executes a script in the context of the meterpreter session.



1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1462

def cmd_run(*args)
  if args.empty? || args.first == '-h'
    cmd_run_help
    return true
  end

  # Get the script name
  begin
    script_name = args.shift
    # First try it as a Post module if we have access to the Metasploit
    # Framework instance.  If we don't, or if no such module exists,
    # fall back to using the scripting interface.
    if msf_loaded? && mod = client.framework.modules.create(script_name)
      original_mod = mod
      reloaded_mod = client.framework.modules.reload_module(original_mod)

      unless reloaded_mod
        error = client.framework.modules.module_load_error_by_path[original_mod.file_path]
        print_error("Failed to reload module: #{error}")

        return
      end

      opts = ''
      if reloaded_mod.is_a?(Msf::Exploit)
        # set the payload as one of the first options, allowing it to be overridden by the user
        opts << "PAYLOAD=#{client.via_payload.delete_prefix('payload/')}," if client.via_payload
      end

      opts  << (args + [ "SESSION=#{client.sid}" ]).join(',')
      result = reloaded_mod.run_simple(
        #'RunAsJob' => true,
        'LocalInput'  => shell.input,
        'LocalOutput' => shell.output,
        'OptionStr'   => opts
      )

      print_status("Session #{result.sid} created in the background.") if result.is_a?(Msf::Session)
    else
      # the rest of the arguments get passed in through the binding
      client.execute_script(script_name, args)
    end
  rescue => e
    print_error("Error in script: #{script_name}")
    elog("Error in script: #{script_name}", error: e)
  end
end

#cmd_run_helpObject



1450
1451
1452
1453
1454
1455
1456
1457
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1450

def cmd_run_help
  print_line('Usage: run <script> [arguments]')
  print_line
  print_line('Executes a ruby script or Metasploit Post module in the context of the')
  print_line('meterpreter session.  Post modules can take arguments in var=val format.')
  print_line('Example: run post/foo/bar BAZ=abcd')
  print_line
end

#cmd_run_tabs(str, words) ⇒ Object



1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1510

def cmd_run_tabs(str, words)
  tabs = []
  unless words[1] && words[1].match(/^\//)
    begin
      tabs += tab_complete_modules(str, words) if msf_loaded?
      [
        ::Msf::Sessions::Meterpreter.script_base,
        ::Msf::Sessions::Meterpreter.user_script_base
      ].each do |dir|
        next if not ::File.exist? dir
        tabs += ::Dir.new(dir).find_all { |e|
          path = dir + ::File::SEPARATOR + e
          ::File.file?(path) and ::File.readable?(path)
        }
      end
    rescue Exception
    end
  end

  tabs.map { |e| e.sub(/\.rb$/, '') }
end

#cmd_secureObject



326
327
328
329
330
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 326

def cmd_secure
  print_status('Negotiating new encryption key ...')
  client.core.secure
  print_good('Done.')
end

#cmd_sessions(*args) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 312

def cmd_sessions(*args)
  if args.length == 0 || args[0].to_i == 0
    cmd_sessions_help
  elsif args[0].to_s == client.name.to_s
    print_status("Session #{client.name} is already interactive.")
  else
    print_status("Backgrounding session #{client.name}...")
    # store the next session id so that it can be referenced as soon
    # as this session is no longer interacting
    client.next_session = args[0]
    client.interacting = false
  end
end

#cmd_sessions_helpObject



304
305
306
307
308
309
310
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 304

def cmd_sessions_help
  print_line('Usage: sessions <id>')
  print_line
  print_line('Interact with a different session Id.')
  print_line('This works the same as calling this from the MSF shell: sessions -i <session id>')
  print_line
end

#cmd_set_timeouts(*args) ⇒ Object



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 667

def cmd_set_timeouts(*args)
  if args.length == 0 || args.include?('-h')
    cmd_set_timeouts_help
    return
  end

  opts = {}

  @@set_timeouts_opts.parse(args) do |opt, idx, val|
    case opt
    when '-c'
      opts[:comm_timeout] = val.to_i if val
    when '-x'
      opts[:session_exp] = val.to_i if val
    when '-t'
      opts[:retry_total] = val.to_i if val
    when '-w'
      opts[:retry_wait] = val.to_i if val
    end
  end

  if opts.keys.length == 0
    print_error('No options set')
  else
    timeouts = client.core.set_transport_timeouts(opts)
    print_timeouts(timeouts)
  end
end

#cmd_set_timeouts_helpObject



654
655
656
657
658
659
660
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 654

def cmd_set_timeouts_help
  print_line('Usage: set_timeouts [options]')
  print_line
  print_line('Set the current timeout options.')
  print_line('Any or all of these can be set at once.')
  print_line(@@set_timeouts_opts.usage)
end

#cmd_set_timeouts_tabs(str, words) ⇒ Object



662
663
664
665
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 662

def cmd_set_timeouts_tabs(str, words)
  return [] if words.length > 1
  @@set_timeouts_opts.option_keys
end

#cmd_sleep(*args) ⇒ Object

Handle the sleep command.



844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 844

def cmd_sleep(*args)
  if args.empty? || args.include?('-h')
    cmd_sleep_help
    return
  end

  seconds = args.shift.to_i

  if seconds <= 0
    cmd_sleep_help
    return
  end

  print_status("Telling the target instance to sleep for #{seconds} seconds ...")
  if client.core.transport_sleep(seconds)
    print_good("Target instance has gone to sleep, terminating current session.")
    client.shutdown_passive_dispatcher
    shell.stop
  else
    print_error("Target instance failed to go to sleep.")
  end
end

#cmd_sleep_helpObject

Display help for the sleep.



831
832
833
834
835
836
837
838
839
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 831

def cmd_sleep_help
  print_line('Usage: sleep <time>')
  print_line
  print_line('  time: Number of seconds to wait (positive integer)')
  print_line
  print_line('  This command tells Meterpreter to go to sleep for the specified')
  print_line('  number of seconds. Sleeping will result in the transport being')
  print_line('  shut down and restarted after the designated timeout.')
end

#cmd_ssl_verify(*args) ⇒ Object

Handle the SSL verification querying and setting function.



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 765

def cmd_ssl_verify(*args)
  if ( args.length == 0 or args.include?("-h") )
    cmd_ssl_verify_help
    return
  end

  unless client.passive_service && client.sock.type? == 'tcp-ssl'
    print_error('The ssl_verify command is not applicable with the current transport')
    return
  end

  query = false
  enable = false
  disable = false

  settings = 0

  @@ssl_verify_opts.parse(args) do |opt, idx, val|
    case opt
    when '-q'
      query = true
      settings += 1
    when '-e'
      enable = true
      settings += 1
    when '-d'
      disable = true
      settings += 1
    end
  end

  # Make sure only one action has been chosen
  if settings != 1
    cmd_ssl_verify_help
    return
  end

  if query
    hash = client.core.get_ssl_hash_verify
    if hash
      print_good("SSL verification is enabled. SHA1 Hash: #{hash.unpack("H*")[0]}")
    else
      print_good('SSL verification is disabled.')
    end

  elsif enable
    hash = client.core.enable_ssl_hash_verify
    if hash
      print_good("SSL verification has been enabled. SHA1 Hash: #{hash.unpack("H*")[0]}")
    else
      print_error('Failed to enable SSL verification')
    end

  else
    if client.core.disable_ssl_hash_verify
      print_good('SSL verification has been disabled')
    else
      print_error('Failed to disable SSL verification')
    end
  end

end

#cmd_ssl_verify_helpObject

Help for ssl verification



754
755
756
757
758
759
760
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 754

def cmd_ssl_verify_help
  print_line('Usage: ssl_verify [options]')
  print_line
  print_line('Change and query the current setting for SSL verification')
  print_line('Only one of the following options can be used at a time')
  print_line(@@ssl_verify_opts.usage)
end

#cmd_transport(*args) ⇒ Object

Manage transports



934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 934

def cmd_transport(*args)
  if ( args.length == 0 or args.include?("-h") )
    cmd_transport_help
    return
  end

  command = args.shift
  unless ['list', 'add', 'change', 'prev', 'next', 'remove'].include?(command)
    cmd_transport_help
    return
  end

  opts = {
    :uuid         => client.payload_uuid,
    :transport    => nil,
    :lhost        => nil,
    :lport        => nil,
    :ua           => nil,
    :proxy_host   => nil,
    :proxy_port   => nil,
    :proxy_type   => nil,
    :proxy_user   => nil,
    :proxy_pass   => nil,
    :comm_timeout => nil,
    :session_exp  => nil,
    :retry_total  => nil,
    :retry_wait   => nil,
    :cert         => nil,
    :verbose      => false
  }

  valid = true
  transport_index = 0
  @@transport_opts.parse(args) do |opt, idx, val|
    case opt
    when '-c'
      opts[:cert] = val
    when '-i'
      transport_index = val.to_i
    when '-u'
      opts[:luri] = val
    when '-H'
      opts[:proxy_host] = val
    when '-P'
      opts[:proxy_port] = val.to_i
    when '-B'
      opts[:proxy_type] = val
    when '-U'
      opts[:proxy_user] = val
    when '-N'
      opts[:proxy_pass] = val
    when '-A'
      opts[:ua] = val
    when '-C'
      opts[:comm_timeout] = val.to_i if val
    when '-X'
      opts[:session_exp] = val.to_i if val
    when '-T'
      opts[:retry_total] = val.to_i if val
    when '-W'
      opts[:retry_wait] = val.to_i if val
    when '-p'
      opts[:lport] = val.to_i if val
    when '-l'
      opts[:lhost] = val
    when '-v'
      opts[:verbose] = true
    when '-t'
      unless client.core.valid_transport?(val)
        cmd_transport_help
        return
      end
      opts[:transport] = val
    else
      valid = false
    end
  end

  unless valid
    cmd_transport_help
    return
  end

  update_transport_map

  case command
  when 'list'
    result = client.core.transport_list

    current_transport_url = result[:transports].first[:url]

    sorted_by_url = result[:transports].sort_by { |k| k[:url] }

    # this will output the session timeout first
    print_timeouts(result)

    columns = ['ID', 'Curr', 'URL', 'Comms T/O', 'Retry Total', 'Retry Wait']

    if opts[:verbose]
      columns << 'User Agent'
      columns << 'Proxy Host'
      columns << 'Proxy User'
      columns << 'Proxy Pass'
      columns << 'Cert Hash'
    end

    # next draw up a table of transport entries
    tbl = Rex::Text::Table.new(
      'SortIndex' => 0, # sort by ID
      'Indent'    => 4,
      'Columns'   => columns)

    sorted_by_url.each_with_index do |t, i|
      entry = [i + 1, current_transport_url == t[:url] ? '*' : '', t[:url],
                t[:comm_timeout], t[:retry_total], t[:retry_wait]]

      if opts[:verbose]
        entry << t[:ua]
        entry << t[:proxy_host]
        entry << t[:proxy_user]
        entry << t[:proxy_pass]
        entry << (t[:cert_hash] || '').unpack("H*")[0]
      end

      tbl << entry
    end

    print("\n" + tbl.to_s + "\n")
  when 'next'
    print_status('Changing to next transport ...')
    if client.core.transport_next
      print_good('Successfully changed to the next transport, killing current session.')
      client.shutdown_passive_dispatcher
      shell.stop
    else
      print_error('Failed to change transport, please check the parameters')
    end
  when 'prev'
    print_status('Changing to previous transport ...')
    if client.core.transport_prev
      print_good('Successfully changed to the previous transport, killing current session.')
      client.shutdown_passive_dispatcher
      shell.stop
    else
      print_error('Failed to change transport, please check the parameters')
    end
  when 'change'
    print_status('Changing to new transport ...')
    if client.core.transport_change(opts)
      print_good("Successfully added #{opts[:transport]} transport, killing current session.")
      client.shutdown_passive_dispatcher
      shell.stop
    else
      print_error('Failed to change transport, please check the parameters')
    end
  when 'add'
    print_status('Adding new transport ...')
    if client.core.transport_add(opts)
      print_good("Successfully added #{opts[:transport]} transport.")
    else
      print_error('Failed to add transport, please check the parameters')
    end
  when 'remove'
    if opts[:transport] && !opts[:transport].end_with?('_tcp') && opts[:uri].nil?
      print_error('HTTP/S transport specified without session URI')
      return
    end

    if !transport_index.zero? && @transport_map.has_key?(transport_index)
      # validate the URL
      url_to_delete = @transport_map[transport_index][:url]
      begin
        uri = URI.parse(url_to_delete)
        opts[:transport] = "reverse_#{uri.scheme}"
        opts[:lhost]     = uri.host
        opts[:lport]     = uri.port
        opts[:uri]       = uri.path[1..-2] if uri.scheme.include?('http')

      rescue URI::InvalidURIError
        print_error("Failed to parse URL: #{url_to_delete}")
        return
      end
    end

    print_status('Removing transport ...')
    if client.core.transport_remove(opts)
      print_good("Successfully removed #{opts[:transport]} transport.")
    else
      print_error('Failed to remove transport, please check the parameters')
    end
  end
end

#cmd_transport_helpObject

Display help for transport management.



893
894
895
896
897
898
899
900
901
902
903
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 893

def cmd_transport_help
  print_line('Usage: transport <list|change|add|next|prev|remove> [options]')
  print_line
  print_line('   list: list the currently active transports.')
  print_line('    add: add a new transport to the transport list.')
  print_line(' change: same as add, but changes directly to the added entry.')
  print_line('   next: jump to the next transport in the list (no options).')
  print_line('   prev: jump to the previous transport in the list (no options).')
  print_line(' remove: remove an existing, non-active transport.')
  print_line(@@transport_opts.usage)
end

#cmd_transport_tabs(str, words) ⇒ Object



905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 905

def cmd_transport_tabs(str, words)
  return %w[list change add next prev remove] + @@transport_opts.option_keys if words.length == 1

  case words[-1]
  when '-c'
    return tab_complete_filenames(str, words)
  when '-i'
    return (1..client.core.transport_list[:transports].length).to_a.map!(&:to_s)
  when '-l'
    return tab_complete_source_address
  when '-t'
    return %w[reverse_tcp reverse_http reverse_https bind_tcp]
  when 'add', 'remove', 'change'
    return @@transport_opts.option_keys
  end

  []
end

#cmd_use(*args) ⇒ Object



1405
1406
1407
1408
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1405

def cmd_use(*args)
  #print_error("Warning: The 'use' command is deprecated in favor of 'load'")
  cmd_load(*args)
end

#cmd_uuid(*args) ⇒ Object

Get the machine ID of the target (should always be up to date locally)



738
739
740
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 738

def cmd_uuid(*args)
  print_good("UUID: #{client.payload_uuid}")
end

#cmd_write(*args) ⇒ Object



1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1663

def cmd_write(*args)
  if args.length == 0 || args.include?("-h")
    cmd_write_help
    return
  end

  src_file = nil
  cid      = nil

  @@write_opts.parse(args) { |opt, idx, val|
    case opt
    when "-f"
      src_file = val
    else
      cid = val.to_i
    end
  }

  # Find the channel associated with this cid, assuming the cid is valid.
  unless cid && channel = client.find_channel(cid)
    print_error('Invalid channel identifier specified.')
    return true
  end

  # If they supplied a source file, read in its contents and write it to
  # the channel
  if src_file
    begin
      data = ''

      ::File.open(src_file, 'rb') { |f|
        data = f.read(f.stat.size)
      }

    rescue Errno::ENOENT
      print_error("Invalid source file specified: #{src_file}")
      return true
    end

    if data && data.length > 0
      channel.write(data)
      print_status("Wrote #{data.length} bytes to channel #{cid}.")
    else
      print_error("No data to send from file #{src_file}")
      return true
    end
  # Otherwise, read from the input descriptor until we're good to go.
  else
    print_line('Enter data followed by a "." on an empty line:')
    print_line
    print_line

    data = ''

    # Keep truckin'
    while s = shell.input.gets
      break if s =~ /^\.\r?\n?$/
      data += s
    end

    if !data || data.length == 0
      print_error('No data to send.')
    else
      channel.write(data)
      print_status("Wrote #{data.length} bytes to channel #{cid}.")
    end
  end

  return true
end

#cmd_write_helpObject



1651
1652
1653
1654
1655
1656
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1651

def cmd_write_help
  print_line('Usage: write [options] channel_id')
  print_line
  print_line('Writes data to the supplied channel.')
  print_line(@@write_opts.usage)
end

#cmd_write_tabs(str, words) ⇒ Object



1658
1659
1660
1661
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1658

def cmd_write_tabs(str, words)
  return tab_complete_filenames(str, words) if words[-1] == '-f'
  tab_complete_channels
end

#commandsObject

List of supported commands.



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
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
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 49

def commands
  cmds = {
    '?'                        => 'Help menu',
    'background'               => 'Backgrounds the current session',
    'bg'                       => 'Alias for background',
    'close'                    => 'Closes a channel',
    'channel'                  => 'Displays information or control active channels',
    'exit'                     => 'Terminate the meterpreter session',
    'help'                     => 'Help menu',
    'irb'                      => 'Open an interactive Ruby shell on the current session',
    'pry'                      => 'Open the Pry debugger on the current session',
    'use'                      => 'Deprecated alias for "load"',
    'load'                     => 'Load one or more meterpreter extensions',
    'machine_id'               => 'Get the MSF ID of the machine attached to the session',
    'secure'                   => '(Re)Negotiate TLV packet encryption on the session',
    'guid'                     => 'Get the session GUID',
    'quit'                     => 'Terminate the meterpreter session',
    'resource'                 => 'Run the commands stored in a file',
    'uuid'                     => 'Get the UUID for the current session',
    'read'                     => 'Reads data from a channel',
    'run'                      => 'Executes a meterpreter script or Post module',
    'bgrun'                    => 'Executes a meterpreter script as a background thread',
    'bgkill'                   => 'Kills a background meterpreter script',
    'sessions'                 => 'Quickly switch to another session',
    'bglist'                   => 'Lists running background scripts',
    'write'                    => 'Writes data to a channel',
    'enable_unicode_encoding'  => 'Enables encoding of unicode strings',
    'disable_unicode_encoding' => 'Disables encoding of unicode strings',
    'migrate'                  => 'Migrate the server to another process',
    'pivot'                    => 'Manage pivot listeners',
    # transport related commands
    'detach'                   => 'Detach the meterpreter session (for http/https)',
    'sleep'                    => 'Force Meterpreter to go quiet, then re-establish session',
    'transport'                => 'Manage the transport mechanisms',
    'get_timeouts'             => 'Get the current session timeout values',
    'set_timeouts'             => 'Set the current session timeout values',
    'ssl_verify'               => 'Modify the SSL certificate verification setting'
  }

  if msf_loaded?
    cmds['info'] = 'Displays information about a Post module'
  end

  reqs = {
    'load'         => [COMMAND_ID_CORE_LOADLIB],
    'machine_id'   => [COMMAND_ID_CORE_MACHINE_ID],
    'migrate'      => [COMMAND_ID_CORE_MIGRATE],
    'pivot'        => [COMMAND_ID_CORE_PIVOT_ADD, COMMAND_ID_CORE_PIVOT_REMOVE],
    'secure'       => [COMMAND_ID_CORE_NEGOTIATE_TLV_ENCRYPTION],
    # channel related commands
    'read'         => [COMMAND_ID_CORE_CHANNEL_READ],
    'write'        => [COMMAND_ID_CORE_CHANNEL_WRITE],
    'close'        => [COMMAND_ID_CORE_CHANNEL_CLOSE],
    # transport related commands
    'sleep'        => [COMMAND_ID_CORE_TRANSPORT_SLEEP],
    'ssl_verify'   => [COMMAND_ID_CORE_TRANSPORT_GETCERTHASH, COMMAND_ID_CORE_TRANSPORT_SETCERTHASH],
    'transport'    => [
      COMMAND_ID_CORE_TRANSPORT_ADD,
      COMMAND_ID_CORE_TRANSPORT_CHANGE,
      COMMAND_ID_CORE_TRANSPORT_LIST,
      COMMAND_ID_CORE_TRANSPORT_NEXT,
      COMMAND_ID_CORE_TRANSPORT_PREV,
      COMMAND_ID_CORE_TRANSPORT_REMOVE
    ],
    'get_timeouts' => [COMMAND_ID_CORE_TRANSPORT_SET_TIMEOUTS],
    'set_timeouts' => [COMMAND_ID_CORE_TRANSPORT_SET_TIMEOUTS],
  }

  # XXX: Remove this line once the payloads gem has had another major version bump from 2.x to 3.x and
  # rapid7/metasploit-payloads#451 has been landed to correct the `enumextcmd` behavior on Windows. Until then, skip
  # filtering for Windows which supports all the filtered commands anyways. This is not the only instance of this
  # workaround.
  reqs.clear if client.base_platform == 'windows'

  filter_commands(cmds, reqs)
end

#get_extension_client_class(mod) ⇒ Object (protected)



1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1870

def get_extension_client_class(mod)
  self.class.client_extension_search_paths.each do |path|
    path = ::File.join(path, "#{mod}.rb")
    klass = CommDispatcher.check_hash(path)
    return klass unless klass.nil?

    old = CommDispatcher.constants
    next unless ::File.exist? path

    return nil unless require(path)

    new  = CommDispatcher.constants
    diff = new - old

    next if (diff.empty?)

    klass = CommDispatcher.const_get(diff[0])

    CommDispatcher.set_hash(path, klass)
    return klass
  end
end

#nameObject

Core baby.



129
130
131
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 129

def name
  'Core'
end

#pivot_add_named_pipe(opts) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 286

def pivot_add_named_pipe(opts)
  unless opts[:lhost]
    print_error('Pipe host must be specified (-l)')
    return false
  end

  unless opts[:name]
    print_error('Pipe name must be specified (-n)')
    return false
  end

  # reconfigure the opts so that they can be passed to the setup function
  opts[:pipe_host] = opts[:lhost]
  opts[:pipe_name] = opts[:name]
  Pivot.create_named_pipe_listener(client, opts)
  print_good("Successfully created #{opts[:type]} pivot.")
end


703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 703

def print_timeouts(timeouts)
  if timeouts[:session_exp]
    print_line("Session Expiry  : @ #{(::Time.now + timeouts[:session_exp]).strftime('%Y-%m-%d %H:%M:%S')}")
  end
  if timeouts[:comm_timeout]
    print_line("Comm Timeout    : #{timeouts[:comm_timeout]} seconds")
  end
  if timeouts[:retry_total]
    print_line("Retry Total Time: #{timeouts[:retry_total]} seconds")
  end
  if timeouts[:retry_wait]
    print_line("Retry Wait Time : #{timeouts[:retry_wait]} seconds")
  end
end

#tab_complete_channelsObject (protected)



1905
1906
1907
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1905

def tab_complete_channels
  client.channels.keys.map { |k| k.to_s }
end

#tab_complete_modules(str, words) ⇒ Object (protected)



1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1893

def tab_complete_modules(str, words)
  tabs = []
  client.framework.modules.post.map do |name,klass|
    tabs << 'post/' + name
  end
  client.framework.modules.module_names('exploit').
    grep(/(multi|#{Regexp.escape(client.platform)})\/local\//).each do |name|
    tabs << 'exploit/' + name
  end
  return tabs.sort
end

#unknown_command(cmd, line) ⇒ Object



1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 1824

def unknown_command(cmd, line)
  status = super

  if status.nil?
    # Check to see if we can find this command in another extension. This relies on the core extension being the last
    # in the dispatcher stack which it should be since it's the first loaded.
    Rex::Post::Meterpreter::ExtensionMapper.get_extension_names.each do |ext_name|
      next if extensions.include?(ext_name)
      ext_klass = get_extension_client_class(ext_name)
      next if ext_klass.nil?

      if ext_klass.has_command?(cmd)
        print_error("The \"#{cmd}\" command requires the \"#{ext_name}\" extension to be loaded (run: `load #{ext_name}`)")
        return :handled
      end
    end
  end

  status
end

#update_transport_mapObject



924
925
926
927
928
929
# File 'lib/rex/post/meterpreter/ui/console/command_dispatcher/core.rb', line 924

def update_transport_map
  result = client.core.transport_list
  @transport_map.clear
  sorted_by_url = result[:transports].sort_by { |k| k[:url] }
  sorted_by_url.each_with_index { |t, i| @transport_map[i+1] = t }
end