Module: Msf::Handler::ReverseUdp

Includes:
Msf::Handler
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

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

Instance Attribute Details

#conn_threadsObject (protected)

:nodoc:


285
286
287
# File 'lib/msf/core/handler/reverse_udp.rb', line 285

def conn_threads
  @conn_threads
end

#handler_threadObject (protected)

:nodoc:


284
285
286
# File 'lib/msf/core/handler/reverse_udp.rb', line 284

def handler_thread
  @handler_thread
end

#listener_sockObject (protected)

:nodoc:


282
283
284
# File 'lib/msf/core/handler/reverse_udp.rb', line 282

def listener_sock
  @listener_sock
end

#listener_threadObject (protected)

:nodoc:


283
284
285
# File 'lib/msf/core/handler/reverse_udp.rb', line 283

def listener_thread
  @listener_thread
end

Class Method Details

.general_handler_typeObject

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


34
35
36
# File 'lib/msf/core/handler/reverse_udp.rb', line 34

def self.general_handler_type
  "reverse"
end

.handler_typeObject

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


26
27
28
# File 'lib/msf/core/handler/reverse_udp.rb', line 26

def self.handler_type
  return "reverse_udp"
end

Instance Method Details

#bind_addressObject (protected)


262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/msf/core/handler/reverse_udp.rb', line 262

def bind_address
  # Switch to IPv6 ANY address if the LHOST is also IPv6
  addr = Rex::Socket.resolv_nbo(datastore['LHOST'])
  # First attempt to bind LHOST. If that fails, the user probably has
  # something else listening on that interface. Try again with ANY_ADDR.
  any = (addr.length == 4) ? "0.0.0.0" : "::0"

  addrs = [ Rex::Socket.addr_ntoa(addr), any  ]

  if not datastore['ReverseListenerBindAddress'].to_s.empty?
    # Only try to bind to this specific interface
    addrs = [ datastore['ReverseListenerBindAddress'] ]

    # Pick the right "any" address if either wildcard is used
    addrs[0] = any if (addrs[0] == "0.0.0.0" or addrs == "::0")
  end

  addrs
end

#bind_portObject (protected)


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

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

#cleanup_handlerObject

Closes the listener socket if one was created.


147
148
149
150
151
152
153
154
155
# File 'lib/msf/core/handler/reverse_udp.rb', line 147

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

#human_nameString

A string suitable for displaying to the user

Returns:

  • (String)

41
42
43
# File 'lib/msf/core/handler/reverse_udp.rb', line 41

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.


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/msf/core/handler/reverse_udp.rb', line 66

def initialize(info = {})
  super

  register_options(
    [
      Opt::LHOST,
      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' ]),
      OptString.new('ReverseListenerComm', [ false, 'The specific communication channel to use for this listener']),
      OptBool.new('ReverseListenerThreaded', [ true, 'Handle every connection in a new thread (experimental)', false])
    ] +
    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/


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

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_uriObject

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


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

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

#setup_handlerObject

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


94
95
96
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/msf/core/handler/reverse_udp.rb', line 94

def setup_handler
  ex = false

  comm = case datastore['ReverseListenerComm'].to_s
    when "local"; ::Rex::Socket::Comm::Local
    when /\A[0-9]+\Z/; framework.sessions[datastore['ReverseListenerComm'].to_i]
    else; nil
    end
  unless comm.is_a? ::Rex::Socket::Comm
    comm = nil
  end

  local_port = bind_port
  addrs = bind_address

  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

      comm_used = comm || Rex::Socket::SwitchBoard.best_comm( ip )
      comm_used = Rex::Socket::Comm::Local if comm_used == nil

      if( comm_used.respond_to?( :type ) and comm_used.respond_to?( :sid ) )
        via = "via the #{comm_used.type} on session #{comm_used.sid}"
      else
        via = ""
      end

      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_handlerObject

Starts monitoring for an inbound connection.


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
229
230
231
# File 'lib/msf/core/handler/reverse_udp.rb', line 160

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, peerhost, peerport = self.listener_sock.recvfrom
        next if peerhost.nil?
        cli_opts = {
          'PeerPort' => peerport,
          'PeerHost' => peerhost,
          'LocalPort' => self.listener_sock.localport,
          'Comm' => self.listener_sock.respond_to?(:comm) ? self.listener_sock.comm : nil
        }

        # 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#{[email protected].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_handlerObject

Stops monitoring for an inbound connection.


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

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