Class: Rex::Services::LocalRelay

Inherits:
Object
  • Object
show all
Includes:
Rex::Service
Defined in:
lib/rex/services/local_relay.rb

Overview

This service acts as a local TCP relay whereby clients can connect to a local listener that forwards to an arbitrary remote endpoint. Interaction with the remote endpoint socket requires that it implement the Rex::IO::Stream interface.

Defined Under Namespace

Modules: Stream, StreamServer Classes: Relay, ReverseRelay

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Rex::Service

#cleanup, #deref

Constructor Details

#initializeLocalRelay

Initializes the local tcp relay monitor.


149
150
151
152
153
154
155
# File 'lib/rex/services/local_relay.rb', line 149

def initialize
  self.relays       = Hash.new
  self.rfds         = Array.new
  self.rev_chans    = Array.new
  self.relay_thread = nil
  self.relay_mutex  = Mutex.new
end

Instance Attribute Details

#relay_mutexObject (protected)

Returns the value of attribute relay_mutex


335
336
337
# File 'lib/rex/services/local_relay.rb', line 335

def relay_mutex
  @relay_mutex
end

#relay_threadObject (protected)

Returns the value of attribute relay_thread


335
336
337
# File 'lib/rex/services/local_relay.rb', line 335

def relay_thread
  @relay_thread
end

#relaysObject (protected)

Returns the value of attribute relays


335
336
337
# File 'lib/rex/services/local_relay.rb', line 335

def relays
  @relays
end

#rev_chansObject (protected)

Returns the value of attribute rev_chans


336
337
338
# File 'lib/rex/services/local_relay.rb', line 336

def rev_chans
  @rev_chans
end

#rfdsObject (protected)

Returns the value of attribute rfds


336
337
338
# File 'lib/rex/services/local_relay.rb', line 336

def rfds
  @rfds
end

Class Method Details

.hardcore_alias(*args) ⇒ Object

Returns the hardcore alias for the local relay service.


166
167
168
# File 'lib/rex/services/local_relay.rb', line 166

def self.hardcore_alias(*args)
  "__#{args}"
end

Instance Method Details

#accept_relay_conn(srvfd) ⇒ Object (protected)

Accepts a client connection on a local relay.


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
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/rex/services/local_relay.rb', line 425

def accept_relay_conn(srvfd)
  relay = srvfd.relay

  begin
    dlog("Accepting relay client connection...", 'rex', LEV_3)

    # Accept the child connection
    lfd = srvfd.accept
    dlog("Got left side of relay: #{lfd}", 'rex', LEV_3)

    # Call the relay's on_local_connection method which should return a
    # remote connection on success
    rfd = srvfd.on_local_connection(relay, lfd)

    dlog("Got right side of relay: #{rfd}", 'rex', LEV_3)
  rescue
    wlog("Failed to get remote half of local connection on relay #{relay.name}: #{$!}", 'rex')
    lfd.close
    return
  end

  # If we have both sides, then we rock.  Extend the instances, associate
  # them with the relay, associate them with each other, and add them to
  # the list of polling file descriptors
  if lfd && rfd
    lfd.extend(Stream)
    rfd.extend(Stream)

    lfd.relay = relay
    rfd.relay = relay

    lfd.other_stream = rfd
    rfd.other_stream = lfd

    self.rfds << lfd
    self.rfds << rfd
  else
    # Otherwise, we don't have both sides, we'll close them.
    close_relay_conn(lfd)
  end
end

#accept_reverse_relay(rrfd) ⇒ Object (protected)

Attempt to accept a new reverse connection on the given reverse relay handle.


397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/rex/services/local_relay.rb', line 397

def accept_reverse_relay(rrfd)

  rfd = rrfd.accept_nonblock

  return unless rfd

  lfd = Rex::Socket::Tcp.create(
    'PeerHost'  => rrfd.relay.opts['PeerHost'],
    'PeerPort'  => rrfd.relay.opts['PeerPort'],
    'Timeout'   => 5
  )

  rfd.extend(Stream)
  lfd.extend(Stream)

  rfd.relay = rrfd.relay
  lfd.relay = rrfd.relay

  self.rfds << lfd
  self.rfds << rfd

  rfd.other_stream = lfd
  lfd.other_stream = rfd
end

#aliasObject

Returns the alias for this service.


173
174
175
# File 'lib/rex/services/local_relay.rb', line 173

def alias
  super || "Local Relay"
end

#close_relay(relay) ⇒ Object (protected)

Closes an cleans up a specific relay


341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/rex/services/local_relay.rb', line 341

def close_relay(relay)

  if relay.kind_of?(ReverseRelay)
    self.rev_chans.delete(relay.channel)
  else
    self.rfds.delete(relay.listener)
  end

  self.relays.delete(relay.name)

  begin
    relay.shutdown
    relay.close
  rescue IOError
  end
end

#close_relay_conn(fd) ⇒ Object (protected)

Closes a specific relay connection without tearing down the actual relay itself.


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
# File 'lib/rex/services/local_relay.rb', line 362

def close_relay_conn(fd)
  relay = fd.relay
  ofd   = fd.other_stream

  self.rfds.delete(fd)

  begin
    if relay.on_conn_close_proc
      relay.on_conn_close_proc.call(fd)
    end

    fd.shutdown
    fd.close
  rescue IOError
  end

  if ofd
    self.rfds.delete(ofd)

    begin
      if (relay.on_conn_close_proc)
        relay.on_conn_close_proc.call(ofd)
      end

      ofd.shutdown
      ofd.close
    rescue IOError
    end
  end
end

#each_tcp_relay(&block) ⇒ Object

Enumerate each TCP relay


320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/rex/services/local_relay.rb', line 320

def each_tcp_relay(&block)
  self.relays.each_pair { |name, relay|
    next if (relay.opts['__RelayType'] != 'tcp')

    yield(
      relay.opts['LocalHost'] || '0.0.0.0',
      relay.opts['LocalPort'],
      relay.opts['PeerHost'],
      relay.opts['PeerPort'],
      relay.opts)
  }
end

#monitor_relaysObject (protected)

Monitors the relays for data and passes it in both directions.


470
471
472
473
474
475
476
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
# File 'lib/rex/services/local_relay.rb', line 470

def monitor_relays
  begin
    # Helps with latency
    Thread.current.priority = 2

    # See if we have any new connections on the existing reverse port
    # forward relays
    rev_chans.each do |rrfd|
      accept_reverse_relay(rrfd)
    end

    # Poll all the streams...
    begin
      socks = Rex::ThreadSafe.select(rfds, nil, nil, 0.25)
    rescue StreamClosedError => e
      dlog("monitor_relays: closing stream #{e.stream}", 'rex', LEV_3)

      # Close the relay connection that is associated with the stream
      # closed error
      if e.stream.kind_of?(Stream)
        close_relay_conn(e.stream)
      end

      dlog("monitor_relays: closed stream #{e.stream}", 'rex', LEV_3)

      next
    rescue => e
      elog("Error in #{self} monitor_relays select:", 'rex', error: e)
      return
    end

    # If socks is nil, go again.
    next unless socks

    # Process read-ready file descriptors, if any.
    socks[0].each { |rfd|

      # If this file descriptor is a server, accept the connection
      if (rfd.kind_of?(StreamServer))
        accept_relay_conn(rfd)
      else
        # Otherwise, it's a relay connection, read data from one side
        # and write it to the other
        begin
          # Pass the data onto the other fd, most likely writing it.
          data = rfd.sysread(65536)
          rfd.other_stream.on_other_data(data)
        # If we catch an error, close the connection
        rescue ::Exception => e
          elog("Error in #{self} monitor_relays read", 'rex', error: e)
          close_relay_conn(rfd)
        end
      end

    } if (socks[0])

  end while true
end

#startObject

Starts the thread that monitors the local relays.


180
181
182
183
184
185
186
187
188
189
190
# File 'lib/rex/services/local_relay.rb', line 180

def start
  if (!self.relay_thread)
    self.relay_thread = Rex::ThreadFactory.spawn("LocalRelay", false) {
      begin
        monitor_relays
      rescue ::Exception => e
        elog("Error in #{self} monitor_relays", 'rex', error: e)
      end
    }
  end
end

#start_relay(stream_server, name, opts = {}) ⇒ Object

Starts a local relay on the supplied local port. This listener will call the supplied callback procedures when various events occur.


275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/rex/services/local_relay.rb', line 275

def start_relay(stream_server, name, opts = {})
  # Create a Relay instance with the local stream and remote stream
  relay = Relay.new(name, stream_server, opts)

  # Extend the stream_server so that we can associate it with this relay
  stream_server.extend(StreamServer)
  stream_server.relay = relay

  # Add the stream associations the appropriate lists and hashes
  self.relay_mutex.synchronize {
    self.relays[name] = relay

    self.rfds << stream_server
  }
  relay
end

#start_reverse_tcp_relay(channel, opts = {}) ⇒ Object

Start a new active listener on the victim ready for reverse connections.


224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/rex/services/local_relay.rb', line 224

def start_reverse_tcp_relay(channel, opts = {})
  opts['__RelayType'] = 'tcp'
  opts['Reverse'] = true

  name = "Reverse-#{opts['LocalPort']}"

  relay = ReverseRelay.new(name, channel, opts)

  # dirty hack to get "relay" support?
  channel.extend(StreamServer)
  channel.relay = relay

  self.relay_mutex.synchronize {
    self.relays[name] = relay
    self.rev_chans << channel
  }
  relay
end

#start_tcp_relay(lport, opts = {}) ⇒ Object

Starts a local TCP relay.


253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/rex/services/local_relay.rb', line 253

def start_tcp_relay(lport, opts = {})
  # Make sure our options are valid
  if ((opts['PeerHost'] == nil or opts['PeerPort'] == nil) and (opts['Stream'] != true))
    raise ArgumentError, "Missing peer host or peer port.", caller
  end

  listener = Rex::Socket.create_tcp_server(
    'LocalHost' => opts['LocalHost'],
    'LocalPort' => lport)

  _, lhost, lport = listener.getlocalname()
  opts['LocalHost']   = lhost
  opts['LocalPort']   = lport
  opts['__RelayType'] = 'tcp'

  start_relay(listener, lport.to_s + opts['LocalHost'], opts)
end

#stopObject

Stops the thread that monitors the local relays and destroys all listeners, both local and remote.


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/rex/services/local_relay.rb', line 196

def stop
  if (self.relay_thread)
    self.relay_thread.kill
    self.relay_thread = nil
  end

  self.relay_mutex.synchronize {
    self.relays.delete_if { |k, v|
      v.shutdown
      v.close
      true
    }
  }

  # make sure we kill off active sockets when we shut down
  while self.rfds.length > 0
    close_relay_conn(self.rfds.shift) rescue nil
  end

  # we can safely clear the channels array because all of the
  # reverse relays were closed down
  self.rev_chans.clear
  self.relays.clear
end

#stop_relay(name) ⇒ Object

Stops a relay with a given name.


302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/rex/services/local_relay.rb', line 302

def stop_relay(name)
  rv = false

  self.relay_mutex.synchronize {
    relay = self.relays[name]

    if relay
      close_relay(relay)
      rv = true
    end
  }

  rv
end

#stop_reverse_tcp_relay(rport) ⇒ Object

Stop an active reverse port forward.


246
247
248
# File 'lib/rex/services/local_relay.rb', line 246

def stop_reverse_tcp_relay(rport)
  stop_relay("Reverse-#{rport}")
end

#stop_tcp_relay(lport, lhost = nil) ⇒ Object

Stops relaying on a given local port.


295
296
297
# File 'lib/rex/services/local_relay.rb', line 295

def stop_tcp_relay(lport, lhost = nil)
  stop_relay(lport.to_s + (lhost || '0.0.0.0'))
end