acme_tiny.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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-staging.api.letsencrypt.org"
  8. DEFAULT_CA = "https://acme-v01.api.letsencrypt.org"
  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):
  13. # helper function base64 encode for jose spec
  14. def _b64(b):
  15. return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "")
  16. # parse account key to get public key
  17. log.info("Parsing account key...")
  18. proc = subprocess.Popen(["openssl", "rsa", "-in", account_key, "-noout", "-text"],
  19. stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  20. out, err = proc.communicate()
  21. if proc.returncode != 0:
  22. raise IOError("OpenSSL Error: {0}".format(err))
  23. pub_hex, pub_exp = re.search(
  24. r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)",
  25. out.decode('utf8'), re.MULTILINE|re.DOTALL).groups()
  26. pub_exp = "{0:x}".format(int(pub_exp))
  27. pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
  28. header = {
  29. "alg": "RS256",
  30. "jwk": {
  31. "e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
  32. "kty": "RSA",
  33. "n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
  34. },
  35. }
  36. accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
  37. thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
  38. # helper function make signed requests
  39. def _send_signed_request(url, payload):
  40. payload64 = _b64(json.dumps(payload).encode('utf8'))
  41. protected = copy.deepcopy(header)
  42. protected["nonce"] = urlopen(CA + "/directory").headers['Replay-Nonce']
  43. protected64 = _b64(json.dumps(protected).encode('utf8'))
  44. proc = subprocess.Popen(["openssl", "dgst", "-sha256", "-sign", account_key],
  45. stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  46. out, err = proc.communicate("{0}.{1}".format(protected64, payload64).encode('utf8'))
  47. if proc.returncode != 0:
  48. raise IOError("OpenSSL Error: {0}".format(err))
  49. data = json.dumps({
  50. "header": header, "protected": protected64,
  51. "payload": payload64, "signature": _b64(out),
  52. })
  53. try:
  54. resp = urlopen(url, data.encode('utf8'))
  55. return resp.getcode(), resp.read()
  56. except IOError as e:
  57. return getattr(e, "code", None), getattr(e, "read", e.__str__)()
  58. # find domains
  59. log.info("Parsing CSR...")
  60. proc = subprocess.Popen(["openssl", "req", "-in", csr, "-noout", "-text"],
  61. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  62. out, err = proc.communicate()
  63. if proc.returncode != 0:
  64. raise IOError("Error loading {0}: {1}".format(csr, err))
  65. domains = set([])
  66. common_name = re.search(r"Subject:.*? CN ?=([^\s,;/]+)", out.decode('utf8'))
  67. if common_name is not None:
  68. domains.add(common_name.group(1))
  69. subject_alt_names = re.search(r"X509v3 Subject Alternative Name: \n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE|re.DOTALL)
  70. if subject_alt_names is not None:
  71. for san in subject_alt_names.group(1).split(", "):
  72. if san.startswith("DNS:"):
  73. domains.add(san[4:])
  74. # get the certificate domains and expiration
  75. log.info("Registering account...")
  76. code, result = _send_signed_request(CA + "/acme/new-reg", {
  77. "resource": "new-reg",
  78. "agreement": "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf",
  79. })
  80. if code == 201:
  81. log.info("Registered!")
  82. elif code == 409:
  83. log.info("Already registered!")
  84. else:
  85. raise ValueError("Error registering: {0} {1}".format(code, result))
  86. # verify each domain
  87. for domain in domains:
  88. log.info("Verifying {0}...".format(domain))
  89. # get new challenge
  90. code, result = _send_signed_request(CA + "/acme/new-authz", {
  91. "resource": "new-authz",
  92. "identifier": {"type": "dns", "value": domain},
  93. })
  94. if code != 201:
  95. raise ValueError("Error requesting challenges: {0} {1}".format(code, result))
  96. # make the challenge file
  97. challenge = [c for c in json.loads(result.decode('utf8'))['challenges'] if c['type'] == "http-01"][0]
  98. token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
  99. keyauthorization = "{0}.{1}".format(token, thumbprint)
  100. wellknown_path = os.path.join(acme_dir, token)
  101. with open(wellknown_path, "w") as wellknown_file:
  102. wellknown_file.write(keyauthorization)
  103. # check that the file is in place
  104. wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(domain, token)
  105. try:
  106. resp = urlopen(wellknown_url)
  107. resp_data = resp.read().decode('utf8').strip()
  108. assert resp_data == keyauthorization
  109. except (IOError, AssertionError):
  110. os.remove(wellknown_path)
  111. raise ValueError("Wrote file to {0}, but couldn't download {1}".format(
  112. wellknown_path, wellknown_url))
  113. # notify challenge are met
  114. code, result = _send_signed_request(challenge['uri'], {
  115. "resource": "challenge",
  116. "keyAuthorization": keyauthorization,
  117. })
  118. if code != 202:
  119. raise ValueError("Error triggering challenge: {0} {1}".format(code, result))
  120. # wait for challenge to be verified
  121. while True:
  122. try:
  123. resp = urlopen(challenge['uri'])
  124. challenge_status = json.loads(resp.read().decode('utf8'))
  125. except IOError as e:
  126. raise ValueError("Error checking challenge: {0} {1}".format(
  127. e.code, json.loads(e.read().decode('utf8'))))
  128. if challenge_status['status'] == "pending":
  129. time.sleep(2)
  130. elif challenge_status['status'] == "valid":
  131. log.info("{0} verified!".format(domain))
  132. os.remove(wellknown_path)
  133. break
  134. else:
  135. raise ValueError("{0} challenge did not pass: {1}".format(
  136. domain, challenge_status))
  137. # get the new certificate
  138. log.info("Signing certificate...")
  139. proc = subprocess.Popen(["openssl", "req", "-in", csr, "-outform", "DER"],
  140. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  141. csr_der, err = proc.communicate()
  142. code, result = _send_signed_request(CA + "/acme/new-cert", {
  143. "resource": "new-cert",
  144. "csr": _b64(csr_der),
  145. })
  146. if code != 201:
  147. raise ValueError("Error signing certificate: {0} {1}".format(code, result))
  148. # return signed certificate!
  149. log.info("Certificate signed!")
  150. return """-----BEGIN CERTIFICATE-----\n{0}\n-----END CERTIFICATE-----\n""".format(
  151. "\n".join(textwrap.wrap(base64.b64encode(result).decode('utf8'), 64)))
  152. def main(argv):
  153. parser = argparse.ArgumentParser(
  154. formatter_class=argparse.RawDescriptionHelpFormatter,
  155. description=textwrap.dedent("""\
  156. This script automates the process of getting a signed TLS certificate from
  157. Let's Encrypt using the ACME protocol. It will need to be run on your server
  158. and have access to your private account key, so PLEASE READ THROUGH IT! It's
  159. only ~200 lines, so it won't take long.
  160. ===Example Usage===
  161. python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed.crt
  162. ===================
  163. ===Example Crontab Renewal (once per month)===
  164. 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
  165. ==============================================
  166. """)
  167. )
  168. parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key")
  169. parser.add_argument("--csr", required=True, help="path to your certificate signing request")
  170. parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory")
  171. parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors")
  172. parser.add_argument("--ca", default=DEFAULT_CA, help="certificate authority, default is Let's Encrypt")
  173. args = parser.parse_args(argv)
  174. LOGGER.setLevel(args.quiet or LOGGER.level)
  175. signed_crt = get_crt(args.account_key, args.csr, args.acme_dir, log=LOGGER, CA=args.ca)
  176. sys.stdout.write(signed_crt)
  177. if __name__ == "__main__": # pragma: no cover
  178. main(sys.argv[1:])