acme_tiny.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 # Python 3
  5. except ImportError:
  6. from urllib2 import urlopen # 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, cmd_input=None):
  19. stdin = subprocess.PIPE if cmd_input is not None else None
  20. proc = subprocess.Popen(cmd_list, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  21. out, err = proc.communicate(cmd_input)
  22. return proc, out, err
  23. # helper function - make request and automatically parse json response
  24. def _do_request(url, data=None, err_msg="Error"):
  25. try:
  26. resp = urlopen(url, data)
  27. resp_data, code, headers = resp.read().decode("utf8"), resp.getcode(), resp.headers
  28. resp_data = json.loads(resp_data) # try to parse json results
  29. except ValueError:
  30. pass # ignore json parsing errors
  31. except IOError as e:
  32. resp_data = e.read().decode("utf8") if hasattr(e, "read") else str(e)
  33. code, headers = getattr(e, "code", None), {}
  34. if code not in [200, 201, 204]:
  35. raise ValueError("{0}:\nUrl: {1}\nData: {2}\nResponse Code: {3}\nResponse: {4}".format(err_msg, url, data, code, resp_data))
  36. return resp_data, code, headers
  37. # helper function - make signed requests
  38. def _send_signed_request(url, payload, err_msg):
  39. payload64 = _b64(json.dumps(payload).encode('utf8'))
  40. new_nonce = _do_request(directory['newNonce'])[2]['Replay-Nonce']
  41. protected = {"url": url, "alg": alg, "nonce": new_nonce}
  42. protected.update({"jwk": jwk} if acct_headers is None else {"kid": acct_headers['Location']})
  43. protected64 = _b64(json.dumps(protected).encode('utf8'))
  44. protected_input = "{0}.{1}".format(protected64, payload64).encode('utf8')
  45. proc, out, err = _cmd(["openssl", "dgst", "-sha256", "-sign", account_key], cmd_input=protected_input)
  46. if proc.returncode != 0:
  47. raise IOError("OpenSSL Error: {0}".format(err))
  48. data = json.dumps({"protected": protected64, "payload": payload64, "signature": _b64(out)})
  49. return _do_request(url, data=data.encode('utf8'), err_msg=err_msg)
  50. # helper function - poll until complete
  51. def _poll_until_not(url, pending_statuses, err_msg):
  52. while True:
  53. result, _, _ = _do_request(url, err_msg=err_msg)
  54. if result['status'] in pending_statuses:
  55. time.sleep(2)
  56. continue
  57. return result
  58. # parse account key to get public key
  59. log.info("Parsing account key...")
  60. proc, out, err = _cmd(["openssl", "rsa", "-in", account_key, "-noout", "-text"])
  61. if proc.returncode != 0:
  62. raise IOError("OpenSSL Error: {0}".format(err))
  63. pub_pattern = r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)"
  64. pub_hex, pub_exp = re.search(pub_pattern, out.decode('utf8'), re.MULTILINE|re.DOTALL).groups()
  65. pub_exp = "{0:x}".format(int(pub_exp))
  66. pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
  67. alg = "RS256"
  68. jwk = {
  69. "e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
  70. "kty": "RSA",
  71. "n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
  72. }
  73. accountkey_json = json.dumps(jwk, sort_keys=True, separators=(',', ':'))
  74. thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
  75. # find domains
  76. log.info("Parsing CSR...")
  77. proc, out, err = _cmd(["openssl", "req", "-in", csr, "-noout", "-text"])
  78. if proc.returncode != 0:
  79. raise IOError("Error loading {0}: {1}".format(csr, err))
  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: {}".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. challenge_payload = {"keyAuthorization": keyauthorization}
  126. _send_signed_request(challenge['url'], challenge_payload, "Error submitting challenges: {0}".format(domain))
  127. authorization = _poll_until_not(auth_url, ["pending"], "Error checking challenge status for {0}".format(domain))
  128. if authorization['status'] != "valid":
  129. raise ValueError("Challenge did not pass for {0}: {1}".format(domain, authorization))
  130. log.info("{0} verified!".format(domain))
  131. # finalize the order with the csr
  132. log.info("Signing certificate...")
  133. proc, csr_der, err = _cmd(["openssl", "req", "-in", csr, "-outform", "DER"])
  134. _send_signed_request(order['finalize'], {"csr": _b64(csr_der)}, "Error finalizing order")
  135. # poll the order to monitor when it's done
  136. order = _poll_until_not(order_headers['Location'], ["pending", "processing"], "Error checking order status")
  137. if order['status'] != "valid":
  138. raise ValueError("Order failed: {0}".format(order))
  139. # download the certificate
  140. certificate_pem, _, _ = _do_request(order['certificate'], err_msg="Certificate download failed")
  141. log.info("Certificate signed!")
  142. return certificate_pem
  143. def main(argv):
  144. parser = argparse.ArgumentParser(
  145. formatter_class=argparse.RawDescriptionHelpFormatter,
  146. description=textwrap.dedent("""\
  147. This script automates the process of getting a signed TLS certificate from
  148. Let's Encrypt using the ACME protocol. It will need to be run on your server
  149. and have access to your private account key, so PLEASE READ THROUGH IT! It's
  150. only ~200 lines, so it won't take long.
  151. ===Example Usage===
  152. python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed.crt
  153. ===================
  154. ===Example Crontab Renewal (once per month)===
  155. 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.crt 2>> /var/log/acme_tiny.log
  156. ==============================================
  157. """)
  158. )
  159. parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
  160. parser.add_argument("--csr", required=True, help="path to your certificate signing request")
  161. parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory")
  162. parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
  163. parser.add_argument("--disable-check", default=False, action="store_true", help="disable checking if the challenge file is hosted correctly before telling the CA")
  164. parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt")
  165. parser.add_argument("--ca", default=DEFAULT_CA, help="DEPRECATED! USE --directory-url INSTEAD!")
  166. args = parser.parse_args(argv)
  167. LOGGER.setLevel(args.quiet or LOGGER.level)
  168. 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)
  169. sys.stdout.write(signed_crt)
  170. if __name__ == "__main__": # pragma: no cover
  171. main(sys.argv[1:])