Class: Rex::Proto::DNS::Resolver

Inherits:
Net::DNS::Resolver
  • Object
show all
Defined in:
lib/rex/proto/dns/resolver.rb

Overview

Provides Rex::Sockets compatible version of Net::DNS::Resolver Modified to work with Dnsruby::Messages, their resolvers are too heavy

Direct Known Subclasses

CachedResolver

Constant Summary collapse

Defaults =
{
  :config_file => nil,
  :log_file => File::NULL, # formerly $stdout, should be tied in with our loggers
  :port => 53,
  :searchlist => [],
  :nameservers => [],
  :domain => "",
  :source_port => 0,
  :source_address => IPAddr.new("0.0.0.0"),
  :retry_interval => 5,
  :retry_number => 4,
  :recursive => true,
  :defname => true,
  :dns_search => true,
  :use_tcp => false,
  :ignore_truncated => false,
  :packet_size => 512,
  :tcp_timeout => TcpTimeout.new(5),
  :udp_timeout => UdpTimeout.new(5),
  :context => {},
  :comm => nil,
  :static_hosts => {}
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Resolver

Provide override for initializer to use local Defaults constant

Parameters:

  • config (Hash) (defaults to: {})

    Configuration options as consumed by parent class

Raises:

  • (ResolverArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
# File 'lib/rex/proto/dns/resolver.rb', line 45

def initialize(config = {})
  raise ResolverArgumentError, "Argument has to be Hash" unless config.kind_of? Hash
  # config.key_downcase!
  @config = Defaults.merge config
  @config[:config_file] ||= self.class.default_config_file
  @raw = false
  # New logger facility
  @logger = Logger.new(@config[:log_file])
  @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN

  #------------------------------------------------------------
  # 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
  #------------------------------------------------------------
  comm = config.delete(:comm)
  context = config.delete(:context)
  static_hosts = config.delete(:static_hosts)
  config.each do |key,val|
    next if key == :log_file or key == :config_file
    begin
      eval "self.#{key.to_s} = val"
    rescue NoMethodError
      raise ResolverArgumentError, "Option #{key} not valid"
    end
  end

  self.static_hostnames = StaticHostnames.new(hostnames: static_hosts)
  begin
    self.static_hostnames.parse_hosts_file
  rescue StandardError => e
    @logger.error 'Failed to parse the hosts file, ignoring it'
    # if the hosts file is corrupted, just use a default instance with any specified hostnames
    self.static_hostnames = StaticHostnames.new(hostnames: static_hosts)
  end
end

Instance Attribute Details

#commObject

Returns the value of attribute comm.



40
41
42
# File 'lib/rex/proto/dns/resolver.rb', line 40

def comm
  @comm
end

#contextObject

Returns the value of attribute context.



40
41
42
# File 'lib/rex/proto/dns/resolver.rb', line 40

def context
  @context
end

#static_hostnamesObject

Returns the value of attribute static_hostnames.



40
41
42
# File 'lib/rex/proto/dns/resolver.rb', line 40

def static_hostnames
  @static_hostnames
end

Class Method Details

.default_config_fileObject



399
400
401
402
403
404
405
406
# File 'lib/rex/proto/dns/resolver.rb', line 399

def self.default_config_file
  %w[
    /etc/resolv.conf
    /data/data/com.termux/files/usr/etc/resolv.conf
  ].find do |path|
    File.file?(path) && File.readable?(path)
  end
end

Instance Method Details

#proxiesString

Provides current proxy setting if configured

Returns:

  • (String)

    Current proxy configuration



101
102
103
# File 'lib/rex/proto/dns/resolver.rb', line 101

def proxies
  @config[:proxies].inspect if @config[:proxies]
end

#proxies=(prox, timeout_added = 250) ⇒ Object

Configure proxy setting and additional timeout

Parameters:

  • prox (String)

    SOCKS proxy connection string

  • timeout_added (Fixnum) (defaults to: 250)

    Added TCP timeout to account for proxy



110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rex/proto/dns/resolver.rb', line 110

def proxies=(prox, timeout_added = 250)
  return if prox.nil?
  if prox.is_a?(String) and prox.strip =~ /^socks/i
    @config[:proxies] = prox.strip
    @config[:use_tcp] = true
    self.tcp_timeout = self.tcp_timeout.to_s.to_i + timeout_added
    @logger.info "SOCKS proxy set, using TCP, increasing timeout"
  else
    raise ResolverError, "Only socks proxies supported"
  end
end

#query(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN) ⇒ Object

Perform query with default domain validation

Parameters:

  • name
  • type (Fixnum) (defaults to: Dnsruby::Types::A)

    Type of record to look up

  • cls (Fixnum) (defaults to: Dnsruby::Classes::IN)

    Class of question to look up



393
394
395
396
397
# File 'lib/rex/proto/dns/resolver.rb', line 393

def query(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)
  name, type, cls = preprocess_query_arguments(name, type, cls)
  @logger.debug "Query(#{name},#{Dnsruby::Types.new(type)},#{Dnsruby::Classes.new(cls)})"
  send(name,type,cls)
end

#search(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN) ⇒ Object

Perform search using the configured searchlist and resolvers

Parameters:

  • name
  • type (Fixnum) (defaults to: Dnsruby::Types::A)

    Type of record to look up

  • cls (Fixnum) (defaults to: Dnsruby::Classes::IN)

    Class of question to look up



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/rex/proto/dns/resolver.rb', line 363

def search(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)
  return query(name,type,cls) if name.class == IPAddr
  # If the name contains at least one dot then try it as is first.
  if name.include? "."
    @logger.debug "Search(#{name},#{Dnsruby::Types.new(type)},#{Dnsruby::Classes.new(cls)})"
    ans = query(name,type,cls)
    return ans if ans.header.ancount > 0
  end
  # If the name doesn't end in a dot then apply the search list.
  if name !~ /\.$/ and @config[:dns_search]
    @config[:searchlist].each do |domain|
      newname = name + "." + domain
      @logger.debug "Search(#{newname},#{Dnsruby::Types.new(type)},#{Dnsruby::Classes.new(cls)})"
      ans = query(newname,type,cls)
      return ans if ans.header.ancount > 0
    end
  end
  # Finally, if the name has no dots then try it as is.
  @logger.debug "Search(#{name},#{Dnsruby::Types.new(type)},#{Dnsruby::Classes.new(cls)})"
  return query(name+".",type,cls)
end

#send(argument, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN) ⇒ Dnsruby::Message

Send DNS request over appropriate transport and process response

Parameters:

  • argument (Object)

    An object holding the DNS message to be processed.

  • type (Fixnum) (defaults to: Dnsruby::Types::A)

    Type of record to look up

  • cls (Fixnum) (defaults to: Dnsruby::Classes::IN)

    Class of question to look up

Returns:

  • (Dnsruby::Message)

    DNS response



150
151
152
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/rex/proto/dns/resolver.rb', line 150

def send(argument, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)
  case argument
  when Dnsruby::Message
    packet = argument
  when Net::DNS::Packet, Resolv::DNS::Message
    packet = Rex::Proto::DNS::Packet.encode_drb(argument)
  else
    net_packet = make_query_packet(argument,type,cls)
    # This returns a Net::DNS::Packet. Convert to Dnsruby::Message for consistency
    packet = Rex::Proto::DNS::Packet.encode_drb(net_packet)
  end


  upstream_resolvers = upstream_resolvers_for_packet(packet)
  if upstream_resolvers.empty?
    raise ResolverError, "No upstream resolvers specified!"
  end

  ans = nil
  upstream_resolvers.each do |upstream_resolver|
    case upstream_resolver.type
    when UpstreamResolver::Type::BLACK_HOLE
      ans = resolve_via_black_hole(upstream_resolver, packet, type, cls)
    when UpstreamResolver::Type::DNS_SERVER
      ans = resolve_via_dns_server(upstream_resolver, packet, type, cls)
    when UpstreamResolver::Type::STATIC
      ans = resolve_via_static(upstream_resolver, packet, type, cls)
    when UpstreamResolver::Type::SYSTEM
      ans = resolve_via_system(upstream_resolver, packet, type, cls)
    end

    break if (ans and ans[0].length > 0)
  end

  unless (ans and ans[0].length > 0)
    @logger.fatal "No response from upstream resolvers: aborting"
    raise NoResponseError
  end

  # response = Net::DNS::Packet.parse(ans[0],ans[1])
  response = Dnsruby::Message.decode(ans[0])

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

  response
end

#send_tcp(packet, packet_data, nameservers, prox = ) ⇒ Object

Send request over TCP

Parameters:

  • packet (Net::DNS::Packet)

    Packet associated with packet_data

  • packet_data (String)

    Data segment of DNS request packet

  • nameservers (Array<[String,Hash]>)

    List of nameservers to use for this request, and their associated socket options

  • prox (String) (defaults to: )

    Proxy configuration for TCP socket



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/rex/proto/dns/resolver.rb', line 214

def send_tcp(packet, packet_data, nameservers, prox = @config[:proxies])
  ans = nil
  length = [packet_data.size].pack("n")
  nameservers.each do |ns, socket_options|
    socket = nil
    config = {
      'PeerHost' => ns.to_s,
      'PeerPort' => @config[:port].to_i,
      'Proxies' => prox,
      'Context' => @config[:context],
      'Comm' => @config[:comm],
      'Timeout' => @config[:tcp_timeout]
    }
    config.update(socket_options)
    unless config['Comm'].nil? || config['Comm'].alive?
      @logger.warn("Session #{config['Comm'].sid} not active, and cannot be used to resolve DNS")
      next
    end

    suffix = " over session #{@config['Comm'].sid}" unless @config['Comm'].nil?
    if @config[:source_port] > 0
      config['LocalPort'] = @config[:source_port]
    end
    if @config[:source_host].to_s != '0.0.0.0'
      config['LocalHost'] = @config[:source_host] unless @config[:source_host].nil?
    end
    begin
      suffix = ''
      begin
        socket = Rex::Socket::Tcp.create(config)
      rescue
        @logger.warn "TCP Socket could not be established to #{ns}:#{@config[:port]} #{@config[:proxies]}#{suffix}"
        next
      end
      next unless socket #
      @logger.info "Contacting nameserver #{ns} port #{@config[:port]}#{suffix}"
      socket.write(length+packet_data)
      got_something = false
      loop do
        buffer = ""
        attempts = 3
        begin
          ans = socket.recv(2)
        rescue Errno::ECONNRESET
          @logger.warn "TCP Socket got Errno::ECONNRESET from #{ns}:#{@config[:port]} #{@config[:proxies]}#{suffix}"
          attempts -= 1
          retry if attempts > 0
        end
        if ans.size == 0
          if got_something
            break #Proper exit from loop
          else
            @logger.warn "Connection reset to nameserver #{ns}#{suffix}, trying next."
            throw :next_ns
          end
        end
        got_something = true
        len = ans.unpack("n")[0]

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

        if len.nil? or len == 0
          @logger.warn "Receiving 0 length packet from nameserver #{ns}#{suffix}, trying next."
          throw :next_ns
        end

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

        unless buffer.size == len
          @logger.warn "Malformed packet from nameserver #{ns}#{suffix}, trying next."
          throw :next_ns
        end
        if block_given?
          yield [buffer,["",@config[:port],ns.to_s,ns.to_s]]
        else
          return [buffer,["",@config[:port],ns.to_s,ns.to_s]]
        end
      end
    rescue Timeout::Error
      @logger.warn "Nameserver #{ns}#{suffix} not responding within TCP timeout, trying next one"
      next
    ensure
      socket.close if socket
    end
  end
  return nil
end

#send_udp(packet, packet_data, nameservers) ⇒ Object

Send request over UDP

Parameters:

  • packet (Net::DNS::Packet)

    Packet associated with packet_data

  • packet_data (String)

    Data segment of DNS request packet

  • nameservers (Array<[String,Hash]>)

    List of nameservers to use for this request, and their associated socket options



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/rex/proto/dns/resolver.rb', line 314

def send_udp(packet,packet_data, nameservers)
  ans = nil
  nameservers.each do |ns, socket_options|
    begin
      config = {
        'PeerHost' => ns.to_s,
        'PeerPort' => @config[:port].to_i,
        'Context' => @config[:context],
        'Comm' => @config[:comm],
        'Timeout' => @config[:udp_timeout]
      }
      config.update(socket_options)
      unless config['Comm'].nil? || config['Comm'].alive?
        @logger.warn("Session #{config['Comm'].sid} not active, and cannot be used to resolve DNS")
        next
      end

      if @config[:source_port] > 0
        config['LocalPort'] = @config[:source_port]
      end
      if @config[:source_host] != IPAddr.new('0.0.0.0')
        config['LocalHost'] = @config[:source_host] unless @config[:source_host].nil?
      end
      socket = Rex::Socket::Udp.create(config)
    rescue
      @logger.warn "UDP Socket could not be established to #{ns}:#{@config[:port]}"
      next
    end
    @logger.info "Contacting nameserver #{ns} port #{@config[:port]}"
    #socket.sendto(packet_data, ns.to_s, @config[:port].to_i, 0)
    socket.write(packet_data)
    ans = socket.recvfrom(@config[:packet_size])
    break if ans
  rescue Timeout::Error
    @logger.warn "Nameserver #{ns} not responding within UDP timeout, trying next one"
    next
  end
  ans
end

#upstream_resolvers_for_packet(_dns_message) ⇒ Array<Array>

Find the nameservers to use for a given DNS request

Parameters:

  • _dns_message (Dnsruby::Message)

    The DNS message to be sent

Returns:

  • (Array<Array>)

    A list of nameservers, each with Rex::Socket options



128
129
130
131
132
# File 'lib/rex/proto/dns/resolver.rb', line 128

def upstream_resolvers_for_packet(_dns_message)
  @config[:nameservers].map do |ns|
    UpstreamResolver.create_dns_server(ns.to_s)
  end
end

#upstream_resolvers_for_query(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN) ⇒ Object



134
135
136
137
138
139
140
# File 'lib/rex/proto/dns/resolver.rb', line 134

def upstream_resolvers_for_query(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)
  name, type, cls = preprocess_query_arguments(name, type, cls)
  net_packet = make_query_packet(name, type, cls)
  # This returns a Net::DNS::Packet. Convert to Dnsruby::Message for consistency
  packet = Rex::Proto::DNS::Packet.encode_drb(net_packet)
  upstream_resolvers_for_packet(packet)
end