generate_caa_record.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python3
  2. # Based on github.com/diafygi/acme-tiny, original copyright:
  3. # Copyright Daniel Roesler, under MIT license, see LICENSE at github.com/diafygi/acme-tiny
  4. import argparse, subprocess, json, os, sys, base64, binascii, time, hashlib, re, copy, textwrap, logging
  5. try:
  6. from urllib.request import urlopen, Request # Python 3
  7. except ImportError: # pragma: no cover
  8. from urllib2 import urlopen, Request # Python 2
  9. DEFAULT_DIRECTORY_URL = "https://acme-v02.api.letsencrypt.org/directory"
  10. LOGGER = logging.getLogger(__name__)
  11. LOGGER.addHandler(logging.StreamHandler())
  12. LOGGER.setLevel(logging.INFO)
  13. def get_id(account_key, log=LOGGER, directory_url=DEFAULT_DIRECTORY_URL, contact=None):
  14. directory, acct_headers, alg, jwk = None, None, None, None # global variables
  15. # helper functions - base64 encode for jose spec
  16. def _b64(b):
  17. return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "")
  18. # helper function - run external commands
  19. def _cmd(cmd_list, stdin=None, cmd_input=None, err_msg="Command Line Error"):
  20. proc = subprocess.Popen(cmd_list, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  21. out, err = proc.communicate(cmd_input)
  22. if proc.returncode != 0:
  23. raise IOError("{0}\n{1}".format(err_msg, err))
  24. return out
  25. # helper function - make request and automatically parse json response
  26. def _do_request(url, data=None, err_msg="Error", depth=0):
  27. try:
  28. resp = urlopen(Request(url, data=data, headers={"Content-Type": "application/jose+json", "User-Agent": "acme-tiny"}))
  29. resp_data, code, headers = resp.read().decode("utf8"), resp.getcode(), resp.headers
  30. except IOError as e:
  31. resp_data = e.read().decode("utf8") if hasattr(e, "read") else str(e)
  32. code, headers = getattr(e, "code", None), {}
  33. try:
  34. resp_data = json.loads(resp_data) # try to parse json results
  35. except ValueError:
  36. pass # ignore json parsing errors
  37. if depth < 100 and code == 400 and resp_data['type'] == "urn:ietf:params:acme:error:badNonce":
  38. raise IndexError(resp_data) # allow 100 retrys for bad nonces
  39. if code not in [200, 201, 204]:
  40. raise ValueError("{0}:\nUrl: {1}\nData: {2}\nResponse Code: {3}\nResponse: {4}".format(err_msg, url, data, code, resp_data))
  41. return resp_data, code, headers
  42. # helper function - make signed requests
  43. def _send_signed_request(url, payload, err_msg, depth=0):
  44. payload64 = "" if payload is None else _b64(json.dumps(payload).encode('utf8'))
  45. new_nonce = _do_request(directory['newNonce'])[2]['Replay-Nonce']
  46. protected = {"url": url, "alg": alg, "nonce": new_nonce}
  47. protected.update({"jwk": jwk} if acct_headers is None else {"kid": acct_headers['Location']})
  48. protected64 = _b64(json.dumps(protected).encode('utf8'))
  49. protected_input = "{0}.{1}".format(protected64, payload64).encode('utf8')
  50. out = _cmd(["openssl", "dgst", "-sha256", "-sign", account_key], stdin=subprocess.PIPE, cmd_input=protected_input, err_msg="OpenSSL Error")
  51. data = json.dumps({"protected": protected64, "payload": payload64, "signature": _b64(out)})
  52. try:
  53. return _do_request(url, data=data.encode('utf8'), err_msg=err_msg, depth=depth)
  54. except IndexError: # retry bad nonces (they raise IndexError)
  55. return _send_signed_request(url, payload, err_msg, depth=(depth + 1))
  56. # helper function - poll until complete
  57. def _poll_until_not(url, pending_statuses, err_msg):
  58. result, t0 = None, time.time()
  59. while result is None or result['status'] in pending_statuses:
  60. assert (time.time() - t0 < 3600), "Polling timeout" # 1 hour timeout
  61. time.sleep(0 if result is None else 2)
  62. result, _, _ = _send_signed_request(url, None, err_msg)
  63. return result
  64. # parse account key to get public key
  65. log.info("Parsing account key...")
  66. out = _cmd(["openssl", "rsa", "-in", account_key, "-noout", "-text"], err_msg="OpenSSL Error")
  67. pub_pattern = r"modulus:[\s]+?00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)"
  68. pub_hex, pub_exp = re.search(pub_pattern, out.decode('utf8'), re.MULTILINE|re.DOTALL).groups()
  69. pub_exp = "{0:x}".format(int(pub_exp))
  70. pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
  71. alg, jwk = "RS256", {
  72. "e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
  73. "kty": "RSA",
  74. "n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
  75. }
  76. accountkey_json = json.dumps(jwk, sort_keys=True, separators=(',', ':'))
  77. thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
  78. # get the ACME directory of urls
  79. log.info("Getting directory...")
  80. directory, _, _ = _do_request(directory_url, err_msg="Error getting directory")
  81. log.info("Directory found!")
  82. # create account and get the global key identifier
  83. log.info("Registering account...")
  84. reg_payload = {"termsOfServiceAgreed": True} if contact is None else {"termsOfServiceAgreed": True, "contact": contact}
  85. account, code, acct_headers = _send_signed_request(directory['newAccount'], reg_payload, "Error registering")
  86. log.info("Registered!" if code == 201 else "Already registered!")
  87. return acct_headers['Location']
  88. def main(argv=None):
  89. parser = argparse.ArgumentParser(
  90. formatter_class=argparse.RawDescriptionHelpFormatter,
  91. description=textwrap.dedent("""\
  92. Generate a CAA record for Mailcow.
  93. Example Usage: python mailcow_gencaa.py --account-key data/assets/ssl/acme/account.pem
  94. """)
  95. )
  96. parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
  97. parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
  98. parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt")
  99. parser.add_argument("--contact", metavar="CONTACT", default=None, nargs="*", help="Contact details (e.g. mailto:aaa@bbb.com) for your account-key")
  100. args = parser.parse_args(argv)
  101. LOGGER.setLevel(args.quiet or LOGGER.level)
  102. id = get_id(args.account_key, log=LOGGER, directory_url=args.directory_url, contact=args.contact)
  103. print("Use this as your CAA record:")
  104. print('issue 128 "letsencrypt.org;accounturi={}"'.format(id))
  105. if __name__ == "__main__": # pragma: no cover
  106. main(sys.argv[1:])