acme_tiny.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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):
  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 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. # create a new order
  101. log.info("Creating new order...")
  102. order_payload = {"identifiers": [{"type": "dns", "value": d} for d in domains]}
  103. order, _, order_headers = _send_signed_request(directory['newOrder'], order_payload, "Error creating new order")
  104. log.info("Order created!")
  105. # get the authorizations that need to be completed
  106. for auth_url in order['authorizations']:
  107. authorization, _, _ = _do_request(auth_url, err_msg="Error getting challenges")
  108. domain = authorization['identifier']['value']
  109. log.info("Verifying {0}...".format(domain))
  110. # find the http-01 challenge and write the challenge file
  111. challenge = [c for c in authorization['challenges'] if c['type'] == "http-01"][0]
  112. token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
  113. keyauthorization = "{0}.{1}".format(token, thumbprint)
  114. wellknown_path = os.path.join(acme_dir, token)
  115. with open(wellknown_path, "w") as wellknown_file:
  116. wellknown_file.write(keyauthorization)
  117. # check that the file is in place
  118. try:
  119. wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(domain, token)
  120. assert(disable_check or _do_request(wellknown_url)[0] == keyauthorization)
  121. except (AssertionError, ValueError) as e:
  122. os.remove(wellknown_path)
  123. raise ValueError("Wrote file to {0}, but couldn't download {1}: {2}".format(wellknown_path, wellknown_url, e))
  124. # say the challenge is done
  125. _send_signed_request(challenge['url'], {}, "Error submitting challenges: {0}".format(domain))
  126. authorization = _poll_until_not(auth_url, ["pending"], "Error checking challenge status for {0}".format(domain))
  127. if authorization['status'] != "valid":
  128. raise ValueError("Challenge did not pass for {0}: {1}".format(domain, authorization))
  129. log.info("{0} verified!".format(domain))
  130. # finalize the order with the csr
  131. log.info("Signing certificate...")
  132. csr_der = _cmd(["openssl", "req", "-in", csr, "-outform", "DER"], err_msg="DER Export Error")
  133. _send_signed_request(order['finalize'], {"csr": _b64(csr_der)}, "Error finalizing order")
  134. # poll the order to monitor when it's done
  135. order = _poll_until_not(order_headers['Location'], ["pending", "processing"], "Error checking order status")
  136. if order['status'] != "valid":
  137. raise ValueError("Order failed: {0}".format(order))
  138. # download the certificate
  139. certificate_pem, _, _ = _do_request(order['certificate'], err_msg="Certificate download failed")
  140. log.info("Certificate signed!")
  141. return certificate_pem
  142. def main(argv=None):
  143. parser = argparse.ArgumentParser(
  144. formatter_class=argparse.RawDescriptionHelpFormatter,
  145. description=textwrap.dedent("""\
  146. This script automates the process of getting a signed TLS certificate from
  147. Let's Encrypt using the ACME protocol. It will need to be run on your server
  148. and have access to your private account key, so PLEASE READ THROUGH IT! It's
  149. only ~200 lines, so it won't take long.
  150. ===Example Usage===
  151. python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed_chain.crt
  152. ===================
  153. ===Example Crontab Renewal (once per month)===
  154. 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
  155. ==============================================
  156. """)
  157. )
  158. parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
  159. parser.add_argument("--csr", required=True, help="path to your certificate signing request")
  160. parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory")
  161. parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
  162. parser.add_argument("--disable-check", default=False, action="store_true", help="disable checking if the challenge file is hosted correctly before telling the CA")
  163. parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt")
  164. parser.add_argument("--ca", default=DEFAULT_CA, help="DEPRECATED! USE --directory-url INSTEAD!")
  165. args = parser.parse_args(argv)
  166. LOGGER.setLevel(args.quiet or LOGGER.level)
  167. 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)
  168. sys.stdout.write(signed_crt)
  169. if __name__ == "__main__": # pragma: no cover
  170. main(sys.argv[1:])