3 #### ACME client (only http-01 challenges supported thus far)
5 import sys, os, getopt, binascii, json, pprint, signal, time, calendar, threading
10 class msgerror(Exception):
11 def report(self, out):
12 out.write("acmecert: undefined error\n")
15 return binascii.b2a_base64(dat).decode("us-ascii").translate({43: 45, 47: 95, 61: None}).strip()
19 if len(h) % 2 == 1: h = "0" + h
20 return base64url(binascii.a2b_hex(h))
22 class maybeopen(object):
23 def __init__(self, name, mode):
31 raise ValueError(mode)
34 self.fp = open(name, mode)
39 def __exit__(self, *excinfo):
49 if _cryptobke is None:
50 from cryptography.hazmat import backends
51 _cryptobke = backends.default_backend()
54 class dererror(Exception):
57 class pemerror(Exception):
60 def pemdec(pem, ptypes):
61 if isinstance(ptypes, str):
65 p = pem.find("-----BEGIN ", p)
67 raise pemerror("could not find any %s in PEM-encoded data" % (ptypes,))
68 p2 = pem.find("-----", p + 11)
70 raise pemerror("incomplete PEM header")
71 ptype = pem[p + 11 : p2]
72 if ptype not in ptypes:
75 p3 = pem.find("-----END " + ptype + "-----", p2 + 5)
77 raise pemerror("incomplete PEM data")
78 pem = pem[p2 + 5 : p3]
79 return binascii.a2b_base64(pem)
81 class derdecoder(object):
82 def __init__(self, data, offset=0, size=None):
85 self.size = len(data) if size is None else size
88 return self.offset >= self.size
91 if self.offset >= self.size:
92 raise dererror("unexpected end-of-data")
93 ret = self.data[self.offset]
98 if self.offset + ln > self.size:
99 raise dererror("unexpected end-of-data")
100 ret = self.data[self.offset : self.offset + ln]
107 cons = (h & 0x20) != 0
110 raise dererror("extended type tags not supported")
118 raise dererror("indefinite lengths not supported in DER")
120 raise dererror("invalid length byte")
124 ret = (ret << 8) + self.byte()
128 cl, cons, tag = self.dectag()
130 return cons, cl, tag, self.splice(ln)
132 def getcons(self, ckcl, cktag):
133 cons, cl, tag, data = self.get()
135 raise dererror("expected constructed value")
136 if (ckcl != None and ckcl != cl) or (cktag != None and cktag != tag):
137 raise dererror("unexpected value tag: got (%d, %d), expected (%d, %d)" % (cl, tag, ckcl, cktag))
138 return derdecoder(data)
141 cons, cl, tag, data = self.get()
142 if (cons, cl, tag) == (False, 0, 2):
147 raise dererror("unexpected integer type: (%s, %d, %d)" % (cons, cl, tag))
150 cons, cl, tag, data = self.get()
151 if (cons, cl, tag) == (False, 0, 12):
152 return data.decode("utf-8")
153 if (cons, cl, tag) == (False, 0, 13):
154 return data.decode("us-ascii")
155 if (cons, cl, tag) == (False, 0, 22):
156 return data.decode("us-ascii")
157 if (cons, cl, tag) == (False, 0, 30):
158 return data.decode("utf-16-be")
159 raise dererror("unexpected string type: (%s, %d, %d)" % (cons, cl, tag))
162 cons, cl, tag, data = self.get()
163 if (cons, cl, tag) == (False, 0, 4):
165 raise dererror("unexpected byte-string type: (%s, %d, %d)" % (cons, cl, tag))
168 cons, cl, tag, data = self.get()
169 if (cons, cl, tag) == (False, 0, 6):
171 ret.append(data[0] // 40)
172 ret.append(data[0] % 40)
179 n = (n + (v & 0x7f)) * 128
185 raise dererror("unexpected object-id type: (%s, %d, %d)" % (cons, cl, tag))
188 def parsetime(data, c):
194 y += 1900 if y > 50 else 2000
200 if data[:1].isdigit():
205 if data[:1].isdigit():
212 while len(data) < p and data[p].isdigit():
214 S += float("0." + data[1:p])
217 raise dererror("unspecified local time not supported for decoding")
221 tz = (int(data[1:3]) * 60) + int(data[3:5])
223 tz = -((int(data[1:3]) * 60) + int(data[3:5]))
225 raise dererror("cannot parse X.690 timestamp")
226 return calendar.timegm((y, m, d, H, M, S)) - (tz * 60)
229 cons, cl, tag, data = self.get()
230 if (cons, cl, tag) == (False, 0, 23):
231 return self.parsetime(data.decode("us-ascii"), False)
232 if (cons, cl, tag) == (False, 0, 24):
233 return self.parsetime(data.decode("us-ascii"), True)
234 raise dererror("unexpected time type: (%s, %d, %d)" % (cons, cl, tag))
237 def frompem(cls, pem, ptypes):
238 return cls(pemdec(pem, ptypes))
240 class certificate(object):
241 def __init__(self, der):
242 ci = der.getcons(0, 16).getcons(0, 16)
243 self.ver = ci.getcons(2, 0).getint()
244 self.serial = ci.getint()
245 ci.getcons(0, 16) # Signature algorithm
246 ci.getcons(0, 16) # Issuer
247 vl = ci.getcons(0, 16)
248 self.startdate = vl.gettime()
249 self.enddate = vl.gettime()
251 def expiring(self, timespec):
252 if timespec.endswith("y"):
253 timespec = int(timespec[:-1]) * 365 * 86400
254 elif timespec.endswith("m"):
255 timespec = int(timespec[:-1]) * 30 * 86400
256 elif timespec.endswith("w"):
257 timespec = int(timespec[:-1]) * 7 * 86400
258 elif timespec.endswith("d"):
259 timespec = int(timespec[:-1]) * 86400
260 elif timespec.endswith("h"):
261 timespec = int(timespec[:-1]) * 3600
263 timespec = int(timespec)
264 return (self.enddate - time.time()) < timespec
268 return cls(derdecoder.frompem(fp.read(), {"CERTIFICATE", "X509 CERTIFICATE"}))
270 class signreq(object):
271 def __init__(self, der):
273 req = derdecoder(der).getcons(0, 16).getcons(0, 16)
274 self.ver = req.getint()
275 req.getcons(0, 16) # Subject
276 req.getcons(0, 16) # Public key
279 attrs = req.getcons(2, 0)
280 while not attrs.end():
281 attr = attrs.getcons(0, 16)
283 if anm == (1, 2, 840, 113549, 1, 9, 14):
284 # Certificate extension request
285 exts = attr.getcons(0, 17).getcons(0, 16)
286 while not exts.end():
287 ext = exts.getcons(0, 16)
289 if extnm == (2, 5, 29, 17):
290 # Subject alternative names
291 names = derdecoder(ext.getbytes()).getcons(0, 16)
292 while not names.end():
293 cons, cl, tag, data = names.get()
294 if (cons, cl, tag) == (False, 2, 2):
295 self.altnames.append(("DNS", data.decode("us-ascii")))
298 return [nm[1] for nm in self.altnames if nm[0] == "DNS"]
305 return cls(pemdec(fp.read(), {"CERTIFICATE REQUEST"}))
307 ### Somewhat general request utilities
310 with urllib.request.urlopen(directory()["newNonce"]) as resp:
312 return resp.headers["Replay-Nonce"]
314 def req(url, data=None, ctype=None, headers={}, method=None, **kws):
315 if data is not None and not isinstance(data, bytes):
316 data = json.dumps(data).encode("utf-8")
317 ctype = "application/jose+json"
318 req = urllib.request.Request(url, data=data, method=method)
319 for hnam, hval in headers.items():
320 req.add_header(hnam, hval)
321 if ctype is not None:
322 req.add_header("Content-Type", ctype)
323 return urllib.request.urlopen(req)
325 class problem(msgerror):
326 def __init__(self, code, data, *args, url=None, **kw):
327 super().__init__(*args, **kw)
331 if not isinstance(data, dict):
332 raise ValueError("unexpected problem object type: %r" % (data,))
336 return self.data.get("type", "about:blank")
339 return self.data.get("title")
342 return self.data.get("detail")
344 def report(self, out):
346 if self.title is None:
349 extra, msg = msg, None
354 msg = self.data.get("type")
356 out.write("acemcert: %s: %s\n" % (
357 ("remote service error" if self.url is None else self.url),
358 ("unspecified error" if msg is None else msg)))
359 if extra is not None:
360 out.write("%s\n" % (extra,))
363 def read(cls, err, **kw):
364 self = cls(err.code, json.loads(err.read().decode("utf-8")), **kw)
367 def jreq(url, data, auth):
368 authdata = {"alg": "RS256", "url": url, "nonce": getnonce()}
369 authdata.update(auth.authdata())
370 authdata = base64url(json.dumps(authdata).encode("us-ascii"))
374 data = base64url(json.dumps(data).encode("us-ascii"))
375 seal = base64url(auth.sign(("%s.%s" % (authdata, data)).encode("us-ascii")))
376 enc = {"protected": authdata, "payload": data, "signature": seal}
378 with req(url, data=enc) as resp:
379 return json.loads(resp.read().decode("utf-8")), resp.headers
380 except urllib.error.HTTPError as exc:
381 if exc.headers["Content-Type"] == "application/problem+json":
382 raise problem.read(exc, url=url)
387 class jwkauth(object):
388 def __init__(self, key):
392 pub = self.key.public_key().public_numbers()
393 return {"jwk": {"kty": "RSA", "e": ebignum(pub.e), "n": ebignum(pub.n)}}
395 def sign(self, data):
396 from cryptography.hazmat.primitives import hashes
397 from cryptography.hazmat.primitives.asymmetric import padding
398 return self.key.sign(data, padding.PKCS1v15(), hashes.SHA256())
400 class account(object):
401 def __init__(self, uri, key):
406 return {"kid": self.uri}
408 def sign(self, data):
409 from cryptography.hazmat.primitives import hashes
410 from cryptography.hazmat.primitives.asymmetric import padding
411 return self.key.sign(data, padding.PKCS1v15(), hashes.SHA256())
414 data, headers = jreq(self.uri, None, self)
418 data = self.getinfo()
419 if data.get("status", "") != "valid":
420 raise Exception("account is not valid: %s" % (data.get("status", "\"\"")))
422 def write(self, out):
423 from cryptography.hazmat.primitives import serialization
424 out.write("%s\n" % (self.uri,))
425 out.write("%s\n" % (self.key.private_bytes(
426 encoding=serialization.Encoding.PEM,
427 format=serialization.PrivateFormat.TraditionalOpenSSL,
428 encryption_algorithm=serialization.NoEncryption()
429 ).decode("us-ascii"),))
433 from cryptography.hazmat.primitives import serialization
436 raise Exception("missing account URI")
438 key = serialization.load_pem_private_key(fp.read().encode("us-ascii"), password=None, backend=cryptobke())
443 service = "https://acme-v02.api.letsencrypt.org/directory"
447 if _directory is None:
448 with req(service) as resp:
449 _directory = json.loads(resp.read().decode("utf-8"))
452 def register(keysize=4096):
453 from cryptography.hazmat.primitives.asymmetric import rsa
454 key = rsa.generate_private_key(public_exponent=65537, key_size=keysize, backend=cryptobke())
455 data, headers = jreq(directory()["newAccount"], {"termsOfServiceAgreed": True}, jwkauth(key))
456 return account(headers["Location"], key)
458 def mkorder(acct, csr):
459 data, headers = jreq(directory()["newOrder"], {"identifiers": [{"type": "dns", "value": dn} for dn in csr.domains()]}, acct)
460 data["acmecert.location"] = headers["Location"]
463 def httptoken(acct, ch):
464 from cryptography.hazmat.primitives import hashes
465 jwk = {"kty": "RSA", "e": ebignum(acct.key.e), "n": ebignum(acct.key.n)}
466 dig = hashes.Hash(hashes.SHA256())
467 dig.update(json.dumps(jwk, separators=(',', ':'), sort_keys=True).encode("us-ascii"))
468 khash = base64url(dig.finalize())
469 return ch["token"], ("%s.%s" % (ch["token"], khash))
471 def finalize(acct, csr, orderid):
472 order, headers = jreq(orderid, None, acct)
473 if order["status"] == "valid":
475 elif order["status"] == "ready":
476 jreq(order["finalize"], {"csr": base64url(csr.der())}, acct)
478 resp, headers = jreq(orderid, None, acct)
479 if resp["status"] == "processing":
481 elif resp["status"] == "valid":
485 raise Exception("unexpected order status when finalizing: %s" % resp["status"])
487 raise Exception("order finalization timed out")
489 raise Exception("unexpected order state when finalizing: %s" % (order["status"],))
490 with req(order["certificate"]) as resp:
491 return resp.read().decode("us-ascii")
495 class htconfig(object):
504 if len(words) < 1 or ln[0] == '#':
506 if words[0] == "root":
507 self.roots[words[1]] = words[2]
509 sys.stderr.write("acmecert: warning: unknown htconfig directive: %s\n" % (words[0]))
512 def authorder(acct, htconf, orderid):
513 order, headers = jreq(orderid, None, acct)
520 raise Exception("challenges refuse to become valid even after 5 retries")
521 for authuri in order["authorizations"]:
522 auth, headers = jreq(authuri, None, acct)
523 if auth["status"] == "valid":
525 elif auth["status"] == "pending":
528 raise Exception("unknown authorization status: %s" % (auth["status"],))
530 if auth["identifier"]["type"] != "dns":
531 raise Exception("unknown authorization type: %s" % (auth["identifier"]["type"],))
532 dn = auth["identifier"]["value"]
533 if dn not in htconf.roots:
534 raise Exception("no configured ht-root for domain name %s" % (dn,))
535 for ch in auth["challenges"]:
536 if ch["type"] == "http-01":
539 raise Exception("no http-01 challenge for %s" % (dn,))
540 root = htconf.roots[dn]
541 tokid, tokval = httptoken(acct, ch)
542 tokpath = os.path.join(root, tokid);
543 fp = open(tokpath, "w")
547 with req("http://%s/.well-known/acme-challenge/%s" % (dn, tokid)) as resp:
548 if resp.read().decode("utf-8") != tokval:
549 raise Exception("challenge from %s does not match written value" % (dn,))
551 resp, headers = jreq(ch["url"], {}, acct)
552 if resp["status"] == "processing":
554 elif resp["status"] == "pending":
555 # I don't think this should happen, but it
556 # does. LE bug? Anyway, just retry.
561 elif resp["status"] == "valid":
564 raise Exception("unexpected challenge status for %s when validating: %s" % (dn, resp["status"]))
566 raise Exception("challenge processing timed out for %s" % (dn,))
570 ### Invocation and commands
572 invdata = threading.local()
575 class usageerr(msgerror):
577 self.cmd = invdata.cmd
579 def report(self, out):
580 out.write("%s\n" % (self.cmd.__doc__,))
585 "usage: acmecert reg [OUTPUT-FILE]"
588 with maybeopen(args[1] if len(args) > 1 else "-", "w") as fp:
590 commands["reg"] = cmd_reg
592 def cmd_validate_acct(args):
593 "usage: acmecert validate-acct ACCOUNT-FILE"
594 if len(args) < 2: raise usageerr()
595 with maybeopen(args[1], "r") as fp:
596 account.read(fp).validate()
597 commands["validate-acct"] = cmd_validate_acct
599 def cmd_acct_info(args):
600 "usage: acmecert acct-info ACCOUNT-FILE"
601 if len(args) < 2: raise usageerr()
602 with maybeopen(args[1], "r") as fp:
603 pprint.pprint(account.read(fp).getinfo())
604 commands["acct-info"] = cmd_acct_info
607 "usage: acmecert order ACCOUNT-FILE CSR [OUTPUT-FILE]"
608 if len(args) < 3: raise usageerr()
609 with maybeopen(args[1], "r") as fp:
610 acct = account.read(fp)
611 with maybeopen(args[2], "r") as fp:
612 csr = signreq.read(fp)
613 order = mkorder(acct, csr)
614 with maybeopen(args[3] if len(args) > 3 else "-", "w") as fp:
615 fp.write("%s\n" % (order["acmecert.location"]))
616 commands["order"] = cmd_order
618 def cmd_http_auth(args):
619 "usage: acmecert http-auth ACCOUNT-FILE HTTP-CONFIG {ORDER-ID|ORDER-FILE}"
620 if len(args) < 4: raise usageerr()
621 with maybeopen(args[1], "r") as fp:
622 acct = account.read(fp)
623 with maybeopen(args[2], "r") as fp:
624 htconf = htconfig.read(fp)
628 with maybeopen(args[3], "r") as fp:
629 orderid = fp.readline().strip()
630 authorder(acct, htconf, orderid)
631 commands["http-auth"] = cmd_http_auth
634 "usage: acmecert get ACCOUNT-FILE CSR {ORDER-ID|ORDER-FILE}"
635 if len(args) < 4: raise usageerr()
636 with maybeopen(args[1], "r") as fp:
637 acct = account.read(fp)
638 with maybeopen(args[2], "r") as fp:
639 csr = signreq.read(fp)
643 with maybeopen(args[3], "r") as fp:
644 orderid = fp.readline().strip()
645 sys.stdout.write(finalize(acct, csr, orderid))
646 commands["get"] = cmd_get
648 def cmd_http_order(args):
649 "usage: acmecert http-order ACCOUNT-FILE CSR HTTP-CONFIG [OUTPUT-FILE]"
650 if len(args) < 4: raise usageerr()
651 with maybeopen(args[1], "r") as fp:
652 acct = account.read(fp)
653 with maybeopen(args[2], "r") as fp:
654 csr = signreq.read(fp)
655 with maybeopen(args[3], "r") as fp:
656 htconf = htconfig.read(fp)
657 orderid = mkorder(acct, csr)["acmecert.location"]
658 authorder(acct, htconf, orderid)
659 with maybeopen(args[4] if len(args) > 4 else "-", "w") as fp:
660 fp.write(finalize(acct, csr, orderid))
661 commands["http-order"] = cmd_http_order
663 def cmd_check_cert(args):
664 "usage: acmecert check-cert CERT-FILE TIME-SPEC"
665 if len(args) < 3: raise usageerr()
666 with maybeopen(args[1], "r") as fp:
667 crt = certificate.read(fp)
668 sys.exit(1 if crt.expiring(args[2]) else 0)
669 commands["check-cert"] = cmd_check_cert
671 def cmd_directory(args):
672 "usage: acmecert directory"
673 pprint.pprint(directory())
674 commands["directory"] = cmd_directory
679 out.write("usage: acmecert [-D SERVICE] COMMAND [ARGS...]\n")
680 out.write(" acmecert -h [COMMAND]\n")
681 buf = " COMMAND is any of: "
684 if len(buf) + len(cmd) > 70:
685 out.write("%s\n" % (buf,))
693 out.write("%s\n" % (buf,))
697 opts, args = getopt.getopt(argv[1:], "hD:")
701 cmd = commands.get(args[0])
703 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
705 sys.stdout.write("%s\n" % (cmd.__doc__,))
714 cmd = commands.get(args[0])
716 sys.stderr.write("acmecert: unknown command: %s\n" % (args[0],))
725 except msgerror as exc:
726 exc.report(sys.stderr)
729 if __name__ == "__main__":
732 except KeyboardInterrupt:
733 signal.signal(signal.SIGINT, signal.SIG_DFL)
734 os.kill(os.getpid(), signal.SIGINT)