class Net::DNS::Resolver

Net::DNS::Resolver - DNS resolver class

The Net::DNS::Resolver class implements a complete DNS resolver written in pure Ruby, without a single C line of code. It has all of the tipical properties of an evoluted resolver, and a bit of OO which comes from having used Ruby.

This project started as a porting of the Net::DNS Perl module, written by Martin Fuhr, but turned out (in the last months) to be an almost complete rewriting. Well, maybe some of the features of the Perl version are still missing, but guys, at least this is readable code!

Environment

The Following Environment variables can also be used to configure the resolver:

Constants

C
Defaults

An hash with the defaults values of almost all the configuration parameters of a resolver object. See the description for each parameter to have an explanation of its usage.

Attributes

spoof_mac[RW]

Public Class Methods

logger=(logger) click to toggle source
# File lib/net/dns/resolver.rb, line 282
def self.logger= logger
  if logger.respond_to?(:warn) && logger.respond_to?(:debug) && logger.respond_to?(:info)
    @@logger = logger
  else
    raise ArgumentError, "Invalid logger provided to #{self.class}"
  end
end
new(config = {}) click to toggle source

Creates a new resolver object.

Argument config can either be empty or be an hash with some configuration parameters. To know what each parameter do, look at the description of each. Some example:

# Use the sistem defaults
res = Net::DNS::Resolver.new

# Specify a configuration file
res = Net::DNS::Resolver.new(:config_file => '/my/dns.conf')

# Set some option
res = Net::DNS::Resolver.new(:nameservers => "172.16.1.1",
                             :recursive => false,
                             :retry => 10)

Config file

Net::DNS::Resolver uses a config file to read the usual values a resolver needs, such as nameserver list and domain names. On UNIX systems the defaults are read from the following files, in the order indicated:

  • /etc/resolv.conf

  • $HOME/.resolv.conf

  • ./.resolv.conf

The following keywords are recognized in resolver configuration files:

  • domain: the default domain.

  • search: a space-separated list of domains to put in the search list.

  • nameserver: a space-separated list of nameservers to query.

Files except for /etc/resolv.conf must be owned by the effective userid running the program or they won’t be read. In addition, several environment variables can also contain configuration information; see Environment in the main description for Resolver class.

On Windows Systems, an attempt is made to determine the system defaults using the registry. This is still a work in progress; systems with many dynamically configured network interfaces may confuse Net::DNS.

You can include a configuration file of your own when creating a resolver object:

# Use my own configuration file
my $res = Net::DNS::Resolver->new(config_file => '/my/dns.conf');

This is supported on both UNIX and Windows. Values pulled from a custom configuration file override the the system’s defaults, but can still be overridden by the other arguments to Resolver::new.

Explicit arguments to Resolver::new override both the system’s defaults and the values of the custom configuration file, if any.

Parameters

The following arguments to Resolver::new are supported:

  • nameservers: an array reference of nameservers to query.

  • searchlist: an array reference of domains.

  • recurse

  • debug

  • domain

  • port

  • srcaddr

  • srcport

  • tcp_timeout

  • udp_timeout

  • retrans

  • retry

  • usevc

  • stayopen

  • igntc

  • defnames

  • dnsrch

  • persistent_tcp

  • persistent_udp

  • dnssec

For more information on any of these options, please consult the method of the same name.

Disclaimer

Part of the above documentation is taken from the one in the Net::DNS::Resolver Perl module.

# File lib/net/dns/resolver.rb, line 240
def initialize(config = {})
  raise ArgumentError, "Expected `config' to be a Hash" unless config.is_a?(Hash)

  # config.downcase_keys!
  @config = Defaults.merge config
  @raw = false

  #------------------------------------------------------------
  # Resolver configuration will be set in order from:
  # 1) initialize arguments
  # 2) ENV variables
  # 3) config file
  # 4) defaults (and /etc/resolv.conf for config)
  #------------------------------------------------------------



  #------------------------------------------------------------
  # Parsing config file
  #------------------------------------------------------------
  parse_config_file

  #------------------------------------------------------------
  # Parsing ENV variables
  #------------------------------------------------------------
  parse_environment_variables

  #------------------------------------------------------------
  # Parsing arguments
  #------------------------------------------------------------
  config.each do |key,val|
    next if key == :config_file
    begin
      eval "self.#{key.to_s} = val"
    rescue NoMethodError
      raise ArgumentError, "Option #{key} not valid"
    end
  end
end
platform_windows?() click to toggle source

Returns true if running on a Windows platform.

Note. This method doesn’t rely on the RUBY_PLATFORM constant because the comparison will fail when running on JRuby. On JRuby RUBY_PLATFORM == ‘java’.

# File lib/net/dns/resolver.rb, line 143
def platform_windows?
  !!(C["host_os"] =~ /msdos|mswin|djgpp|mingw/i)
end
start(*params) click to toggle source

Quick resolver method. Bypass the configuration using the defaults.

Net::DNS::Resolver.start "www.google.com"
# File lib/net/dns/resolver.rb, line 134
def start(*params)
  new.search(*params)
end

Public Instance Methods

axfr(name, cls = Net::DNS::IN) click to toggle source

Performs a zone transfer for the zone passed as a parameter.

It is actually only a wrapper to a send with type set as Net::DNS::AXFR, since it is using the same infrastucture.

# File lib/net/dns/resolver.rb, line 961
def axfr(name, cls = Net::DNS::IN)
  info "Requested AXFR transfer, zone #{name} class #{cls}"
  query(name, Net::DNS::AXFR, cls)
end
debug(*args) click to toggle source
# File lib/net/dns/resolver.rb, line 296
def debug *args
  if @@logger
    @debug *args
  end
end
defname()
Alias for: defname?
defname=(bool) click to toggle source

Set the flag defname in a boolean state. if defname is true, calls to Resolver#query will append the default domain to names that contain no dots. Example:

# Domain example.com
res.defname = true
res.query("machine1")
  #=> This will perform a query for machine1.example.com

Default is true.

# File lib/net/dns/resolver.rb, line 651
def defname=(bool)
  case bool
  when TrueClass,FalseClass
    @config[:defname] = bool
    info("Defname state changed to #{bool}")
  else
    raise ArgumentError, "Argument must be boolean"
  end
end
defname?() click to toggle source

Checks whether the defname flag has been activate.

# File lib/net/dns/resolver.rb, line 634
def defname?
  @config[:defname]
end
Also aliased as: defname
dns_search=(bool) click to toggle source

Set the flag dns_search in a boolean state. If dns_search is true, when using the Resolver#search method will be applied the search list. Default is true.

# File lib/net/dns/resolver.rb, line 670
def dns_search=(bool)
  case bool
  when TrueClass,FalseClass
    @config[:dns_search] = bool
    info("DNS search state changed to #{bool}")
  else
    raise ArgumentError, "Argument must be boolean"
  end
end
Also aliased as: dnsrch=
dnsrch()
Alias for: dns_search
dnsrch=(bool)
Alias for: dns_search=
domain() click to toggle source

Return a string with the default domain.

# File lib/net/dns/resolver.rb, line 377
def domain
  @config[:domain].inspect
end
domain=(name) click to toggle source

Set the domain for the query.

# File lib/net/dns/resolver.rb, line 382
def domain=(name)
  @config[:domain] = name if valid? name
end
ignore_truncated()
Alias for: ignore_truncated?
ignore_truncated=(bool) click to toggle source
# File lib/net/dns/resolver.rb, line 715
def ignore_truncated=(bool)
  case bool
  when TrueClass,FalseClass
    @config[:ignore_truncated] = bool
    info("Ignore truncated flag changed to #{bool}")
  else
    raise ArgumentError, "Argument must be boolean"
  end
end
ignore_truncated?() click to toggle source
# File lib/net/dns/resolver.rb, line 710
def ignore_truncated?
  @config[:ignore_truncated]
end
Also aliased as: ignore_truncated
info(*args) click to toggle source
# File lib/net/dns/resolver.rb, line 302
def info *args
  if @@logger
    @@logger.info *args
  end
end
inspect()
Alias for: state
interface() click to toggle source
# File lib/net/dns/resolver.rb, line 471
def interface
  @config[:interface]
end
interface=(iface) click to toggle source
# File lib/net/dns/resolver.rb, line 539
def interface=(iface)
  @config[:interface] = iface
end
mx(name, cls = Net::DNS::IN) click to toggle source

Performs an MX query for the domain name passed as parameter.

It actually uses the same methods a normal Resolver query would use, but automatically sort the results based on preferences and returns an ordered array.

res = Net::DNS::Resolver.new
res.mx("google.com")
# File lib/net/dns/resolver.rb, line 975
def mx(name, cls = Net::DNS::IN)
  arr = []
  query(name, Net::DNS::MX, cls).answer.each do |entry|
    arr << entry if entry.type == 'MX'
  end
  arr.sort_by { |a| a.preference }
end
nameserver()
Alias for: nameservers
nameserver=(arg)
Alias for: nameservers=
nameservers() click to toggle source

Get the list of resolver nameservers, in a dotted decimal format-

res.nameservers
  #=> ["192.168.0.1","192.168.0.2"]
# File lib/net/dns/resolver.rb, line 350
def nameservers
  @config[:nameservers].map(&:to_s)
end
Also aliased as: nameserver
nameservers=(arg) click to toggle source

Set the list of resolver nameservers. arg can be a single ip address or an array of addresses.

res.nameservers = "192.168.0.1"
res.nameservers = ["192.168.0.1","192.168.0.2"]

If you want you can specify the addresses as IPAddr instances.

ip = IPAddr.new("192.168.0.3")
res.nameservers << ip
#=> ["192.168.0.1","192.168.0.2","192.168.0.3"]

The default is 127.0.0.1 (localhost)

# File lib/net/dns/resolver.rb, line 370
def nameservers=(arg)
  @config[:nameservers] = convert_nameservers_arg_to_ips(arg)
  info "Nameservers list changed to value #{@config[:nameservers].inspect}"
end
Also aliased as: nameserver=
packet_size() click to toggle source

Return the defined size of the packet.

# File lib/net/dns/resolver.rb, line 387
def packet_size
  @config[:packet_size]
end
packet_size=(arg) click to toggle source
# File lib/net/dns/resolver.rb, line 391
def packet_size=(arg)
  if arg.respond_to? :to_i
    @config[:packet_size] = arg.to_i
    info "Packet size changed to value #{@config[:packet_size].inspect}"
  else
    @logger.error "Packet size not set, #{arg.class} does not respond to to_i"
  end
end
port() click to toggle source

Get the port number to which the resolver sends queries.

puts "Sending queries to port #{res.port}"
# File lib/net/dns/resolver.rb, line 404
def port
  @config[:port]
end
port=(num) click to toggle source

Set the port number to which the resolver sends queries. This can be useful for testing a nameserver running on a non-standard port.

res.port = 10053

The default is port 53.

# File lib/net/dns/resolver.rb, line 415
def port=(num)
  if (0..65535).include? num
    @config[:port] = num
    info "Port number changed to #{num}"
  else
    raise ArgumentError, "Wrong port number #{num}"
  end
end
print()
Alias for: state
query(argument, type = Net::DNS::A, cls = Net::DNS::IN) click to toggle source

Performs a DNS query for the given name. Neither the searchlist nor the default domain will be appended.

The argument list can be either a Net::DNS::Packet object or a name string plus optional type and class, which if omitted default to A and IN.

Returns a Net::DNS::Packet object.

# Executes the query with a +Packet+ object
send_packet = Net::DNS::Packet.new("host.example.com", Net::DNS::NS, Net::DNS::HS)
packet = res.query(send_packet)

# Executes the query with a host, type and cls
packet = res.query("host.example.com")
packet = res.query("host.example.com", Net::DNS::NS)
packet = res.query("host.example.com", Net::DNS::NS, Net::DNS::HS)

If the name is an IP address (Ipv4 or IPv6), in the form of a string or a IPAddr object, then an appropriate PTR query will be performed:

ip = IPAddr.new("172.16.100.2")
packet = res.query(ip)

packet = res.query("172.16.100.2")

Use packet.header.ancount or packet.answer to find out if there were any records in the answer section.

# File lib/net/dns/resolver.rb, line 875
def query(argument, type = Net::DNS::A, cls = Net::DNS::IN)
  if @config[:nameservers].size == 0
    raise Resolver::Error, "No nameservers specified!"
  end

  method = :query_udp
  packet = if argument.kind_of? Net::DNS::Packet
    argument
  else
    make_query_packet(argument, type, cls)
  end

  # Store packet_data for performance improvements,
  # so methods don't keep on calling Packet#data
  packet_data = packet.data
  packet_size = packet_data.size

  # Choose whether use TCP, UDP or RAW
  if packet_size > @config[:packet_size] # Must use TCP, either plain or raw
    if @raw # Use raw sockets?
      info "Sending #{packet_size} bytes using TCP over RAW socket"
      method = :send_raw_tcp
    else
      info "Sending #{packet_size} bytes using TCP"
      method = :query_tcp
    end
  else # Packet size is inside the boundaries
    if @raw # Use raw sockets?
      info "Sending #{packet_size} bytes using UDP over RAW socket"
      method = :send_raw_udp
    elsif use_tcp? # User requested TCP
      info "Sending #{packet_size} bytes using TCP"
      method = :query_tcp
    else # Finally use UDP
      info "Sending #{packet_size} bytes using UDP"
      method = :query_udp
    end
  end

  if type == Net::DNS::AXFR
    if @raw
      info "AXFR query, switching to TCP over RAW socket"
      method = :send_raw_tcp
    else
      info "AXFR query, switching to TCP"
      method = :query_tcp
    end
  end

  ans = self.send(method, packet, packet_data)

  # Don't have any responses with the raw,
  # since currently raw is only used when source_address is changed
  if @raw
    return nil
  end

  if not ans
    message = "No response from nameservers list"
    # NoMethodError: undefined method `fatal' for nil:NilClass
    #@logger.fatal(message)
    warn(message)
    raise NoResponseError, message
  end

  info "Received #{ans[0].size} bytes from #{ans[1][2]+":"+ans[1][1].to_s}"
  response = Net::DNS::Packet.parse(ans[0],ans[1])

  if response.header.truncated? and not ignore_truncated?
    info "Packet truncated, retrying using TCP"
    self.use_tcp = true
    begin
      return query(argument,type,cls)
    ensure
      self.use_tcp = false
    end
  end

  return response
end
recurse()
Alias for: recursive?
recurse=(bool)
Alias for: recursive=
recursive()
Alias for: recursive?
recursive=(bool) click to toggle source

Sets whether or not the resolver should perform recursive queries. Default is true.

res.recursive = false # perform non-recursive query
# File lib/net/dns/resolver.rb, line 599
def recursive=(bool)
  case bool
  when TrueClass,FalseClass
    @config[:recursive] = bool
    info("Recursive state changed to #{bool}")
  else
    raise ArgumentError, "Argument must be boolean"
  end
end
Also aliased as: recurse=
recursive?() click to toggle source

This method will return true if the resolver is configured to perform recursive queries.

print "The resolver will perform a "
print res.recursive? ? "" : "not "
puts "recursive query"
# File lib/net/dns/resolver.rb, line 588
def recursive?
  @config[:recursive]
end
Also aliased as: recurse, recursive
retrans()
Alias for: retry_interval
retrans=(num)
Alias for: retry_interval=
retry=(num)
Alias for: retry_number=
retry_interval() click to toggle source

Return the retrasmission interval (in seconds) the resolvers has been set on.

# File lib/net/dns/resolver.rb, line 545
def retry_interval
  @config[:retry_interval]
end
Also aliased as: retrans
retry_interval=(num) click to toggle source

Set the retrasmission interval in seconds. Default 5 seconds.

# File lib/net/dns/resolver.rb, line 551
def retry_interval=(num)
  if num > 0
    @config[:retry_interval] = num
    info "Retransmission interval changed to #{num} seconds"
  else
    raise ArgumentError, "Interval must be positive"
  end
end
Also aliased as: retrans=
retry_number() click to toggle source

The number of times the resolver will try a query.

puts "Will try a max of #{res.retry_number} queries"
# File lib/net/dns/resolver.rb, line 565
def retry_number
  @config[:retry_number]
end
retry_number=(num) click to toggle source

Set the number of times the resolver will try a query. Default 4 times.

# File lib/net/dns/resolver.rb, line 571
def retry_number=(num)
  if num.kind_of? Integer and num > 0
    @config[:retry_number] = num
    info "Retrasmissions number changed to #{num}"
  else
    raise ArgumentError, "Retry value must be a positive integer"
  end
end
Also aliased as: retry=
searchlist() click to toggle source

Get the resolver search list, returned as an array of entries.

res.searchlist
#=> ["example.com","a.example.com","b.example.com"]
# File lib/net/dns/resolver.rb, line 314
def searchlist
  @config[:searchlist].inspect
end
searchlist=(arg) click to toggle source

Set the resolver searchlist. arg can be a single string or an array of strings.

res.searchstring = "example.com"
res.searchstring = ["example.com","a.example.com","b.example.com"]

Note that you can also append a new name to the searchlist.

res.searchlist << "c.example.com"
res.searchlist
#=> ["example.com","a.example.com","b.example.com","c.example.com"]

The default is an empty array.

# File lib/net/dns/resolver.rb, line 332
def searchlist=(arg)
  case arg
  when String
    @config[:searchlist] = [arg] if valid? arg
    info "Searchlist changed to value #{@config[:searchlist].inspect}"
  when Array
    @config[:searchlist] = arg if arg.all? {|x| valid? x}
    info "Searchlist changed to value #{@config[:searchlist].inspect}"
  else
    raise ArgumentError, "Wrong argument format, neither String nor Array"
  end
end
source_address() click to toggle source

Get the local address from which the resolver sends queries

puts "Sending queries using source address #{res.source_address}"
# File lib/net/dns/resolver.rb, line 460
def source_address
  @config[:source_address].to_s
end
Also aliased as: srcaddr
source_address=(addr) click to toggle source

Set the local source address from which the resolver sends its queries.

res.source_address = "172.16.100.1"
res.source_address = IPAddr.new("172.16.100.1")

You can specify arg as either a string containing the ip address or an instance of IPAddr class.

Normally this can be used to force queries out a specific interface on a multi-homed host. In this case, you should of course need to know the addresses of the interfaces.

Another way to use this option is for some kind of spoofing attacks towards weak nameservers, to probe the security of your network. This includes specifing ranged attacks such as DoS and others. For a paper on DNS security, checks htpt://www.marcoceresa.com/security/

Note that if you want to set a non-binded source address you need root priviledges, as raw sockets will be used to generate packets. The class will then generate an exception if you’re not root.

The default is 0.0.0.0, meaning any local address (chosen on routing needs).

# File lib/net/dns/resolver.rb, line 498
def source_address=(addr)
  unless addr.respond_to? :to_s
    raise ArgumentError, "Wrong address argument #{addr}"
  end

  begin
    port = rand(64000)+1024
    info "Try to determine state of source address #{addr} with port #{port}"
    a = TCPServer.new(addr.to_s,port)
  rescue SystemCallError => e
    case e.errno
    when 98 # Port already in use!
      info "Port already in use"
      retry
    when 99 # Address is not valid: raw socket
      if Process.uid == 0
        @raw = true
        info "Using raw sockets"
      else
        raise RuntimeError, "Raw sockets requested but not running as root."
      end
    else
      raise SystemCallError, e
    end
  else
    a.close
  end

  case addr
  when String
    @config[:source_address] = IPAddr.new(addr)
    info "Using new source address: #{@config[:source_address]}"
  when IPAddr
    @config[:source_address] = addr
    info "Using new source address: #{@config[:source_address]}"
  else
    raise ArgumentError, "Unknown dest_address format"
  end
end
Also aliased as: srcaddr=
source_address_inet6() click to toggle source

Get the local ipv6 address from which the resolver sends queries

# File lib/net/dns/resolver.rb, line 467
def source_address_inet6
  @config[:source_address_inet6].to_s
end
source_port() click to toggle source

Get the value of the source port number.

puts "Sending queries using port #{res.source_port}"
# File lib/net/dns/resolver.rb, line 428
def source_port
  @config[:source_port]
end
Also aliased as: srcport
source_port=(num) click to toggle source

Set the local source port from which the resolver sends its queries.

res.source_port = 40000

Note that if you want to set a port you need root priviledges, as raw sockets will be used to generate packets. The class will then generate the exception ResolverPermissionError if you’re not root.

The default is 0, which means that the port will be chosen by the underlaying layers.

# File lib/net/dns/resolver.rb, line 444
def source_port=(num)
  unless root?
    raise ResolverPermissionError, "Are you root?"
  end
  if (0..65535).include?(num)
    @config[:source_port] = num
  else
    raise ArgumentError, "Wrong port number #{num}"
  end
end
Also aliased as: srcport=
srcaddr()
Alias for: source_address
srcaddr=(addr)
Alias for: source_address=
srcport()
Alias for: source_port
srcport=(num)
Alias for: source_port=
state() click to toggle source

Return a string representing the resolver state, suitable for printing on the screen.

puts "Resolver state:"
puts res.state
# File lib/net/dns/resolver.rb, line 616
def state
  str = ";; RESOLVER state:\n;; "
  i = 1
  @config.each do |key,val|
    if key == :log_file or key == :config_file
      str << "#{key}: #{val} \t"
    else
      str << "#{key}: #{eval(key.to_s)} \t"
    end
    str << "\n;; " if i % 2 == 0
    i += 1
  end
  str
end
Also aliased as: print, inspect
tcp_timeout() click to toggle source

Return an object representing the value of the stored TCP timeout the resolver will use in is queries. This object is an instance of the class TcpTimeout, and two methods are available for printing informations: TcpTimeout#to_s and TcpTimeout#pretty_to_s.

Here’s some example:

puts "Timeout of #{res.tcp_timeout} seconds" # implicit to_s
  #=> Timeout of 150 seconds

puts "You set a timeout of " + res.tcp_timeout.pretty_to_s
  #=> You set a timeout of 2 minutes and 30 seconds

If the timeout is infinite, a string “infinite” will be returned.

# File lib/net/dns/resolver.rb, line 741
def tcp_timeout
  @config[:tcp_timeout].to_s
end
tcp_timeout=(secs) click to toggle source

Set the value of TCP timeout for resolver queries that will be performed using TCP. A value of 0 means that the timeout will be infinite. The value is stored internally as a TcpTimeout object, see the description for Resolver#tcp_timeout

Default is 5 seconds.

# File lib/net/dns/resolver.rb, line 753
def tcp_timeout=(secs)
  @config[:tcp_timeout] = TcpTimeout.new(secs)
  info("New TCP timeout value: #{@config[:tcp_timeout]} seconds")
end
udp_timeout() click to toggle source

Return an object representing the value of the stored UDP timeout the resolver will use in is queries. This object is an instance of the class UdpTimeout, and two methods are available for printing information: UdpTimeout#to_s and UdpTimeout#pretty_to_s.

Here’s some example:

puts "Timeout of #{res.udp_timeout} seconds" # implicit to_s
  #=> Timeout of 150 seconds

puts "You set a timeout of " + res.udp_timeout.pretty_to_s
  #=> You set a timeout of 2 minutes and 30 seconds

If the timeout is zero, a string “not defined” will be returned.

# File lib/net/dns/resolver.rb, line 775
def udp_timeout
  @config[:udp_timeout].to_s
end
udp_timeout=(secs) click to toggle source

Set the value of UDP timeout for resolver queries that will be performed using UDP. A value of 0 means that the timeout will not be used, and the resolver will use only retry_number and retry_interval parameters.

Default is 5 seconds.

The value is stored internally as a UdpTimeout object, see the description for Resolver#udp_timeout.

# File lib/net/dns/resolver.rb, line 789
def udp_timeout=(secs)
  @config[:udp_timeout] = UdpTimeout.new(secs)
  info("New UDP timeout value: #{@config[:udp_timeout]} seconds")
end
use_tcp()
Alias for: use_tcp?
use_tcp=(bool) click to toggle source

If use_tcp is true, the resolver will perform all queries using TCP virtual circuits instead of UDP datagrams, which is the default for the DNS protocol.

res.use_tcp = true
res.query "host.example.com"
  #=> Sending TCP segments...

Default is false.

# File lib/net/dns/resolver.rb, line 699
def use_tcp=(bool)
  case bool
  when TrueClass,FalseClass
    @config[:use_tcp] = bool
    info("Use tcp flag changed to #{bool}")
  else
    raise ArgumentError, "Argument must be boolean"
  end
end
Also aliased as: usevc=
use_tcp?() click to toggle source

Get the state of the use_tcp flag.

# File lib/net/dns/resolver.rb, line 683
def use_tcp?
  @config[:use_tcp]
end
Also aliased as: usevc, use_tcp
usevc()
Alias for: use_tcp?
usevc=(bool)
Alias for: use_tcp=
warn(*args) click to toggle source
# File lib/net/dns/resolver.rb, line 290
def warn *args
  if @@logger
    @@logger.warn *args
  end
end

Private Instance Methods

convert_nameservers_arg_to_ips(arg) click to toggle source
# File lib/net/dns/resolver.rb, line 1033
def convert_nameservers_arg_to_ips(arg)
  if arg.kind_of? IPAddr
    [arg]
  elsif arg.respond_to? :map
    arg.map{|x| convert_nameservers_arg_to_ips(x) }.flatten
  elsif arg.respond_to? :to_a
    arg.to_a.map{|x| convert_nameservers_arg_to_ips(x) }.flatten
  elsif arg.respond_to? :to_s
    begin
      [IPAddr.new(arg.to_s)]
    rescue ArgumentError # arg is in the name form, not IP
      nameservers_from_name(arg)
    end
  else
    raise ArgumentError, "Wrong nameservers argument format, cannot convert to array of IPAddrs"
  end
end
make_query_packet(string, type, cls) click to toggle source
# File lib/net/dns/resolver.rb, line 1061
def make_query_packet(string, type, cls)
  begin
    name = IPAddr.new(string.chomp(".")).reverse
    type = Net::DNS::PTR
  rescue ArgumentError
    name = string if valid? string
  end

  if name.nil?
    raise ArgumentError, "Bad query string"
  end

  # Create the packet
  packet = Net::DNS::Packet.new(name, type, cls)

  if packet.query?
    packet.header.recursive = @config[:recursive] ? 1 : 0
  end

  # DNSSEC and TSIG stuff to be inserted here

  packet
end
nameservers_from_name(arg) click to toggle source
# File lib/net/dns/resolver.rb, line 1051
def nameservers_from_name(arg)
  arr = []
  arg.split(" ").each do |name|
    Resolver.new.search(name).each_address do |ip|
      arr << ip
    end
  end
  arr
end
parse_config_file() click to toggle source

Parses a configuration file specified as the argument.

# File lib/net/dns/resolver.rb, line 986
def parse_config_file
  if self.class.platform_windows?
    require 'win32/resolv'
    arr = Win32::Resolv.get_resolv_info
    self.domain = arr[0].first.to_s
    self.nameservers = arr[1]
  else
    nameservers = []
    IO.foreach(@config[:config_file]) do |line|
      line.gsub!(/\s*[;#].*/,"")
      next unless line =~ /\S/
      case line
      when /^\s*domain\s+(\S+)/
        self.domain = $1
      when /^\s*search\s+(.*)/
        self.searchlist = $1.split(" ")
      when /^\s*nameserver\s+(.*)/
        nameservers << $1.split(" ")
      end
    end
    self.nameservers = nameservers.flatten
  end
end
parse_environment_variables() click to toggle source

Parses environment variables.

# File lib/net/dns/resolver.rb, line 1011
def parse_environment_variables
  if ENV['RES_NAMESERVERS']
    self.nameservers = ENV['RES_NAMESERVERS'].split(" ")
  end
  if ENV['RES_SEARCHLIST']
    self.searchlist = ENV['RES_SEARCHLIST'].split(" ")
  end
  if ENV['LOCALDOMAIN']
    self.domain = ENV['LOCALDOMAIN']
  end
  if ENV['RES_OPTIONS']
    ENV['RES_OPTIONS'].split(" ").each do |opt|
      name,val = opt.split(":")
      begin
        eval("self.#{name} = #{val}")
      rescue NoMethodError
        raise ArgumentError, "Invalid ENV option #{name}"
      end
    end
  end
end
query_tcp(packet, packet_data) click to toggle source
# File lib/net/dns/resolver.rb, line 1085
def query_tcp(packet, packet_data)

  ans = nil
  length = [packet_data.size].pack("n")

  @config[:nameservers].each do |ns|
    begin
      buffer = ""
      socket = Socket.new(Socket::AF_INET,Socket::SOCK_STREAM,0)
      socket.bind(Socket.pack_sockaddr_in(@config[:source_port],@config[:source_address].to_s))

      sockaddr = Socket.pack_sockaddr_in(@config[:port],ns.to_s)

      @config[:tcp_timeout].timeout do
        socket.connect(sockaddr)
        info "Contacting nameserver #{ns} port #{@config[:port]}"
        socket.write(length+packet_data)
        ans = socket.recv(Net::DNS::INT16SZ)
        len = ans.unpack("n")[0]

        info "Receiving #{len} bytes..."

        if len == 0
          info "Receiving 0 lenght packet from nameserver #{ns}, trying next."
          next
        end

        while (buffer.size < len)
          left = len - buffer.size
          temp,from = socket.recvfrom(left)
          buffer += temp
        end

        unless buffer.size == len
          info "Malformed packet from nameserver #{ns}, trying next."
          next
        end
      end
      return [buffer,["",@config[:port],ns.to_s,ns.to_s]]
    rescue TimeoutError
      info "Nameserver #{ns} not responding within TCP timeout, trying next one"
      next
    ensure
      socket.close
    end
  end
  ans
end
query_udp(packet, packet_data) click to toggle source
# File lib/net/dns/resolver.rb, line 1134
def query_udp(packet, packet_data)
  socket4 = UDPSocket.new
  socket4.bind(@config[:source_address].to_s,@config[:source_port])
  if @config[:nameservers].any? { |ns| ns.ipv6? }
    socket6 = UDPSocket.new(Socket::AF_INET6)
    socket6.bind(@config[:source_address_inet6].to_s,@config[:source_port])
  end

  ans = nil
  response = ""
  @config[:nameservers].each do |ns|
    begin
      @config[:udp_timeout].timeout do
        info "Contacting nameserver #{ns} port #{@config[:port]}"
        ans = if ns.ipv6?
          socket6.send(packet_data, 0, ns.to_s, @config[:port])
          socket6.recvfrom(@config[:packet_size])
        else
          socket4.send(packet_data, 0, ns.to_s, @config[:port])
          socket4.recvfrom(@config[:packet_size])
        end
      end
      break if ans
    rescue TimeoutError
      info "Nameserver #{ns} not responding within UDP timeout, trying next one"
      next
    end
  end
  ans
end
send_raw_tcp(packet, packet_data) click to toggle source
# File lib/net/dns/resolver.rb, line 1165
def send_raw_tcp(packet, packet_data)
  socket = nil
  packet = PacketFu::TCPPacket.new({body: packet_data})


  if @config[:source_address]
    octet = PacketFu::Octets.new
    octet.read_quad @config[:source_address].to_s
    packet.ip_src = octet
    packet.udp_src =rand(0xffff-1024) + 1024
    if @config[:spoof_mac]
      packet.eth_saddr = PacketFu::Utils.arp(@config[:source_address].to_s, {iface: @config[:interface]})
    end
  elsif @config[:source_address_inet6]
    octet = PacketFu::Octets.new
    octet.read_quad @config[:source_address_inet6].to_s
    packet.ip_src = octet
    packet.udp_src = @config[:source_address_inet6].to_i
    if @config[:spoof_mac]
      packet.eth_saddr = PacketFu::Utils.arp(@config[:source_address_inet6].to_s, {iface: @config[:interface]})
    end
  else
    raise ArgumentError, "No source address specified, cannot send"
  end

  @config[:nameservers].each do |ns|
    octet = PacketFu::Octets.new
    octet.read_quad ns.to_s
    packet.ip_dst = octet
    packet.udp_dst = 53
    packet.recalc arg=:all
    packet.to_w @config[:interface]
  end
  nil
end
send_raw_udp(packet, packet_data) click to toggle source
# File lib/net/dns/resolver.rb, line 1201
def send_raw_udp(packet, packet_data)
  socket = nil
  packet = PacketFu::UDPPacket.new({body: packet_data})


  if @config[:source_address]
    octet = PacketFu::Octets.new
    octet.read_quad @config[:source_address].to_s
    packet.ip_src = octet
    packet.udp_src =rand(0xffff-1024) + 1024
    if @config[:spoof_mac]
      packet.eth_saddr = PacketFu::Utils.arp(@config[:source_address].to_s, {iface: @config[:interface]})
    end
  elsif @config[:source_address_inet6]
    octet = PacketFu::Octets.new
    octet.read_quad @config[:source_address_inet6].to_s
    packet.ip_src = octet
    packet.udp_src = @config[:source_address_inet6].to_i
    if @config[:spoof_mac]
      packet.eth_saddr = PacketFu::Utils.arp(@config[:source_address_inet6].to_s, {iface: @config[:interface]})
    end
  else
    raise ArgumentError, "No source address specified, cannot send"
  end

  @config[:nameservers].each do |ns|
    octet = PacketFu::Octets.new
    octet.read_quad ns.to_s
    packet.ip_dst = octet
    packet.udp_dst = 53
    packet.recalc arg=:all
    packet.to_w @config[:interface]
  end
  nil
end
valid?(name) click to toggle source
# File lib/net/dns/resolver.rb, line 1237
def valid?(name)
  if name =~ /[^-\w\.]/
    false
  else
    true
  end
end