Class: Msf::Sessions::Meterpreter
- Inherits:
-
Rex::Post::Meterpreter::Client
- Object
- Rex::Post::Meterpreter::Client
- Msf::Sessions::Meterpreter
- Includes:
- Msf::Session, Msf::Session::Comm, Msf::Session::Interactive, Msf::Session::Provider::SingleCommandShell, Scriptable
- Defined in:
- lib/msf/base/sessions/meterpreter.rb
Overview
This class represents a session compatible interface to a meterpreter server instance running on a remote machine. It provides the means of interacting with the server instance both at an API level as well as at a console level.
Direct Known Subclasses
Meterpreter_Java_Java, Meterpreter_Multi, Meterpreter_Php_Php, Meterpreter_Python_Python, Meterpreter_aarch64_Apple_iOS, Meterpreter_aarch64_Linux, Meterpreter_aarch64_OSX, Meterpreter_armbe_Linux, Meterpreter_armle_Apple_iOS, Meterpreter_armle_Linux, Meterpreter_mips64_Linux, Meterpreter_mipsbe_Linux, Meterpreter_mipsle_Linux, Meterpreter_ppc64le_Linux, Meterpreter_ppc_Linux, Meterpreter_ppce500v2_Linux, Meterpreter_x64_Linux, Meterpreter_x64_OSX, Meterpreter_x64_Win, Meterpreter_x86_BSD, Meterpreter_x86_Linux, Meterpreter_x86_OSX, Meterpreter_x86_Win, Meterpreter_zarch_Linux
Constant Summary
Constants included from Rex::Post::Meterpreter::PacketDispatcher
Rex::Post::Meterpreter::PacketDispatcher::PACKET_TIMEOUT, Rex::Post::Meterpreter::PacketDispatcher::PING_TIME
Instance Attribute Summary collapse
-
#base_arch ⇒ Object
These are the base arch/platform for the original payload, required for when the session is first created thanks to the fact that the DB session recording happens before the session is even established.
-
#base_platform ⇒ Object
Returns the value of attribute base_platform.
-
#console ⇒ Object
:nodoc:.
-
#max_threads ⇒ Object
Returns the value of attribute max_threads.
-
#rstream ⇒ Object
protected
:nodoc:.
-
#skip_cleanup ⇒ Object
Returns the value of attribute skip_cleanup.
-
#skip_ssl ⇒ Object
Returns the value of attribute skip_ssl.
-
#target_id ⇒ Object
Returns the value of attribute target_id.
Attributes included from Rex::Ui::Interactive
#completed, #interacting, #next_session, #on_command_proc, #on_print_proc, #on_run_command_error_proc, #orig_suspend, #orig_usr1, #orig_winch
Attributes included from Rex::Ui::Subscriber::Input
Attributes included from Rex::Ui::Subscriber::Output
Attributes included from Msf::Session
#alive, #db_record, #exploit, #exploit_datastore, #exploit_task, #exploit_uuid, #framework, #info, #machine_id, #payload_uuid, #routes, #sid, #sname, #target_host, #target_port, #username, #uuid, #via, #workspace
Attributes included from Framework::Offspring
Attributes inherited from Rex::Post::Meterpreter::Client
#alive, #capabilities, #comm_timeout, #commands, #conn_id, #debug_build, #encode_unicode, #expiration, #ext, #ext_aliases, #last_checkin, #parser, #passive_dispatcher, #pivot_session, #response_timeout, #retry_total, #retry_wait, #send_keepalives, #sock, #ssl, #ssl_cert, #url
Attributes included from Rex::Post::Meterpreter::PivotContainer
#pivot_listeners, #pivot_sessions
Attributes included from Rex::Post::Meterpreter::PacketDispatcher
#comm_mutex, #dispatcher_thread, #passive_service, #receiver_thread, #recv_queue, #send_queue, #session_guid, #tlv_enc_key, #tlv_log_file, #tlv_log_file_path, #tlv_log_output, #tlv_logging_error_occured, #waiters
Attributes included from Rex::Post::Channel::Container
Class Method Summary collapse
- .can_cleanup_files ⇒ Object
-
.type ⇒ Object
Returns the session type as being ‘meterpreter’.
Instance Method Summary collapse
-
#_interact ⇒ Object
:category: Msf::Session::Interactive implementors.
-
#arch ⇒ Object
Get a string representation of the current session architecture.
-
#binary_suffix ⇒ Object
Generate a binary suffix based on arch.
- #bootstrap(datastore = {}, handler = nil) ⇒ Object
-
#cleanup ⇒ Object
:category: Msf::Session overrides.
-
#create(param) ⇒ Object
:category: Msf::Session::Comm implementors.
-
#desc ⇒ Object
:category: Msf::Session overrides.
-
#execute_file(full_path, args) ⇒ Object
:category: Msf::Session::Scriptable implementors.
- #exit ⇒ Object
-
#find_internet_connected_address ⇒ String?
protected
Rummage through this host’s routes and interfaces looking for an address that it uses to talk to the internet.
- #guess_target_platform(os) ⇒ Object
-
#init_ui(input, output) ⇒ Object
:category: Msf::Session::Interactive implementors.
-
#initialize(rstream, opts = {}) ⇒ Meterpreter
constructor
Initializes a meterpreter session instance using the supplied rstream that is to be used as the client’s connection to the server.
-
#kill(reason = '') ⇒ Object
Terminates the session.
-
#load_priv ⇒ Object
Load the priv extension.
-
#load_session_info ⇒ Object
Populate the session information.
-
#load_stdapi ⇒ Object
Load the stdapi extension.
-
#lookup_error(code) ⇒ Object
Called by PacketDispatcher to resolve error codes to names.
-
#native_arch ⇒ Object
Get a string representation of the architecture of the process in which the current session is running.
-
#platform ⇒ Object
Get a string representation of the current session platform.
-
#queue_cmd(cmd) ⇒ Object
Run the supplied command as if it came from suer input.
-
#reset_ui ⇒ Object
:category: Msf::Session::Interactive implementors.
-
#run_cmd(cmd, output_object = nil) ⇒ Object
:category: Msf::Session::Interactive implementors.
-
#shell_close ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors.
- #shell_command(cmd, timeout = 5) ⇒ Object
-
#shell_init ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors.
-
#shell_read(length = nil, timeout = 1) ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors.
-
#shell_write(buf) ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors.
-
#supports_ssl? ⇒ Boolean
Override for server implementations that can’t do SSL.
- #supports_udp? ⇒ Boolean
-
#supports_zlib? ⇒ Boolean
Override for server implementations that can’t do zlib.
- #tunnel_to_s ⇒ Object
-
#type ⇒ Object
Calls the class method.
- #update_session_info ⇒ Object
Methods included from Scriptable
#execute_script, included, #legacy_script_to_post_module
Methods included from Msf::Session::Provider::SingleCommandShell
#command_termination, #set_is_echo_shell, #shell_command_token, #shell_command_token_base, #shell_command_token_unix, #shell_command_token_win32, #shell_read_until_token, #to_cmd
Methods included from Msf::Session::Interactive
#_interact_complete, #_interrupt, #_suspend, #_usr1, #abort_foreground, #abort_foreground_supported, #comm_channel, #interactive?, #tunnel_local, #tunnel_peer, #user_want_abort?
Methods included from Rex::Ui::Interactive
#_interact_complete, #_interrupt, #_local_fd, #_remote_fd, #_stream_read_local_write_remote, #_stream_read_remote_write_local, #_suspend, #_winch, #detach, #handle_suspend, #handle_usr1, #handle_winch, #interact, #interact_stream, #prompt, #prompt_yesno, #restore_suspend, #restore_usr1, #restore_winch
Methods included from Rex::Ui::Subscriber
Methods included from Rex::Ui::Subscriber::Input
Methods included from Rex::Ui::Subscriber::Output
#flush, #print, #print_blank_line, #print_error, #print_good, #print_line, #print_status, #print_warning
Methods included from Msf::Session
#alive?, #comm_channel, #dead?, #inspect, #interactive?, #log_file_name, #log_source, #name, #name=, #register?, #session_host, #session_host=, #session_port, #session_port=, #session_type, #set_from_exploit, #set_via, #tunnel_local, #tunnel_peer, #via_exploit, #via_payload
Methods inherited from Rex::Post::Meterpreter::Client
#add_extension, check_ext_hash, #cleanup_meterpreter, default_timeout, #deregister_extension, #deregister_extension_alias, #dump_extension_tree, #each_extension, #generate_ssl_context, #init_meterpreter, lookup_error, #method_missing, #register_extension_alias, #register_extension_aliases, set_ext_hash, #swap_sock_plain_to_ssl, #swap_sock_ssl_to_plain, #unicode_filter_decode, #unicode_filter_encode
Methods included from Rex::Post::Meterpreter::PivotContainer
#add_pivot_listener, #add_pivot_session, #find_pivot_listener, #find_pivot_session, #initialize_pivots, #remove_pivot_listener, #remove_pivot_session
Methods included from Rex::Post::Meterpreter::PacketDispatcher
#add_response_waiter, #decrypt_inbound_packet, #deregister_inbound_handler, #dispatch_inbound_packet, #initialize_inbound_handlers, #initialize_passive_dispatcher, #initialize_tlv_logging, #keepalive, #log_packet, #log_packet_to_console, #log_packet_to_file, #monitor_socket, #monitor_stop, #notify_response_waiter, #on_passive_request, #pivot_keepalive_start, #receive_packet, #register_inbound_handler, #remove_response_waiter, #send_packet, #send_packet_wait_response, #send_request, #shutdown_passive_dispatcher, #shutdown_tlv_logging
Methods included from Rex::Post::Channel::Container
#add_channel, #find_channel, #initialize_channels, #remove_channel
Constructor Details
#initialize(rstream, opts = {}) ⇒ Meterpreter
Initializes a meterpreter session instance using the supplied rstream that is to be used as the client’s connection to the server.
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 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 54 def initialize(rstream, opts={}) super opts[:capabilities] = { :ssl => supports_ssl?, :zlib => supports_zlib? } # The caller didn't request to skip ssl, so make sure we support it if not opts[:skip_ssl] opts.merge!(:skip_ssl => (not supports_ssl?)) end # # Parse options passed in via the datastore # # Extract the HandlerSSLCert option if specified by the user if opts[:datastore] and opts[:datastore]['HandlerSSLCert'] opts[:ssl_cert] = opts[:datastore]['HandlerSSLCert'] end # Extract the MeterpreterDebugBuild option if specified by the user if opts[:datastore] opts[:debug_build] = opts[:datastore]['MeterpreterDebugBuild'] end # Don't pass the datastore into the init_meterpreter method opts.delete(:datastore) # Assume by default that 10 threads is a safe number for this session self.max_threads ||= 10 # # Initialize the meterpreter client # self.init_meterpreter(rstream, opts) # # Create the console instance # self.console = Rex::Post::Meterpreter::Ui::Console.new(self) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class Rex::Post::Meterpreter::Client
Instance Attribute Details
#base_arch ⇒ Object
These are the base arch/platform for the original payload, required for when the session is first created thanks to the fact that the DB session recording happens before the session is even established.
689 690 691 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 689 def base_arch @base_arch end |
#base_platform ⇒ Object
Returns the value of attribute base_platform.
690 691 692 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 690 def base_platform @base_platform end |
#console ⇒ Object
:nodoc:
692 693 694 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 692 def console @console end |
#max_threads ⇒ Object
Returns the value of attribute max_threads.
696 697 698 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 696 def max_threads @max_threads end |
#rstream ⇒ Object (protected)
:nodoc:
700 701 702 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 700 def rstream @rstream end |
#skip_cleanup ⇒ Object
Returns the value of attribute skip_cleanup.
694 695 696 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 694 def skip_cleanup @skip_cleanup end |
#skip_ssl ⇒ Object
Returns the value of attribute skip_ssl.
693 694 695 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 693 def skip_ssl @skip_ssl end |
#target_id ⇒ Object
Returns the value of attribute target_id.
695 696 697 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 695 def target_id @target_id end |
Class Method Details
.can_cleanup_files ⇒ Object
121 122 123 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 121 def self.can_cleanup_files true end |
.type ⇒ Object
Returns the session type as being ‘meterpreter’.
110 111 112 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 110 def self.type "meterpreter" end |
Instance Method Details
#_interact ⇒ Object
:category: Msf::Session::Interactive implementors
Interacts with the meterpreter client at a user interface level.
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 569 def _interact framework.events.on_session_interact(self) console.framework = framework if framework.datastore['MeterpreterPrompt'] console.update_prompt(framework.datastore['MeterpreterPrompt']) end # Call the console interaction subsystem of the meterpreter client and # pass it a block that returns whether or not we should still be # interacting. This will allow the shell to abort if interaction is # canceled. console.interact { self.interacting != true } console.framework = nil # If the stop flag has been set, then that means the user exited. Raise # the EOFError so we can drop this handle like a bad habit. raise EOFError if (console.stopped? == true) end |
#arch ⇒ Object
Get a string representation of the current session architecture
632 633 634 635 636 637 638 639 640 641 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 632 def arch if self.payload_uuid # return the actual arch of the current session if it's there self.payload_uuid.arch else # otherwise just use the base for the session type tied to this handler. # If we don't do this, storage of sessions in the DB dies self.base_arch end end |
#binary_suffix ⇒ Object
Generate a binary suffix based on arch
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 655 def binary_suffix # generate a file/binary suffix based on the current arch and platform. # Platform-agnostic archs go first case self.arch when 'java' ['jar'] when 'php' ['php'] when 'python' ['py'] else # otherwise we fall back to the platform case self.platform when 'windows' ["#{self.arch}.dll"] when 'linux' , 'aix' , 'hpux' , 'irix' , 'unix' ['bin', 'elf'] when 'osx' ['elf'] when 'android', 'java' ['jar'] when 'php' ['php'] when 'python' ['py'] else nil end end end |
#bootstrap(datastore = {}, handler = nil) ⇒ Object
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 140 def bootstrap(datastore = {}, handler = nil) session = self # Configure unicode encoding before loading stdapi session.encode_unicode = datastore['EnableUnicodeEncoding'] session.init_ui(self.user_input, self.user_output) initialize_tlv_logging(datastore['SessionTlvLogging']) unless datastore['SessionTlvLogging'].nil? verification_timeout = datastore['AutoVerifySessionTimeout']&.to_i || session.comm_timeout begin session.tlv_enc_key = session.core.negotiate_tlv_encryption(timeout: verification_timeout) rescue Rex::TimeoutError end if session.tlv_enc_key.nil? # Fail-closed if TLV encryption can't be negotiated (close the session as invalid) dlog("Session #{session.sid} failed to negotiate TLV encryption") print_error("Meterpreter session #{session.sid} is not valid and will be closed") # Terminate the session without cleanup if it did not validate session.skip_cleanup = true session.kill return nil end # always make sure that the new session has a new guid if it's not already known guid = session.session_guid if guid == "\x00" * 16 guid = [SecureRandom.uuid.gsub('-', '')].pack('H*') session.core.set_session_guid(guid) session.session_guid = guid # TODO: New stageless session, do some account in the DB so we can track it later. else # TODO: This session was either staged or previously known, and so we should do some accounting here! end session.commands.concat(session.core.get_loaded_extension_commands('core')) if session.tlv_enc_key[:weak_key?] print_warning("Meterpreter session #{session.sid} is using a weak encryption key.") print_warning('Meterpreter start up operations have been aborted. Use the session at your own risk.') return nil end extensions = datastore['AutoLoadExtensions']&.delete(' ').split(',') || [] # BEGIN: This should be removed on MSF 7 # Unhook the process prior to loading stdapi to reduce logging/inspection by any AV/PSP (by default unhook is first, see meterpreter_options/windows.rb) extensions.push('unhook') if datastore['AutoUnhookProcess'] && session.platform == 'windows' extensions.push('stdapi') if datastore['AutoLoadStdapi'] extensions.push('priv') if datastore['AutoLoadStdapi'] && session.platform == 'windows' extensions.push('android') if session.platform == 'android' extensions = extensions.uniq # END original = console.disable_output console.disable_output = true # TODO: abstract this a little, perhaps a "post load" function that removes # platform-specific stuff? extensions.each do |extension| begin console.run_single("load #{extension}") console.run_single('unhook_pe') if extension == 'unhook' session.load_session_info if extension == 'stdapi' && datastore['AutoSystemInfo'] rescue => e print_warning("Failed loading extension #{extension}") end end console.disable_output = original ['InitialAutoRunScript', 'AutoRunScript'].each do |key| unless datastore[key].nil? || datastore[key].empty? args = Shellwords.shellwords(datastore[key]) print_status("Session ID #{session.sid} (#{session.tunnel_to_s}) processing #{key} '#{datastore[key]}'") session.execute_script(args.shift, *args) end end end |
#cleanup ⇒ Object
:category: Msf::Session overrides
Cleans up the meterpreter client session.
305 306 307 308 309 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 305 def cleanup cleanup_meterpreter super end |
#create(param) ⇒ Object
:category: Msf::Session::Comm implementors
Creates a connection based on the supplied parameters and returns it to the caller. The connection is created relative to the remote machine on which the meterpreter server instance is running.
596 597 598 599 600 601 602 603 604 605 606 607 608 609 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 596 def create(param) sock = nil # Notify handlers before we create the socket notify_before_socket_create(self, param) sock = net.socket.create(param) # Notify now that we've created the socket notify_socket_created(self, sock, param) # Return the socket to the caller sock end |
#desc ⇒ Object
:category: Msf::Session overrides
Returns the session description.
316 317 318 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 316 def desc "Meterpreter" end |
#execute_file(full_path, args) ⇒ Object
:category: Msf::Session::Scriptable implementors
Runs the Meterpreter script or resource file.
326 327 328 329 330 331 332 333 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 326 def execute_file(full_path, args) # Infer a Meterpreter script by .rb extension if File.extname(full_path) == '.rb' Rex::Script::Meterpreter.new(self, full_path).run(args) else console.load_resource(full_path) end end |
#exit ⇒ Object
98 99 100 101 102 103 104 105 106 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 98 def exit begin self.core.shutdown rescue StandardError nil end self.shutdown_passive_dispatcher self.console.stop end |
#find_internet_connected_address ⇒ String? (protected)
Rummage through this host’s routes and interfaces looking for an address that it uses to talk to the internet.
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 711 def find_internet_connected_address ifaces = self.net.config.get_interfaces().flatten rescue [] routes = self.net.config.get_routes().flatten rescue [] # Try to match our visible IP to a real interface found = !!(ifaces.find { |i| i.addrs.find { |a| a == session_host } }) nhost = nil # If the host has no address that matches what we see, then one of # us is behind NAT so we have to look harder. if !found # Grab all routes to the internet default_routes = routes.select { |r| r.subnet == "0.0.0.0" || r.subnet == "::" } default_routes.each do |route| # Now try to find an interface whose network includes this # Route's gateway, which means it's the one the host uses to get # to the interweb. ifaces.each do |i| # Try all the addresses this interface has configured addr_and_mask = i.addrs.zip(i.netmasks).find do |addr, netmask| bits = Rex::Socket.net2bitmask( netmask ) range = Rex::Socket::RangeWalker.new("#{addr}/#{bits}") rescue nil !!(range && range.valid? && range.include?(route.gateway)) end if addr_and_mask nhost = addr_and_mask[0] break end end break if nhost end if !nhost # No internal address matches what we see externally and no # interface has a default route. Fall back to the first # non-loopback address non_loopback = ifaces.find { |i| i.ip != "127.0.0.1" && i.ip != "::1" } if non_loopback nhost = non_loopback.ip end end end nhost end |
#guess_target_platform(os) ⇒ Object
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 454 def guess_target_platform(os) case os when /windows/i Msf::Module::Platform::Windows.realname.downcase when /darwin/i Msf::Module::Platform::OSX.realname.downcase when /mac os ?x/i # this happens with java on OSX (for real!) Msf::Module::Platform::OSX.realname.downcase when /freebsd/i Msf::Module::Platform::FreeBSD.realname.downcase when /openbsd/i, /netbsd/i Msf::Module::Platform::BSD.realname.downcase else Msf::Module::Platform::Linux.realname.downcase end end |
#init_ui(input, output) ⇒ Object
:category: Msf::Session::Interactive implementors
Initializes the console’s I/O handles.
341 342 343 344 345 346 347 348 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 341 def init_ui(input, output) self.user_input = input self.user_output = output console.init_ui(input, output) console.set_log_source(log_source) super end |
#kill(reason = '') ⇒ Object
Terminates the session
363 364 365 366 367 368 369 370 371 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 363 def kill(reason='') begin cleanup_meterpreter self.sock.close if self.sock rescue ::Exception end # deregister will actually trigger another cleanup framework.sessions.deregister(self, reason) end |
#load_priv ⇒ Object
Load the priv extension.
417 418 419 420 421 422 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 417 def load_priv original = console.disable_output console.disable_output = true console.run_single('load priv') console.disable_output = original end |
#load_session_info ⇒ Object
Populate the session information.
Also reports a session_fingerprint note for host os normalization.
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 477 def load_session_info begin ::Timeout.timeout(60) do update_session_info hobj = nil nhost = find_internet_connected_address original_session_host = self.session_host # If we found a better IP address for this session, change it # up. Only handle cases where the DB is not connected here if nhost && !(framework.db && framework.db.active) self.session_host = nhost end # The rest of this requires a database, so bail if it's not # there return if !(framework.db && framework.db.active) ::ApplicationRecord.connection_pool.with_connection { wspace = framework.db.find_workspace(workspace) # Account for finding ourselves on a different host if nhost and self.db_record # Create or switch to a new host in the database hobj = framework.db.report_host(:workspace => wspace, :host => nhost) if hobj self.session_host = nhost self.db_record.host_id = hobj[:id] end end sysinfo = sys.config.sysinfo host = Msf::Util::Host.normalize_host(self) framework.db.report_note({ :type => "host.os.session_fingerprint", :host => host, :workspace => wspace, :data => { :name => sysinfo["Computer"], :os => sysinfo["OS"], :arch => sysinfo["Architecture"], } }) if self.db_record framework.db.update_session(self) end # XXX: This is obsolete given the Mdm::Host.normalize_os() support for host.os.session_fingerprint # framework.db.update_host_via_sysinfo(:host => self, :workspace => wspace, :info => sysinfo) if nhost framework.db.report_note({ :type => "host.nat.server", :host => original_session_host, :workspace => wspace, :data => { :info => "This device is acting as a NAT gateway for #{nhost}", :client => nhost }, :update => :unique_data }) framework.db.report_host(:host => original_session_host, :purpose => 'firewall' ) framework.db.report_note({ :type => "host.nat.client", :host => nhost, :workspace => wspace, :data => { :info => "This device is traversing NAT gateway #{original_session_host}", :server => original_session_host }, :update => :unique_data }) framework.db.report_host(:host => nhost, :purpose => 'client' ) end } end rescue ::Interrupt dlog("Interrupt while loading sysinfo: #{e.class}: #{e}") raise $! rescue ::Exception => e # Log the error but otherwise ignore it so we don't kill the # session if reporting failed for some reason elog('Error loading sysinfo', error: e) dlog("Call stack:\n#{e.backtrace.join("\n")}") end end |
#load_stdapi ⇒ Object
Load the stdapi extension.
407 408 409 410 411 412 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 407 def load_stdapi original = console.disable_output console.disable_output = true console.run_single('load stdapi') console.disable_output = original end |
#lookup_error(code) ⇒ Object
Called by PacketDispatcher to resolve error codes to names. This is the default version (return the number itself)
296 297 298 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 296 def lookup_error(code) "#{code}" end |
#native_arch ⇒ Object
Get a string representation of the architecture of the process in which the current session is running. This defaults to the same value of arch but can be overridden by specific meterpreter implementations to add support.
648 649 650 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 648 def native_arch arch end |
#platform ⇒ Object
Get a string representation of the current session platform
618 619 620 621 622 623 624 625 626 627 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 618 def platform if self.payload_uuid # return the actual platform of the current session if it's there self.payload_uuid.platform else # otherwise just use the base for the session type tied to this handler. # If we don't do this, storage of sessions in the DB dies self.base_platform end end |
#queue_cmd(cmd) ⇒ Object
Run the supplied command as if it came from suer input.
376 377 378 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 376 def queue_cmd(cmd) console.queue_cmd(cmd) end |
#reset_ui ⇒ Object
:category: Msf::Session::Interactive implementors
Resets the console’s I/O handles.
355 356 357 358 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 355 def reset_ui console.unset_log_source console.reset_ui end |
#run_cmd(cmd, output_object = nil) ⇒ Object
:category: Msf::Session::Interactive implementors
Explicitly runs a command in the meterpreter console.
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 385 def run_cmd(cmd,output_object=nil) stored_output_state = nil # If the user supplied an Output IO object, then we tell # the console to use that, while saving it's previous output/ if output_object stored_output_state = console.output console.send(:output=, output_object) end success = console.run_single(cmd) # If we stored the previous output object of the channel # we restore it here to put everything back the way we found it # We re-use the conditional above, because we expect in many cases for # the stored state to actually be nil here. if output_object console.send(:output=,stored_output_state) end success end |
#shell_close ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors
Terminate the shell channel
268 269 270 271 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 268 def shell_close @shell.close @shell = nil end |
#shell_command(cmd, timeout = 5) ⇒ Object
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 273 def shell_command(cmd, timeout = 5) # Send the shell channel's stdin. shell_write(cmd + "\n") etime = ::Time.now.to_f + timeout buff = "" # Keep reading data until no more data is available or the timeout is # reached. while (::Time.now.to_f < etime) res = shell_read(-1, timeout) break unless res timeout = etime - ::Time.now.to_f buff << res end buff end |
#shell_init ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors
Create a channelized shell process on the target
130 131 132 133 134 135 136 137 138 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 130 def shell_init return true if @shell # COMSPEC is special-cased on all meterpreters to return a viable # shell. sh = sys.config.getenv('COMSPEC') @shell = sys.process.execute(sh, nil, { "Hidden" => true, "Channelized" => true }) end |
#shell_read(length = nil, timeout = 1) ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors
Read from the command shell.
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 222 def shell_read(length=nil, timeout=1) shell_init length = nil if length.nil? or length < 0 begin rv = nil # Meterpreter doesn't offer a way to timeout on the victim side, so # we have to do it here. I'm concerned that this will cause loss # of data. Timeout.timeout(timeout) { rv = @shell.channel.read(length) } framework.events.on_session_output(self, rv) if rv return rv rescue ::Timeout::Error return nil rescue ::Exception => e shell_close raise e end end |
#shell_write(buf) ⇒ Object
:category: Msf::Session::Provider::SingleCommandShell implementors
Write to the command shell.
249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 249 def shell_write(buf) shell_init begin framework.events.on_session_command(self, buf.strip) len = @shell.channel.write("#{buf}\n") rescue ::Exception => e shell_close raise e end len end |
#supports_ssl? ⇒ Boolean
Override for server implementations that can’t do SSL
33 34 35 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 33 def supports_ssl? true end |
#supports_udp? ⇒ Boolean
611 612 613 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 611 def supports_udp? true end |
#supports_zlib? ⇒ Boolean
Override for server implementations that can’t do zlib
38 39 40 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 38 def supports_zlib? true end |
#tunnel_to_s ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 42 def tunnel_to_s if self.pivot_session "Pivot via [#{self.pivot_session.tunnel_to_s}]" else super end end |
#type ⇒ Object
Calls the class method
117 118 119 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 117 def type self.class.type end |
#update_session_info ⇒ Object
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 |
# File 'lib/msf/base/sessions/meterpreter.rb', line 424 def update_session_info # sys.config.getuid, and fs.dir.getwd cache their results, so update them begin fs&.dir&.getwd rescue Rex::Post::Meterpreter::RequestError => e elog('failed retrieving working directory', error: e) end username = self.sys.config.getuid sysinfo = self.sys.config.sysinfo # when updating session information, we need to make sure we update the platform # in the UUID to match what the target is actually running on, but only for a # subset of platforms. if ['java', 'python', 'php'].include?(self.platform) new_platform = guess_target_platform(sysinfo['OS']) if self.platform != new_platform self.payload_uuid.platform = new_platform self.core.set_uuid(self.payload_uuid) end end safe_info = "#{username} @ #{sysinfo['Computer']}" safe_info.force_encoding("ASCII-8BIT") if safe_info.respond_to?(:force_encoding) # Should probably be using Rex::Text.ascii_safe_hex but leave # this as is for now since "\xNN" is arguably uglier than "_" # showing up in various places in the UI. safe_info.gsub!(/[\x00-\x08\x0b\x0c\x0e-\x19\x7f-\xff]+/n,"_") self.info = safe_info end |