3 #### ACME client (only http-01 challenges supported thus far)
5 import sys, os, getopt, binascii, json, pprint, signal, time, calendar, threading
7 import Crypto.PublicKey.RSA, Crypto.Random, Crypto.Hash.SHA256, Crypto.Signature.PKCS1_v1_5
11 class msgerror(Exception):
12 def report(self, out):
13 out.write("acmecert: undefined error\n")
16 return binascii.b2a_base64(dat).decode("us-ascii").translate({43: 45, 47: 95, 61: None}).strip()
20 if len(h) % 2 == 1: h = "0" + h
21 return base64url(binascii.a2b_hex(h))
23 class maybeopen(object):
24 def __init__(self, name, mode):
32 raise ValueError(mode)
35 self.fp = open(name, mode)
40 def __exit__(self, *excinfo):
47 class dererror(Exception):
50 class pemerror(Exception):
53 def pemdec(pem, ptypes):
54 if isinstance(ptypes, str):
58 p = pem.find("-----BEGIN ", p)
60 raise pemerror("could not find any %s in PEM-encoded data" % (ptypes,))
61 p2 = pem.find("-----", p + 11)
63 raise pemerror("incomplete PEM header")
64 ptype = pem[p + 11 : p2]
65 if ptype not in ptypes:
68 p3 = pem.find("-----END " + ptype + "-----", p2 + 5)
70 raise pemerror("incomplete PEM data")
71 pem = pem[p2 + 5 : p3]
72 return binascii.a2b_base64(pem)
74 class derdecoder(object):
75 def __init__(self, data, offset=0, size=None):
78 self.size = len(data) if size is None else size
81 return self.offset >= self.size
84 if self.offset >= self.size:
85 raise dererror("unexpected end-of-data")
86 ret = self.data[self.offset]
91 if self.offset + ln > self.size:
92 raise dererror("unexpected end-of-data")
93 ret = self.data[self.offset : self.offset + ln]
100 cons = (h & 0x20) != 0
103 raise dererror("extended type tags not supported")
111 raise dererror("indefinite lengths not supported in DER")
113 raise dererror("invalid length byte")
117 ret = (ret << 8) + self.byte()
121 cl, cons, tag = self.dectag()
123 return cons, cl, tag, self.splice(ln)
125 def getcons(self, ckcl, cktag):
126 cons, cl, tag, data = self.get()
128 raise dererror("expected constructed value")
129 if (ckcl != None and ckcl != cl) or (cktag != None and cktag != tag):
130 raise dererror("unexpected value tag: got (%d, %d), expected (%d, %d)" % (cl, tag, ckcl, cktag))
131 return derdecoder(data)
134 cons, cl, tag, data = self.get()
135 if (cons, cl, tag) == (False, 0, 2):
140 raise dererror("unexpected integer type: (%s, %d, %d)" % (cons, cl, tag))
143 cons, cl, tag, data = self.get()
144 if (cons, cl, tag) == (False, 0, 12):
145 return data.decode("utf-8")
146 if (cons, cl, tag) == (False, 0, 13):
147 return data.decode("us-ascii")
148 if (cons, cl, tag) == (False, 0, 22):
149 return data.decode("us-ascii")
150 if (cons, cl, tag) == (False, 0, 30):
151 return data.decode("utf-16-be")
152 raise dererror("unexpected string type: (%s, %d, %d)" % (cons, cl, tag))
155 cons, cl, tag, data = self.get()
156 if (cons, cl, tag) == (False, 0, 4):
158 raise dererror("unexpected byte-string type: (%s, %d, %d)" % (cons, cl, tag))
161 cons, cl, tag, data = self.get()
162 if (cons, cl, tag) == (False, 0, 6):
164 ret.append(data[0] // 40)
165 ret.append(data[0] % 40)
172 n = (n + (v & 0x7f)) * 128
178 raise dererror("unexpected object-id type: (%s, %d, %d)" % (cons, cl, tag))
181 def parsetime(data, c):
187 y += 1900 if y > 50 else 2000
193 if data[:1].isdigit():
198 if data[:1].isdigit():
205 while len(data) < p and data[p].isdigit():
207 S += float("0." + data[1:p])
210 raise dererror("unspecified local time not supported for decoding")
214 tz = (int(data[1:3]) * 60) + int(data[3:5])
216 tz = -((int(data[1:3]) * 60) + int(data[3:5]))
218 raise dererror("cannot parse X.690 timestamp")
219 return calendar.timegm((y, m, d, H, M, S)) - (tz * 60)
222 cons, cl, tag, data = self.get()
223 if (cons, cl, tag) == (False, 0, 23):
224 return self.parsetime(data.decode("us-ascii"), False)
225 if (cons, cl, tag) == (False, 0, 24):
226 return self.parsetime(data.decode("us-ascii"), True)
227 raise dererror("unexpected time type: (%s, %d, %d)" % (cons, cl, tag))
230 def frompem(cls, pem, ptypes):
231 return cls(pemdec(pem, ptypes))
233 class certificate(object):
234 def __init__(self, der):
235 ci = der.getcons(0, 16).getcons(0, 16)
236 self.ver = ci.getcons(2, 0).getint()
237 self.serial = ci.getint()
238 ci.getcons(0, 16) # Signature algorithm
239 ci.getcons(0, 16) # Issuer
240 vl = ci.getcons(0, 16)
241 self.startdate = vl.gettime()
242 self.enddate = vl.gettime()
244 def expiring(self, timespec):
245 if timespec.endswith("y"):
246 timespec = int(timespec[:-1]) * 365 * 86400
247 elif timespec.endswith("m"):
248 timespec = int(timespec[:-1]) * 30 * 86400
249 elif timespec.endswith("w"):
250 timespec = int(timespec[:-1]) * 7 * 86400
251 elif timespec.endswith("d"):
252 timespec = int(timespec[:-1]) * 86400
253 elif timespec.endswith("h"):
254 timespec = int(timespec[:-1]) * 3600
256 timespec = int(timespec)
257 return (self.enddate - time.time()) < timespec
261 return cls(derdecoder.frompem(fp.read(), {"CERTIFICATE", "X509 CERTIFICATE"}))
263 class signreq(object):
264 def __init__(self, der):
266 req = derdecoder(der).getcons(0, 16).getcons(0, 16)
267 self.ver = req.getint()
268 req.getcons(0, 16) # Subject
269 req.getcons(0, 16) # Public key
272 attrs = req.getcons(2, 0)
273 while not attrs.end():
274 attr = attrs.getcons(0, 16)
276 if anm == (1, 2, 840, 113549, 1, 9, 14):
277 # Certificate extension request
278 exts = attr.getcons(0, 17).getcons(0, 16)
279 while not exts.end():
280 ext = exts.getcons(0, 16)
282 if extnm == (2, 5, 29, 17):
283 # Subject alternative names
284 names = derdecoder(ext.getbytes()).getcons(0, 16)
285 while not names.end():
286 cons, cl, tag, data = names.get()
287 if (cons, cl, tag) == (False, 2, 2):
288 self.altnames.append(("DNS", data.decode("us-ascii")))
291 return [nm[1] for nm in self.altnames if nm[0] == "DNS"]
298 return cls(pemdec(fp.read(), {"CERTIFICATE REQUEST"}))
300 ### Somewhat general request utilities
303 with urllib.request.urlopen(directory()["newNonce"]) as resp:
305 return resp.headers["Replay-Nonce"]
307 def req(url, data=None, ctype=None, headers={}, method=None, **kws):
308 if data is not None and not isinstance(data, bytes):
309 data = json.dumps(data).encode("utf-8")
310 ctype = "application/jose+json"
311 req = urllib.request.Request(url, data=data, method=method)
312 for hnam, hval in headers.items():
313 req.add_header(hnam, hval)
314 if ctype is not None:
315 req.add_header("Content-Type", ctype)
316 return urllib.request.urlopen(req)
318 class problem(msgerror):
319 def __init__(self, code, data, *args, url=None, **kw):
320 super().__init__(*args, **kw)
324 if not isinstance(data, dict):
325 raise ValueError("unexpected problem object type: %r" % (data,))
329 return self.data.get("type", "about:blank")
332 return self.data.get("title")
335 return self.data.get("detail")
337 def report(self, out):
339 if self.title is None:
342 extra, msg = msg, None
347 msg = self.data.get("type")
349 out.write("acemcert: %s: %s\n" % (
350 ("remote service error" if self.url is None else self.url),
351 ("unspecified error" if msg is None else msg)))
352 if extra is not None:
353 out.write("%s\n" % (extra,))
356 def read(cls, err, **kw):
357 self = cls(err.code, json.load(err), **kw)
360 def jreq(url, data, auth):
361 authdata = {"alg": "RS256", "url": url, "nonce": getnonce()}
362 authdata.update(auth.authdata())
363 authdata = base64url(json.dumps(authdata).encode("us-ascii"))
367 data = base64url(json.dumps(data).encode("us-ascii"))
368 seal = base64url(auth.sign(("%s.%s" % (authdata, data)).encode("us-ascii")))
369 enc = {"protected": authdata, "payload": data, "signature": seal}
371 with req(url, data=enc) as resp:
372 return json.load(resp), resp.headers
373 except urllib.error.HTTPError as exc:
374 if exc.headers["Content-Type"] == "application/problem+json":
375 raise problem.read(exc, url=url)
380 class jwkauth(object):
381 def __init__(self, key):
385 return {"jwk": {"kty": "RSA", "e": ebignum(self.key.e), "n": ebignum(self.key.n)}}
387 def sign(self, data):
388 dig = Crypto.Hash.SHA256.new()
390 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
392 class account(object):
393 def __init__(self, uri, key):
398 return {"kid": self.uri}
400 def sign(self, data):
401 dig = Crypto.Hash.SHA256.new()
403 return Crypto.Signature.PKCS1_v1_5.new(self.key).sign(dig)
406 data, headers = jreq(self.uri, None, self)
410 data = self.getinfo()
411 if data.get("status", "") != "valid":
412 raise Exception("account is not valid: %s" % (data.get("status", "\"\"")))
414 def write(self, out):
415 out.write("%s\n" % (self.uri,))
416 out.write("%s\n" % (self.key.exportKey().decode("us-ascii"),))
422 raise Exception("missing account URI")
424 key = Crypto.PublicKey.RSA.importKey(fp.read())
429 service = "https://acme-v02.api.letsencrypt.org/directory"
433 if _directory is None:
434 with req(service) as resp:
435 _directory = json.load(resp)
438 def register(keysize=4096):
439 key = Crypto.PublicKey.RSA.generate(keysize, Crypto.Random.new().read)
440 data, headers = jreq(directory()["newAccount"], {"termsOfServiceAgreed": True}, jwkauth(key))
441 return account(headers["Location"], key)
443 def mkorder(acct, csr):
444 data, headers = jreq(directory()["newOrder"], {"identifiers": [{"type": "dns", "value": dn} for dn in csr.domains()]}, acct)
445 data["acmecert.location"] = headers["Location"]
448 def httptoken(acct, ch):
449 jwk = {"kty": "RSA", "e": ebignum(acct.key.e), "n": ebignum(acct.key.n)}
450 dig = Crypto.Hash.SHA256.new()
451 dig.update(json.dumps(jwk, separators=(',', ':'), sort_keys=True).encode("us-ascii"))
452 khash = base64url(dig.digest())
453 return ch["token"], ("%s.%s" % (ch["token"], khash))
455 def finalize(acct, csr, orderid):
456 order, headers = jreq(orderid, None, acct)
457 if order["status"] == "valid":
459 elif order["status"] == "ready":
460 jreq(order["finalize"], {"csr": base64url(csr.der())}, acct)
462 resp, headers = jreq(orderid, None, acct)
463 if resp["status"] == "processing":
465 elif resp["status"] == "valid":
469 raise Exception("unexpected order status when finalizing: %s" % resp["status"])
471 raise Exception("order finalization timed out")
473 raise Exception("unexpected order state when finalizing: %s" % (order["status"],))
474 with req(order["certificate"]) as resp:
475 return resp.read().decode("us-ascii")
479 class htconfig(object):
488 if len(words) < 1 or ln[0] == '#':
490 if words[0] == "root":
491 self.roots[words[1]] = words[2]
493 sys.stderr.write("acmecert: warning: unknown htconfig directive: %s\n" % (words[0]))
496 def authorder(acct, htconf, orderid):
497 order, headers = jreq(orderid, None, acct)
504 raise Exception("challenges refuse to become valid even after 5 retries")
505 for authuri in order["authorizations"]:
506 auth, headers = jreq(authuri, None, acct)
507 if auth["status"] == "valid":
509 elif auth["status"] == "pending":
512 raise Exception("unknown authorization status: %s" % (auth["status"],))
514 if auth["identifier"]["type"] != "dns":
515 raise Exception("unknown authorization type: %s" % (auth["identifier"]["type"],))
516 dn = auth["identifier"]["value"]
517 if dn not in htconf.roots:
518 raise Exception("no configured ht-root for domain name %s" % (dn,))
519 for ch in auth["challenges"]:
520 if ch["type"] == "http-01":
523 raise Exception("no http-01 challenge for %s" % (dn,))
524 root = htconf.roots[dn]
525 tokid, tokval = httptoken(acct, ch)
526 tokpath = os.path.join(root, tokid);
527 fp = open(tokpath, "w")
531 with req("http://%s/.well-known/acme-challenge/%s" % (dn, tokid)) as resp:
532 if resp.read().decode("utf-8") != tokval:
533 raise Exception("challenge from %s does not match written value" % (dn,))
535 resp, headers = jreq(ch["url"], {}, acct)
536 if resp["status"] == "processing":
538 elif resp["status"] == "pending":
539 # I don't think this should happen, but it
540 # does. LE bug? Anyway, just retry.
545 elif resp["status"] == "valid":
548 raise Exception("unexpected challenge status for %s when validating: %s" % (dn, resp["status"]))
550 raise Exception("challenge processing timed out for %s" % (dn,))
554 ### Invocation and commands
556 invdata = threading.local()
559 class usageerr(msgerror):
561 self.cmd = invdata.cmd
563 def report(self, out):
564 out.write("%s\n" % (self.cmd.__doc__,))
569 "usage: acmecert reg [OUTPUT-FILE]"
572 with maybeopen(args[1] if len(args) > 1 else "-", "w") as fp:
574 commands["reg"] = cmd_reg
576 def cmd_validate_acct(args):
577 "usage: acmecert validate-acct ACCOUNT-FILE"
578 if len(args) < 2: raise usageerr()
579 with maybeopen(args[1], "r") as fp:
580 account.read(fp).validate()
581 commands["validate-acct"] = cmd_validate_acct
583 def cmd_acct_info(args):
584 "usage: acmecert acct-info ACCOUNT-FILE"
585 if len(args) < 2: raise usageerr()
586 with maybeopen(args[1], "r") as fp:
587 pprint.pprint(account.read(fp).getinfo())
588 commands["acct-info"] = cmd_acct_info
591 "usage: acmecert order ACCOUNT-FILE CSR [OUTPUT-FILE]"
592 if len(args) < 3: raise usageerr()
593 with maybeopen(args[1], "r") as fp:
594 acct = account.read(fp)
595 with maybeopen(args[2], "r") as fp:
596 csr = signreq.read(fp)
597 order = mkorder(acct, csr)
598 with maybeopen(args[3] if len(args) > 3 else "-", "w") as fp:
599 fp.write("%s\n" % (order["acmecert.location"]))
600 commands["order"] = cmd_order
602 def cmd_http_auth(args):
603 "usage: acmecert http-auth ACCOUNT-FILE HTTP-CONFIG {ORDER-ID|ORDER-FILE}"
604 if len(args) < 4: raise usageerr()
605 with maybeopen(args[1], "r") as fp:
606 acct = account.read(fp)
607 with maybeopen(args[2], "r") as fp:
608 htconf = htconfig.read(fp)
612 with maybeopen(args[3], "r") as fp:
613 orderid = fp.readline().strip()
614 authorder(acct, htconf, orderid)
615 commands["http-auth"] = cmd_http_auth
618 "usage: acmecert get ACCOUNT-FILE CSR {ORDER-ID|ORDER-FILE}"
619 if len(args) < 4: raise usageerr()
620 with maybeopen(args[1], "r") as fp:
621 acct = account.read(fp)
622 with maybeopen(args[2], "r") as fp:
623 csr = signreq.read(fp)
627 with maybeopen(args[3], "r") as fp:
628 orderid = fp.readline().strip()
629 sys.stdout.write(finalize(acct, csr, orderid))
630 commands["get"] = cmd_get
632 def cmd_http_order(args):
633 "usage: acmecert http-order ACCOUNT-FILE CSR HTTP-CONFIG [OUTPUT-FILE]"
634 if len(args) < 4: raise usageerr()
635 with maybeopen(args[1], "r") as fp:
636 acct = account.read(fp)
637 with maybeopen(args[2], "r") as fp:
638 csr = signreq.read(fp)
639 with maybeopen(args[3], "r") as fp:
640 htconf = htconfig.read(fp)
641 orderid = mkorder(acct, csr)["acmecert.location"]
642 authorder(acct, htconf, orderid)
643 with maybeopen(args[4] if len(args) > 4 else "-", "w") as fp:
644 fp.write(finalize(acct, csr, orderid))
645 commands["http-order"] = cmd_http_order
647 def cmd_check_cert(args):
648 "usage: acmecert check-cert CERT-FILE TIME-SPEC"
649 if len(args) < 3: raise usageerr()
650 with maybeopen(args[1], "r") as fp:
651 crt = certificate.read(fp)
652 sys.exit(1 if crt.expiring(args[2]) else 0)
653 commands["check-cert"] = cmd_check_cert
655 def cmd_directory(args):
656 "usage: acmecert directory"
657 pprint.pprint(directory())
658 commands["directory"] = cmd_directory
663 out.write("usage: acmecert [-D SERVICE] COMMAND [ARGS...]\n")
664 out.write(" acmecert -h [COMMAND]\n")
665 buf = " COMMAND is any of: "
668 if len(buf) + len(cmd) > 70:
669 out.write("%s\n" % (buf,))
677 out.write("%s\n" % (buf,))
681 opts, args = getopt.getopt(argv[1:], "hD:")
685 cmd = commands.get(args[0])
687 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
689 sys.stdout.write("%s\n" % (cmd.__doc__,))
698 cmd = commands.get(args[0])
700 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
709 except msgerror as exc:
710 exc.report(sys.stderr)
713 if __name__ == "__main__":
716 except KeyboardInterrupt:
717 signal.signal(signal.SIGINT, signal.SIG_DFL)
718 os.kill(os.getpid(), signal.SIGINT)