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 => "/dev/null", # default can lead to info leaks
  :log_file => "/dev/null", # formerly $stdout, should be tied in with our loggers
  :port => 53,
  :searchlist => [],
  :nameservers => [IPAddr.new("127.0.0.1")],
  :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(30),
  :udp_timeout => UdpTimeout.new(30),
  :context => {},
  :comm => nil
}

Instance Attribute 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 conusumed by parent class

Raises:

  • (ResolverArgumentError)


44
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
# File 'lib/rex/proto/dns/resolver.rb', line 44

def initialize(config = {})
  raise ResolverArgumentError, "Argument has to be Hash" unless config.kind_of? Hash
  # config.key_downcase!
  @config = Defaults.merge config
  @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 = context = config.delete(:context)
  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
end

Instance Attribute Details

#commObject

Returns the value of attribute comm.



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

def comm
  @comm
end

#contextObject

Returns the value of attribute context.



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

def context
  @context
end

Instance Method Details

#proxiesString

Provides current proxy setting if configured

Returns:

  • (String)

    Current proxy configuration



92
93
94
# File 'lib/rex/proto/dns/resolver.rb', line 92

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



101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rex/proto/dns/resolver.rb', line 101

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



366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/rex/proto/dns/resolver.rb', line 366

def query(name, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)

  return send(name,type,cls) if name.class == IPAddr

  # If the name doesn't contain any dots then append the default domain.
  if name !~ /\./ and name !~ /:/ and @config[:defname]
    name += "." + @config[:domain]
  end

  @logger.debug "Query(#{name},#{Dnsruby::Types.new(type)},#{Dnsruby::Classes.new(cls)})"

  return 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



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/rex/proto/dns/resolver.rb', line 336

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



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
# File 'lib/rex/proto/dns/resolver.rb', line 121

def send(argument, type = Dnsruby::Types::A, cls = Dnsruby::Classes::IN)
  if @config[:nameservers].size == 0
    raise ResolverError, "No nameservers specified!"
  end

  method = self.use_tcp? ? :send_tcp : :send_udp

  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

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

  # Choose whether use TCP, UDP
  if packet_size > @config[:packet_size] # Must use TCP
    @logger.info "Sending #{packet_size} bytes using TCP due to size"
    method = :send_tcp
  else # Packet size is inside the boundaries
    if use_tcp? or !(proxies.nil? or proxies.empty?) # User requested TCP
      @logger.info "Sending #{packet_size} bytes using TCP due to tcp flag"
      method = :send_tcp
    else # Finally use UDP
      @logger.info "Sending #{packet_size} bytes using UDP"
      method = :send_udp unless method == :send_tcp
    end
  end

  if type == Dnsruby::Types::AXFR
    @logger.warn "AXFR query, switching to TCP" unless method == :send_tcp
    method = :send_tcp
  end

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

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

  @logger.info "Received #{ans[0].size} bytes from #{ans[1][2]+":"+ans[1][1].to_s}"
  # 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, 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

  • prox (String) (defaults to: )

    Proxy configuration for TCP socket



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
# File 'lib/rex/proto/dns/resolver.rb', line 195

def send_tcp(packet,packet_data,prox = @config[:proxies])
  ans = nil
  length = [packet_data.size].pack("n")
  @config[:nameservers].each do |ns|
    begin
      socket = nil
      @config[:tcp_timeout].timeout do
        catch(:next_ns) do
          begin
            config = {
              'PeerHost' => ns.to_s,
              'PeerPort' => @config[:port].to_i,
              'Proxies' => prox,
              'Context' => @config[:context],
              'Comm' => @config[:comm]
            }
            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
            socket = Rex::Socket::Tcp.create(config)
          rescue
            @logger.warn "TCP Socket could not be established to #{ns}:#{@config[:port]} #{@config[:proxies]}"
            throw :next_ns
          end
          next unless socket #
          @logger.info "Contacting nameserver #{ns} port #{@config[:port]}"
          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]}"
              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}, 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}, 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}, 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
        end
      end
    rescue Timeout::Error
      @logger.warn "Nameserver #{ns} not responding within TCP timeout, trying next one"
      next
    ensure
      socket.close if socket
    end
  end
  return nil
end

#send_udp(packet, packet_data) ⇒ Object

Send request over UDP

Parameters:

  • packet (Net::DNS::Packet)

    Packet associated with packet_data

  • packet_data (String)

    Data segment of DNS request packet



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/rex/proto/dns/resolver.rb', line 289

def send_udp(packet,packet_data)
  ans = nil
  response = ""
  @config[:nameservers].each do |ns|
    begin
      @config[:udp_timeout].timeout do
        begin
          config = {
            'PeerHost' => ns.to_s,
            'PeerPort' => @config[:port].to_i,
            'Context' => @config[:context],
            'Comm' => @config[:comm]
          }
          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]}"
          return nil
        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])
      end
      break if ans
    rescue Timeout::Error
      @logger.warn "Nameserver #{ns} not responding within UDP timeout, trying next one"
      next
    end
  end
  return ans
end