Class: Rex::Post::Meterpreter::Client

Inherits:
Object
  • Object
show all
Includes:
ChannelContainer, PacketDispatcher
Defined in:
lib/rex/post/meterpreter/client.rb

Overview

This class represents a logical meterpreter client class. This class provides an interface that is compatible with the Rex post-exploitation interface in terms of the feature set that it attempts to expose. This class is meant to drive a single meterpreter client session.

Constant Summary collapse

@@ext_hash =

Extension name to class hash.

{}
@@ssl_ctx =

Cached SSL certificate (required to scale)

nil
@@ssl_mutex =

Mutex to synchronize class-wide operations

::Mutex.new

Constants included from PacketDispatcher

PacketDispatcher::PacketTimeout

Instance Attribute Summary collapse

Attributes included from ChannelContainer

#channels

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ChannelContainer

#add_channel, #find_channel, #initialize_channels, #remove_channel

Methods included from PacketDispatcher

#add_response_waiter, #deregister_inbound_handler, #dispatch_inbound_packet, #initialize_inbound_handlers, #monitor_socket, #monitor_stop, #notify_response_waiter, #receive_packet, #register_inbound_handler, #remove_response_waiter, #send_packet, #send_packet_wait_response, #send_request

Constructor Details

#initialize(sock, opts = {}) ⇒ Client

Initializes the client context with the supplied socket through which communication with the server will be performed.



80
81
82
# File 'lib/rex/post/meterpreter/client.rb', line 80

def initialize(sock,opts={})
  init_meterpreter(sock, opts)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object

Translates unhandled methods into registered extension aliases if a matching extension alias exists for the supplied symbol.



259
260
261
# File 'lib/rex/post/meterpreter/client.rb', line 259

def method_missing(symbol, *args)
  self.ext_aliases.aliases[symbol.to_s]
end

Instance Attribute Details

#aliveObject

Whether this session is alive. If the socket is disconnected or broken, this will be false



373
374
375
# File 'lib/rex/post/meterpreter/client.rb', line 373

def alive
  @alive
end

#capabilitiesObject

The libraries available to this meterpreter server



381
382
383
# File 'lib/rex/post/meterpreter/client.rb', line 381

def capabilities
  @capabilities
end

#extObject

The extension alias under which all extensions can be accessed by name. For example:

client.ext.stdapi


356
357
358
# File 'lib/rex/post/meterpreter/client.rb', line 356

def ext
  @ext
end

#response_timeoutObject

The timeout value to use when waiting for responses.



364
365
366
# File 'lib/rex/post/meterpreter/client.rb', line 364

def response_timeout
  @response_timeout
end

#send_keepalivesObject

Whether to send pings every so often to determine liveness.



368
369
370
# File 'lib/rex/post/meterpreter/client.rb', line 368

def send_keepalives
  @send_keepalives
end

#sockObject

The socket the client is communicating over.



360
361
362
# File 'lib/rex/post/meterpreter/client.rb', line 360

def sock
  @sock
end

#target_idObject

The unique target identifier for this payload



377
378
379
# File 'lib/rex/post/meterpreter/client.rb', line 377

def target_id
  @target_id
end

Class Method Details

.check_ext_hash(name) ⇒ Object

Checks the extension hash to see if a class has already been associated with the supplied extension name.



65
66
67
# File 'lib/rex/post/meterpreter/client.rb', line 65

def self.check_ext_hash(name)
  @@ext_hash[name]
end

.default_timeoutObject

Returns the default timeout that request packets will use when waiting for a response.



245
246
247
# File 'lib/rex/post/meterpreter/client.rb', line 245

def Client.default_timeout
  return 300
end

.lookup_error(code) ⇒ Object

Lookup the error that occurred



57
58
59
# File 'lib/rex/post/meterpreter/client.rb', line 57

def self.lookup_error(code)
  code
end

.set_ext_hash(name, klass) ⇒ Object

Stores the name to class association for the supplied extension name.



72
73
74
# File 'lib/rex/post/meterpreter/client.rb', line 72

def self.set_ext_hash(name, klass)
  @@ext_hash[name] = klass
end

Instance Method Details

#add_extension(name) ⇒ Object

Loads the client half of the supplied extension and initializes it as a registered extension that can be reached through client.ext..



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/rex/post/meterpreter/client.rb', line 273

def add_extension(name)
  # Check to see if this extension has already been loaded.
  if ((klass = self.class.check_ext_hash(name.downcase)) == nil)
    old = Rex::Post::Meterpreter::Extensions.constants
    require("rex/post/meterpreter/extensions/#{name.downcase}/#{name.downcase}")
    new = Rex::Post::Meterpreter::Extensions.constants

    # No new constants added?
    if ((diff = new - old).empty?)
      diff = [ name.capitalize ]
    end

    klass = Rex::Post::Meterpreter::Extensions.const_get(diff[0]).const_get(diff[0])

    # Save the module name to class association now that the code is
    # loaded.
    self.class.set_ext_hash(name.downcase, klass)
  end

  # Create a new instance of the extension
  inst = klass.new(self)

  self.ext.aliases[inst.name] = inst

  return true
end

#cleanup_meterpreterObject

Cleans up the meterpreter instance, terminating the dispatcher thread.



87
88
89
90
91
92
# File 'lib/rex/post/meterpreter/client.rb', line 87

def cleanup_meterpreter
  ext.aliases.each_value do | extension |
    extension.cleanup if extension.respond_to?( 'cleanup' )
  end
  dispatcher_thread.kill if dispatcher_thread
end

#deregister_extension(name) ⇒ Object

Deregisters an extension alias of the supplied name.



303
304
305
# File 'lib/rex/post/meterpreter/client.rb', line 303

def deregister_extension(name)
  self.ext.aliases.delete(name)
end

#deregister_extension_alias(name) ⇒ Object

Deregisters a previously registered extension alias.



334
335
336
# File 'lib/rex/post/meterpreter/client.rb', line 334

def deregister_extension_alias(name)
  self.ext_aliases.aliases.delete(name)
end

#dump_extension_treeObject

Dumps the extension tree.



341
342
343
344
345
346
347
# File 'lib/rex/post/meterpreter/client.rb', line 341

def dump_extension_tree()
  items = []
  items.concat(self.ext.dump_alias_tree('client.ext'))
  items.concat(self.ext_aliases.dump_alias_tree('client'))

  return items.sort
end

#each_extension(&block) ⇒ Object

Enumerates all of the loaded extensions.



310
311
312
# File 'lib/rex/post/meterpreter/client.rb', line 310

def each_extension(&block)
  self.ext.aliases.each(block)
end

#generate_ssl_contextObject



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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/rex/post/meterpreter/client.rb', line 177

def generate_ssl_context
  @@ssl_mutex.synchronize do 
  if not @@ssl_ctx
  
  wlog("Generating SSL certificate for Meterpreter sessions")

  key  = OpenSSL::PKey::RSA.new(1024){ }
  cert = OpenSSL::X509::Certificate.new
  cert.version = 2
  cert.serial  = rand(0xFFFFFFFF)

  subject = OpenSSL::X509::Name.new([
      ["C","US"],
      ['ST', Rex::Text.rand_state()],
      ["L", Rex::Text.rand_text_alpha(rand(20) + 10)],
      ["O", Rex::Text.rand_text_alpha(rand(20) + 10)],
      ["CN", self.sock.getsockname[1] || Rex::Text.rand_hostname],
    ])
  issuer = OpenSSL::X509::Name.new([
      ["C","US"],
      ['ST', Rex::Text.rand_state()],
      ["L", Rex::Text.rand_text_alpha(rand(20) + 10)],
      ["O", Rex::Text.rand_text_alpha(rand(20) + 10)],
      ["CN", Rex::Text.rand_text_alpha(rand(20) + 10)],
    ])

  cert.subject = subject
  cert.issuer = issuer
  cert.not_before = Time.now - (3600 * 365) + rand(3600 * 14)
  cert.not_after = Time.now + (3600 * 365) + rand(3600 * 14)
  cert.public_key = key.public_key
  ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
  cert.extensions = [
    ef.create_extension("basicConstraints","CA:FALSE"),
    ef.create_extension("subjectKeyIdentifier","hash"),
    ef.create_extension("extendedKeyUsage","serverAuth"),
    ef.create_extension("keyUsage","keyEncipherment,dataEncipherment,digitalSignature")
  ]
  ef.issuer_certificate = cert
  cert.add_extension ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always")
  cert.sign(key, OpenSSL::Digest::SHA1.new)

  ctx = OpenSSL::SSL::SSLContext.new(:SSLv3)
  ctx.key = key
  ctx.cert = cert

  ctx.session_id_context = Rex::Text.rand_text(16)

  wlog("Generated SSL certificate for Meterpreter sessions")
  
  @@ssl_ctx = ctx
  
  end # End of if not @ssl_ctx
  end # End of mutex.synchronize
  
  @@ssl_ctx
end

#init_meterpreter(sock, opts = {}) ⇒ Object

Initializes the meterpreter client instance



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/client.rb', line 97

def init_meterpreter(sock,opts={})
  self.sock        = sock
  self.parser      = PacketParser.new
  self.ext         = ObjectAliases.new
  self.ext_aliases = ObjectAliases.new
  self.alive       = true
  self.target_id   = opts[:target_id]
  self.capabilities= opts[:capabilities] || {}

  self.response_timeout =  opts[:timeout] || self.class.default_timeout
  self.send_keepalives  = true


  # Switch the socket to SSL mode and receive the hello if needed
  if capabilities[:ssl] and not opts[:skip_ssl]
    swap_sock_plain_to_ssl()
  end

  register_extension_alias('core', ClientCore.new(self))

  initialize_inbound_handlers
  initialize_channels

  # Register the channel inbound packet handler
  register_inbound_handler(Rex::Post::Meterpreter::Channel)

  monitor_socket
end

#register_extension_alias(name, ext) ⇒ Object

Registers an aliased extension that can be referenced through client.name.



318
319
320
# File 'lib/rex/post/meterpreter/client.rb', line 318

def register_extension_alias(name, ext)
  self.ext_aliases.aliases[name] = ext
end

#register_extension_aliases(aliases) ⇒ Object

Registers zero or more aliases that are provided in an array.



325
326
327
328
329
# File 'lib/rex/post/meterpreter/client.rb', line 325

def register_extension_aliases(aliases)
  aliases.each { |a|
    register_extension_alias(a['name'], a['ext'])
  }
end

#swap_sock_plain_to_sslObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/rex/post/meterpreter/client.rb', line 126

def swap_sock_plain_to_ssl
  # Create a new SSL session on the existing socket
  ctx = generate_ssl_context()
  ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)

  if not ssl.respond_to?(:accept_nonblock)
    ssl.accept
  else
    begin
      ssl.accept_nonblock

    # Ruby 1.8.7 and 1.9.0/1.9.1 uses a standard Errno
    rescue ::Errno::EAGAIN, ::Errno::EWOULDBLOCK
        IO::select(nil, nil, nil, 0.10)
        retry
        
    # Ruby 1.9.2+ uses IO::WaitReadable/IO::WaitWritable    
    rescue ::Exception => e
      if ::IO.const_defined?('WaitReadable') and e.kind_of?(::IO::WaitReadable)
        IO::select( [ ssl ], nil, nil, 0.10 )
        retry
      end
        
      if ::IO.const_defined?('WaitWritable') and e.kind_of?(::IO::WaitWritable)            
        IO::select( nil, [ ssl ], nil, 0.10 )
        retry
      end
        
      raise e
    end
  end      

  self.sock.extend(Rex::Socket::SslTcp)
  self.sock.sslsock = ssl
  self.sock.sslctx  = ctx

  tag = self.sock.get_once(-1, 30)
  if(not tag or tag !~ /^GET \//)
    raise RuntimeError, "Could not read the HTTP hello token"
  end
end

#swap_sock_ssl_to_plainObject



168
169
170
171
172
173
174
175
# File 'lib/rex/post/meterpreter/client.rb', line 168

def swap_sock_ssl_to_plain
  # Remove references to the SSLSocket and Context
  self.sock.sslsock.close
  self.sock.sslsock = nil
  self.sock.sslctx  = nil
  self.sock = self.sock.fd
  self.sock.extend(::Rex::Socket::Tcp)
end