Module: Rex::Post::Meterpreter::PacketDispatcher

Included in:
Client
Defined in:
lib/rex/post/meterpreter/packet_dispatcher.rb

Overview

Handles packet transmission, reception, and correlation, and processing

Constant Summary collapse

PacketTimeout =
600

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#comm_mutexObject

Synchronization



52
53
54
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 52

def comm_mutex
  @comm_mutex
end

#passive_serviceObject

Passive Dispatching



61
62
63
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 61

def passive_service
  @passive_service
end

#recv_queueObject

Passive Dispatching



61
62
63
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 61

def recv_queue
  @recv_queue
end

#send_queueObject

Passive Dispatching



61
62
63
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 61

def send_queue
  @send_queue
end

Instance Method Details

#add_response_waiter(request, completion_routine = nil, completion_param = nil) ⇒ Object

Adds a waiter association with the supplied request packet.



444
445
446
447
448
449
450
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 444

def add_response_waiter(request, completion_routine = nil, completion_param = nil)
  waiter = PacketResponseWaiter.new(request.rid, completion_routine, completion_param)

  self.waiters << waiter

  return waiter
end

#deregister_inbound_handler(handler) ⇒ Object

Deregisters a previously registered inbound packet handler.



550
551
552
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 550

def deregister_inbound_handler(handler)
  @inbound_handlers.delete(handler)
end

#dispatch_inbound_packet(packet, client = nil) ⇒ Object

Dispatches and processes an inbound packet. If the packet is a response that has an associated waiter, the waiter is notified. Otherwise, the packet is passed onto any registered dispatch handlers until one returns success.



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
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 494

def dispatch_inbound_packet(packet, client = nil)
  handled = false

  # If no client context was provided, return self as PacketDispatcher
  # is a mixin for the Client instance
  if (client == nil)
    client = self
  end

  # Update our last reply time
  client.last_checkin = Time.now

  # If the packet is a response, try to notify any potential
  # waiters
  if ((resp = packet.response?))
    if (notify_response_waiter(packet))
      return true
    end
  end

  # Enumerate all of the inbound packet handlers until one handles
  # the packet
  @inbound_handlers.each { |handler|

    handled = nil
    begin

    if ! resp
      handled = handler.request_handler(client, packet)
    else
      handled = handler.response_handler(client, packet)
    end

    rescue ::Exception => e
      dlog("Exception caught in dispatch_inbound_packet: handler=#{handler} #{e.class} #{e} #{e.backtrace}", 'meterpreter', LEV_1)
      return true
    end

    if (handled)
      break
    end
  }
  return handled
end

#initialize_inbound_handlersObject

Initializes the inbound handlers.



484
485
486
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 484

def initialize_inbound_handlers
  @inbound_handlers = []
end

#initialize_passive_dispatcherObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 63

def initialize_passive_dispatcher
  self.send_queue = []
  self.recv_queue = []
  self.waiters    = []
  self.alive      = true

  # Ensure that there is only one leading and trailing slash on the URI
  resource_uri = "/" + self.conn_id.to_s.gsub(/(^\/|\/$)/, '') + "/"

  self.passive_service = self.passive_dispatcher
  self.passive_service.remove_resource(resource_uri)
  self.passive_service.add_resource(resource_uri,
    'Proc'             => Proc.new { |cli, req| on_passive_request(cli, req) },
    'VirtualDirectory' => true
  )
end

#monitor_socketObject

Reception

Monitors the PacketDispatcher’s sock for data in its own thread context and parsers all inbound packets.



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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 247

def monitor_socket

  # Skip if we are using a passive dispatcher
  return if self.passive_service

  self.comm_mutex = ::Mutex.new

  self.waiters = []

  @pqueue = []
  @finish = false
  @last_recvd = Time.now
  @ping_sent = false

  self.alive = true

  # Spawn a thread for receiving packets
  self.receiver_thread = Rex::ThreadFactory.spawn("MeterpreterReceiver", false) do
    while (self.alive)
      begin
        rv = Rex::ThreadSafe.select([ self.sock.fd ], nil, nil, 0.25)
        ping_time = 60
        # If there's nothing to read, and it's been awhile since we
        # saw a packet, we need to send a ping.  We wait
        # ping_time*2 seconds before deciding a session is dead.
        if (not rv and self.send_keepalives and Time.now - @last_recvd > ping_time)
          # If the queue is empty and we've already sent a
          # keepalive without getting a reply, then this
          # session is hosed, and we should give up on it.
          if @ping_sent and @pqueue.empty? and (Time.now - @last_recvd > ping_time * 2)
            dlog("No response to ping, session #{self.sid} is dead", LEV_3)
            self.alive = false
            @finish = true
            break
          end
          # Let the packet queue processor finish up before
          # we send a ping.
          if not @ping_sent and @pqueue.empty?
            # Our 'ping' is actually just a check for eof on
            # channel id 0.  This method has no side effects
            # and always returns an answer (regardless of the
            # existence of chan 0), which is all that's
            # needed for a liveness check.  The answer itself
            # is unimportant and is ignored.
            pkt = Packet.create_request('core_channel_eof')
            pkt.add_tlv(TLV_TYPE_CHANNEL_ID, 0)
            waiter = Proc.new { |response, param|
                @ping_sent = false
                @last_recvd = Time.now
              }
            send_packet(pkt, waiter)
            @ping_sent = true
          end
          next
        end
        next if not rv
        packet = receive_packet
        @pqueue << packet if packet
        @last_recvd = Time.now
      rescue ::Exception
        dlog("Exception caught in monitor_socket: #{$!}", 'meterpreter', LEV_1)
        @finish = true
        self.alive = false
        break
      end
    end
  end

  # Spawn a new thread that monitors the socket
  self.dispatcher_thread = Rex::ThreadFactory.spawn("MeterpreterDispatcher", false) do
    begin
    # Whether we're finished or not is determined by the receiver
    # thread above.
    while(not @finish)
      if(@pqueue.empty?)
        ::IO.select(nil, nil, nil, 0.10)
        next
      end

      incomplete = []
      backlog    = []

      while(@pqueue.length > 0)
        backlog << @pqueue.shift
      end

      #
      # Prioritize message processing here
      # 1. Close should always be processed at the end
      # 2. Command responses always before channel data
      #

      tmp_command = []
      tmp_channel = []
      tmp_close   = []
      backlog.each do |pkt|
        if(pkt.response?)
          tmp_command << pkt
          next
        end
        if(pkt.method == "core_channel_close")
          tmp_close << pkt
          next
        end
        tmp_channel << pkt
      end

      backlog = []
      backlog.push(*tmp_command)
      backlog.push(*tmp_channel)
      backlog.push(*tmp_close)


      #
      # Process the message queue
      #

      backlog.each do |pkt|

        begin
        if ! dispatch_inbound_packet(pkt)
          # Keep Packets in the receive queue until a handler is registered
          # for them. Packets will live in the receive queue for up to
          # PacketTimeout, after which they will be dropped.
          #
          # A common reason why there would not immediately be a handler for
          # a received Packet is in channels, where a connection may
          # open and receive data before anything has asked to read.
          if (::Time.now.to_i - pkt.created_at.to_i < PacketTimeout)
            incomplete << pkt
          end
        end

        rescue ::Exception => e
          dlog("Dispatching exception with packet #{pkt}: #{e} #{e.backtrace}", 'meterpreter', LEV_1)
        end
      end

      # If the backlog and incomplete arrays are the same, it means
      # dispatch_inbound_packet wasn't able to handle any of the
      # packets. When that's the case, we can get into a situation
      # where @pqueue is not empty and, since nothing else bounds this
      # loop, we spin CPU trying to handle packets that can't be
      # handled. Sleep here to treat that situation as though the
      # queue is empty.
      if (backlog.length > 0 && backlog.length == incomplete.length)
        ::IO.select(nil, nil, nil, 0.10)
      end

      @pqueue.unshift(*incomplete)

      if(@pqueue.length > 100)
        dlog("Backlog has grown to over 100 in monitor_socket, dropping older packets: #{@pqueue[0 .. 25].map{|x| x.inspect}.join(" - ")}", 'meterpreter', LEV_1)
        @pqueue = @pqueue[25 .. 100]
      end
    end
    rescue ::Exception => e
      dlog("Exception caught in monitor_socket dispatcher: #{e.class} #{e} #{e.backtrace}", 'meterpreter', LEV_1)
    ensure
      self.receiver_thread.kill if self.receiver_thread
    end
  end
end

#monitor_stopObject

Stop the monitor



423
424
425
426
427
428
429
430
431
432
433
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 423

def monitor_stop
  if(self.receiver_thread)
    self.receiver_thread.kill
    self.receiver_thread = nil
  end

  if(self.dispatcher_thread)
    self.dispatcher_thread.kill
    self.dispatcher_thread = nil
  end
end

#notify_response_waiter(response) ⇒ Object

Notifies a whomever is waiting for a the supplied response, if anyone.



456
457
458
459
460
461
462
463
464
465
466
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 456

def notify_response_waiter(response)
  self.waiters.each() { |waiter|
    if (waiter.waiting_for?(response))
      waiter.notify(response)

      remove_response_waiter(waiter)

      break
    end
  }
end

#on_passive_request(cli, req) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 101

def on_passive_request(cli, req)

  begin

  resp = Rex::Proto::Http::Response.new(200, "OK")
  resp['Content-Type'] = 'application/octet-stream'
  resp['Connection']   = 'close'

  self.last_checkin = Time.now

  # If the first 4 bytes are "RECV", return the oldest packet from the outbound queue
  if req.body[0,4] == "RECV"
    rpkt = send_queue.shift
    resp.body = rpkt || ''
    begin
      cli.send_response(resp)
    rescue ::Exception => e
      send_queue.unshift(rpkt) if rpkt
      elog("Exception sending a reply to the reader request: #{cli.inspect} #{e.class} #{e} #{e.backtrace}")
    end
  else
    resp.body = ""
    if req.body and req.body.length > 0
      packet = Packet.new(0)
      packet.from_r(req.body)
      dispatch_inbound_packet(packet)
    end
    cli.send_response(resp)
  end

  rescue ::Exception => e
    elog("Exception handling request: #{cli.inspect} #{req.inspect} #{e.class} #{e} #{e.backtrace}")
  end
end

#receive_packetObject

Parses data from the dispatcher’s sock and returns a Packet context once a full packet has been received.



416
417
418
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 416

def receive_packet
  return parser.recv(self.sock)
end

#register_inbound_handler(handler) ⇒ Object

Registers an inbound packet handler that implements the InboundPacketHandler interface.



543
544
545
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 543

def register_inbound_handler(handler)
  @inbound_handlers << handler
end

#remove_response_waiter(waiter) ⇒ Object

Removes a waiter from the list of waiters.



471
472
473
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 471

def remove_response_waiter(waiter)
  self.waiters.delete(waiter)
end

#send_packet(packet, completion_routine = nil, completion_param = nil) ⇒ Object

Sends a packet without waiting for a response.



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
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 145

def send_packet(packet, completion_routine = nil, completion_param = nil)
  if (completion_routine)
    add_response_waiter(packet, completion_routine, completion_param)
  end

  bytes = 0
  raw   = packet.to_r
  err   = nil

  # Short-circuit send when using a passive dispatcher
  if self.passive_service
    send_queue.push(raw)
    return raw.size # Lie!
  end

  if (raw)

    # This mutex is used to lock out new commands during an
    # active migration.

    self.comm_mutex.synchronize do
      begin
        bytes = self.sock.write(raw)
      rescue ::Exception => e
        err = e
      end
    end

    if bytes.to_i == 0
      # Mark the session itself as dead
      self.alive = false

      # Indicate that the dispatcher should shut down too
      @finish = true

      # Reraise the error to the top-level caller
      raise err if err
    end
  end

  return bytes
end

#send_packet_wait_response(packet, t) ⇒ Object

Transmits a packet and waits for a response.



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 216

def send_packet_wait_response(packet, t)
  # First, add the waiter association for the supplied packet
  waiter = add_response_waiter(packet)

  # Transmit the packet
  if (send_packet(packet).to_i <= 0)
    # Remove the waiter if we failed to send the packet.
    remove_response_waiter(waiter)
    return nil
  end

  # Wait for the supplied time interval
  waiter.wait(t)

  # Remove the waiter from the list of waiters in case it wasn't
  # removed
  remove_response_waiter(waiter)

  # Return the response packet, if any
  return waiter.response
end

#send_request(packet, t = self.response_timeout) ⇒ Object

Sends a packet and waits for a timeout for the given time interval.



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 191

def send_request(packet, t = self.response_timeout)
  if not t
    send_packet(packet)
    return nil
  end

  response = send_packet_wait_response(packet, t)

  if (response == nil)
    raise TimeoutError.new("Send timed out")
  elsif (response.result != 0)
    einfo = lookup_error(response.result)
    e = RequestError.new(packet.method, einfo, response.result)

    e.set_backtrace(caller)

    raise e
  end

  return response
end

#shutdown_passive_dispatcherObject



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/rex/post/meterpreter/packet_dispatcher.rb', line 80

def shutdown_passive_dispatcher
  return if not self.passive_service

  # Ensure that there is only one leading and trailing slash on the URI
  resource_uri = "/" + self.conn_id.to_s.gsub(/(^\/|\/$)/, '') + "/"

  self.passive_service.remove_resource(resource_uri)

  # If there are no more resources registered on the service, stop it entirely
  if self.passive_service.resources.empty?
    Rex::ServiceManager.stop_service(self.passive_service)
  end

  self.alive      = false
  self.send_queue = []
  self.recv_queue = []
  self.waiters    = []

  self.passive_service = nil
end