Module: Msf::Handler::ReverseUdp

Includes:
Msf::Handler, Msf::Handler::Reverse::Bind, Msf::Handler::Reverse::Comm
Defined in:
lib/msf/core/handler/reverse_udp.rb

Overview

This module implements the reverse UDP handler. This means that it listens on a port waiting for a connection until either one is established or it is told to abort.

This handler depends on having a local host and port to listen on.

Constant Summary

Constants included from Msf::Handler

Claimed, Unused

Instance Attribute Summary collapse

Attributes included from Msf::Handler

#exploit_config, #parent_payload, #pending_connections, #session_waiter_event, #sessions

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Msf::Handler::Reverse::Bind

#bind_addresses, #is_loopback_address?

Methods included from Msf::Handler::Reverse::Comm

#select_comm, #via_string

Methods included from Msf::Handler

#add_handler, #create_session, #handle_connection, #handler, #handler_name, #interrupt_wait_for_session, #register_session, #wait_for_session, #wfs_delay

Instance Attribute Details

#conn_threads ⇒ Object (protected)

:nodoc:



262
263
264
# File 'lib/msf/core/handler/reverse_udp.rb', line 262

def conn_threads
  @conn_threads
end

#handler_thread ⇒ Object (protected)

:nodoc:



261
262
263
# File 'lib/msf/core/handler/reverse_udp.rb', line 261

def handler_thread
  @handler_thread
end

#listener_sock ⇒ Object (protected)

:nodoc:



259
260
261
# File 'lib/msf/core/handler/reverse_udp.rb', line 259

def listener_sock
  @listener_sock
end

#listener_thread ⇒ Object (protected)

:nodoc:



260
261
262
# File 'lib/msf/core/handler/reverse_udp.rb', line 260

def listener_thread
  @listener_thread
end

Class Method Details

.general_handler_type ⇒ Object

Returns the connection-described general handler type, in this case 'reverse'.



36
37
38
# File 'lib/msf/core/handler/reverse_udp.rb', line 36

def self.general_handler_type
  "reverse"
end

.handler_type ⇒ Object

Returns the string representation of the handler type, in this case 'reverse_udp'.



28
29
30
# File 'lib/msf/core/handler/reverse_udp.rb', line 28

def self.handler_type
  return "reverse_udp"
end

Instance Method Details

#bind_port ⇒ Object (protected)



254
255
256
257
# File 'lib/msf/core/handler/reverse_udp.rb', line 254

def bind_port
  port = datastore['ReverseListenerBindPort'].to_i
  port > 0 ? port : datastore['LPORT'].to_i
end

#cleanup_handler ⇒ Object

Closes the listener socket if one was created.



141
142
143
144
145
146
147
148
149
# File 'lib/msf/core/handler/reverse_udp.rb', line 141

def cleanup_handler
  stop_handler

  # Kill any remaining handle_connection threads that might
  # be hanging around
  conn_threads.each { |thr|
    thr.kill rescue nil
  }
end

#comm_string ⇒ Object



54
55
56
57
58
59
60
# File 'lib/msf/core/handler/reverse_udp.rb', line 54

def comm_string
  if listener_sock.nil?
    "(setting up)"
  else
    via_string(self.listener_sock.channel.client) if self.listener_sock.respond_to?(:channel) && self.listener_sock.channel.respond_to?(:client)
  end
end

#human_name ⇒ String

A string suitable for displaying to the user

Returns:

  • (String)


43
44
45
# File 'lib/msf/core/handler/reverse_udp.rb', line 43

def human_name
  "reverse UDP"
end

#initialize(info = {}) ⇒ Object

Initializes the reverse UDP handler and ads the options that are required for all reverse UDP payloads, like local host and local port.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/msf/core/handler/reverse_udp.rb', line 76

def initialize(info = {})
  super

  register_options(
    [
      Msf::OptAddressOrHostname.new('LHOST', [true, 'The listen address (an interface may be specified)']),
      Opt::LPORT(4444)
    ], Msf::Handler::ReverseUdp)

  # XXX: Not supported by all modules
  register_advanced_options(
    [
      OptAddress.new('ReverseListenerBindAddress', [ false, 'The specific IP address to bind to on the local system']),
      OptInt.new('ReverseListenerBindPort', [ false, 'The port to bind to on the local system if different from LPORT' ]),
      OptBool.new('ReverseListenerThreaded', [ true, 'Handle every connection in a new thread (experimental)', false]),
      OptString.new('ReverseListenerComm', [ false, 'The specific communication channel to use for this listener'])
    ] +
    Msf::Opt::stager_retry_options,
    Msf::Handler::ReverseUdp)

  self.conn_threads = []
end

#listener_uri(addr = datastore['ReverseListenerBindAddress']) ⇒ String

A URI describing where we are listening

Parameters:

  • addr (String) (defaults to: datastore['ReverseListenerBindAddress']) —

    the address that

Returns:

  • (String) —

    A URI of the form scheme://host:port/



66
67
68
69
70
# File 'lib/msf/core/handler/reverse_udp.rb', line 66

def listener_uri(addr = datastore['ReverseListenerBindAddress'])
  addr = datastore['LHOST'] if addr.nil? || addr.empty?
  uri_host = Rex::Socket.is_ipv6?(addr) ? "[#{addr}]" : addr
  "udp://#{uri_host}:#{bind_port}"
end

#payload_uri ⇒ Object

A URI describing what the payload is configured to use for transport



48
49
50
51
52
# File 'lib/msf/core/handler/reverse_udp.rb', line 48

def payload_uri
  addr = datastore['LHOST']
  uri_host = Rex::Socket.is_ipv6?(addr) ? "[#{addr}]" : addr
  "udp://#{uri_host}:#{datastore['LPORT']}"
end

#setup_handler ⇒ Object

Starts the listener but does not actually attempt to accept a connection. Throws socket exceptions if it fails to start the listener.



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
135
136
# File 'lib/msf/core/handler/reverse_udp.rb', line 104

def setup_handler
  ex = false

  comm = select_comm
  local_port = bind_port
  addrs = bind_addresses

  addrs.each { |ip|
    begin

      self.listener_sock = Rex::Socket::Udp.create(
        'LocalHost' => ip,
        'LocalPort' => local_port,
        'Comm'      => comm,
        'Context'   =>
          {
            'Msf'        => framework,
            'MsfPayload' => self,
            'MsfExploit' => assoc_exploit
          })

      ex = false

      via = via_string(self.listener_sock.channel.client) if self.listener_sock.respond_to?(:channel) && self.listener_sock.channel.respond_to?(:client)
      print_status("Started #{human_name} handler on #{ip}:#{local_port} #{via}")
      break
    rescue
      ex = $!
      print_error("Handler failed to bind to #{ip}:#{local_port}")
    end
  }
  raise ex if (ex)
end

#start_handler ⇒ Object

Starts monitoring for an inbound connection.



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
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/msf/core/handler/reverse_udp.rb', line 154

def start_handler
  queue = ::Queue.new

  local_port = bind_port

  self.listener_thread = framework.threads.spawn("ReverseUdpHandlerListener-#{local_port}", false, queue) { |lqueue|
    loop do
      # Accept a client connection
      begin
        inbound, addr = self.listener_sock.recvfrom(65535)
        peerhost, peerport = addr[3], addr[1]
        next if peerhost.nil?
        comm = self.listener_sock.channel.client if self.listener_sock.respond_to?(:channel) && self.listener_sock.channel.respond_to?(:client)

        cli_opts = {
          'PeerPort' => peerport,
          'PeerHost' => peerhost,
          'LocalPort' => self.listener_sock.localport,
          'Comm' => comm
        }

        # unless ['::', '0.0.0.0'].any? {|alladdr| self.listener_sock.localhost == alladdr }
        #   cli_opts['LocalHost'] = self.listener_sock.localhost
        # end

        client = Rex::Socket.create_udp(cli_opts)
        client.extend(Rex::IO::Stream)
        if ! client
          wlog("ReverseUdpHandlerListener-#{local_port}: No client received in call to accept, exiting...")
          break
        end

        self.pending_connections += 1
        lqueue.push([client,inbound])
      rescue ::Exception
        wlog("ReverseUdpHandlerListener-#{local_port}: Exception raised during listener accept: #{$!}\n\n#{$@.join("\n")}")
        break
      end
    end
  }

  self.handler_thread = framework.threads.spawn("ReverseUdpHandlerWorker-#{local_port}", false, queue) { |cqueue|
    loop do
      begin
        client, inbound = cqueue.pop

        if ! client
          elog("ReverseUdpHandlerWorker-#{local_port}: Queue returned an empty result, exiting...")
          break
        end

        # Timeout and datastore options need to be passed through to the client
        opts = {
          :datastore    => datastore,
          :expiration   => datastore['SessionExpirationTimeout'].to_i,
          :comm_timeout => datastore['SessionCommunicationTimeout'].to_i,
          :retry_total  => datastore['SessionRetryTotal'].to_i,
          :retry_wait   => datastore['SessionRetryWait'].to_i,
          :udp_session  => inbound
        }

        if datastore['ReverseListenerThreaded']
          self.conn_threads << framework.threads.spawn("ReverseUdpHandlerSession-#{local_port}-#{client.peerhost}", false, client) { |client_copy|
            handle_connection(client_copy, opts)
          }
        else
          handle_connection(client, opts)
        end
      rescue ::Exception => e
        elog('Exception raised from handle_connection', error: e)
      end
    end
  }

end

#stop_handler ⇒ Object

Stops monitoring for an inbound connection.



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/msf/core/handler/reverse_udp.rb', line 233

def stop_handler
  # Terminate the listener thread
  if (self.listener_thread and self.listener_thread.alive? == true)
    self.listener_thread.kill
    self.listener_thread = nil
  end

  # Terminate the handler thread
  if (self.handler_thread and self.handler_thread.alive? == true)
    self.handler_thread.kill
    self.handler_thread = nil
  end

  if (self.listener_sock)
    self.listener_sock.close
    self.listener_sock = nil
  end
end