tsig.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2001-2007, 2009-2011 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """DNS TSIG support."""
  17. import base64
  18. import hashlib
  19. import hmac
  20. import struct
  21. import dns.exception
  22. import dns.rdataclass
  23. import dns.name
  24. import dns.rcode
  25. class BadTime(dns.exception.DNSException):
  26. """The current time is not within the TSIG's validity time."""
  27. class BadSignature(dns.exception.DNSException):
  28. """The TSIG signature fails to verify."""
  29. class BadKey(dns.exception.DNSException):
  30. """The TSIG record owner name does not match the key."""
  31. class BadAlgorithm(dns.exception.DNSException):
  32. """The TSIG algorithm does not match the key."""
  33. class PeerError(dns.exception.DNSException):
  34. """Base class for all TSIG errors generated by the remote peer"""
  35. class PeerBadKey(PeerError):
  36. """The peer didn't know the key we used"""
  37. class PeerBadSignature(PeerError):
  38. """The peer didn't like the signature we sent"""
  39. class PeerBadTime(PeerError):
  40. """The peer didn't like the time we sent"""
  41. class PeerBadTruncation(PeerError):
  42. """The peer didn't like amount of truncation in the TSIG we sent"""
  43. # TSIG Algorithms
  44. HMAC_MD5 = dns.name.from_text("HMAC-MD5.SIG-ALG.REG.INT")
  45. HMAC_SHA1 = dns.name.from_text("hmac-sha1")
  46. HMAC_SHA224 = dns.name.from_text("hmac-sha224")
  47. HMAC_SHA256 = dns.name.from_text("hmac-sha256")
  48. HMAC_SHA256_128 = dns.name.from_text("hmac-sha256-128")
  49. HMAC_SHA384 = dns.name.from_text("hmac-sha384")
  50. HMAC_SHA384_192 = dns.name.from_text("hmac-sha384-192")
  51. HMAC_SHA512 = dns.name.from_text("hmac-sha512")
  52. HMAC_SHA512_256 = dns.name.from_text("hmac-sha512-256")
  53. GSS_TSIG = dns.name.from_text("gss-tsig")
  54. default_algorithm = HMAC_SHA256
  55. class GSSTSig:
  56. """
  57. GSS-TSIG TSIG implementation. This uses the GSS-API context established
  58. in the TKEY message handshake to sign messages using GSS-API message
  59. integrity codes, per the RFC.
  60. In order to avoid a direct GSSAPI dependency, the keyring holds a ref
  61. to the GSSAPI object required, rather than the key itself.
  62. """
  63. def __init__(self, gssapi_context):
  64. self.gssapi_context = gssapi_context
  65. self.data = b''
  66. self.name = 'gss-tsig'
  67. def update(self, data):
  68. self.data += data
  69. def sign(self):
  70. # defer to the GSSAPI function to sign
  71. return self.gssapi_context.get_signature(self.data)
  72. def verify(self, expected):
  73. try:
  74. # defer to the GSSAPI function to verify
  75. return self.gssapi_context.verify_signature(self.data, expected)
  76. except Exception:
  77. # note the usage of a bare exception
  78. raise BadSignature
  79. class GSSTSigAdapter:
  80. def __init__(self, keyring):
  81. self.keyring = keyring
  82. def __call__(self, message, keyname):
  83. if keyname in self.keyring:
  84. key = self.keyring[keyname]
  85. if isinstance(key, Key) and key.algorithm == GSS_TSIG:
  86. if message:
  87. GSSTSigAdapter.parse_tkey_and_step(key, message, keyname)
  88. return key
  89. else:
  90. return None
  91. @classmethod
  92. def parse_tkey_and_step(cls, key, message, keyname):
  93. # if the message is a TKEY type, absorb the key material
  94. # into the context using step(); this is used to allow the
  95. # client to complete the GSSAPI negotiation before attempting
  96. # to verify the signed response to a TKEY message exchange
  97. try:
  98. rrset = message.find_rrset(message.answer, keyname,
  99. dns.rdataclass.ANY,
  100. dns.rdatatype.TKEY)
  101. if rrset:
  102. token = rrset[0].key
  103. gssapi_context = key.secret
  104. return gssapi_context.step(token)
  105. except KeyError:
  106. pass
  107. class HMACTSig:
  108. """
  109. HMAC TSIG implementation. This uses the HMAC python module to handle the
  110. sign/verify operations.
  111. """
  112. _hashes = {
  113. HMAC_SHA1: hashlib.sha1,
  114. HMAC_SHA224: hashlib.sha224,
  115. HMAC_SHA256: hashlib.sha256,
  116. HMAC_SHA256_128: (hashlib.sha256, 128),
  117. HMAC_SHA384: hashlib.sha384,
  118. HMAC_SHA384_192: (hashlib.sha384, 192),
  119. HMAC_SHA512: hashlib.sha512,
  120. HMAC_SHA512_256: (hashlib.sha512, 256),
  121. HMAC_MD5: hashlib.md5,
  122. }
  123. def __init__(self, key, algorithm):
  124. try:
  125. hashinfo = self._hashes[algorithm]
  126. except KeyError:
  127. raise NotImplementedError(f"TSIG algorithm {algorithm} " +
  128. "is not supported")
  129. # create the HMAC context
  130. if isinstance(hashinfo, tuple):
  131. self.hmac_context = hmac.new(key, digestmod=hashinfo[0])
  132. self.size = hashinfo[1]
  133. else:
  134. self.hmac_context = hmac.new(key, digestmod=hashinfo)
  135. self.size = None
  136. self.name = self.hmac_context.name
  137. if self.size:
  138. self.name += f'-{self.size}'
  139. def update(self, data):
  140. return self.hmac_context.update(data)
  141. def sign(self):
  142. # defer to the HMAC digest() function for that digestmod
  143. digest = self.hmac_context.digest()
  144. if self.size:
  145. digest = digest[: (self.size // 8)]
  146. return digest
  147. def verify(self, expected):
  148. # re-digest and compare the results
  149. mac = self.sign()
  150. if not hmac.compare_digest(mac, expected):
  151. raise BadSignature
  152. def _digest(wire, key, rdata, time=None, request_mac=None, ctx=None,
  153. multi=None):
  154. """Return a context containing the TSIG rdata for the input parameters
  155. @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object
  156. @raises ValueError: I{other_data} is too long
  157. @raises NotImplementedError: I{algorithm} is not supported
  158. """
  159. first = not (ctx and multi)
  160. if first:
  161. ctx = get_context(key)
  162. if request_mac:
  163. ctx.update(struct.pack('!H', len(request_mac)))
  164. ctx.update(request_mac)
  165. ctx.update(struct.pack('!H', rdata.original_id))
  166. ctx.update(wire[2:])
  167. if first:
  168. ctx.update(key.name.to_digestable())
  169. ctx.update(struct.pack('!H', dns.rdataclass.ANY))
  170. ctx.update(struct.pack('!I', 0))
  171. if time is None:
  172. time = rdata.time_signed
  173. upper_time = (time >> 32) & 0xffff
  174. lower_time = time & 0xffffffff
  175. time_encoded = struct.pack('!HIH', upper_time, lower_time, rdata.fudge)
  176. other_len = len(rdata.other)
  177. if other_len > 65535:
  178. raise ValueError('TSIG Other Data is > 65535 bytes')
  179. if first:
  180. ctx.update(key.algorithm.to_digestable() + time_encoded)
  181. ctx.update(struct.pack('!HH', rdata.error, other_len) + rdata.other)
  182. else:
  183. ctx.update(time_encoded)
  184. return ctx
  185. def _maybe_start_digest(key, mac, multi):
  186. """If this is the first message in a multi-message sequence,
  187. start a new context.
  188. @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object
  189. """
  190. if multi:
  191. ctx = get_context(key)
  192. ctx.update(struct.pack('!H', len(mac)))
  193. ctx.update(mac)
  194. return ctx
  195. else:
  196. return None
  197. def sign(wire, key, rdata, time=None, request_mac=None, ctx=None, multi=False):
  198. """Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata
  199. for the input parameters, the HMAC MAC calculated by applying the
  200. TSIG signature algorithm, and the TSIG digest context.
  201. @rtype: (string, dns.tsig.HMACTSig or dns.tsig.GSSTSig object)
  202. @raises ValueError: I{other_data} is too long
  203. @raises NotImplementedError: I{algorithm} is not supported
  204. """
  205. ctx = _digest(wire, key, rdata, time, request_mac, ctx, multi)
  206. mac = ctx.sign()
  207. tsig = rdata.replace(time_signed=time, mac=mac)
  208. return (tsig, _maybe_start_digest(key, mac, multi))
  209. def validate(wire, key, owner, rdata, now, request_mac, tsig_start, ctx=None,
  210. multi=False):
  211. """Validate the specified TSIG rdata against the other input parameters.
  212. @raises FormError: The TSIG is badly formed.
  213. @raises BadTime: There is too much time skew between the client and the
  214. server.
  215. @raises BadSignature: The TSIG signature did not validate
  216. @rtype: dns.tsig.HMACTSig or dns.tsig.GSSTSig object"""
  217. (adcount,) = struct.unpack("!H", wire[10:12])
  218. if adcount == 0:
  219. raise dns.exception.FormError
  220. adcount -= 1
  221. new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start]
  222. if rdata.error != 0:
  223. if rdata.error == dns.rcode.BADSIG:
  224. raise PeerBadSignature
  225. elif rdata.error == dns.rcode.BADKEY:
  226. raise PeerBadKey
  227. elif rdata.error == dns.rcode.BADTIME:
  228. raise PeerBadTime
  229. elif rdata.error == dns.rcode.BADTRUNC:
  230. raise PeerBadTruncation
  231. else:
  232. raise PeerError('unknown TSIG error code %d' % rdata.error)
  233. if abs(rdata.time_signed - now) > rdata.fudge:
  234. raise BadTime
  235. if key.name != owner:
  236. raise BadKey
  237. if key.algorithm != rdata.algorithm:
  238. raise BadAlgorithm
  239. ctx = _digest(new_wire, key, rdata, None, request_mac, ctx, multi)
  240. ctx.verify(rdata.mac)
  241. return _maybe_start_digest(key, rdata.mac, multi)
  242. def get_context(key):
  243. """Returns an HMAC context for the specified key.
  244. @rtype: HMAC context
  245. @raises NotImplementedError: I{algorithm} is not supported
  246. """
  247. if key.algorithm == GSS_TSIG:
  248. return GSSTSig(key.secret)
  249. else:
  250. return HMACTSig(key.secret, key.algorithm)
  251. class Key:
  252. def __init__(self, name, secret, algorithm=default_algorithm):
  253. if isinstance(name, str):
  254. name = dns.name.from_text(name)
  255. self.name = name
  256. if isinstance(secret, str):
  257. secret = base64.decodebytes(secret.encode())
  258. self.secret = secret
  259. if isinstance(algorithm, str):
  260. algorithm = dns.name.from_text(algorithm)
  261. self.algorithm = algorithm
  262. def __eq__(self, other):
  263. return (isinstance(other, Key) and
  264. self.name == other.name and
  265. self.secret == other.secret and
  266. self.algorithm == other.algorithm)
  267. def __repr__(self):
  268. r = f"<DNS key name='{self.name}', " + \
  269. f"algorithm='{self.algorithm}'"
  270. if self.algorithm != GSS_TSIG:
  271. r += f", secret='{base64.b64encode(self.secret).decode()}'"
  272. r += ">"
  273. return r