Class: Dnsruby::ZoneTransfer

Inherits:
Object
  • Object
show all
Defined in:
lib/dnsruby/zone_transfer.rb

Overview

This class performs zone transfers as per RFC1034 (AXFR) and RFC1995 (IXFR).

Defined Under Namespace

Classes: Delta

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ ZoneTransfer

Returns a new instance of ZoneTransfer.



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/dnsruby/zone_transfer.rb', line 66

def initialize
  @server=Config.new.nameserver[0]
  @transfer_type = Types.AXFR
  @klass=Classes.IN
  @port=53
  @serial=0
  @tsig = nil
  @axfr = nil
  @src_address = nil
  @connect_timeout = 5
  @io_timeout = 30
  @transfer_timeout = nil
end

Instance Attribute Details

#connect_timeout ⇒ Object

Sets the connect timeout in seconds



37
38
39
# File 'lib/dnsruby/zone_transfer.rb', line 37

def connect_timeout
  @connect_timeout
end

#io_timeout ⇒ Object

Maximum seconds for one complete DNS frame to be read or written.



39
40
41
# File 'lib/dnsruby/zone_transfer.rb', line 39

def io_timeout
  @io_timeout
end

#klass ⇒ Object

The class - defaults to IN



25
26
27
# File 'lib/dnsruby/zone_transfer.rb', line 25

def klass
  @klass
end

#last_tsigstate ⇒ Object (readonly)

Returns the tsigstate of the last transfer (nil if no TSIG signed transfer has occurred)



35
36
37
# File 'lib/dnsruby/zone_transfer.rb', line 35

def last_tsigstate
  @last_tsigstate
end

#port ⇒ Object

The port to connect to - defaults to 53



27
28
29
# File 'lib/dnsruby/zone_transfer.rb', line 27

def port
  @port
end

#serial ⇒ Object

If using IXFR, this is the SOA serial number to start the incrementals from



29
30
31
# File 'lib/dnsruby/zone_transfer.rb', line 29

def serial
  @serial
end

#server ⇒ Object

The nameserver to use for the zone transfer - defaults to system config



21
22
23
# File 'lib/dnsruby/zone_transfer.rb', line 21

def server
  @server
end

#src_address ⇒ Object

The source address to connect to



31
32
33
# File 'lib/dnsruby/zone_transfer.rb', line 31

def src_address
  @src_address
end

#transfer_timeout ⇒ Object

Optional maximum seconds per server, including connect and IXFR fallback.



41
42
43
# File 'lib/dnsruby/zone_transfer.rb', line 41

def transfer_timeout
  @transfer_timeout
end

#transfer_type ⇒ Object

What type of transfer to do (IXFR or AXFR) - defaults to AXFR



23
24
25
# File 'lib/dnsruby/zone_transfer.rb', line 23

def transfer_type
  @transfer_type
end

#tsig ⇒ Object

The TSIG record used to sign the transfer



33
34
35
# File 'lib/dnsruby/zone_transfer.rb', line 33

def tsig
  @tsig
end

Instance Method Details

#compare_serial(s1, s2) ⇒ Object

Compare two serials according to RFC 1982. Return 0 if equal, -1 if s1 is bigger, 1 if s1 is smaller.



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/dnsruby/zone_transfer.rb', line 259

def compare_serial(s1, s2)
  if s1 == s2
    return 0
  end
  if s1 < s2 and (s2 - s1) < (2**31)
    return 1
  end
  if s1 > s2 and (s1 - s2) > (2**31)
    return 1
  end
  if s1 < s2 and (s2 - s1) > (2**31)
    return -1
  end
  if s1 > s2 and (s1 - s2) < (2**31)
    return -1
  end
  return 0
end

#do_transfer(zone, server) ⇒ Object

:nodoc: all



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
186
187
188
189
190
191
192
193
194
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
# File 'lib/dnsruby/zone_transfer.rb', line 128

def do_transfer(zone, server) #:nodoc: all
  @transfer_type = Types.new(@transfer_type)
  @state = :InitialSoa
  @axfr = @ixfr = nil
  @initialsoa = @end_serial = @current_serial = @rtype = nil
  @last_tsigstate = nil
  @transfer_deadline = @transfer_timeout && TransportClock.now + @transfer_timeout
  socket = nil
  begin
    connect_limit = [@connect_timeout, @transfer_timeout].compact.min
    socket = Socket.tcp(server, @port, @src_address, connect_timeout: connect_limit)
    #  Send an initial query
    msg = Message.new(zone, @transfer_type, @klass)
    # Compare SOA owners with the absolute name sent in the question.
    @zone_name = msg.question.first.qname
    if @transfer_type == Types.IXFR
      rr = RR.create("#{zone} 0 #{@klass} SOA " + '0 0 %u 0 0 0 0' % @serial)
      msg.add_authority(rr)
    end
    @request = msg
    send_message(socket, msg)

    while (@state != :End)
      response = receive_message(socket)
      validate_response(response)
      # An error can terminate a transfer after earlier successful frames.
      if @state != :InitialSoa && response.rcode != RCode.NOERROR
        raise ResolvError, response.rcode.string
      end

      if (@state == :InitialSoa)
        rcode = response.rcode
        if (rcode != RCode.NOERROR)
          if (@transfer_type == Types.IXFR &&
                rcode == RCode.NOTIMP)
            #  IXFR didn't work - let's try AXFR
            Dnsruby.log.debug("IXFR DID NOT WORK (rcode = NOTIMP) - TRYING AXFR!!")
            @state = :InitialSoa
            @transfer_type=Types.AXFR
            #  Send an initial AXFR query
            msg = Message.new(zone, @transfer_type, @klass)
            @request = msg
            send_message(socket, msg)
            next
          end
          raise ResolvError.new(rcode.string);
        end

        if (response.header.ancount == 0 && @transfer_type == Types.IXFR)
          Dnsruby.log.debug("IXFR DID NOT WORK (ancount = 0) - TRYING AXFR!!")
          #  IXFR didn't work - let's try AXFR
          @transfer_type=Types.AXFR
          #  Send an initial AXFR query
          @state = :InitialSoa
          msg = Message.new(zone, @transfer_type, @klass)
          @request = msg
          send_message(socket, msg)
          next
        end
      end

      response.each_answer { |rr|
        parseRR(rr)
      }
      if (@state == :End &&
            response.tsigstate == :Intermediate)
        raise ResolvError.new("last message must be signed")
      end
      if (@state == :End && @tsig)
        if (response.tsigstate != :Verified)
          @last_tsigstate = :Failed
          raise ResolvError.new("Zone transfer not correctly signed")
        end
        @last_tsigstate = :Verified
      end
    end
    #  This could return with an IXFR response, or an AXFR response.
    #  If it fails completely, then try to send an AXFR query.
    #  Once the query has been sent, then enter the main response loop.
    #  Unless we know we're definitely AXFR, we should be prepared for either IXFR or AXFR
    #  AXFR response : The first and the last RR of the response is the SOA record of the zone.
    #                  The whole zone is returned inbetween.
    #  IXFR response : one or more difference sequences is returned.  The list of difference
    #                  sequences is preceded and followed by a copy of the server's current
    #                  version of the SOA.
    #                  Each difference sequence represents one update to the zone (one SOA
    #                  serial change) consisting of deleted RRs and added RRs.  The first RR
    #                  of the deleted RRs is the older SOA RR and the first RR of the added
    #                  RRs is the newer SOA RR.
    if (@axfr!=nil)
      return @axfr.uniq
    end
    return @ixfr
  ensure
    begin
      socket.close if socket && !socket.closed?
    rescue IOError, SystemCallError
      # Preserve the transfer's result or original failure if close races.
    end
    @transfer_deadline = nil
  end
end

#parseRR(rec) ⇒ Object

:nodoc: all



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
305
306
307
308
309
310
311
312
313
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/dnsruby/zone_transfer.rb', line 278

def parseRR(rec) #:nodoc: all
  type = rec.type

  case @state
  when :InitialSoa
    if (type != Types.SOA)
      raise ResolvError.new("missing initial SOA")
    end
    unless rec.name == @zone_name && rec.klass == Classes.new(@klass)
      raise ResolvError, "initial SOA does not match transfer zone"
    end
    @initialsoa = rec
    #  Remember the serial number in the initial SOA; we need it
    #  to recognize the end of an IXFR.
    @end_serial = rec.serial
    #         if ((@transfer_type == Types.IXFR) && (@end_serial <= @serial))
    if ((@transfer_type == Types.IXFR) && (compare_serial(@end_serial, @serial) >= 0))
      Dnsruby.log.debug("zone up to date")
      raise ZoneSerialError.new("IXFR up to date: expected serial " +
          @serial.to_s + " , got " + rec.serial.to_s);
      @state = :End
    else
      @state = :FirstData
    end
  when :FirstData
    #  If the transfer begins with 1 SOA, it's an AXFR.
    #  If it begins with 2 SOAs, it's an IXFR.
    if (@transfer_type == Types.IXFR && type == Types.SOA &&
          rec.serial == @serial)
      Dnsruby.log.debug("IXFR response - using IXFR")
      @rtype = Types.IXFR
      @ixfr = []
      @state = :Ixfr_DelSoa
    else
      Dnsruby.log.debug("AXFR response - using AXFR")
      @rtype = Types.AXFR
      @transfer_type = Types.AXFR
      @axfr = []
      @axfr << @initialsoa
      @state = :Axfr
    end
    parseRR(rec) # Restart...
    return

  when :Ixfr_DelSoa
    delta = Delta.new
    @ixfr.push(delta)
    delta.start = rec.serial
    delta.deletes << rec
    @state = :Ixfr_Del

  when :Ixfr_Del
    if (type == Types.SOA)
      @current_serial = rec.serial
      @state = :Ixfr_AddSoa
      parseRR(rec); # Restart...
      return;
    end
    delta = @ixfr[@ixfr.length - 1]
    delta.deletes << rec

  when :Ixfr_AddSoa
    delta = @ixfr[@ixfr.length - 1]
    delta.end = rec.serial
    delta.adds << rec
    @state = :Ixfr_Add

  when :Ixfr_Add
    if (type == Types.SOA)
      soa_serial = rec.serial
      if (soa_serial == @end_serial)
        unless same_soa?(rec, @initialsoa)
          raise ResolvError, "closing SOA does not match initial SOA"
        end
        @state = :End
        return
      elsif (soa_serial != @current_serial)
        raise ZoneSerialError.new("IXFR out of sync: expected serial " +
            @current_serial.to_s + " , got " + soa_serial.to_s);
      else
        @state = :Ixfr_DelSoa
        parseRR(rec); # Restart...
        return;
      end
    end
    delta = @ixfr[@ixfr.length - 1]
    delta.adds << rec

  when :Axfr
    #  Old BINDs sent cross class A records for non IN classes.
    if (type == Types.A && rec.klass() != @klass)
    else
      if (type == Types.SOA)
        unless same_soa?(rec, @initialsoa)
          raise ResolvError, "closing SOA does not match initial SOA"
        end
        @state = :End
      else
        @axfr << rec
      end
    end
  when :End
    raise ResolvError.new("extra data in zone transfer")

  else
    raise ResolvError.new("invalid state for zone transfer")
  end
end

#receive_message(socket) ⇒ Object

:nodoc: all

Raises:



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/dnsruby/zone_transfer.rb', line 444

def receive_message(socket) #:nodoc: all
  deadline = io_deadline
  buf = tcp_read(socket, 2, deadline)
  answersize = buf.unpack('n')[0]
  #  Some servers (e.g. dnscache) apparently hang up on some connections.
  #  Thanks to Matt Palmer for the fix.
  raise ResolvError.new("Server did not send a valid answer") if answersize.nil?
  buf = tcp_read(socket, answersize, deadline)
  msg = Message.decode(buf)
  if (@tsig)
    signature = msg.tsig
    verified = @tsig.verify_envelope(msg, buf)
    @last_tsigstate = msg.tsigstate
    if !verified
      authenticated_error = RR::TSIG.authenticated_error(msg, signature)
      raise authenticated_error if authenticated_error
      Dnsruby.log.error("Bad signature on zone transfer - closing connection")
      raise ResolvError.new("Bad signature on zone transfer")
    end
  end
  return msg
end

#send_message(socket, msg) ⇒ Object

:nodoc: all

Raises:



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/dnsruby/zone_transfer.rb', line 388

def send_message(socket, msg) #:nodoc: all
  msg.tsig.warn_if_legacy_algorithm if msg.tsig
  if (@tsig)
    # Keep the last query's TSIG available to callers. Generate a fresh
    # timestamp for each transfer or retry unless the caller set one.
    if @last_tsig_time.nil? || @tsig.time_signed != @last_tsig_time
      @tsig_configured_time = @tsig.time_signed
    end
    signing_key = @tsig.dup
    signing_key.time_signed = @tsig_configured_time
    signing_key.apply(msg)
    @tsig = msg.tsig
    @last_tsig_time = @tsig.time_signed
  end
  query_packet = msg.encode
  raise EncodeError, "DNS message exceeds the 65535-byte wire limit" if query_packet.bytesize > 65_535
  frame = [query_packet.bytesize].pack('n') + query_packet
  deadline = io_deadline
  offset = 0
  while offset < frame.bytesize
    check_deadline(deadline)
    begin
      written = socket.write_nonblock(frame.byteslice(offset, frame.bytesize - offset))
      raise IOError, "zone transfer write made no progress" unless written && written > 0
      offset += written
    rescue IO::WaitWritable
      wait_for_io(socket, deadline, false)
    rescue IO::WaitReadable
      wait_for_io(socket, deadline, true)
    rescue Errno::EINTR
      next
    end
  end
end

#tcp_read(socket, len, deadline = io_deadline) ⇒ Object

:nodoc: all



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/dnsruby/zone_transfer.rb', line 423

def tcp_read(socket, len, deadline = io_deadline) #:nodoc: all
  buf = +"".b
  while buf.bytesize < len
    check_deadline(deadline)
    begin
      part = socket.read_nonblock(len - buf.bytesize)
      raise ResolvError, "Server closed an incomplete zone transfer" if part.nil? || part.empty?
      buf << part
    rescue IO::WaitReadable
      wait_for_io(socket, deadline, true)
    rescue IO::WaitWritable
      wait_for_io(socket, deadline, false)
    rescue Errno::EINTR
      next
    rescue EOFError
      raise ResolvError, "Server closed an incomplete zone transfer"
    end
  end
  buf
end

#transfer(zone) ⇒ Object

Perform a zone transfer (RFC1995) If an IXFR query is unsuccessful, then AXFR is tried (and @transfer_type is set to AXFR) TCP is used as the only transport

If AXFR is performed, then the zone will be returned as a set of records :

   zt = Dnsruby::ZoneTransfer.new
   zt.transfer_type = Dnsruby::Types.AXFR
   zt.server = "ns0.validation-test-servers.nominet.org.uk"
   zone = zt.transfer("validation-test-servers.nominet.org.uk")
   soa = zone[0]
   rec1 = zone[1]
   print zone.to_s

If IXFR is performed, then the incrementals will be returned as a set of Deltas. Each Delta contains the start and end SOA serial number, as well as an array of adds and deletes that occurred between the start and end.

    zt = Dnsruby::ZoneTransfer.new
    zt.transfer_type = Dnsruby::Types.IXFR
    zt.server = "ns0.validation-test-servers.nominet.org.uk"
    zt.serial = 2007090401
    deltas = zt.transfer("validation-test-servers.nominet.org.uk")
    assert_equal("Should show up in transfer", deltas[0].adds[1].data)


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/dnsruby/zone_transfer.rb', line 106

def transfer(zone)
  servers = @server
  if (servers.class == String)
    servers=[servers]
  end
  xfr = nil
  exception = nil
  servers.each do |server|
    begin
      server=Config.resolve_server(server)
      xfr = do_transfer(zone, server)
      break
    rescue Exception => e
      exception = e
    end
  end
  if (xfr == nil && exception != nil)
    raise exception
  end
  return xfr
end