tsigkeyring.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-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. """A place to store TSIG keys."""
  17. import base64
  18. import dns.name
  19. import dns.tsig
  20. def from_text(textring):
  21. """Convert a dictionary containing (textual DNS name, base64 secret)
  22. pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or
  23. a dictionary containing (textual DNS name, (algorithm, base64 secret))
  24. pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs.
  25. @rtype: dict"""
  26. keyring = {}
  27. for (name, value) in textring.items():
  28. name = dns.name.from_text(name)
  29. if isinstance(value, str):
  30. keyring[name] = dns.tsig.Key(name, value).secret
  31. else:
  32. (algorithm, secret) = value
  33. keyring[name] = dns.tsig.Key(name, secret, algorithm)
  34. return keyring
  35. def to_text(keyring):
  36. """Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs
  37. into a text keyring which has (textual DNS name, (textual algorithm,
  38. base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes)
  39. pairs into a text keyring which has (textual DNS name, base64 secret) pairs.
  40. @rtype: dict"""
  41. textring = {}
  42. def b64encode(secret):
  43. return base64.encodebytes(secret).decode().rstrip()
  44. for (name, key) in keyring.items():
  45. name = name.to_text()
  46. if isinstance(key, bytes):
  47. textring[name] = b64encode(key)
  48. else:
  49. if isinstance(key.secret, bytes):
  50. text_secret = b64encode(key.secret)
  51. else:
  52. text_secret = str(key.secret)
  53. textring[name] = (key.algorithm.to_text(), text_secret)
  54. return textring