Class: Dnsruby::RR::TSIG

Inherits:
Dnsruby::RR show all
Defined in:
lib/dnsruby/resource/TSIG.rb

Overview

TSIG implements RFC2845.

“This protocol allows for transaction level authentication using shared secrets and one way hashing. It can be used to authenticate dynamic updates as coming from an approved client, or to authenticate responses as coming from an approved recursive name server.”

A Dnsruby::RR::TSIG can represent the data present in a TSIG RR. However, it can also represent the data (specified in RFC2845) used to sign or verify a DNS message.

Example code :

res = Dnsruby::Resolver.new("ns0.validation-test-servers.nominet.org.uk")

# Now configure the resolver with the TSIG key for signing/verifying
KEY_NAME="rubytsig"
KEY = "8n6gugn4aJ7MazyNlMccGKH1WxD2B3UvN/O/RA6iBupO2/03u9CTa3Ewz3gBWTSBCH3crY4Kk+tigNdeJBAvrw=="
res.tsig=KEY_NAME, KEY

update = Dnsruby::Update.new("validation-test-servers.nominet.org.uk")
# Generate update record name, and test it has been made. Then delete it and check it has been deleted
update_name = generate_update_name
update.absent(update_name)
update.add(update_name, 'TXT', 100, "test signed update")

# Resolver will automatically sign message and verify response
response = res.send_message(update)
assert(response.verified?) # Check that the response has been verified

Constant Summary collapse

HMAC_MD5 =
Name.create("HMAC-MD5.SIG-ALG.REG.INT.")
HMAC_SHA1 =
Name.create("hmac-sha1.")
HMAC_SHA256 =
Name.create("hmac-sha256.")
HMAC_SHA512 =
Name.create("hmac-sha512.")
DEFAULT_FUDGE =
300
DEFAULT_ALGORITHM =
HMAC_MD5
TypeValue =

:nodoc: all

Types::TSIG
ClassValue =

:nodoc: all

nil

Constants inherited from Dnsruby::RR

ClassInsensitiveTypes

Instance Attribute Summary collapse

Attributes inherited from Dnsruby::RR

#klass, #name, #rdata, #ttl, #type

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Dnsruby::RR

#<=>, #==, #clone, create, #eql?, find_class, #from_hash, get_class, get_num, #hash, implemented_rrs, new_from_data, new_from_hash, new_from_string, #rdlength, #sameRRset, #to_s

Instance Attribute Details

#algorithmObject

Gets or sets the domain name that specifies the name of the algorithm. The only algorithms currently supported are hmac-md5 and hmac-sha1.

rr.algorithm=(algorithm_name)
print "algorithm = ", rr.algorithm, "\n"


399
400
401
# File 'lib/dnsruby/resource/TSIG.rb', line 399

def algorithm
  @algorithm
end

#errorObject

Returns the RCODE covering TSIG processing. Common values are NOERROR, BADSIG, BADKEY, and BADTIME. See RFC 2845 for details.

print "error = ", rr.error, "\n"


449
450
451
# File 'lib/dnsruby/resource/TSIG.rb', line 449

def error
  @error
end

#fudgeObject

Gets or sets the “fudge”, i.e., the seconds of error permitted in the signing time.

The default fudge is 300 seconds.

rr.fudge=(60)
print "fudge = ", rr.fudge, "\n"


419
420
421
# File 'lib/dnsruby/resource/TSIG.rb', line 419

def fudge
  @fudge
end

#keyObject

Stores the secret key used for signing/verifying messages.



467
468
469
# File 'lib/dnsruby/resource/TSIG.rb', line 467

def key
  @key
end

#macObject

Returns the message authentication code (MAC) as a string of hex characters. The programmer must call a Net::DNS::Packet object’s data method before this will return anything meaningful.

print "MAC = ", rr.mac, "\n"


435
436
437
# File 'lib/dnsruby/resource/TSIG.rb', line 435

def mac
  @mac
end

#mac_sizeObject

Returns the number of octets in the message authentication code (MAC). The programmer must call a Net::DNS::Packet object’s data method before this will return anything meaningful.

print "MAC size = ", rr.mac_size, "\n"


427
428
429
# File 'lib/dnsruby/resource/TSIG.rb', line 427

def mac_size
  @mac_size
end

#original_idObject

Gets or sets the original message ID.

rr.original_id(12345)
print "original ID = ", rr.original_id, "\n"


442
443
444
# File 'lib/dnsruby/resource/TSIG.rb', line 442

def original_id
  @original_id
end

#other_dataObject

Returns the Other Data. This field should be empty unless the error is BADTIME, in which case it will contain the server’s time as the number of seconds since 1 Jan 1970 00:00:00 UTC.

print "other data = ", rr.other_data, "\n"


464
465
466
# File 'lib/dnsruby/resource/TSIG.rb', line 464

def other_data
  @other_data
end

#other_sizeObject

Returns the length of the Other Data. Should be zero unless the error is BADTIME.

print "other len = ", rr.other_size, "\n"


456
457
458
# File 'lib/dnsruby/resource/TSIG.rb', line 456

def other_size
  @other_size
end

#time_signedObject

Gets or sets the signing time as the number of seconds since 1 Jan 1970 00:00:00 UTC.

The default signing time is the current time.

rr.time_signed=(time)
print "time signed = ", rr.time_signed, "\n"


409
410
411
# File 'lib/dnsruby/resource/TSIG.rb', line 409

def time_signed
  @time_signed
end

Class Method Details

.decode_rdata(msg) ⇒ Object

:nodoc: all



584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'lib/dnsruby/resource/TSIG.rb', line 584

def self.decode_rdata(msg) #:nodoc: all
  alg=msg.get_name
  time_high, time_low = msg.get_unpack("nN")
  time_signed = (time_high << 32) + time_low
  fudge, = msg.get_unpack("n")
  mac_size, = msg.get_unpack("n")
  mac = msg.get_bytes(mac_size)
  original_id, = msg.get_unpack("n")
  error, = msg.get_unpack("n")
  other_size, = msg.get_unpack("n")
  other_data = msg.get_bytes(other_size)
  return self.new([alg, time_signed, fudge, mac_size, mac, original_id, error, other_size, other_data])
end

Instance Method Details

#apply(message, original_request = nil) ⇒ Object

Generates a TSIG record and adds it to the message. Takes an optional original_request argument for the case where this is a response to a query (RFC2845 3.4.1)

Message#tsigstate will be set to :Signed.



68
69
70
71
72
73
74
75
76
# File 'lib/dnsruby/resource/TSIG.rb', line 68

def apply(message, original_request=nil)
  if (!message.signed?)
    tsig_rr = generate(message, original_request)
    message.add_additional(tsig_rr)
    message.tsigstate = :Signed
    @query = message
    tsig_rr.query = message
  end
end

#calculate_mac(algorithm, data) ⇒ Object



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
# File 'lib/dnsruby/resource/TSIG.rb', line 144

def calculate_mac(algorithm, data)
  mac=nil
# + if (key_size > max_digest_len) {
# +   EVP_DigestInit(&ectx, digester);
# +   EVP_DigestUpdate(&ectx, (const void*) key_bytes, key_size);
# +   EVP_DigestFinal(&ectx, key_bytes, NULL);
# +   key_size = max_digest_len;
# + }
  key = @key.gsub(" ", "")
 #        key = Base64::decode64(key)
  key = key.unpack("m*")[0]
  if (algorithm.to_s.downcase == HMAC_MD5.to_s.downcase)
    mac = OpenSSL::HMAC.digest(OpenSSL::Digest::MD5.new, key, data)
  elsif (algorithm == HMAC_SHA1)
    mac = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, key, data)
  elsif (algorithm == HMAC_SHA256)
    mac = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA256.new, key, data)
  elsif (algorithm == HMAC_SHA512)
    mac = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA512.new, key, data)
  else
    #  Should we allow client to pass in their own signing function?
    raise VerifyError.new("Algorithm #{algorithm} unsupported by TSIG")
  end
  return mac
end

#encode_rdata(msg, canonical = false) ⇒ Object

:nodoc: all



569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/dnsruby/resource/TSIG.rb', line 569

def encode_rdata(msg, canonical=false) #:nodoc: all
  #  Name needs to be added with no compression - done in Dnsruby::Message#encode
  msg.put_name(@algorithm.downcase, true)
  time_high = (@time_signed >> 32)
  time_low = (@time_signed & 0xFFFFFFFF)
  msg.put_pack('nN', time_high, time_low)
  msg.put_pack('n', @fudge)
  msg.put_pack('n', @mac_size)
  msg.put_bytes(@mac)
  msg.put_pack('n', @original_id)
  msg.put_pack('n', @error)
  msg.put_pack('n', @other_size)
  msg.put_bytes(@other_data)
end

#from_data(data) ⇒ Object

:nodoc: all



488
489
490
# File 'lib/dnsruby/resource/TSIG.rb', line 488

def from_data(data) #:nodoc: all
  @algorithm, @time_signed, @fudge, @mac_size, @mac, @original_id, @error, @other_size, @other_data = data
end

#from_string(str) ⇒ Object

Create the RR from a standard string



504
505
506
507
508
509
510
511
512
513
514
# File 'lib/dnsruby/resource/TSIG.rb', line 504

def from_string(str) #:nodoc: all
  parts = str.split("[:/]")
  if (parts.length < 2 || parts.length > 3)
    raise ArgumentException.new("Invalid TSIG key specification")
  end
  if (parts.length == 3)
    return TSIG.new(parts[0], parts[1], parts[2]);
  else
    return TSIG.new(HMAC_MD5, parts[0], parts[1]);
  end
end

#generate(msg, original_request = nil, data = "", msg_bytes = nil, tsig_rr = self) ⇒ Object

Generates a TSIG record



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/dnsruby/resource/TSIG.rb', line 84

def generate(msg, original_request = nil, data="", msg_bytes=nil, tsig_rr=self)#:nodoc: all
  time_signed=@time_signed
  if (!time_signed)
    time_signed=Time.now.to_i
  end
  if (tsig_rr.time_signed)
    time_signed = tsig_rr.time_signed
  end

  if (original_request)
    # 	# Add the request MAC if present (used to validate responses).
    # 	  hmac.update(pack("H*", request_mac))
    mac_bytes = MessageEncoder.new {|m|
      m.put_pack('n', original_request.tsig.mac_size)
      m.put_bytes(original_request.tsig.mac)
    }.to_s
    data  += mac_bytes
    #  Original ID - should we set message ID to original ID?
    if (tsig_rr != self)
      msg.header.id = tsig_rr.original_id
    else
      msg.header.id = original_request.header.id
    end
  end

  if (!msg_bytes)
    msg_bytes = msg.encode
    data += msg_bytes
  else
    #  If msg_bytes came in, we need somehow to remove the TSIG RR
    #  It is the last record, so we can strip it if we know where it starts
    #  We must also poke the header ARcount to decrement it
    msg_bytes = Header.decrement_arcount_encoded(msg_bytes)
    data += msg_bytes[0, msg.tsigstart]
  end

  data += sig_data(tsig_rr, time_signed)

  mac = calculate_mac(tsig_rr.algorithm, data)

  mac_size = mac.length

  new_tsig_rr = Dnsruby::RR.create({
      :name        => tsig_rr.name,
      :type        => Types.TSIG,
      :ttl         => tsig_rr.ttl,
      :klass       => tsig_rr.klass,
      :algorithm   => tsig_rr.algorithm,
      :fudge       => tsig_rr.fudge,
      :key         => @key,
      :mac         => mac,
      :mac_size    => mac_size,
      :error       => tsig_rr.error,
      :time_signed => time_signed,
      :original_id => msg.header.id
    })
  return new_tsig_rr

end

#init_defaultsObject



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/dnsruby/resource/TSIG.rb', line 469

def init_defaults
  #  @TODO@ Have new() method which takes key_name and key?
  @algorithm   = DEFAULT_ALGORITHM
  @fudge       = DEFAULT_FUDGE
  @mac_size    = 0
  @mac         = ""
  @original_id = rand(65536)
  @error       = 0
  @other_size   = 0
  @other_data  = ""
  @time_signed = nil
  @buf = nil

  #  RFC 2845 Section 2.3
  @klass = Classes.ANY

  @ttl = 0 # RFC 2845 Section 2.3
end

#name=(n) ⇒ Object



492
493
494
495
496
497
498
499
500
501
# File 'lib/dnsruby/resource/TSIG.rb', line 492

def name=(n)
  if (n.instance_of?String)
    n = Name.create(n)
  end
  if (!n.absolute?)
    @name = Name.create(n.to_s + ".")
  else
    @name = n
  end
end

#query=(q) ⇒ Object

:nodoc: all



78
79
80
# File 'lib/dnsruby/resource/TSIG.rb', line 78

def query=q#:nodoc: all
  @query = q
end

#rdata_to_stringObject



554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/dnsruby/resource/TSIG.rb', line 554

def rdata_to_string
  rdatastr=""
  if (@algorithm!=nil)
    error = @error
    error = "UNDEFINED" unless error!=nil
    rdatastr = "#{@original_id} #{@time_signed} #{@algorithm.to_s(true)} #{error}";
    if (@other_size > 0 && @other_data!=nil)
      rdatastr += " #{@other_data}"
    end
    rdatastr += " " + mac.unpack("H*").to_s
  end

  return rdatastr
end

#sig_data(tsig_rr, time_signed = @time_signed) ⇒ Object

Private method to return the TSIG RR data to be signed



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/dnsruby/resource/TSIG.rb', line 171

def sig_data(tsig_rr, time_signed=@time_signed) #:nodoc: all
  return MessageEncoder.new { |msg|
    msg.put_name(tsig_rr.name.downcase, true)
    msg.put_pack('nN', tsig_rr.klass.code, tsig_rr.ttl)
    msg.put_name(tsig_rr.algorithm.downcase, true)

    time_high = (time_signed >> 32)
    time_low = (time_signed & 0xFFFFFFFF)
    msg.put_pack('nN', time_high, time_low)
    msg.put_pack('n', tsig_rr.fudge)
    msg.put_pack('n', tsig_rr.error)
    msg.put_pack('n', tsig_rr.other_size)
    msg.put_bytes(tsig_rr.other_data)
  }.to_s
end

#verify(query, response, response_bytes, buf = "") ⇒ Object

Verify a response. This method will be called by Dnsruby::SingleResolver before passing a response to the client code. The TSIG record will be removed from packet before passing to client, and the Message#tsigstate and Message#tsigerror will be set accordingly. Message#tsigstate will be set to one of :

  • :Failed

  • :Verified



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
230
231
232
# File 'lib/dnsruby/resource/TSIG.rb', line 194

def verify(query, response, response_bytes, buf="")
  #         4.6. Client processing of answer
  # 
  #    When a client receives a response from a server and expects to see a
  #    TSIG, it first checks if the TSIG RR is present in the response.
  #    Otherwise, the response is treated as having a format error and
  #    discarded.  The client then extracts the TSIG, adjusts the ARCOUNT,
  #    and calculates the keyed digest in the same way as the server.  If
  #    the TSIG does not validate, that response MUST be discarded, unless
  #    the RCODE is 9 (NOTAUTH), in which case the client SHOULD attempt to
  #    verify the response as if it were a TSIG Error response, as specified
  #    in [4.3].  A message containing an unsigned TSIG record or a TSIG
  #    record which fails verification SHOULD not be considered an
  #    acceptable response; the client SHOULD log an error and continue to
  #    wait for a signed response until the request times out.

  #  So, this verify method should simply remove the TSIG RR and calculate
  #  the MAC (using original request MAC if required).
  #  Should set tsigstate on packet appropriately, and return error.
  #  Side effect is packet is stripped of TSIG.
  #  Resolver (or client) can then decide what to do...

  msg_tsig_rr = response.tsig
  if (!verify_common(response))
    return false
  end

  new_msg_tsig_rr = generate(response, query, buf, response_bytes, msg_tsig_rr)

  if (msg_tsig_rr.mac == new_msg_tsig_rr.mac)
    response.tsigstate = :Verified
    response.tsigerror = RCode.NOERROR
    return true
  else
    response.tsigstate = :Failed
    response.tsigerror = RCode.BADSIG
    return false
  end
end

#verify_common(response) ⇒ Object

:nodoc: all



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
# File 'lib/dnsruby/resource/TSIG.rb', line 234

def verify_common(response)#:nodoc: all
  tsig_rr = response.tsig

	if (!tsig_rr)
    response.tsigerror = RCode.FORMERR
    response.tsigstate = :Failed
    return false
  end

  response.additional.delete(tsig_rr)
  response.header.arcount-=1

  #  First, check the TSIG error in the RR
  if (tsig_rr.error != RCode.NOERROR)
    response.tsigstate = :Failed
    response.tsigerror = tsig_rr.error
    return false
  end

	if ((tsig_rr.name != @name) || (tsig_rr.algorithm.downcase != @algorithm.downcase))
    Dnsruby.log.error("BADKEY failure")
    response.tsigstate = :Failed
    response.tsigerror = RCode.BADKEY
    return false
  end

  #  Check time_signed (RFC2845, 4.5.2) - only really necessary for server
  if (Time.now.to_i > tsig_rr.time_signed + tsig_rr.fudge  ||
        Time.now.to_i < tsig_rr.time_signed - tsig_rr.fudge)
    Dnsruby.log.error("TSIG failed with BADTIME")
    response.tsigstate = :Failed
    response.tsigerror = RCode.BADTIME
    return false
  end

  return true
end

#verify_envelope(response, response_bytes) ⇒ Object

Checks TSIG signatures across sessions of multiple DNS envelopes. This method is called each time a new envelope comes in. The envelope is checked - if a TSIG is present, them the stream so far is verified, and the response#tsigstate set to :Verified. If a TSIG is not present, and does not need to be present, then the message is added to the digest stream and the response#tsigstate is set to :Intermediate. If there is an error with the TSIG verification, then the response#tsigstate is set to :Failed. Like verify, this method will only be called by the Dnsruby::SingleResolver class. Client code need not call this method directly.



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
386
# File 'lib/dnsruby/resource/TSIG.rb', line 282

def verify_envelope(response, response_bytes)
  # RFC2845 Section 4.4
  # -----
  # A DNS TCP session can include multiple DNS envelopes.  This is, for
  # example, commonly used by zone transfer.  Using TSIG on such a
  # connection can protect the connection from hijacking and provide data
  # integrity.  The TSIG MUST be included on the first and last DNS
  # envelopes.  It can be optionally placed on any intermediary
  # envelopes.  It is expensive to include it on every envelopes, but it
  # MUST be placed on at least every 100'th envelope.  The first envelope
  # is processed as a standard answer, and subsequent messages have the
  # following digest components:
  # 
  # *   Prior Digest (running)
  # *   DNS Messages (any unsigned messages since the last TSIG)
  # *   TSIG Timers (current message)
  # 
  # This allows the client to rapidly detect when the session has been
  # altered; at which point it can close the connection and retry.  If a
  # client TSIG verification fails, the client MUST close the connection.
  # If the client does not receive TSIG records frequently enough (as
  # specified above) it SHOULD assume the connection has been hijacked
  # and it SHOULD close the connection.  The client SHOULD treat this the
  # same way as they would any other interrupted transfer (although the
  # exact behavior is not specified).
  # -----
  # 
  #  Each time a new envelope comes in, this method is called on the QUERY TSIG RR.
  #  It will set the response tsigstate to :Verified :Intermediate or :Failed
  #  as appropriate.

  #  Keep digest going of messages as they come in (and mark them intermediate)
  #  When TSIG comes in, work out what key should be and check. If OK, mark
  #  verified. Can reset digest then.
  if (!@buf)
    @num_envelopes = 0
    @last_signed = 0
  end
  @num_envelopes += 1
  if (!response.tsig)
    if ((@num_envelopes > 1) && (@num_envelopes - @last_signed < 100))
      Dnsruby.log.debug("Receiving intermediate envelope in TSIG TCP session")
      response.tsigstate = :Intermediate
      response.tsigerror = RCode.NOERROR
      @buf = @buf + response_bytes
      return
    else
      response.tsigstate = :Failed
      Dnsruby.log.error("Expecting signed packet")
      return false
    end
  end
  @last_signed = @num_envelopes

  #  We have a TSIG - process it!
  tsig = response.tsig
  if (@num_envelopes == 1)
    Dnsruby.log.debug("First response in TSIG TCP session - verifying normally")
    #  Process it as a standard answer
    ok = verify(@query, response, response_bytes)
    if (ok)
      mac_bytes = MessageEncoder.new {|m|
        m.put_pack('n', tsig.mac_size)
        m.put_bytes(tsig.mac)
      }.to_s
      @buf = mac_bytes
    end
    return ok
  end
  Dnsruby.log.debug("Processing TSIG on TSIG TCP session")

  if (!verify_common(response))
    return false
  end

  #  Now add the current message data - remember to frig the arcount
  response_bytes = Header.decrement_arcount_encoded(response_bytes)
  @buf += response_bytes[0, response.tsigstart]

  #  Let's add the timers
  timers_data = MessageEncoder.new { |msg|
    time_high = (tsig.time_signed >> 32)
    time_low = (tsig.time_signed & 0xFFFFFFFF)
    msg.put_pack('nN', time_high, time_low)
    msg.put_pack('n', tsig.fudge)
  }.to_s
  @buf += timers_data

  mac = calculate_mac(tsig.algorithm, @buf)

  if (mac != tsig.mac)
    Dnsruby.log.error("TSIG Verify error on TSIG TCP session")
    response.tsigstate = :Failed
    return false
  end
  mac_bytes = MessageEncoder.new {|m|
    m.put_pack('n', mac.length)
    m.put_bytes(mac)
  }.to_s
  @buf=mac_bytes

  response.tsigstate = :Verified
  response.tsigerror = RCode.NOERROR
  return true
end