acme_tiny.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/env python
  2. import argparse, subprocess, json, os, sys, base64, binascii, time, hashlib, re, copy, textwrap, logging
  3. try:
  4. from urllib.request import urlopen, Request # Python 3
  5. except ImportError:
  6. from urllib2 import urlopen, Request # Python 2
  7. DEFAULT_CA = "https://acme-v02.api.letsencrypt.org" # DEPRECATED! USE DEFAULT_DIRECTORY_URL INSTEAD
  8. DEFAULT_DIRECTORY_URL = "https://acme-v02.api.letsencrypt.org/directory"
  9. LOGGER = logging.getLogger(__name__)
  10. LOGGER.addHandler(logging.StreamHandler())
  11. LOGGER.setLevel(logging.INFO)
  12. def get_crt(account_key, csr, acme_dir, log=LOGGER, CA=DEFAULT_CA, disable_check=False, directory_url=DEFAULT_DIRECTORY_URL, contact=None):
  13. directory, acct_headers, alg, jwk = None, None, None, None # global variables
  14. # helper functions - base64 encode for jose spec
  15. def _b64(b):
  16. return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "")
  17. # helper function - run external commands
  18. def _cmd(cmd_list, stdin=None, cmd_input=None, err_msg="Command Line Error"):
  19. proc = subprocess.Popen(cmd_list, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  20. out, err = proc.communicate(cmd_input)
  21. if proc.returncode != 0:
  22. raise IOError("{0}\n{1}".format(err_msg, err))
  23. return out
  24. # helper function - make request and automatically parse json response
  25. def _do_request(url, data=None, err_msg="Error", depth=0):
  26. try:
  27. resp = urlopen(Request(url, data=data, headers={"Content-Type": "application/jose+json"}))
  28. resp_data, code, headers = resp.read().decode("utf8"), resp.getcode(), resp.headers
  29. resp_data = json.loads(resp_data) # try to parse json results
  30. except ValueError:
  31. pass # ignore json parsing errors
  32. except IOError as e:
  33. resp_data = e.read().decode("utf8") if hasattr(e, "read") else str(e)
  34. code, headers = getattr(e, "code", None), {}
  35. if depth < 100 and code == 400 and json.loads(resp_data)['type'] == "urn:ietf:params:acme:error:badNonce":
  36. raise IndexError(resp_data) # allow 100 retrys for bad nonces
  37. if code not in [200, 201, 204]:
  38. raise ValueError("{0}:\nUrl: {1}\nData: {2}\nResponse Code: {3}\nResponse: {4}".format(err_msg, url, data, code, resp_data))
  39. return resp_data, code, headers
  40. # helper function - make signed requests
  41. def _send_signed_request(url, payload, err_msg, depth=0):
  42. payload64 = _b64(json.dumps(payload).encode('utf8'))
  43. new_nonce = _do_request(directory['newNonce'])[2]['Replay-Nonce']
  44. protected = {"url": url, "alg": alg, "nonce": new_nonce}
  45. protected.update({"jwk": jwk} if acct_headers is None else {"kid": acct_headers['Location']})
  46. protected64 = _b64(json.dumps(protected).encode('utf8'))
  47. protected_input = "{0}.{1}".format(protected64, payload64).encode('utf8')
  48. out = _cmd(["openssl", "dgst", "-sha256", "-sign", account_key], stdin=subprocess.PIPE, cmd_input=protected_input, err_msg="OpenSSL Error")
  49. data = json.dumps({"protected": protected64, "payload": payload64, "signature": _b64(out)})
  50. try:
  51. return _do_request(url, data=data.encode('utf8'), err_msg=err_msg, depth=depth)
  52. except IndexError: # retry bad nonces (they raise IndexError)
  53. return _send_signed_request(url, payload, err_msg, depth=(depth + 1))
  54. # helper function - poll until complete
  55. def _poll_until_not(url, pending_statuses, err_msg):
  56. while True:
  57. result, _, _ = _do_request(url, err_msg=err_msg)
  58. if result['status'] in pending_statuses:
  59. time.sleep(2)
  60. continue
  61. return result
  62. # parse account key to get public key
  63. log.info("Parsing account key...")
  64. out = _cmd(["openssl", "rsa", "-in", account_key, "-noout", "-text"], err_msg="OpenSSL Error")
  65. pub_pattern = r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)"
  66. pub_hex, pub_exp = re.search(pub_pattern, out.decode('utf8'), re.MULTILINE|re.DOTALL).groups()
  67. pub_exp = "{0:x}".format(int(pub_exp))
  68. pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
  69. alg = "RS256"
  70. jwk = {
  71. "e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
  72. "kty": "RSA",
  73. "n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
  74. }
  75. accountkey_json = json.dumps(jwk, sort_keys=True, separators=(',', ':'))
  76. thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
  77. # find domains
  78. log.info("Parsing CSR...")
  79. out = _cmd(["openssl", "req", "-in", csr, "-noout", "-text"], err_msg="Error loading {0}".format(csr))
  80. domains = set([])
  81. common_name = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode('utf8'))
  82. if common_name is not None:
  83. domains.add(common_name.group(1))
  84. subject_alt_names = re.search(r"X509v3 Subject Alternative Name: \n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE|re.DOTALL)
  85. if subject_alt_names is not None:
  86. for san in subject_alt_names.group(1).split(", "):
  87. if san.startswith("DNS:"):
  88. domains.add(san[4:])
  89. log.info("Found domains: {0}".format(", ".join(domains)))
  90. # get the ACME directory of urls
  91. log.info("Getting directory...")
  92. directory_url = CA + "/directory" if CA != DEFAULT_CA else directory_url # backwards compatibility with deprecated CA kwarg
  93. directory, _, _ = _do_request(directory_url, err_msg="Error getting directory")
  94. log.info("Directory found!")
  95. # create account, update contact details (if any), and set the global key identifier
  96. log.info("Registering account...")
  97. reg_payload = {"termsOfServiceAgreed": True}
  98. account, code, acct_headers = _send_signed_request(directory['newAccount'], reg_payload, "Error registering")
  99. log.info("Registered!" if code == 201 else "Already registered!")
  100. if contact is not None:
  101. account, _, _ = _send_signed_request(acct_headers['Location'], {"contact": contact}, "Error updating contact details")
  102. log.info("Updated contact details:\n{}".format("\n".join(account['contact'])))
  103. # create a new order
  104. log.info("Creating new order...")
  105. order_payload = {"identifiers": [{"type": "dns", "value": d} for d in domains]}
  106. order, _, order_headers = _send_signed_request(directory['newOrder'], order_payload, "Error creating new order")
  107. log.info("Order created!")
  108. # get the authorizations that need to be completed
  109. for auth_url in order['authorizations']:
  110. authorization, _, _ = _do_request(auth_url, err_msg="Error getting challenges")
  111. domain = authorization['identifier']['value']
  112. log.info("Verifying {0}...".format(domain))
  113. # find the http-01 challenge and write the challenge file
  114. challenge = [c for c in authorization['challenges'] if c['type'] == "http-01"][0]
  115. token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
  116. keyauthorization = "{0}.{1}".format(token, thumbprint)
  117. wellknown_path = os.path.join(acme_dir, token)
  118. with open(wellknown_path, "w") as wellknown_file:
  119. wellknown_file.write(keyauthorization)
  120. # check that the file is in place
  121. try:
  122. wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(domain, token)
  123. assert(disable_check or _do_request(wellknown_url)[0] == keyauthorization)
  124. except (AssertionError, ValueError) as e:
  125. os.remove(wellknown_path)
  126. raise ValueError("Wrote file to {0}, but couldn't download {1}: {2}".format(wellknown_path, wellknown_url, e))
  127. # say the challenge is done
  128. _send_signed_request(challenge['url'], {}, "Error submitting challenges: {0}".format(domain))
  129. authorization = _poll_until_not(auth_url, ["pending"], "Error checking challenge status for {0}".format(domain))
  130. if authorization['status'] != "valid":
  131. raise ValueError("Challenge did not pass for {0}: {1}".format(domain, authorization))
  132. log.info("{0} verified!".format(domain))
  133. # finalize the order with the csr
  134. log.info("Signing certificate...")
  135. csr_der = _cmd(["openssl", "req", "-in", csr, "-outform", "DER"], err_msg="DER Export Error")
  136. _send_signed_request(order['finalize'], {"csr": _b64(csr_der)}, "Error finalizing order")
  137. # poll the order to monitor when it's done
  138. order = _poll_until_not(order_headers['Location'], ["pending", "processing"], "Error checking order status")
  139. if order['status'] != "valid":
  140. raise ValueError("Order failed: {0}".format(order))
  141. # download the certificate
  142. certificate_pem, _, _ = _do_request(order['certificate'], err_msg="Certificate download failed")
  143. log.info("Certificate signed!")
  144. return certificate_pem
  145. def main(argv=None):
  146. parser = argparse.ArgumentParser(
  147. formatter_class=argparse.RawDescriptionHelpFormatter,
  148. description=textwrap.dedent("""\
  149. This script automates the process of getting a signed TLS certificate from
  150. Let's Encrypt using the ACME protocol. It will need to be run on your server
  151. and have access to your private account key, so PLEASE READ THROUGH IT! It's
  152. only ~200 lines, so it won't take long.
  153. ===Example Usage===
  154. python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed_chain.crt
  155. ===================
  156. ===Example Crontab Renewal (once per month)===
  157. 0 0 1 * * python /path/to/acme_tiny.py --account-key /path/to/account.key --csr /path/to/domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > /path/to/signed_chain.crt 2>> /var/log/acme_tiny.log
  158. ==============================================
  159. """)
  160. )
  161. parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
  162. parser.add_argument("--csr", required=True, help="path to your certificate signing request")
  163. parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory")
  164. parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
  165. parser.add_argument("--disable-check", default=False, action="store_true", help="disable checking if the challenge file is hosted correctly before telling the CA")
  166. parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt")
  167. parser.add_argument("--ca", default=DEFAULT_CA, help="DEPRECATED! USE --directory-url INSTEAD!")
  168. parser.add_argument("--contact", metavar="CONTACT", default=None, nargs="*", help="Contact details (e.g. mailto:aaa@bbb.com) for your account-key")
  169. args = parser.parse_args(argv)
  170. LOGGER.setLevel(args.quiet or LOGGER.level)
  171. signed_crt = get_crt(args.account_key, args.csr, args.acme_dir, log=LOGGER, CA=args.ca, disable_check=args.disable_check, directory_url=args.directory_url, contact=args.contact)
  172. sys.stdout.write(signed_crt)
  173. if __name__ == "__main__": # pragma: no cover
  174. main(sys.argv[1:])