acme_tiny.py 8.2 KB

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