acme_tiny.py 8.6 KB

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