3 import sys, os, getopt, binascii, json, pprint, signal, time, threading
5 import Crypto.PublicKey.RSA, Crypto.Random, Crypto.Hash.SHA256, Crypto.Signature.PKCS1_v1_5
7 class msgerror(Exception):
9 out.write("acmecert: undefined error\n")
11 service = "https://acme-v02.api.letsencrypt.org/directory"
15 if _directory is None:
16 with req(service) as resp:
17 _directory = json.loads(resp.read().decode("utf-8"))
21 return binascii.b2a_base64(dat).decode("us-ascii").translate({43: 45, 47: 95, 61: None}).strip()
25 if len(h) % 2 == 1: h = "0" + h
26 return base64url(binascii.a2b_hex(h))
29 with urllib.request.urlopen(directory()["newNonce"]) as resp:
31 return resp.headers["Replay-Nonce"]
33 def req(url, data=None, ctype=None, headers={}, method=None, **kws):
34 if data is not None and not isinstance(data, bytes):
35 data = json.dumps(data).encode("utf-8")
36 ctype = "application/jose+json"
37 req = urllib.request.Request(url, data=data, method=method)
38 for hnam, hval in headers.items():
39 req.add_header(hnam, hval)
41 req.add_header("Content-Type", ctype)
42 return urllib.request.urlopen(req)
44 def jreq(url, data, auth):
45 authdata = {"alg": "RS256", "url": url, "nonce": getnonce()}
46 authdata.update(auth.authdata())
47 authdata = base64url(json.dumps(authdata).encode("us-ascii"))
51 data = base64url(json.dumps(data).encode("us-ascii"))
52 seal = base64url(auth.sign(("%s.%s" % (authdata, data)).encode("us-ascii")))
53 enc = {"protected": authdata, "payload": data, "signature": seal}
54 with req(url, data=enc) as resp:
55 return json.loads(resp.read().decode("utf-8")), resp.headers
57 class certificate(object):
60 # No X509 parser for Python?
61 import subprocess, re, calendar
62 with subprocess.Popen(["openssl", "x509", "-noout", "-enddate"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
63 openssl.stdin.write(self.data.encode("us-ascii"))
65 resp = openssl.stdout.read().decode("utf-8")
66 if openssl.wait() != 0:
67 raise Exception("openssl error")
68 m = re.search(r"notAfter=(.*)$", resp)
69 if m is None: raise Exception("unexpected openssl reply: %r" % (resp,))
70 return calendar.timegm(time.strptime(m.group(1), "%b %d %H:%M:%S %Y GMT"))
72 def expiring(self, timespec):
73 if timespec.endswith("y"):
74 timespec = int(timespec[:-1]) * 365 * 86400
75 elif timespec.endswith("m"):
76 timespec = int(timespec[:-1]) * 30 * 86400
77 elif timespec.endswith("w"):
78 timespec = int(timespec[:-1]) * 7 * 86400
79 elif timespec.endswith("d"):
80 timespec = int(timespec[:-1]) * 86400
81 elif timespec.endswith("h"):
82 timespec = int(timespec[:-1]) * 3600
84 timespec = int(timespec)
85 return (self.enddate - time.time()) < timespec
93 class signreq(object):
95 # No PCKS10 parser for Python?
97 with subprocess.Popen(["openssl", "req", "-noout", "-text"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
98 openssl.stdin.write(self.data.encode("us-ascii"))
100 resp = openssl.stdout.read().decode("utf-8")
101 if openssl.wait() != 0:
102 raise Exception("openssl error")
103 m = re.search(r"X509v3 Subject Alternative Name:[^\n]*\n\s*((\w+:\S+,\s*)*\w+:\S+)\s*\n", resp)
107 for nm in m.group(1).split(","):
109 typ, nm = nm.split(":", 1)
116 with subprocess.Popen(["openssl", "req", "-outform", "der"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as openssl:
117 openssl.stdin.write(self.data.encode("us-ascii"))
118 openssl.stdin.close()
119 resp = openssl.stdout.read()
120 if openssl.wait() != 0:
121 raise Exception("openssl error")
127 self.data = fp.read()
130 class jwkauth(object):
131 def __init__(self, key):
135 return {"jwk": {"kty": "RSA", "e": ebignum(self.key.e), "n": ebignum(self.key.n)}}
137 def sign(self, data):
138 dig = Crypto.Hash.SHA256.new()
140 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
142 class account(object):
143 def __init__(self, uri, key):
148 return {"kid": self.uri}
150 def sign(self, data):
151 dig = Crypto.Hash.SHA256.new()
153 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
156 data, headers = jreq(self.uri, None, self)
160 data = self.getinfo()
161 if data.get("status", "") != "valid":
162 raise Exception("account is not valid: %s" % (data.get("status", "\"\"")))
164 def write(self, out):
165 out.write("%s\n" % (self.uri,))
166 out.write("%s\n" % (self.key.exportKey().decode("us-ascii"),))
172 raise Exception("missing account URI")
174 key = Crypto.PublicKey.RSA.importKey(fp.read())
177 class htconfig(object):
186 if len(words) < 1 or ln[0] == '#':
188 if words[0] == "root":
189 self.roots[words[1]] = words[2]
191 sys.stderr.write("acmecert: warning: unknown htconfig directive: %s\n" % (words[0]))
194 def register(keysize=4096):
195 key = Crypto.PublicKey.RSA.generate(keysize, Crypto.Random.new().read)
196 data, headers = jreq(directory()["newAccount"], {"termsOfServiceAgreed": True}, jwkauth(key))
197 return account(headers["Location"], key)
199 def mkorder(acct, csr):
200 data, headers = jreq(directory()["newOrder"], {"identifiers": [{"type": "dns", "value": dn} for dn in csr.domains()]}, acct)
201 data["acmecert.location"] = headers["Location"]
204 def httptoken(acct, ch):
205 jwk = {"kty": "RSA", "e": ebignum(acct.key.e), "n": ebignum(acct.key.n)}
206 dig = Crypto.Hash.SHA256.new()
207 dig.update(json.dumps(jwk, separators=(',', ':'), sort_keys=True).encode("us-ascii"))
208 khash = base64url(dig.digest())
209 return ch["token"], ("%s.%s" % (ch["token"], khash))
211 def authorder(acct, htconf, orderid):
212 order, headers = jreq(orderid, None, acct)
219 raise Exception("challenges refuse to become valid even after 5 retries")
220 for authuri in order["authorizations"]:
221 auth, headers = jreq(authuri, None, acct)
222 if auth["status"] == "valid":
224 elif auth["status"] == "pending":
227 raise Exception("unknown authorization status: %s" % (auth["status"],))
229 if auth["identifier"]["type"] != "dns":
230 raise Exception("unknown authorization type: %s" % (auth["identifier"]["type"],))
231 dn = auth["identifier"]["value"]
232 if dn not in htconf.roots:
233 raise Exception("no configured ht-root for domain name %s" % (dn,))
234 for ch in auth["challenges"]:
235 if ch["type"] == "http-01":
238 raise Exception("no http-01 challenge for %s" % (dn,))
239 root = htconf.roots[dn]
240 tokid, tokval = httptoken(acct, ch)
241 tokpath = os.path.join(root, tokid);
242 fp = open(tokpath, "w")
246 with req("http://%s/.well-known/acme-challenge/%s" % (dn, tokid)) as resp:
247 if resp.read().decode("utf-8") != tokval:
248 raise Exception("challenge from %s does not match written value" % (dn,))
250 resp, headers = jreq(ch["url"], {}, acct)
251 if resp["status"] == "processing":
253 elif resp["status"] == "pending":
254 # I don't think this should happen, but it
255 # does. LE bug? Anyway, just retry.
260 elif resp["status"] == "valid":
263 raise Exception("unexpected challenge status for %s when validating: %s" % (dn, resp["status"]))
265 raise Exception("challenge processing timed out for %s" % (dn,))
269 def finalize(acct, csr, orderid):
270 order, headers = jreq(orderid, None, acct)
271 if order["status"] == "valid":
273 elif order["status"] == "ready":
274 jreq(order["finalize"], {"csr": base64url(csr.der())}, acct)
276 resp, headers = jreq(orderid, None, acct)
277 if resp["status"] == "processing":
279 elif resp["status"] == "valid":
283 raise Exception("unexpected order status when finalizing: %s" % resp["status"])
285 raise Exception("order finalization timed out")
287 raise Exception("unexpected order state when finalizing: %s" % (order["status"],))
288 with req(order["certificate"]) as resp:
289 return resp.read().decode("us-ascii")
291 class maybeopen(object):
292 def __init__(self, name, mode):
300 raise ValueError(mode)
303 self.fp = open(name, mode)
308 def __exit__(self, *excinfo):
313 invdata = threading.local()
316 class usageerr(msgerror):
318 self.cmd = invdata.cmd
320 def report(self, out):
321 out.write("%s\n" % (self.cmd.__doc__,))
324 "usage: acmecert reg [OUTPUT-FILE]"
327 with maybeopen(args[1] if len(args) > 1 else "-", "w") as fp:
329 commands["reg"] = cmd_reg
331 def cmd_validate_acct(args):
332 "usage: acmecert validate-acct ACCOUNT-FILE"
333 if len(args) < 2: raise usageerr()
334 with maybeopen(args[1], "r") as fp:
335 account.read(fp).validate()
336 commands["validate-acct"] = cmd_validate_acct
338 def cmd_acct_info(args):
339 "usage: acmecert acct-info ACCOUNT-FILE"
340 if len(args) < 2: raise usageerr()
341 with maybeopen(args[1], "r") as fp:
342 pprint.pprint(account.read(fp).getinfo())
343 commands["acct-info"] = cmd_acct_info
346 "usage: acmecert order ACCOUNT-FILE CSR [OUTPUT-FILE]"
347 if len(args) < 3: raise usageerr()
348 with maybeopen(args[1], "r") as fp:
349 acct = account.read(fp)
350 with maybeopen(args[2], "r") as fp:
351 csr = signreq.read(fp)
352 order = mkorder(acct, csr)
353 with maybeopen(args[3] if len(args) > 3 else "-", "w") as fp:
354 fp.write("%s\n" % (order["acmecert.location"]))
355 commands["order"] = cmd_order
357 def cmd_http_auth(args):
358 "usage: acmecert http-auth ACCOUNT-FILE HTTP-CONFIG {ORDER-ID|ORDER-FILE}"
359 if len(args) < 4: raise usageerr()
360 with maybeopen(args[1], "r") as fp:
361 acct = account.read(fp)
362 with maybeopen(args[2], "r") as fp:
363 htconf = htconfig.read(fp)
367 with maybeopen(args[3], "r") as fp:
368 orderid = fp.readline().strip()
369 authorder(acct, htconf, orderid)
370 commands["http-auth"] = cmd_http_auth
373 "usage: acmecert get ACCOUNT-FILE CSR {ORDER-ID|ORDER-FILE}"
374 if len(args) < 4: raise usageerr()
375 with maybeopen(args[1], "r") as fp:
376 acct = account.read(fp)
377 with maybeopen(args[2], "r") as fp:
378 csr = signreq.read(fp)
382 with maybeopen(args[3], "r") as fp:
383 orderid = fp.readline().strip()
384 sys.stdout.write(finalize(acct, csr, orderid))
385 commands["get"] = cmd_get
387 def cmd_http_order(args):
388 "usage: acmecert http-order ACCOUNT-FILE CSR HTTP-CONFIG [OUTPUT-FILE]"
389 if len(args) < 4: raise usageerr()
390 with maybeopen(args[1], "r") as fp:
391 acct = account.read(fp)
392 with maybeopen(args[2], "r") as fp:
393 csr = signreq.read(fp)
394 with maybeopen(args[3], "r") as fp:
395 htconf = htconfig.read(fp)
396 orderid = mkorder(acct, csr)["acmecert.location"]
397 authorder(acct, htconf, orderid)
398 with maybeopen(args[4] if len(args) > 4 else "-", "w") as fp:
399 fp.write(finalize(acct, csr, orderid))
400 commands["http-order"] = cmd_http_order
402 def cmd_check_cert(args):
403 "usage: acmecert check-cert CERT-FILE TIME-SPEC"
404 if len(args) < 3: raise usageerr()
405 with maybeopen(args[1], "r") as fp:
406 crt = certificate.read(fp)
407 sys.exit(1 if crt.expiring(args[2]) else 0)
408 commands["check-cert"] = cmd_check_cert
410 def cmd_directory(args):
411 "usage: acmecert directory"
412 pprint.pprint(directory())
413 commands["directory"] = cmd_directory
416 out.write("usage: acmecert [-D SERVICE] COMMAND [ARGS...]\n")
417 out.write(" acmecert -h [COMMAND]\n")
418 buf = " COMMAND is any of: "
421 if len(buf) + len(cmd) > 70:
422 out.write("%s\n" % (buf,))
430 out.write("%s\n" % (buf,))
434 opts, args = getopt.getopt(argv[1:], "hD:")
438 cmd = commands.get(args[0])
440 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
442 sys.stdout.write("%s\n" % (cmd.__doc__,))
451 cmd = commands.get(args[0])
453 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
462 except msgerror as exc:
463 exc.report(sys.stderr)
466 if __name__ == "__main__":
469 except KeyboardInterrupt:
470 signal.signal(signal.SIGINT, signal.SIG_DFL)
471 os.kill(os.getpid(), signal.SIGINT)