tsig-keygen.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. """
  3. Pure Python TSIG key generator, with multiple output formats.
  4. """
  5. import os, base64, argparse
  6. algorithm_bits = dict(("hmac-sha{}".format(bits), bits // 8) for bits in (256, 384, 512))
  7. bind9_template = '''
  8. key {name} {{
  9. algorithm {algorithm};
  10. secret "{secret}";
  11. }};
  12. '''
  13. nsd_template = '''
  14. key:
  15. name: "{name}"
  16. algorithm: {algorithm}
  17. secret: "{secret}"
  18. '''
  19. ap = argparse.ArgumentParser(description = __doc__)
  20. ap.add_argument("-a", "--algorithm",
  21. choices = tuple(sorted(algorithm_bits)),
  22. default = sorted(algorithm_bits)[0])
  23. ap.add_argument("-f", "--format",
  24. choices = ("bind9", "nsd"))
  25. ap.add_argument("-n", "--name",
  26. default = "tsig.example.org")
  27. ap.add_argument("-o", "--output",
  28. default = "-", type = argparse.FileType("w"))
  29. ap.add_argument("-s", "--servers", nargs = "+")
  30. ap.add_argument("-z", "--zones", nargs = "+")
  31. args = ap.parse_args()
  32. params = dict(
  33. name = args.name,
  34. algorithm = args.algorithm,
  35. secret = base64.b64encode(os.urandom(algorithm_bits[args.algorithm])).decode("ascii"),
  36. )
  37. if args.format is None or args.format == "bind9":
  38. args.output.write(bind9_template.format(**params))
  39. if args.format is None or args.format == "nsd":
  40. args.output.write(nsd_template.format(**params))