metasploit-framework/lib/rex/io/socket_abstraction.rb

206 lines
4.3 KiB
Ruby
Raw Normal View History

Implement consistent socket abstraction In current nomenclature, Rex Sockets are objects created by calls to Rex::Socket::<Transport>.create and Rex::Socket.create_... When the LocalHost or Comm parameters are set to remotely routed addresses (currently via Meterpreter sessions), Rex will create a Channel which will abstract communications with the remote end of the session. These channel based abstractions are called pivots, and present in three separate flavors: 1 - TcpClientChannel, a fully abstracted, selectable Socket. 2 - TcpServerChannel, a virtual Channel which distributes client channels. 3 - UdpChannel, a virtual Channel which provides common methods for UDP socket operations, but is not a full (selectable) abstraction. Unfortunately this differentiation results in inconsistent returns from the aforementioned socket creation calls, as the call chain creates parameters and supplies them to the create method on the comm object referenced in the params. The comm object may be a channel, and produce a virtual representation of a socket with functional methods analogous to Sockets, but without a kernel FD. This commit begins the work of ensuring that all calls for socket creation return selectable Rex::Socket objects with semantics familiar to Ruby developers who have not read into the details of Rex::Socket and Rex::Post. ----- Summary of changes: Convert Rex::IO::StreamAbstraction to SocketAbstraction and use the new mixin in StreamAbstraction and DatagramAbstraction. This approach allows for common methods to reuse the abstraction data flow, while initializing separate types of socket obects and an optional monitor as needed. In the Rex::Post::Meterpreter namespace, extract common methods from Stream to a SocketAbstraction mixin, include that mixin in Stream, and add Datagram with the dio_write handler override exported from the current implementation of UdpChannel, also using the mixin. This relies on the Rex::IO work above to implement the proper type of socket abstraction to the Channel descendants. In Rex::Post::Meterpreter::Extensions::Stdapi::Net, convert the UdpChannel to inherit from the Rex::Post::Meterpreter::Datagram class, implementing only the send method at this tier. Convert create_udp_channel to return the local socket side of the datagram abstraction presented analogous to the TcpClientChannel approach used before. ----- Notes and intricacies: In order to implement recvfrom on the UDP abstraction, a shim layer has been put in place to forward the sockaddr information from the remote peer to the local UDP socketpair in the abstraction. This information takes up buffer space in the UDP socket, and in order to maintain compatibility with consumers, the dio_write_handler pushes the data buffer, and in a separate send call, he sockaddr information from the remote socket. On the abstraction side, the recvfrom_nonblock call of the real UDPSocket has been overriden via the mixed in module to call the real method twice, once for the data buffer, and once for the packed sockaddr data. The Rex level consumer for recvfrom calls the underlying nonblock method and expects this exact set of returns (as opposed to what standard library UDPSocket.recvfrom returns, which is a data buffer and an Array of sockaddr data). ----- Testing: Local and lab testing only so far. Test RC script to be added in GH comments. ----- Issues: Currently, sendto on a remote socket does not appear to honor LocalPort which causes DNS responses (#6611) to come from the wrong port to remote clients being serviced over a pivot socket.
2016-03-21 04:53:34 +00:00
# -*- coding: binary -*-
require 'socket'
require 'fcntl'
module Rex
module IO
###
#
# This class provides an abstraction to a stream based
# connection through the use of a streaming socketpair.
#
###
module SocketAbstraction
###
#
# Extension information for required Stream interface.
#
###
module Ext
#
# Initializes peer information.
#
def initinfo(peer,local)
@peer = peer
@local = local
end
#
# Symbolic peer information.
#
def peerinfo
(@peer || "Remote Pipe")
end
#
# Symbolic local information.
#
def localinfo
(@local || "Local Pipe")
end
end
#
# Override this method to init the abstraction
#
def initialize_abstraction
self.lsock, self.rsock = Rex::Compat.pipe
end
#
# This method cleans up the abstraction layer.
#
def cleanup_abstraction
self.lsock.close if (self.lsock and !self.lsock.closed?)
self.rsock.close if (self.rsock and !self.rsock.closed?)
self.lsock = nil
self.rsock = nil
end
#
# Low-level write to the local side.
#
def syswrite(buffer)
lsock.syswrite(buffer)
end
#
# Low-level read from the local side.
#
def sysread(length)
lsock.sysread(length)
end
#
# Shuts down the local side of the stream abstraction.
#
def shutdown(how)
lsock.shutdown(how)
end
#
# Closes both sides of the stream abstraction.
#
def close
cleanup_abstraction
super
end
#
# Symbolic peer information.
#
def peerinfo
"Remote-side of Pipe"
end
#
# Symbolic local information.
#
def localinfo
"Local-side of Pipe"
end
#
# The left side of the stream.
#
attr_reader :lsock
#
# The right side of the stream.
#
attr_reader :rsock
protected
def monitor_rsock(threadname = "SocketMonitorRemote")
self.monitor_thread = Rex::ThreadFactory.spawn(threadname, false) {
loop do
closed = false
buf = nil
if not self.rsock
wlog("monitor_rsock: the remote socket is nil, exiting loop")
break
end
begin
s = Rex::ThreadSafe.select( [ self.rsock ], nil, nil, 0.2 )
if( s == nil || s[0] == nil )
next
end
rescue Exception => e
wlog("monitor_rsock: exception during select: #{e.class} #{e}")
closed = true
end
if( closed == false )
begin
buf = self.rsock.sysread( 32768 )
if buf == nil
closed = true
wlog("monitor_rsock: closed remote socket due to nil read")
end
rescue EOFError => e
closed = true
dlog("monitor_rsock: EOF in rsock")
rescue ::Exception => e
closed = true
wlog("monitor_rsock: exception during read: #{e.class} #{e}")
end
end
if( closed == false )
total_sent = 0
total_length = buf.length
while( total_sent < total_length )
begin
data = buf[total_sent, buf.length]
# Note that this must be write() NOT syswrite() or put() or anything like it.
# Using syswrite() breaks SSL streams.
sent = self.write( data )
# sf: Only remove the data off the queue is write was successfull.
# This way we naturally perform a resend if a failure occured.
# Catches an edge case with meterpreter TCP channels where remote send
# failes gracefully and a resend is required.
if (sent.nil?)
closed = true
wlog("monitor_rsock: failed writing, socket must be dead")
break
elsif (sent > 0)
total_sent += sent
end
rescue ::IOError, ::EOFError => e
closed = true
wlog("monitor_rsock: exception during write: #{e.class} #{e}")
break
end
end
end
if( closed )
begin
self.close_write if self.respond_to?('close_write')
rescue IOError
end
break
end
end
}
end
protected
attr_accessor :monitor_thread
attr_writer :lsock
attr_writer :rsock
end
end; end