3 import sys, os, getopt, binascii, json, pprint, signal, time
5 import Crypto.PublicKey.RSA, Crypto.Random, Crypto.Hash.SHA256, Crypto.Signature.PKCS1_v1_5
7 service = "https://acme-v02.api.letsencrypt.org/directory"
11 if _directory is None:
12 with req(service) as resp:
13 _directory = json.loads(resp.read().decode("utf-8"))
17 return binascii.b2a_base64(dat).decode("us-ascii").translate({43: 45, 47: 95, 61: None}).strip()
21 if len(h) % 2 == 1: h = "0" + h
22 return base64url(binascii.a2b_hex(h))
25 with urllib.request.urlopen(directory()["newNonce"]) as resp:
27 return resp.headers["Replay-Nonce"]
29 def req(url, data=None, ctype=None, headers={}, method=None, **kws):
30 if data is not None and not isinstance(data, bytes):
31 data = json.dumps(data).encode("utf-8")
32 ctype = "application/jose+json"
33 req = urllib.request.Request(url, data=data, method=method)
34 for hnam, hval in headers.items():
35 req.add_header(hnam, hval)
37 req.add_header("Content-Type", ctype)
38 return urllib.request.urlopen(req)
40 def jreq(url, data, auth):
41 authdata = {"alg": "RS256", "url": url, "nonce": getnonce()}
42 authdata.update(auth.authdata())
43 authdata = base64url(json.dumps(authdata).encode("us-ascii"))
47 data = base64url(json.dumps(data).encode("us-ascii"))
48 seal = base64url(auth.sign(("%s.%s" % (authdata, data)).encode("us-ascii")))
49 enc = {"protected": authdata, "payload": data, "signature": seal}
50 with req(url, data=enc) as resp:
51 return json.loads(resp.read().decode("utf-8")), resp.headers
53 class certificate(object):
56 # No X509 parser for Python?
57 import subprocess, re, calendar
58 with subprocess.Popen(["openssl", "x509", "-noout", "-enddate"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
59 openssl.stdin.write(self.data.encode("us-ascii"))
61 resp = openssl.stdout.read().decode("utf-8")
62 if openssl.wait() != 0:
63 raise Exception("openssl error")
64 m = re.search(r"notAfter=(.*)$", resp)
65 if m is None: raise Exception("unexpected openssl reply: %r" % (resp,))
66 return calendar.timegm(time.strptime(m.group(1), "%b %d %H:%M:%S %Y GMT"))
68 def expiring(self, timespec):
69 if timespec.endswith("y"):
70 timespec = int(timespec[:-1]) * 365 * 86400
71 elif timespec.endswith("m"):
72 timespec = int(timespec[:-1]) * 30 * 86400
73 elif timespec.endswith("w"):
74 timespec = int(timespec[:-1]) * 7 * 86400
75 elif timespec.endswith("d"):
76 timespec = int(timespec[:-1]) * 86400
77 elif timespec.endswith("h"):
78 timespec = int(timespec[:-1]) * 3600
80 timespec = int(timespec)
81 return (self.enddate - time.time()) < timespec
89 class signreq(object):
91 # No PCKS10 parser for Python?
93 with subprocess.Popen(["openssl", "req", "-noout", "-text"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
94 openssl.stdin.write(self.data.encode("us-ascii"))
96 resp = openssl.stdout.read().decode("utf-8")
97 if openssl.wait() != 0:
98 raise Exception("openssl error")
99 m = re.search(r"X509v3 Subject Alternative Name:[^\n]*\n\s*((\w+:\S+,\s*)*\w+:\S+)\s*\n", resp)
103 for nm in m.group(1).split(","):
105 typ, nm = nm.split(":", 1)
112 with subprocess.Popen(["openssl", "req", "-outform", "der"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
113 openssl.stdin.write(self.data.encode("us-ascii"))
114 openssl.stdin.close()
115 resp = openssl.stdout.read()
116 if openssl.wait() != 0:
117 raise Exception("openssl error")
123 self.data = fp.read()
126 class jwkauth(object):
127 def __init__(self, key):
131 return {"jwk": {"kty": "RSA", "e": ebignum(self.key.e), "n": ebignum(self.key.n)}}
133 def sign(self, data):
134 dig = Crypto.Hash.SHA256.new()
136 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
138 class account(object):
139 def __init__(self, uri, key):
144 return {"kid": self.uri}
146 def sign(self, data):
147 dig = Crypto.Hash.SHA256.new()
149 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
152 data, headers = jreq(self.uri, None, self)
156 data = self.getinfo()
157 if data.get("status", "") != "valid":
158 raise Exception("account is not valid: %s" % (data.get("status", "\"\"")))
160 def write(self, out):
161 out.write("%s\n" % (self.uri,))
162 out.write("%s\n" % (self.key.exportKey().decode("us-ascii"),))
168 raise Exception("missing account URI")
170 key = Crypto.PublicKey.RSA.importKey(fp.read())
173 class htconfig(object):
182 if len(words) < 1 or ln[0] == '#':
184 if words[0] == "root":
185 self.roots[words[1]] = words[2]
187 sys.stderr.write("acmecert: warning: unknown htconfig directive: %s\n" % (words[0]))
190 def register(keysize=4096):
191 key = Crypto.PublicKey.RSA.generate(keysize, Crypto.Random.new().read)
192 # jwk = {"kty": "RSA", "e": ebignum(key.e), "n": ebignum(key.n)}
193 # cjwk = json.dumps(jwk, separators=(',', ':'), sort_keys=True)
194 data, headers = jreq(directory()["newAccount"], {"termsOfServiceAgreed": True}, jwkauth(key))
195 return account(headers["Location"], key)
197 def mkorder(acct, csr):
198 data, headers = jreq(directory()["newOrder"], {"identifiers": [{"type": "dns", "value": dn} for dn in csr.domains()]}, acct)
199 data["acmecert.location"] = headers["Location"]
202 def httptoken(acct, ch):
203 jwk = {"kty": "RSA", "e": ebignum(acct.key.e), "n": ebignum(acct.key.n)}
204 dig = Crypto.Hash.SHA256.new()
205 dig.update(json.dumps(jwk, separators=(',', ':'), sort_keys=True).encode("us-ascii"))
206 khash = base64url(dig.digest())
207 return ch["token"], ("%s.%s" % (ch["token"], khash))
209 def authorder(acct, htconf, orderid):
210 order, headers = jreq(orderid, None, acct)
217 raise Exception("challenges refuse to become valid even after 5 retries")
218 for authuri in order["authorizations"]:
219 auth, headers = jreq(authuri, None, acct)
220 if auth["status"] == "valid":
222 elif auth["status"] == "pending":
225 raise Exception("unknown authorization status: %s" % (auth["status"],))
227 if auth["identifier"]["type"] != "dns":
228 raise Exception("unknown authorization type: %s" % (auth["identifier"]["type"],))
229 dn = auth["identifier"]["value"]
230 if dn not in htconf.roots:
231 raise Exception("no configured ht-root for domain name %s" % (dn,))
232 for ch in auth["challenges"]:
233 if ch["type"] == "http-01":
236 raise Exception("no http-01 challenge for %s" % (dn,))
237 root = htconf.roots[dn]
238 tokid, tokval = httptoken(acct, ch)
239 tokpath = os.path.join(root, tokid);
240 fp = open(tokpath, "w")
244 with req("http://%s/.well-known/acme-challenge/%s" % (dn, tokid)) as resp:
245 if resp.read().decode("utf-8") != tokval:
246 raise Exception("challenge from %s does not match written value" % (dn,))
248 resp, headers = jreq(ch["url"], {}, acct)
249 if resp["status"] == "processing":
251 elif resp["status"] == "valid":
254 raise Exception("unexpected challenge status for %s when validating: %s" % (dn, resp["status"]))
256 raise Exception("challenge processing timed out for %s" % (dn,))
260 def finalize(acct, csr, orderid):
261 order, headers = jreq(orderid, None, acct)
262 if order["status"] == "valid":
264 elif order["status"] == "ready":
265 jreq(order["finalize"], {"csr": base64url(csr.der())}, acct)
267 resp, headers = jreq(orderid, None, acct)
268 if resp["status"] == "processing":
270 elif resp["status"] == "valid":
274 raise Exception("unexpected order status when finalizing: %s" % resp["status"])
276 raise Exception("order finalization timed out")
278 raise Exception("unexpected order state when finalizing: %s" % (order["status"],))
279 with req(order["certificate"]) as resp:
280 return resp.read().decode("us-ascii")
282 class maybeopen(object):
283 def __init__(self, name, mode):
291 raise ValueError(mode)
294 self.fp = open(name, mode)
299 def __exit__(self, *excinfo):
304 class usageerr(Exception):
310 "usage: acmecert reg [OUTPUT-FILE]"
313 with maybeopen(args[1] if len(args) > 1 else "-", "w") as fp:
315 commands["reg"] = cmd_reg
317 def cmd_validate_acct(args):
318 "usage: acmecert validate-acct ACCOUNT-FILE"
319 if len(args) < 2: raise usageerr()
320 with maybeopen(args[1], "r") as fp:
321 account.read(fp).valudate()
322 commands["validate-acct"] = cmd_validate_acct
324 def cmd_acct_info(args):
325 "usage: acmecert acct-info ACCOUNT-FILE"
326 if len(args) < 2: raise usageerr()
327 with maybeopen(args[1], "r") as fp:
328 pprint.pprint(account.read(fp).getinfo())
329 commands["acct-info"] = cmd_validate_acct
332 "usage: acmecert order ACCOUNT-FILE CSR [OUTPUT-FILE]"
333 if len(args) < 4: raise usageerr()
334 with maybeopen(args[1], "r") as fp:
335 acct = account.read(fp)
336 with maybeopen(args[2], "r") as fp:
337 csr = signreq.read(fp)
338 order = mkorder(acct, csr)
339 with maybeopen(args[3] if len(args) > 3 else "-", "w") as fp:
340 fp.write("%s\n" % (order["acmecert.location"]))
341 commands["order"] = cmd_order
343 def cmd_http_auth(args):
344 "usage: acmecert http-auth ACCOUNT-FILE HTTP-CONFIG {ORDER-ID|ORDER-FILE}"
345 if len(args) < 4: raise usageerr()
346 with maybeopen(args[1], "r") as fp:
347 acct = account.read(fp)
348 with maybeopen(args[2], "r") as fp:
349 htconf = htconfig.read(fp)
353 with maybeopen(args[3], "r") as fp:
354 orderid = fp.readline().strip()
355 authorder(acct, htconf, orderid)
356 commands["http-auth"] = cmd_http_auth
359 "usage: acmecert get ACCOUNT-FILE CSR {ORDER-ID|ORDER-FILE}"
360 if len(args) < 4: raise usageerr()
361 with maybeopen(args[1], "r") as fp:
362 acct = account.read(fp)
363 with maybeopen(args[2], "r") as fp:
364 csr = signreq.read(fp)
368 with maybeopen(args[3], "r") as fp:
369 orderid = fp.readline().strip()
370 sys.stdout.write(finalize(acct, csr, orderid))
371 commands["get"] = cmd_get
373 def cmd_http_order(args):
374 "usage: acmecert http-order ACCOUNT-FILE CSR HTTP-CONFIG [OUTPUT-FILE]"
375 if len(args) < 4: raise usageerr()
376 with maybeopen(args[1], "r") as fp:
377 acct = account.read(fp)
378 with maybeopen(args[2], "r") as fp:
379 csr = signreq.read(fp)
380 with maybeopen(args[3], "r") as fp:
381 htconf = htconfig.read(fp)
382 orderid = mkorder(acct, csr)["acmecert.location"]
383 authorder(acct, htconf, orderid)
384 with maybeopen(args[4] if len(args) > 4 else "-", "w") as fp:
385 fp.write(finalize(acct, csr, orderid))
386 commands["http-order"] = cmd_http_order
388 def cmd_check_cert(args):
389 "usage: acmecert check-cert CERT-FILE TIME-SPEC"
390 if len(args) < 3: raise usageerr()
391 with maybeopen(args[1], "r") as fp:
392 crt = certificate.read(fp)
393 sys.exit(1 if crt.expiring(args[2]) else 0)
394 commands["check-cert"] = cmd_check_cert
396 def cmd_directory(args):
397 "usage: acmecert directory"
398 pprint.pprint(directory())
399 commands["directory"] = cmd_directory
402 out.write("usage: acmecert [-D SERVICE] COMMAND [ARGS...]\n")
403 out.write(" acmecert -h [COMMAND]\n")
404 buf = " COMMAND is any of: "
407 if len(buf) + len(cmd) > 70:
408 out.write("%s\n" % (buf,))
416 out.write("%s\n" % (buf,))
420 opts, args = getopt.getopt(argv[1:], "hD:")
424 cmd = commands.get(args[0])
426 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
428 sys.stdout.write("%s\n" % (cmd.__doc__,))
437 cmd = commands.get(args[0])
439 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
445 sys.stderr.write("%s\n" % (cmd.__doc__,))
448 if __name__ == "__main__":
451 except KeyboardInterrupt:
452 signal.signal(signal.SIGINT, signal.SIG_DFL)
453 os.kill(os.getpid(), signal.SIGINT)