Module: Rex::Socket

Included in:
Proto::DHCP::Server, Ip, Tcp, TcpServer, Udp
Defined in:
lib/rex/socket.rb,
lib/rex/socket/comm.rb,
lib/rex/socket/range_walker.rb,
lib/rex/socket/switch_board.rb,
lib/rex/socket/subnet_walker.rb

Overview

Base class for all sockets.

Defined Under Namespace

Modules: Comm, Ip, SslTcp, SslTcpServer, Tcp, TcpServer, Udp Classes: Parameters, Range, RangeWalker, SubnetWalker, SwitchBoard, UnitTest

Constant Summary collapse

@@support_ipv6 =

Cache our IPv6 support flag

nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#contextObject

Contextual information that describes the source and other instance-specific attributes. This comes from the param.context attribute.



666
667
668
# File 'lib/rex/socket.rb', line 666

def context
  @context
end

#ipvObject

The IP version of the socket



660
661
662
# File 'lib/rex/socket.rb', line 660

def ipv
  @ipv
end

#localhostObject

The local host of the connected socket.



652
653
654
# File 'lib/rex/socket.rb', line 652

def localhost
  @localhost
end

#localportObject

The local port of the connected socket.



656
657
658
# File 'lib/rex/socket.rb', line 656

def localport
  @localport
end

#peerhostObject

The peer host of the connected socket.



644
645
646
# File 'lib/rex/socket.rb', line 644

def peerhost
  @peerhost
end

#peerportObject

The peer port of the connected socket.



648
649
650
# File 'lib/rex/socket.rb', line 648

def peerport
  @peerport
end

Class Method Details

.addr_atoc(mask) ⇒ Object

Converts an ASCII IP address to a CIDR mask. Returns nil if it’s not convertable.



243
244
245
246
247
248
249
250
251
252
253
# File 'lib/rex/socket.rb', line 243

def self.addr_atoc(mask)
	mask_i = resolv_nbo_i(mask)
	cidr = nil
	0.upto(32) do |i|
		if ((1 << i)-1) << (32-i) == mask_i
			cidr = i
			break
		end
	end
	return cidr
end

.addr_atoi(addr) ⇒ Object

Converts a ascii address into an integer



274
275
276
# File 'lib/rex/socket.rb', line 274

def self.addr_atoi(addr)
	resolv_nbo_i(addr)
end

.addr_aton(addr) ⇒ Object

Converts a ascii address to network byte order



297
298
299
# File 'lib/rex/socket.rb', line 297

def self.addr_aton(addr)
	resolv_nbo(addr)
end

.addr_ctoa(cidr) ⇒ Object

Resolves a CIDR bitmask into a dotted-quad. Returns nil if it’s not convertable.



259
260
261
262
# File 'lib/rex/socket.rb', line 259

def self.addr_ctoa(cidr)
	return nil unless (0..32) === cidr.to_i
	addr_itoa(((1 << cidr)-1) << 32-cidr)
end

.addr_itoa(addr, v6 = false) ⇒ Object

Converts an integer address into ascii



281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/rex/socket.rb', line 281

def self.addr_itoa(addr, v6=false)

	nboa = addr_iton(addr, v6)

	# IPv4
	if (addr < 0x100000000 and not v6)
		nboa.unpack('C4').join('.')
	# IPv6
	else
		nboa.unpack('n8').map{ |c| "%.4x" % c }.join(":")
	end
end

.addr_iton(addr, v6 = false) ⇒ Object

Converts an integer into a network byte order address



342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/rex/socket.rb', line 342

def self.addr_iton(addr, v6=false)
	if(addr < 0x100000000 and not v6)
		return [addr].pack('N')
	else
		w    = []
		w[0] = (addr >> 96) & 0xffffffff
		w[1] = (addr >> 64) & 0xffffffff
		w[2] = (addr >> 32) & 0xffffffff
		w[3] = addr & 0xffffffff
		return w.pack('N4')
	end
end

.addr_ntoa(addr) ⇒ Object

Converts a network byte order address to ascii

Raises:



304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/rex/socket.rb', line 304

def self.addr_ntoa(addr)

	# IPv4
	if (addr.length == 4)
		return addr.unpack('C4').join('.')
	end

	# IPv6
	if (addr.length == 16)
		return addr.unpack('n8').map{ |c| "%.4x" % c }.join(":")
	end

	raise RuntimeError, "Invalid address format"
end

.addr_ntoi(addr) ⇒ Object

Converts a network byte order address to an integer

Raises:



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/rex/socket.rb', line 322

def self.addr_ntoi(addr)

	bits = addr.unpack("N*")

	if (bits.length == 1)
		return bits[0]
	end

	if (bits.length == 4)
		val = 0
		bits.each_index { |i| val += (  bits[i] << (96 - (i * 32)) ) }
		return val
	end

	raise RuntimeError, "Invalid address format"
end

.bit2netmask(bitmask) ⇒ Object

Converts a bitmask (28) into a netmask (255.255.255.240) TODO: IPv6 (use is ambiguous right now)



409
410
411
# File 'lib/rex/socket.rb', line 409

def self.bit2netmask(bitmask)
	[ (~((2 ** (32 - bitmask)) - 1)) & 0xffffffff ].pack('N').unpack('CCCC').join('.')
end

.cidr_crack(cidr, v6 = false) ⇒ Object

Converts a CIDR subnet into an array (base, bcast)



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/rex/socket.rb', line 358

def self.cidr_crack(cidr, v6=false)
	tmp = cidr.split('/')

	tst,scope = tmp[0].split("%",2)
	scope     = "%" + scope if scope
	scope   ||= ""

	addr = addr_atoi(tst)

	bits = 32
	mask = 0
	use6 = false

	if (addr > 0xffffffff or v6 or cidr =~ /:/)
		use6 = true
		bits = 128
	end

	mask = (2 ** bits) - (2 ** (bits - tmp[1].to_i))
	base = addr & mask

	stop = base + (2 ** (bits - tmp[1].to_i)) - 1
	return [self.addr_itoa(base, use6) + scope, self.addr_itoa(stop, use6) + scope]
end

.create(opts = {}) ⇒ Object

Create a socket instance using the supplied parameter hash.



38
39
40
# File 'lib/rex/socket.rb', line 38

def self.create(opts = {})
	return create_param(Rex::Socket::Parameters.from_hash(opts))
end

.create_ip(opts = {}) ⇒ Object

Create a IP socket using the supplied parameter hash.



73
74
75
# File 'lib/rex/socket.rb', line 73

def self.create_ip(opts = {})
	return create_param(Rex::Socket::Parameters.from_hash(opts.merge('Proto' => 'ip')))
end

.create_param(param) ⇒ Object

Create a socket using the supplied Rex::Socket::Parameter instance.



45
46
47
# File 'lib/rex/socket.rb', line 45

def self.create_param(param)
	return param.comm.create(param)
end

.create_tcp(opts = {}) ⇒ Object

Create a TCP socket using the supplied parameter hash.



52
53
54
# File 'lib/rex/socket.rb', line 52

def self.create_tcp(opts = {})
	return create_param(Rex::Socket::Parameters.from_hash(opts.merge('Proto' => 'tcp')))
end

.create_tcp_server(opts = {}) ⇒ Object

Create a TCP server socket using the supplied parameter hash.



59
60
61
# File 'lib/rex/socket.rb', line 59

def self.create_tcp_server(opts = {})
	return create_tcp(opts.merge('Server' => true))
end

.create_udp(opts = {}) ⇒ Object

Create a UDP socket using the supplied parameter hash.



66
67
68
# File 'lib/rex/socket.rb', line 66

def self.create_udp(opts = {})
	return create_param(Rex::Socket::Parameters.from_hash(opts.merge('Proto' => 'udp')))
end

.dotted_ip?(addr) ⇒ Boolean

Checks to see if the supplied address is a dotted quad.

Returns:

  • (Boolean)


126
127
128
129
130
131
132
# File 'lib/rex/socket.rb', line 126

def self.dotted_ip?(addr)
	# Assume anything with a colon is IPv6
	return true if (support_ipv6? and addr =~ /:/)

	# Otherwise assume this is IPv4
	(addr =~ /^(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))$/) ? true : false
end

.from_sockaddr(saddr) ⇒ Object

Returns the address family, host, and port of the supplied sockaddr as

af, host, port


216
217
218
219
220
221
222
223
# File 'lib/rex/socket.rb', line 216

def self.from_sockaddr(saddr)
	port, host = ::Socket::unpack_sockaddr_in(saddr)
	af = ::Socket::AF_INET
	if (support_ipv6?() and is_ipv6?(host))
		af = ::Socket::AF_INET6
	end
	return [ af, host, port ]
end

.getaddress(addr, accept_ipv6 = true) ⇒ Object

Wrapper for Resolv.getaddress that takes special care to see if the supplied address is already a dotted quad, for instance. This is necessary to prevent calls to gethostbyaddr (which occurs on windows). These calls can be quite slow. This also fixes an issue with the Resolv.getaddress() call being non-functional on Ruby 1.9.1 (Win32).



153
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
# File 'lib/rex/socket.rb', line 153

def self.getaddress(addr, accept_ipv6 = true)
	begin
	
		if dotted_ip?(addr)
			return addr
		end
		
		res = ::Socket.gethostbyname(addr)
		return nil if not res
		
		# Shift the first three elements out
		rname  = res.shift
		ralias = res.shift
		rtype  = res.shift
		
		# Reject IPv6 addresses if we don't accept them			
		if not accept_ipv6
			res.reject!{|nbo| nbo.length != 4}
		end
		
		# Make sure we have at least one name
		return nil if res.length == 0			
		
		# Return the first address of the result
		self.addr_ntoa( res[0] )
	rescue ::ArgumentError # Win32 bug
		nil
	end
end

.gethostbyname(host) ⇒ Object

Wrapper for Socket.gethostbyname which takes into account whether or not an IP address is supplied. If it is, then reverse DNS resolution does not occur. This is done in order to prevent delays, such as would occur on Windows.



189
190
191
192
193
194
195
196
197
# File 'lib/rex/socket.rb', line 189

def self.gethostbyname(host)
	if (dotted_ip?(host))
		if (is_ipv4?(host))
			return [ host, host, 2, host.split('.').map{ |c| c.to_i }.pack("C4") ]
		end
	end

	::Socket.gethostbyname(host)
end

Identifies the link-local address of a given interface (if IPv6 is enabled)



505
506
507
508
509
# File 'lib/rex/socket.rb', line 505

def self.ipv6_link_address(intf)
	r = source_address("FF02::1%#{intf}")
	return if not (r and r =~ /^fe80/i)
	r
end

.ipv6_mac(intf) ⇒ Object

Identifies the mac address of a given interface (if IPv6 is enabled)



514
515
516
517
518
519
# File 'lib/rex/socket.rb', line 514

def self.ipv6_mac(intf)
	r = ipv6_link_address(intf)
	return if not r
	raw = addr_aton(r)[-8, 8]
	(raw[0,3] + raw[5,3]).unpack("C*").map{|c| "%.2x" % c}.join(":")
end

.is_internal?(addr) ⇒ Boolean

Return true if addr is within the ranges specified in RFC1918, or RFC5735/RFC3927

Returns:

  • (Boolean)


138
139
140
141
142
143
144
# File 'lib/rex/socket.rb', line 138

def self.is_internal?(addr)
	if self.dotted_ip?(addr)
		addr =~ /^(?:10\.|192\.168|172.(?:1[6-9]|2[0-9]|3[01])\.|169\.254)/
	else
		false
	end
end

.is_ipv4?(addr) ⇒ Boolean

Determine whether this is an IPv4 address

Returns:

  • (Boolean)


110
111
112
113
# File 'lib/rex/socket.rb', line 110

def self.is_ipv4?(addr)
	res = Rex::Socket.getaddress(addr)
	res.match(/:/) ? false : true
end

.is_ipv6?(addr) ⇒ Boolean

Determine whether this is an IPv6 address

Returns:

  • (Boolean)


118
119
120
121
# File 'lib/rex/socket.rb', line 118

def self.is_ipv6?(addr)
	res = Rex::Socket.getaddress(addr)
	res.match(/:/) ? true : false
end

.net2bitmask(netmask) ⇒ Object

Converts a netmask (255.255.255.240) into a bitmask (28). This is the lame kid way of doing it.



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/rex/socket.rb', line 387

def self.net2bitmask(netmask)

	nmask = resolv_nbo(netmask)
	imask = addr_ntoi(nmask)
	bits  = 32

	if (imask > 0xffffffff)
		bits = 128
	end

	0.upto(bits-1) do |bit|
		p = 2 ** bit
		return (bits - bit) if ((imask & p) == p)
	end

	0
end

.portlist_to_portspec(parr) ⇒ Object

Converts a port list like [1,2,3,4,5,100] into a range specification like “1-5,100”



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/rex/socket.rb', line 445

def self.portlist_to_portspec(parr)
	ranges = []
	range  = []
	lastp  = nil

	parr.uniq.sort{|a,b| a<=>b}.map{|a| a.to_i}.each do |n|
		next if (n < 1 or n > 65535)
		if not lastp
			range = [n]
			lastp = n
			next
		end

		if lastp == n - 1
			range << n
		else
			ranges << range
			range = [n]
		end
		lastp = n
	end

	ranges << range
	ranges.delete(nil)
	ranges.uniq.map{|x| x.length == 1 ? "#{x[0]}" : "#{x[0]}-#{x[-1]}"}.join(",")
end

.portspec_crack(pspec) ⇒ Object



414
415
416
# File 'lib/rex/socket.rb', line 414

def self.portspec_crack(pspec)
	portspec_to_portlist(pspec)
end

.portspec_to_portlist(pspec) ⇒ Object

Converts a port specification like “80,21-23,443” into a sorted, unique array of valid port numbers like [21,22,23,80,443]



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/rex/socket.rb', line 422

def self.portspec_to_portlist(pspec)
	ports = []

	# Build ports array from port specification
	pspec.split(/,/).each do |item|
		start, stop = item.split(/-/).map { |p| p.to_i }

		start ||= 0
		stop ||= item.match(/-/) ? 65535 : start

		start, stop = stop, start if stop < start

		start.upto(stop) { |p| ports << p }
	end

	# Sort, and remove dups and invalid ports
	ports.sort.uniq.delete_if { |p| p < 1 or p > 65535 }
end

.resolv_nbo(host) ⇒ Object

Resolves a host to raw network-byte order.



228
229
230
# File 'lib/rex/socket.rb', line 228

def self.resolv_nbo(host)
	self.gethostbyname(Rex::Socket.getaddress(host))[3]
end

.resolv_nbo_i(host) ⇒ Object

Resolves a host to a network-byte order ruby integer.



235
236
237
# File 'lib/rex/socket.rb', line 235

def self.resolv_nbo_i(host)
	addr_ntoi(resolv_nbo(host))
end

.resolv_to_dotted(host) ⇒ Object

Resolves a host to a dotted address.



267
268
269
# File 'lib/rex/socket.rb', line 267

def self.resolv_to_dotted(host)
	addr_ntoa(addr_aton(host))
end

.source_address(dest = '8.8.8.8', comm = ::Rex::Socket::Comm::Local) ⇒ Object

This method does NOT send any traffic to the destination, instead, it uses a “bound” UDP socket to determine what source address we would use to communicate with the specified destination. The destination defaults to Google’s DNS server to make the standard behavior determine which IP we would use to communicate with the internet.



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/rex/socket.rb', line 485

def self.source_address(dest='8.8.8.8', comm = ::Rex::Socket::Comm::Local)
	begin
		s = self.create_udp(
			'PeerHost' => dest,
			'PeerPort' => 31337,
			'Comm'     => comm
		)
		r = s.getsockname[1]
		s.close
		
		# Trim off the trailing interface ID for link-local IPv6
		return r.split('%').first
	rescue ::Exception
		return '127.0.0.1'
	end
end

.support_ipv6?Boolean

Determine whether we support IPv6

Returns:

  • (Boolean)


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/rex/socket.rb', line 90

def self.support_ipv6?
	return @@support_ipv6 if not @@support_ipv6.nil?

	@@support_ipv6 = false

	if (::Socket.const_defined?('AF_INET6'))
		begin
			s = ::Socket.new(::Socket::AF_INET6, ::Socket::SOCK_DGRAM, ::Socket::IPPROTO_UDP)
			s.close
			@@support_ipv6 = true
		rescue
		end
	end

	return @@support_ipv6
end

.tcp_socket_pairObject

Create a TCP socket pair.

sf: This create a socket pair using native ruby sockets and will work on Windows where ::Socket.pair is not implemented. Note: OpenSSL requires native ruby sockets for its io.

Note: Even though sub-threads are smashing the parent threads local, there

is no concurrent use of the same locals and this is safe.


530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/rex/socket.rb', line 530

def self.tcp_socket_pair
	lsock   = nil
	rsock   = nil
	laddr   = '127.0.0.1'
	lport   = 0
	threads = []
	mutex   = ::Mutex.new

	threads << Rex::ThreadFactory.spawn('TcpSocketPair', false) {
		server = nil
		mutex.synchronize {
			threads << Rex::ThreadFactory.spawn('TcpSocketPairClient', false) {
				mutex.synchronize {
					rsock = ::TCPSocket.new( laddr, lport )
				}
			}
			server = ::TCPServer.new(laddr, 0)
			if (server.getsockname =~ /127\.0\.0\.1:/)
				# JRuby ridiculousness
				caddr, lport = server.getsockname.split(":")
				caddr = caddr[1,caddr.length]
				lport = lport.to_i
			else
				# Sane implementations where Socket#getsockname returns a
				# sockaddr
				lport, caddr = ::Socket.unpack_sockaddr_in( server.getsockname )
			end
		}
		lsock, saddr = server.accept
		server.close
	}

	threads.each { |t| t.join }

	return [lsock, rsock]
end

.to_sockaddr(ip, port) ⇒ Object

Create a sockaddr structure using the supplied IP address, port, and address family



203
204
205
206
207
208
209
210
# File 'lib/rex/socket.rb', line 203

def self.to_sockaddr(ip, port)

	if (ip == '::ffff:0.0.0.0')
		ip = support_ipv6?() ? '::' : '0.0.0.0'
	end

	return ::Socket.pack_sockaddr_in(port, ip)
end

.udp_socket_pairObject

Create a UDP socket pair using native ruby UDP sockets.



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/rex/socket.rb', line 570

def self.udp_socket_pair
	laddr = '127.0.0.1'

	lsock = ::UDPSocket.new
	lsock.bind( laddr, 0 )

	rsock = ::UDPSocket.new
	rsock.bind( laddr, 0 )

	rsock.connect( *lsock.addr.values_at(3,1) )

	lsock.connect( *rsock.addr.values_at(3,1) )

	return [lsock, rsock]
end

Instance Method Details

#fdObject

By default, all sockets are themselves selectable file descriptors.



609
610
611
# File 'lib/rex/socket.rb', line 609

def fd
	self
end

#getlocalnameObject

Wrapper around getsockname



623
624
625
# File 'lib/rex/socket.rb', line 623

def getlocalname
	getsockname
end

#getpeernameObject

Return peer connection information.



630
631
632
# File 'lib/rex/socket.rb', line 630

def getpeername
	return Socket.from_sockaddr(super)
end

#getsocknameObject

Returns local connection information.



616
617
618
# File 'lib/rex/socket.rb', line 616

def getsockname
	Socket.from_sockaddr(super)
end

#initsock(params = nil) ⇒ Object

Initialize general socket parameters.



595
596
597
598
599
600
601
602
603
604
# File 'lib/rex/socket.rb', line 595

def initsock(params = nil)
	if (params)
		self.peerhost  = params.peerhost
		self.peerport  = params.peerport
		self.localhost = params.localhost
		self.localport = params.localport
		self.context   = params.context || {}
		self.ipv       = params.v6 ? 6 : 4
	end
end

#type?Boolean

Returns a string that indicates the type of the socket, such as ‘tcp’.

Returns:

  • (Boolean)

Raises:



637
638
639
# File 'lib/rex/socket.rb', line 637

def type?
	raise NotImplementedError, "Socket type is not supported."
end