Module: Rex::Socket
- Defined in:
- lib/rex/socket.rb,
lib/rex/socket/comm.rb,
lib/rex/socket/version.rb,
lib/rex/socket/ssh_factory.rb,
lib/rex/socket/range_walker.rb,
lib/rex/socket/switch_board.rb,
lib/rex/socket/subnet_walker.rb,
lib/rex/socket/x509_certificate.rb
Overview
Base class for all sockets.
Defined Under Namespace
Modules: Comm, Ip, Sctp, SctpServer, Ssl, SslTcp, SslTcpServer, Tcp, TcpServer, Udp Classes: Host, Parameters, Range, RangeWalker, SSHFactory, SubnetWalker, SwitchBoard, X509Certificate
Constant Summary collapse
- LogSource =
'rex-socket'
- MATCH_DNS_NAME =
/^(((?!-))(xn--)?([a-z0-9_][a-z0-9_\-]{0,59})?[a-z0-9_]\.)*(xn--)?([a-z0-9_\-]{1,61}|[a-z0-9_-]{1,30}\.[a-z]{2,})$/i
- MATCH_IPV6 =
/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
- MATCH_IPV4 =
/^\s*(?:(?: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}))\s*$/
- MATCH_IPV4_PRIVATE =
/^\s*(?:10\.|192\.168|172.(?:1[6-9]|2[0-9]|3[01])\.|169\.254)/
- MATCH_MAC_ADDR =
/^(?:[[:xdigit:]]{2}([-:]))(?:[[:xdigit:]]{2}\1){4}[[:xdigit:]]{2}$/
- VERSION =
"0.1.58"
- @@support_ipv6 =
Cache our IPv6 support flag
nil
- @@resolver =
Cache our resolver
nil
Instance Attribute Summary collapse
-
#context ⇒ Object
readonly
Contextual information that describes the source and other instance-specific attributes.
-
#ipv ⇒ Object
readonly
The IP version of the socket.
-
#localhost ⇒ Object
readonly
The local host of the connected socket.
-
#localport ⇒ Object
readonly
The local port of the connected socket.
-
#peerhost ⇒ Object
readonly
The peer host of the connected socket.
-
#peerhostname ⇒ Object
readonly
The peer hostname of the connected socket.
-
#peerport ⇒ Object
readonly
The peer port of the connected socket.
Class Method Summary collapse
-
._install_global_resolver(res) ⇒ Rex::Proto::DNS::CachedResolver
Install Rex::Proto::DNS::CachedResolver, or similar, to pivot DNS.
-
.addr_atoc(mask) ⇒ Object
Converts an ASCII IP address to a CIDR mask.
-
.addr_atoi(addr) ⇒ Object
Converts a ascii address into an integer.
-
.addr_atoi_list(addr) ⇒ Object
Converts a ascii address into a list of addresses.
-
.addr_aton(addr) ⇒ Object
Converts a ascii address to network byte order.
-
.addr_ctoa(cidr, v6: false) ⇒ Object
Resolves a CIDR bitmask into a dotted-quad.
-
.addr_itoa(addr, v6 = false) ⇒ Object
Converts an integer address into ascii.
-
.addr_iton(addr, v6 = false) ⇒ Object
Converts an integer into a network byte order address.
-
.addr_ntoa(addr) ⇒ String
Converts a network byte order address to ascii.
-
.addr_ntoi(addr) ⇒ Object
Converts a network byte order address to an integer.
-
.bit2netmask(bitmask, ipv6 = false) ⇒ Object
Converts a bitmask (28) into a netmask (255.255.255.240).
-
.cidr_crack(cidr, v6 = false) ⇒ Object
Converts a CIDR subnet into an array (base, bcast).
-
.compress_address(addr) ⇒ String
Implement zero compression for IPv6 addresses.
-
.create(opts = {}) ⇒ Object
Create a socket instance using the supplied parameter hash.
-
.create_ip(opts = {}) ⇒ Object
Create a IP socket using the supplied parameter hash.
-
.create_param(param) ⇒ Object
Create a socket using the supplied Rex::Socket::Parameter instance.
-
.create_tcp(opts = {}) ⇒ Object
Create a TCP socket using the supplied parameter hash.
-
.create_tcp_server(opts = {}) ⇒ Object
Create a TCP server socket using the supplied parameter hash.
-
.create_udp(opts = {}) ⇒ Object
Create a UDP socket using the supplied parameter hash.
-
.dotted_ip?(addr) ⇒ Boolean
Checks to see if the supplied address is in “dotted” form.
-
.eth_aton(mac) ⇒ Object
Converts a colon-delimited MAC address into a 6-byte binary string.
-
.eth_ntoa(bin) ⇒ Object
Converts a 6-byte binary string into a colon-delimited MAC address.
-
.from_sockaddr(saddr) ⇒ Object
Returns the address family, host, and port of the supplied sockaddr as [ af, host, port ].
-
.getaddress(hostname, accept_ipv6 = true) ⇒ String
Get the first address returned by a DNS lookup for
hostname
. -
.getaddresses(hostname, accept_ipv6 = true) ⇒ Array<String>
Wrapper for
::Addrinfo.getaddrinfo
that takes special care to see if the supplied address is already an ASCII IP address. -
.gethostbyname(host) ⇒ Object
deprecated
Deprecated.
Please use #getaddress, #resolv_nbo, or similar instead.
-
.getresources(name, typeclass) ⇒ Array<String>
Wrapper for Resolv::DNS.getresources which normalizes the return value to a list of hostnames regardless of the resource class.
-
.ipv6_link_address(intf) ⇒ Object
Identifies the link-local address of a given interface (if IPv6 is enabled).
-
.ipv6_mac(intf) ⇒ Object
Identifies the mac address of a given interface (if IPv6 is enabled).
-
.is_internal?(addr) ⇒ Boolean
Return true if
addr
is within the ranges specified in RFC1918, or RFC5735/RFC3927. -
.is_ip_addr?(addr) ⇒ Boolean
Determine whether this is an IP address at all Check for v4 (less expensive), v6, else false.
-
.is_ipv4?(addr) ⇒ Boolean
Determine whether this is an IPv4 address.
-
.is_ipv6?(addr) ⇒ Boolean
Determine whether this is an IPv6 address.
-
.is_mac_addr?(addr) ⇒ Boolean
Determine whether this is a MAC address.
-
.is_name?(name) ⇒ Boolean
Determine whether this is a valid DNS name without trying to resolve it.
-
.net2bitmask(netmask) ⇒ Object
Converts a netmask (255.255.255.240) into a bitmask (28).
-
.portlist_to_portspec(parr) ⇒ Object
Converts a port list like [1,2,3,4,5,100] into a range specification like “1-5,100”.
- .portspec_crack(pspec) ⇒ Object
-
.portspec_to_portlist(pspec) ⇒ Object
Converts a port specification like “80,21-25,!24,443” into a sorted, unique array of valid port numbers like [21,22,23,25,80,443].
-
.resolv_nbo(host, accepts_ipv6 = true) ⇒ Object
Resolves a host to raw network-byte order.
-
.resolv_nbo_i(host) ⇒ Object
Resolves a host to a network-byte order ruby integer.
-
.resolv_nbo_i_list(host) ⇒ Object
Resolves a host to a list of network-byte order ruby integers.
-
.resolv_nbo_list(host) ⇒ Object
Resolves a host to raw network-byte order.
-
.resolv_to_dotted(host) ⇒ Object
Resolves a host to a dotted address.
-
.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.
-
.support_ipv6? ⇒ Boolean
Determine whether we support IPv6.
-
.tcp_socket_pair ⇒ Object
Create a TCP socket pair.
-
.to_authority(host, port = nil) ⇒ String
Checks to see if an address is an IPv6 address and if so, converts it into its square bracket format for addressing as noted in RFC 6874 which states that an IPv6 address literal in a URL is always embedded between [ and ].
-
.to_sockaddr(ip, port) ⇒ Object
Create a sockaddr structure using the supplied IP address, port, and address family.
-
.udp_socket_pair ⇒ Object
Create a UDP socket pair using native ruby UDP sockets.
Instance Method Summary collapse
-
#fd ⇒ Object
By default, all sockets are themselves selectable file descriptors.
-
#getlocalname ⇒ Object
Wrapper around getsockname that stores the local address and local port values.
-
#getpeername_as_array ⇒ Object
Returns peer connection information as an array.
-
#getsockname ⇒ Object
Returns local connection information.
-
#initsock(params = nil) ⇒ Object
Initialize general socket parameters.
-
#localinfo ⇒ Object
Returns local information (host + port) in host:port format.
-
#peerinfo ⇒ Object
Returns peer information (host + port) in host:port format.
-
#type? ⇒ Boolean
Returns a string that indicates the type of the socket, such as ‘tcp’.
Instance Attribute Details
#context ⇒ Object
Contextual information that describes the source and other instance-specific attributes. This comes from the param.context attribute.
911 912 913 |
# File 'lib/rex/socket.rb', line 911 def context @context end |
#ipv ⇒ Object
The IP version of the socket
905 906 907 |
# File 'lib/rex/socket.rb', line 905 def ipv @ipv end |
#localhost ⇒ Object
The local host of the connected socket.
897 898 899 |
# File 'lib/rex/socket.rb', line 897 def localhost @localhost end |
#localport ⇒ Object
The local port of the connected socket.
901 902 903 |
# File 'lib/rex/socket.rb', line 901 def localport @localport end |
#peerhost ⇒ Object
The peer host of the connected socket.
885 886 887 |
# File 'lib/rex/socket.rb', line 885 def peerhost @peerhost end |
#peerhostname ⇒ Object
The peer hostname of the connected socket.
889 890 891 |
# File 'lib/rex/socket.rb', line 889 def peerhostname @peerhostname end |
#peerport ⇒ Object
The peer port of the connected socket.
893 894 895 |
# File 'lib/rex/socket.rb', line 893 def peerport @peerport end |
Class Method Details
._install_global_resolver(res) ⇒ Rex::Proto::DNS::CachedResolver
Install Rex::Proto::DNS::CachedResolver, or similar, to pivot DNS
790 791 792 |
# File 'lib/rex/socket.rb', line 790 def self._install_global_resolver(res) @@resolver = res end |
.addr_atoc(mask) ⇒ Object
Converts an ASCII IP address to a CIDR mask. Returns nil if it’s not convertable.
357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/rex/socket.rb', line 357 def self.addr_atoc(mask) bits = is_ipv6?(mask) ? 128 : 32 mask_i = resolv_nbo_i(mask) cidr = nil 0.upto(bits) do |i| if ((1 << i)-1) << (bits - i) == mask_i cidr = i break end end return cidr end |
.addr_atoi(addr) ⇒ Object
Converts a ascii address into an integer
391 392 393 |
# File 'lib/rex/socket.rb', line 391 def self.addr_atoi(addr) resolv_nbo_i(addr) end |
.addr_atoi_list(addr) ⇒ Object
Converts a ascii address into a list of addresses
398 399 400 |
# File 'lib/rex/socket.rb', line 398 def self.addr_atoi_list(addr) resolv_nbo_i_list(addr) end |
.addr_aton(addr) ⇒ Object
Converts a ascii address to network byte order
416 417 418 |
# File 'lib/rex/socket.rb', line 416 def self.addr_aton(addr) resolv_nbo(addr) end |
.addr_ctoa(cidr, v6: false) ⇒ Object
Resolves a CIDR bitmask into a dotted-quad. Returns nil if it’s not convertable.
374 375 376 377 378 379 |
# File 'lib/rex/socket.rb', line 374 def self.addr_ctoa(cidr, v6: false) bits = v6 ? 128 : 32 cidr = cidr.to_i return nil unless (0..bits) === cidr addr_itoa(((1 << cidr)-1) << bits-cidr, v6) end |
.addr_itoa(addr, v6 = false) ⇒ Object
Converts an integer address into ascii
407 408 409 410 411 |
# File 'lib/rex/socket.rb', line 407 def self.addr_itoa(addr, v6=false) nboa = addr_iton(addr, v6) addr_ntoa(nboa) end |
.addr_iton(addr, v6 = false) ⇒ Object
Converts an integer into a network byte order address
488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/rex/socket.rb', line 488 def self.addr_iton(addr, v6=false) if(addr < 0x100000000 && !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) ⇒ String
Converts a network byte order address to ascii
425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/rex/socket.rb', line 425 def self.addr_ntoa(addr) # IPv4 if (addr.length == 4) return addr.unpack('C4').join('.') end # IPv6 if (addr.length == 16) return compress_address(addr.unpack('n8').map{ |c| "%x" % c }.join(":")) end raise RuntimeError, "Invalid address format" end |
.addr_ntoi(addr) ⇒ Object
Converts a network byte order address to an integer
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
# File 'lib/rex/socket.rb', line 466 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, ipv6 = false) ⇒ Object
Converts a bitmask (28) into a netmask (255.255.255.240)
567 568 569 570 571 572 573 574 575 |
# File 'lib/rex/socket.rb', line 567 def self.bit2netmask(bitmask, ipv6=false) if bitmask > 32 or ipv6 i = ((~((2 ** (128 - bitmask)) - 1)) & (2**128-1)) n = Rex::Socket.addr_iton(i, true) return Rex::Socket.addr_ntoa(n) else [ (~((2 ** (32 - bitmask)) - 1)) & 0xffffffff ].pack('N').unpack('CCCC').join('.') end end |
.cidr_crack(cidr, v6 = false) ⇒ Object
Converts a CIDR subnet into an array (base, bcast)
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 |
# File 'lib/rex/socket.rb', line 518 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 |
.compress_address(addr) ⇒ String
Implement zero compression for IPv6 addresses. Uses the compression method from Marco Ceresa’s IPAddress GEM
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/rex/socket.rb', line 447 def self.compress_address(addr) return addr unless is_ipv6?(addr) addr = addr.dup while true break if addr.sub!(/\A0:0:0:0:0:0:0:0\Z/, '::') break if addr.sub!(/\b0:0:0:0:0:0:0\b/, ':') break if addr.sub!(/\b0:0:0:0:0:0\b/, ':') break if addr.sub!(/\b0:0:0:0:0\b/, ':') break if addr.sub!(/\b0:0:0:0\b/, ':') break if addr.sub!(/\b0:0:0\b/, ':') break if addr.sub!(/\b0:0\b/, ':') break end addr.sub(/:{3,}/, '::') end |
.create(opts = {}) ⇒ Object
Create a socket instance using the supplied parameter hash.
44 45 46 |
# File 'lib/rex/socket.rb', line 44 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.
79 80 81 |
# File 'lib/rex/socket.rb', line 79 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.
51 52 53 |
# File 'lib/rex/socket.rb', line 51 def self.create_param(param) return param.comm.create(param) end |
.create_tcp(opts = {}) ⇒ Object
Create a TCP socket using the supplied parameter hash.
58 59 60 |
# File 'lib/rex/socket.rb', line 58 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.
65 66 67 |
# File 'lib/rex/socket.rb', line 65 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.
72 73 74 |
# File 'lib/rex/socket.rb', line 72 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 in “dotted” form
172 173 174 |
# File 'lib/rex/socket.rb', line 172 def self.dotted_ip?(addr) (support_ipv6? && self.is_ipv6?(addr)) || self.is_ipv4?(addr) end |
.eth_aton(mac) ⇒ Object
Converts a colon-delimited MAC address into a 6-byte binary string
504 505 506 |
# File 'lib/rex/socket.rb', line 504 def self.eth_aton(mac) mac.split(":").map{|c| c.to_i(16) }.pack("C*") end |
.eth_ntoa(bin) ⇒ Object
Converts a 6-byte binary string into a colon-delimited MAC address
511 512 513 |
# File 'lib/rex/socket.rb', line 511 def self.eth_ntoa(bin) bin.unpack("C6").map{|x| "%.2x" % x }.join(":").upcase end |
.from_sockaddr(saddr) ⇒ Object
Returns the address family, host, and port of the supplied sockaddr as
- af, host, port
313 314 315 316 317 318 319 320 |
# File 'lib/rex/socket.rb', line 313 def self.from_sockaddr(saddr) port, host = ::Socket::unpack_sockaddr_in(saddr) af = ::Socket::AF_INET if support_ipv6?() && is_ipv6?(host) af = ::Socket::AF_INET6 end return [ af, host, port ] end |
.getaddress(hostname, accept_ipv6 = true) ⇒ String
Get the first address returned by a DNS lookup for hostname
.
216 217 218 |
# File 'lib/rex/socket.rb', line 216 def self.getaddress(hostname, accept_ipv6 = true) getaddresses(hostname, accept_ipv6).first end |
.getaddresses(hostname, accept_ipv6 = true) ⇒ Array<String>
Wrapper for ::Addrinfo.getaddrinfo
that takes special care to see if the supplied address is already an ASCII IP address. This is necessary to prevent blocking while waiting on a DNS reverse lookup when we already have what we need.
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
# File 'lib/rex/socket.rb', line 228 def self.getaddresses(hostname, accept_ipv6 = true) raise ::SocketError, 'getaddrinfo: nodename nor servname provided, or not known' if hostname.nil? if hostname =~ MATCH_IPV4 || (accept_ipv6 && hostname =~ MATCH_IPV6) return [hostname] end if @@resolver res = self.rex_getaddrinfo(hostname) else res = ::Addrinfo.getaddrinfo(hostname, 0, ::Socket::AF_UNSPEC, ::Socket::SOCK_STREAM) end res.map! do |address_info| address_info.ip_address end unless accept_ipv6 res.reject! { |ascii| ascii =~ MATCH_IPV6 } end res end |
.gethostbyname(host) ⇒ Object
Please use #getaddress, #resolv_nbo, or similar instead.
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.
259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/rex/socket.rb', line 259 def self.gethostbyname(host) warn "NOTE: #{self}.#{__method__} is deprecated, use getaddress, resolv_nbo, or similar instead. It will be removed in the next Major version" if is_ipv4?(host) return [ host, [], 2, host.split('.').map{ |c| c.to_i }.pack("C4") ] end if is_ipv6?(host) # pop off the scopeid since gethostbyname isn't smart enough to # deal with it. host, _ = host.split('%', 2) end @@resolver ? self.rex_gethostbyname(host) : ::Socket.gethostbyname(host) end |
.getresources(name, typeclass) ⇒ Array<String>
Wrapper for Resolv::DNS.getresources which normalizes the return value to a list of hostnames regardless of the resource class.
282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/rex/socket.rb', line 282 def self.getresources(name, typeclass) return self.rex_getresources(name, typeclass) if @@resolver typeclass = typeclass.upcase attribute = DNS_RESOURCE_ATTRIBUTE_NAMES[typeclass] if attribute.nil? raise ArgumentError, "Invalid typeclass: #{typeclass}" end const = Resolv::DNS::Resource::IN.const_get(typeclass) dns = Resolv::DNS.new resources = dns.getresources(name, const) resources.map(&attribute).map(&:to_s) end |
.ipv6_link_address(intf) ⇒ Object
Identifies the link-local address of a given interface (if IPv6 is enabled)
684 685 686 687 688 |
# File 'lib/rex/socket.rb', line 684 def self.ipv6_link_address(intf) r = source_address("FF02::1%#{intf}") return nil if r.nil? || r !~ /^fe80/i r end |
.ipv6_mac(intf) ⇒ Object
Identifies the mac address of a given interface (if IPv6 is enabled)
693 694 695 696 697 698 |
# File 'lib/rex/socket.rb', line 693 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
206 207 208 |
# File 'lib/rex/socket.rb', line 206 def self.is_internal?(addr) self.dotted_ip?(addr) && addr =~ MATCH_IPV4_PRIVATE end |
.is_ip_addr?(addr) ⇒ Boolean
Determine whether this is an IP address at all Check for v4 (less expensive), v6, else false
165 166 167 |
# File 'lib/rex/socket.rb', line 165 def self.is_ip_addr?(addr) self.is_ipv4?(addr) || self.is_ipv6?(addr) end |
.is_ipv4?(addr) ⇒ Boolean
Determine whether this is an IPv4 address
143 144 145 |
# File 'lib/rex/socket.rb', line 143 def self.is_ipv4?(addr) addr =~ MATCH_IPV4 ? (addr =~ /\s/).nil? : false end |
.is_ipv6?(addr) ⇒ Boolean
Determine whether this is an IPv6 address
150 151 152 |
# File 'lib/rex/socket.rb', line 150 def self.is_ipv6?(addr) addr =~ MATCH_IPV6 ? (addr =~ /\s/).nil? : false end |
.is_mac_addr?(addr) ⇒ Boolean
Determine whether this is a MAC address
157 158 159 |
# File 'lib/rex/socket.rb', line 157 def self.is_mac_addr?(addr) addr =~ MATCH_MAC_ADDR ? (addr =~ /\s/).nil? : false end |
.is_name?(name) ⇒ Boolean
Determine whether this is a valid DNS name without trying to resolve it
135 136 137 138 |
# File 'lib/rex/socket.rb', line 135 def self.is_name?(name) return false if name.length > 253 name.delete_suffix('.') =~ MATCH_DNS_NAME ? (name =~ /\s/).nil? : 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.
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/rex/socket.rb', line 547 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”
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 |
# File 'lib/rex/socket.rb', line 623 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
578 579 580 |
# File 'lib/rex/socket.rb', line 578 def self.portspec_crack(pspec) portspec_to_portlist(pspec) end |
.portspec_to_portlist(pspec) ⇒ Object
Converts a port specification like “80,21-25,!24,443” into a sorted, unique array of valid port numbers like [21,22,23,25,80,443]
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 |
# File 'lib/rex/socket.rb', line 586 def self.portspec_to_portlist(pspec) ports = [] remove = [] # Build ports array from port specification pspec.split(/,/).each do |item| target = ports item.strip! if item.start_with? '!' item.delete! '!' target = remove end 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| target << p } end if ports.empty? and not remove.empty? then ports = 1.upto 65535 end # Sort, and remove dups and invalid ports ports.sort.uniq.delete_if { |p| p < 1 or p > 65535 or remove.include? p } end |
.resolv_nbo(host, accepts_ipv6 = true) ⇒ Object
Resolves a host to raw network-byte order.
325 326 327 328 |
# File 'lib/rex/socket.rb', line 325 def self.resolv_nbo(host, accepts_ipv6 = true) ip_address = Rex::Socket.getaddress(host, accepts_ipv6) IPAddr.new(ip_address).hton end |
.resolv_nbo_i(host) ⇒ Object
Resolves a host to a network-byte order ruby integer.
342 343 344 |
# File 'lib/rex/socket.rb', line 342 def self.resolv_nbo_i(host) addr_ntoi(resolv_nbo(host)) end |
.resolv_nbo_i_list(host) ⇒ Object
Resolves a host to a list of network-byte order ruby integers.
349 350 351 |
# File 'lib/rex/socket.rb', line 349 def self.resolv_nbo_i_list(host) resolv_nbo_list(host).map{|addr| addr_ntoi(addr) } end |
.resolv_nbo_list(host) ⇒ Object
Resolves a host to raw network-byte order.
333 334 335 336 337 |
# File 'lib/rex/socket.rb', line 333 def self.resolv_nbo_list(host) Rex::Socket.getaddresses(host).map do |addresses| IPAddr.new(addresses).hton end end |
.resolv_to_dotted(host) ⇒ Object
Resolves a host to a dotted address.
384 385 386 |
# File 'lib/rex/socket.rb', line 384 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.
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 |
# File 'lib/rex/socket.rb', line 663 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] # Trim off the trailing interface ID for link-local IPv6 return r.split('%').first rescue ::Exception return '127.0.0.1' ensure s.close if s end end |
.support_ipv6? ⇒ Boolean
Determine whether we support IPv6
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/rex/socket.rb', line 111 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_pair ⇒ Object
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.
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 |
# File 'lib/rex/socket.rb', line 709 def self.tcp_socket_pair lsock = nil last_child_error = nil accept_timeout = 10 rsock = nil laddr = '127.0.0.1' lport = 0 threads = [] mutex = ::Mutex.new threads << Rex::ThreadFactory.spawn('TcpSocketPair', false) do server = nil begin mutex.synchronize do threads << Rex::ThreadFactory.spawn('TcpSocketPairClient', false) do mutex.synchronize do begin rsock = ::TCPSocket.new( laddr, lport ) rescue => e last_child_error = "#{e.class} - #{e.}" raise end end end 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 end readable, _writable, _errors = ::IO.select([server], nil, nil, accept_timeout) if readable && readable.any? lsock, _ = server.accept_nonblock else raise RuntimeError, "rsock didn't connect in #{accept_timeout} seconds" end ensure server.close if server end end threads.each.with_index do |thread, i| thread.join rescue => e raise "Thread #{i} - error #{e} - last child error: #{last_child_error}" end return [lsock, rsock] end |
.to_authority(host, port = nil) ⇒ String
Checks to see if an address is an IPv6 address and if so, converts it into its square bracket format for addressing as noted in RFC 6874 which states that an IPv6 address literal in a URL is always embedded between [ and ]. Please also refer to RFC5952, RFC3986, and RFC6874 for more info.
RFC3986 section 3.2.2 specifically notes “A host identified by an Internet Protocol literal address, version 6
- RFC3513
-
or later, is distinguished by enclosing the IP literal
within square brackets (“[” and “]”). This is the only place where square bracket characters are allowed in the URI syntax.“
RFC6874 reinforces this in section 2 where it notes “In a URI, a literal IPv6 address is always embedded between ‘[’ and ‘]’”.
193 194 195 196 197 198 199 200 |
# File 'lib/rex/socket.rb', line 193 def self.(host, port=nil) unless host.kind_of?(String) raise ArgumentError.new("Expected a string for the host parameter!") end host = "[#{host}]" if is_ipv6?(host) host += ":#{port}" if port host end |
.to_sockaddr(ip, port) ⇒ Object
Create a sockaddr structure using the supplied IP address, port, and address family
301 302 303 304 305 306 307 |
# File 'lib/rex/socket.rb', line 301 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_pair ⇒ Object
Create a UDP socket pair using native ruby UDP sockets.
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 |
# File 'lib/rex/socket.rb', line 769 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
#fd ⇒ Object
By default, all sockets are themselves selectable file descriptors.
819 820 821 |
# File 'lib/rex/socket.rb', line 819 def fd self end |
#getlocalname ⇒ Object
Wrapper around getsockname that stores the local address and local port values.
833 834 835 836 837 838 839 840 |
# File 'lib/rex/socket.rb', line 833 def getlocalname if [nil, '0.0.0.0', '::'].include?(self.localhost) && [nil, 0].include?(self.localport) _, self.localhost, self.localport = getsockname end family = Socket.is_ipv4?(self.localhost) ? ::Socket::AF_INET : ::Socket::AF_INET6 [family, self.localhost, self.localport] end |
#getpeername_as_array ⇒ Object
Returns peer connection information as an array.
845 846 847 848 849 850 851 852 853 854 855 |
# File 'lib/rex/socket.rb', line 845 def getpeername_as_array peer_name = nil begin peer_name = Socket.from_sockaddr(self.getpeername) rescue ::Errno::EINVAL => e # Ruby's getpeername method may call rb_sys_fail("getpeername(2)") elog("#{e.} (#{e.class})#{e.backtrace * "\n"}\n", LogSource, LEV_3) end return peer_name end |
#getsockname ⇒ Object
Returns local connection information.
826 827 828 |
# File 'lib/rex/socket.rb', line 826 def getsockname Socket.from_sockaddr(super) end |
#initsock(params = nil) ⇒ Object
Initialize general socket parameters.
804 805 806 807 808 809 810 811 812 813 814 |
# File 'lib/rex/socket.rb', line 804 def initsock(params = nil) if (params) self.peerhost = params.peerhost self.peerhostname = params.peerhostname self.peerport = params.peerport self.localhost = params.localhost self.localport = params.localport self.context = params.context || {} self.ipv = params.v6 ? 6 : 4 end end |
#localinfo ⇒ Object
Returns local information (host + port) in host:port format.
869 870 871 872 873 |
# File 'lib/rex/socket.rb', line 869 def localinfo if (pi = getlocalname) return pi[1] + ':' + pi[2].to_s end end |
#peerinfo ⇒ Object
Returns peer information (host + port) in host:port format.
860 861 862 863 864 |
# File 'lib/rex/socket.rb', line 860 def peerinfo if (pi = getpeername_as_array) return pi[1] + ':' + pi[2].to_s end end |
#type? ⇒ Boolean
Returns a string that indicates the type of the socket, such as ‘tcp’.
878 879 880 |
# File 'lib/rex/socket.rb', line 878 def type? raise NotImplementedError, "Socket type is not supported." end |