Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/msf/base/sessions/meterpreter.rb
21545 views
1
# -*- coding: binary -*-
2
require 'rex/post/meterpreter/client'
3
require 'rex/post/meterpreter/ui/console'
4
5
module Msf
6
module Sessions
7
8
###
9
#
10
# This class represents a session compatible interface to a meterpreter server
11
# instance running on a remote machine. It provides the means of interacting
12
# with the server instance both at an API level as well as at a console level.
13
#
14
###
15
16
class Meterpreter < Rex::Post::Meterpreter::Client
17
18
include Msf::Session
19
#
20
# The meterpreter session is interactive
21
#
22
include Msf::Session::Interactive
23
include Msf::Session::Comm
24
25
#
26
# This interface supports interacting with a single command shell.
27
#
28
include Msf::Session::Provider::SingleCommandShell
29
30
include Msf::Sessions::Scriptable
31
32
# Override for server implementations that can't do SSL
33
def supports_ssl?
34
true
35
end
36
37
# Override for server implementations that can't do zlib
38
def supports_zlib?
39
true
40
end
41
42
def tunnel_to_s
43
if self.pivot_session
44
"Pivot via [#{self.pivot_session.tunnel_to_s}]"
45
else
46
super
47
end
48
end
49
50
#
51
# Initializes a meterpreter session instance using the supplied rstream
52
# that is to be used as the client's connection to the server.
53
#
54
def initialize(rstream, opts={})
55
super
56
57
opts[:capabilities] = {
58
:ssl => supports_ssl?,
59
:zlib => supports_zlib?
60
}
61
62
# The caller didn't request to skip ssl, so make sure we support it
63
if not opts[:skip_ssl]
64
opts.merge!(:skip_ssl => (not supports_ssl?))
65
end
66
67
#
68
# Parse options passed in via the datastore
69
#
70
71
# Extract the HandlerSSLCert option if specified by the user
72
if opts[:datastore] and opts[:datastore]['HandlerSSLCert']
73
opts[:ssl_cert] = opts[:datastore]['HandlerSSLCert']
74
end
75
76
# Extract the MeterpreterDebugBuild option if specified by the user
77
if opts[:datastore]
78
opts[:debug_build] = opts[:datastore]['MeterpreterDebugBuild']
79
end
80
81
# Don't pass the datastore into the init_meterpreter method
82
opts.delete(:datastore)
83
84
# Assume by default that 10 threads is a safe number for this session
85
self.max_threads ||= 10
86
87
#
88
# Initialize the meterpreter client
89
#
90
self.init_meterpreter(rstream, opts)
91
92
#
93
# Create the console instance
94
#
95
self.console = Rex::Post::Meterpreter::Ui::Console.new(self)
96
end
97
98
def exit
99
begin
100
self.core.shutdown
101
rescue StandardError
102
nil
103
end
104
self.shutdown_passive_dispatcher
105
self.console.stop
106
end
107
#
108
# Returns the session type as being 'meterpreter'.
109
#
110
def self.type
111
"meterpreter"
112
end
113
114
#
115
# Calls the class method
116
#
117
def type
118
self.class.type
119
end
120
121
def self.can_cleanup_files
122
true
123
end
124
125
##
126
# :category: Msf::Session::Provider::SingleCommandShell implementors
127
#
128
# Create a channelized shell process on the target
129
#
130
def shell_init
131
return true if @shell
132
133
# COMSPEC is special-cased on all meterpreters to return a viable
134
# shell.
135
sh = sys.config.getenv('COMSPEC')
136
@shell = sys.process.execute(sh, nil, { "Hidden" => true, "Channelized" => true })
137
138
end
139
140
def bootstrap(datastore = {}, handler = nil)
141
session = self
142
143
# Configure unicode encoding before loading stdapi
144
session.encode_unicode = datastore['EnableUnicodeEncoding']
145
146
session.init_ui(self.user_input, self.user_output)
147
148
initialize_tlv_logging(datastore['SessionTlvLogging']) unless datastore['SessionTlvLogging'].nil?
149
150
verification_timeout = datastore['AutoVerifySessionTimeout']&.to_i || session.comm_timeout
151
begin
152
session.tlv_enc_key = session.core.negotiate_tlv_encryption(timeout: verification_timeout)
153
rescue Rex::TimeoutError
154
end
155
156
if session.tlv_enc_key.nil?
157
# Fail-closed if TLV encryption can't be negotiated (close the session as invalid)
158
dlog("Session #{session.sid} failed to negotiate TLV encryption")
159
print_error("Meterpreter session #{session.sid} is not valid and will be closed")
160
# Terminate the session without cleanup if it did not validate
161
session.skip_cleanup = true
162
session.kill
163
return nil
164
end
165
166
# always make sure that the new session has a new guid if it's not already known
167
guid = session.session_guid
168
if guid == "\x00" * 16
169
guid = [SecureRandom.uuid.gsub('-', '')].pack('H*')
170
session.core.set_session_guid(guid)
171
session.session_guid = guid
172
# TODO: New stageless session, do some account in the DB so we can track it later.
173
else
174
# TODO: This session was either staged or previously known, and so we should do some accounting here!
175
end
176
177
session.commands.concat(session.core.get_loaded_extension_commands('core'))
178
if session.tlv_enc_key[:weak_key?]
179
print_warning("Meterpreter session #{session.sid} is using a weak encryption key.")
180
print_warning('Meterpreter start up operations have been aborted. Use the session at your own risk.')
181
return nil
182
end
183
extensions = datastore['AutoLoadExtensions']&.delete(' ').split(',') || []
184
185
# BEGIN: This should be removed on MSF 7
186
# 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)
187
extensions.push('unhook') if datastore['AutoUnhookProcess'] && session.platform == 'windows'
188
extensions.push('stdapi') if datastore['AutoLoadStdapi']
189
extensions.push('priv') if datastore['AutoLoadStdapi'] && session.platform == 'windows'
190
extensions.push('android') if session.platform == 'android'
191
extensions = extensions.uniq
192
# END
193
original = console.disable_output
194
console.disable_output = true
195
# TODO: abstract this a little, perhaps a "post load" function that removes
196
# platform-specific stuff?
197
extensions.each do |extension|
198
begin
199
console.run_single("load #{extension}")
200
console.run_single('unhook_pe') if extension == 'unhook'
201
session.load_session_info if extension == 'stdapi' && datastore['AutoSystemInfo']
202
rescue => e
203
print_warning("Failed loading extension #{extension}")
204
end
205
end
206
console.disable_output = original
207
208
['InitialAutoRunScript', 'AutoRunScript'].each do |key|
209
unless datastore[key].nil? || datastore[key].empty?
210
args = Shellwords.shellwords(datastore[key])
211
print_status("Session ID #{session.sid} (#{session.tunnel_to_s}) processing #{key} '#{datastore[key]}'")
212
session.execute_script(args.shift, *args)
213
end
214
end
215
end
216
217
##
218
# :category: Msf::Session::Provider::SingleCommandShell implementors
219
#
220
# Read from the command shell.
221
#
222
def shell_read(length=nil, timeout=1)
223
shell_init
224
225
length = nil if length.nil? or length < 0
226
begin
227
rv = nil
228
# Meterpreter doesn't offer a way to timeout on the victim side, so
229
# we have to do it here. I'm concerned that this will cause loss
230
# of data.
231
Timeout.timeout(timeout) {
232
rv = @shell.channel.read(length)
233
}
234
framework.events.on_session_output(self, rv) if rv
235
return rv
236
rescue ::Timeout::Error
237
return nil
238
rescue ::Exception => e
239
shell_close
240
raise e
241
end
242
end
243
244
##
245
# :category: Msf::Session::Provider::SingleCommandShell implementors
246
#
247
# Write to the command shell.
248
#
249
def shell_write(buf)
250
shell_init
251
252
begin
253
framework.events.on_session_command(self, buf.strip)
254
len = @shell.channel.write("#{buf}\n")
255
rescue ::Exception => e
256
shell_close
257
raise e
258
end
259
260
len
261
end
262
263
##
264
# :category: Msf::Session::Provider::SingleCommandShell implementors
265
#
266
# Terminate the shell channel
267
#
268
def shell_close
269
@shell.close
270
@shell = nil
271
end
272
273
def shell_command(cmd, timeout = 5)
274
# Send the shell channel's stdin.
275
shell_write(cmd + "\n")
276
277
etime = ::Time.now.to_f + timeout
278
buff = ""
279
280
# Keep reading data until no more data is available or the timeout is
281
# reached.
282
while (::Time.now.to_f < etime)
283
res = shell_read(-1, timeout)
284
break unless res
285
timeout = etime - ::Time.now.to_f
286
buff << res
287
end
288
289
buff
290
end
291
292
#
293
# Called by PacketDispatcher to resolve error codes to names.
294
# This is the default version (return the number itself)
295
#
296
def lookup_error(code)
297
"#{code}"
298
end
299
300
##
301
# :category: Msf::Session overrides
302
#
303
# Cleans up the meterpreter client session.
304
#
305
def cleanup
306
cleanup_meterpreter
307
308
super
309
end
310
311
##
312
# :category: Msf::Session overrides
313
#
314
# Returns the session description.
315
#
316
def desc
317
"Meterpreter"
318
end
319
320
321
##
322
# :category: Msf::Session::Scriptable implementors
323
#
324
# Runs the Meterpreter script or resource file.
325
#
326
def execute_file(full_path, args)
327
# Infer a Meterpreter script by .rb extension
328
if File.extname(full_path) == '.rb'
329
Rex::Script::Meterpreter.new(self, full_path).run(args)
330
else
331
console.load_resource(full_path)
332
end
333
end
334
335
336
##
337
# :category: Msf::Session::Interactive implementors
338
#
339
# Initializes the console's I/O handles.
340
#
341
def init_ui(input, output)
342
self.user_input = input
343
self.user_output = output
344
console.init_ui(input, output)
345
console.set_log_source(log_source)
346
347
super
348
end
349
350
##
351
# :category: Msf::Session::Interactive implementors
352
#
353
# Resets the console's I/O handles.
354
#
355
def reset_ui
356
console.unset_log_source
357
console.reset_ui
358
end
359
360
#
361
# Terminates the session
362
#
363
def kill(reason='')
364
begin
365
cleanup_meterpreter
366
self.sock.close if self.sock
367
rescue ::Exception
368
end
369
# deregister will actually trigger another cleanup
370
framework.sessions.deregister(self, reason)
371
end
372
373
#
374
# Run the supplied command as if it came from suer input.
375
#
376
def queue_cmd(cmd)
377
console.queue_cmd(cmd)
378
end
379
380
##
381
# :category: Msf::Session::Interactive implementors
382
#
383
# Explicitly runs a command in the meterpreter console.
384
#
385
def run_cmd(cmd,output_object=nil)
386
stored_output_state = nil
387
# If the user supplied an Output IO object, then we tell
388
# the console to use that, while saving it's previous output/
389
if output_object
390
stored_output_state = console.output
391
console.send(:output=, output_object)
392
end
393
success = console.run_single(cmd)
394
# If we stored the previous output object of the channel
395
# we restore it here to put everything back the way we found it
396
# We re-use the conditional above, because we expect in many cases for
397
# the stored state to actually be nil here.
398
if output_object
399
console.send(:output=,stored_output_state)
400
end
401
success
402
end
403
404
#
405
# Load the stdapi extension.
406
#
407
def load_stdapi
408
original = console.disable_output
409
console.disable_output = true
410
console.run_single('load stdapi')
411
console.disable_output = original
412
end
413
414
#
415
# Load the priv extension.
416
#
417
def load_priv
418
original = console.disable_output
419
console.disable_output = true
420
console.run_single('load priv')
421
console.disable_output = original
422
end
423
424
def update_session_info
425
# sys.config.getuid, and fs.dir.getwd cache their results, so update them
426
begin
427
fs&.dir&.getwd
428
rescue Rex::Post::Meterpreter::RequestError => e
429
elog('failed retrieving working directory', error: e)
430
end
431
username = self.sys.config.getuid
432
sysinfo = self.sys.config.sysinfo
433
434
# when updating session information, we need to make sure we update the platform
435
# in the UUID to match what the target is actually running on, but only for a
436
# subset of platforms.
437
if ['java', 'python', 'php'].include?(self.platform)
438
new_platform = guess_target_platform(sysinfo['OS'])
439
if self.platform != new_platform
440
self.payload_uuid.platform = new_platform
441
self.core.set_uuid(self.payload_uuid)
442
end
443
end
444
445
safe_info = "#{username} @ #{sysinfo['Computer']}"
446
safe_info.force_encoding("ASCII-8BIT") if safe_info.respond_to?(:force_encoding)
447
# Should probably be using Rex::Text.ascii_safe_hex but leave
448
# this as is for now since "\xNN" is arguably uglier than "_"
449
# showing up in various places in the UI.
450
safe_info.gsub!(/[\x00-\x08\x0b\x0c\x0e-\x19\x7f-\xff]+/n,"_")
451
self.info = safe_info
452
end
453
454
def guess_target_platform(os)
455
case os
456
when /windows/i
457
Msf::Module::Platform::Windows.realname.downcase
458
when /darwin/i
459
Msf::Module::Platform::OSX.realname.downcase
460
when /mac os ?x/i
461
# this happens with java on OSX (for real!)
462
Msf::Module::Platform::OSX.realname.downcase
463
when /freebsd/i
464
Msf::Module::Platform::FreeBSD.realname.downcase
465
when /openbsd/i, /netbsd/i
466
Msf::Module::Platform::BSD.realname.downcase
467
else
468
Msf::Module::Platform::Linux.realname.downcase
469
end
470
end
471
472
#
473
# Populate the session information.
474
#
475
# Also reports a session_fingerprint note for host os normalization.
476
#
477
def load_session_info
478
begin
479
::Timeout.timeout(60) do
480
update_session_info
481
482
hobj = nil
483
484
nhost = find_internet_connected_address
485
486
original_session_host = self.session_host
487
# If we found a better IP address for this session, change it
488
# up. Only handle cases where the DB is not connected here
489
if nhost && !(framework.db && framework.db.active)
490
self.session_host = nhost
491
end
492
493
# The rest of this requires a database, so bail if it's not
494
# there
495
return if !(framework.db && framework.db.active)
496
497
::ApplicationRecord.connection_pool.with_connection {
498
wspace = framework.db.find_workspace(workspace)
499
500
# Account for finding ourselves on a different host
501
if nhost and self.db_record
502
# Create or switch to a new host in the database
503
hobj = framework.db.report_host(:workspace => wspace, :host => nhost)
504
if hobj
505
self.session_host = nhost
506
self.db_record.host_id = hobj[:id]
507
end
508
end
509
510
sysinfo = sys.config.sysinfo
511
host = Msf::Util::Host.normalize_host(self)
512
513
framework.db.report_note({
514
:type => "host.os.session_fingerprint",
515
:host => host,
516
:workspace => wspace,
517
:data => {
518
:name => sysinfo["Computer"],
519
:os => sysinfo["OS"],
520
:arch => sysinfo["Architecture"],
521
}
522
})
523
524
if self.db_record
525
framework.db.update_session(self)
526
end
527
528
# XXX: This is obsolete given the Mdm::Host.normalize_os() support for host.os.session_fingerprint
529
# framework.db.update_host_via_sysinfo(:host => self, :workspace => wspace, :info => sysinfo)
530
531
if nhost
532
framework.db.report_note({
533
:type => "host.nat.server",
534
:host => original_session_host,
535
:workspace => wspace,
536
:data => { :info => "This device is acting as a NAT gateway for #{nhost}", :client => nhost },
537
:update => :unique_data
538
})
539
framework.db.report_host(:host => original_session_host, :purpose => 'firewall' )
540
541
framework.db.report_note({
542
:type => "host.nat.client",
543
:host => nhost,
544
:workspace => wspace,
545
:data => { :info => "This device is traversing NAT gateway #{original_session_host}", :server => original_session_host },
546
:update => :unique_data
547
})
548
framework.db.report_host(:host => nhost, :purpose => 'client' )
549
end
550
}
551
552
end
553
rescue ::Interrupt
554
dlog("Interrupt while loading sysinfo: #{e.class}: #{e}")
555
raise $!
556
rescue ::Exception => e
557
# Log the error but otherwise ignore it so we don't kill the
558
# session if reporting failed for some reason
559
elog('Error loading sysinfo', error: e)
560
dlog("Call stack:\n#{e.backtrace.join("\n")}")
561
end
562
end
563
564
##
565
# :category: Msf::Session::Interactive implementors
566
#
567
# Interacts with the meterpreter client at a user interface level.
568
#
569
def _interact
570
framework.events.on_session_interact(self)
571
572
console.framework = framework
573
if framework.datastore['MeterpreterPrompt']
574
console.update_prompt(framework.datastore['MeterpreterPrompt'])
575
end
576
# Call the console interaction subsystem of the meterpreter client and
577
# pass it a block that returns whether or not we should still be
578
# interacting. This will allow the shell to abort if interaction is
579
# canceled.
580
console.interact { self.interacting != true }
581
console.framework = nil
582
583
# If the stop flag has been set, then that means the user exited. Raise
584
# the EOFError so we can drop this handle like a bad habit.
585
raise EOFError if (console.stopped? == true)
586
end
587
588
589
##
590
# :category: Msf::Session::Comm implementors
591
#
592
# Creates a connection based on the supplied parameters and returns it to
593
# the caller. The connection is created relative to the remote machine on
594
# which the meterpreter server instance is running.
595
#
596
def create(param)
597
sock = nil
598
599
# Notify handlers before we create the socket
600
notify_before_socket_create(self, param)
601
602
sock = net.socket.create(param)
603
604
# Notify now that we've created the socket
605
notify_socket_created(self, sock, param)
606
607
# Return the socket to the caller
608
sock
609
end
610
611
def supports_udp?
612
true
613
end
614
615
#
616
# Get a string representation of the current session platform
617
#
618
def platform
619
if self.payload_uuid
620
# return the actual platform of the current session if it's there
621
self.payload_uuid.platform
622
else
623
# otherwise just use the base for the session type tied to this handler.
624
# If we don't do this, storage of sessions in the DB dies
625
self.base_platform
626
end
627
end
628
629
#
630
# Get a string representation of the current session architecture
631
#
632
def arch
633
if self.payload_uuid
634
# return the actual arch of the current session if it's there
635
self.payload_uuid.arch
636
else
637
# otherwise just use the base for the session type tied to this handler.
638
# If we don't do this, storage of sessions in the DB dies
639
self.base_arch
640
end
641
end
642
643
#
644
# Get a string representation of the architecture of the process in which the
645
# current session is running. This defaults to the same value of arch but can
646
# be overridden by specific meterpreter implementations to add support.
647
#
648
def native_arch
649
arch
650
end
651
652
#
653
# Generate a binary suffix based on arch
654
#
655
def binary_suffix
656
# generate a file/binary suffix based on the current arch and platform.
657
# Platform-agnostic archs go first
658
case self.arch
659
when 'java'
660
['jar']
661
when 'php'
662
['php']
663
when 'python'
664
['py']
665
else
666
# otherwise we fall back to the platform
667
case self.platform
668
when 'windows'
669
["#{self.arch}.dll"]
670
when 'linux' , 'aix' , 'hpux' , 'irix' , 'unix'
671
['bin', 'elf']
672
when 'osx'
673
['elf']
674
when 'android', 'java'
675
['jar']
676
when 'php'
677
['php']
678
when 'python'
679
['py']
680
else
681
nil
682
end
683
end
684
end
685
686
# These are the base arch/platform for the original payload, required for when the
687
# session is first created thanks to the fact that the DB session recording
688
# happens before the session is even established.
689
attr_accessor :base_arch
690
attr_accessor :base_platform
691
692
attr_accessor :console # :nodoc:
693
attr_accessor :skip_ssl
694
attr_accessor :skip_cleanup
695
attr_accessor :target_id
696
attr_accessor :max_threads
697
698
protected
699
700
attr_accessor :rstream # :nodoc:
701
702
# Rummage through this host's routes and interfaces looking for an
703
# address that it uses to talk to the internet.
704
#
705
# @see Rex::Post::Meterpreter::Extensions::Stdapi::Net::Config#get_interfaces
706
# @see Rex::Post::Meterpreter::Extensions::Stdapi::Net::Config#get_routes
707
# @return [String] The address from which this host reaches the
708
# internet, as ASCII. e.g.: "192.168.100.156"
709
# @return [nil] If there is an interface with an address that matches
710
# {#session_host}
711
def find_internet_connected_address
712
713
ifaces = self.net.config.get_interfaces().flatten rescue []
714
routes = self.net.config.get_routes().flatten rescue []
715
716
# Try to match our visible IP to a real interface
717
found = !!(ifaces.find { |i| i.addrs.find { |a| a == session_host } })
718
nhost = nil
719
720
# If the host has no address that matches what we see, then one of
721
# us is behind NAT so we have to look harder.
722
if !found
723
# Grab all routes to the internet
724
default_routes = routes.select { |r| r.subnet == "0.0.0.0" || r.subnet == "::" }
725
726
default_routes.each do |route|
727
# Now try to find an interface whose network includes this
728
# Route's gateway, which means it's the one the host uses to get
729
# to the interweb.
730
ifaces.each do |i|
731
# Try all the addresses this interface has configured
732
addr_and_mask = i.addrs.zip(i.netmasks).find do |addr, netmask|
733
bits = Rex::Socket.net2bitmask( netmask )
734
range = Rex::Socket::RangeWalker.new("#{addr}/#{bits}") rescue nil
735
736
!!(range && range.valid? && range.include?(route.gateway))
737
end
738
if addr_and_mask
739
nhost = addr_and_mask[0]
740
break
741
end
742
end
743
break if nhost
744
end
745
746
if !nhost
747
# No internal address matches what we see externally and no
748
# interface has a default route. Fall back to the first
749
# non-loopback address
750
non_loopback = ifaces.find { |i| i.ip != "127.0.0.1" && i.ip != "::1" }
751
if non_loopback
752
nhost = non_loopback.ip
753
end
754
end
755
end
756
757
nhost
758
end
759
760
end
761
762
end
763
end
764
765