Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: tests

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
python-version: ["3.10", "3.12", "3.13"]
include:
- os: macos-latest
python-version: "3.9"
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: ${{ matrix.python-version }}
- name: Unit tests
run: python -m unittest -v
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

## 1.1.0

- `--json` output with subject, issuer, DNS SANs, not_after and days_left
- Hosts are checked in parallel (`--workers`) and reported in input order
- `--timeout`, and `--crit` must now be lower than `--warn`
- Installable with pip (`certwatch` command), CI on Linux and macOS

## 1.0.0

Initial release.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Use it only against servers you own or are authorized to monitor.
python3 certwatch.py example.com
python3 certwatch.py example.com:8443 internal.example.org
python3 certwatch.py -f hosts.txt --warn 45 --crit 10
python3 certwatch.py -f hosts.txt --json --workers 16 --timeout 5
# or: pip install git+https://github.com/TPOALOS/certwatch && certwatch example.com
```

`hosts.txt` holds one `host` or `host:port` per line; `#` starts a comment.
Expand All @@ -19,6 +21,9 @@ Statuses: `OK`, `WARNING` (under `--warn` days, default 30), `CRITICAL` (under
`--crit`, default 7), `EXPIRED`, `INVALID` (verification failed, e.g. untrusted or
hostname mismatch), `ERROR` (network problem).

`--json` adds the subject, issuer, DNS subject alternative names, `not_after` and `days_left` for every host. Hosts are checked in
parallel (`--workers`, default 8) and always reported in the order you gave them. `--crit` must be lower than `--warn`.

Exit codes: `0` all OK, `1` any non-OK result, `2` usage error. Suitable for cron.

## Tests
Expand Down
65 changes: 57 additions & 8 deletions certwatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
Standard library only. Exit code 0 = all OK, 1 = warning/critical/error, 2 = usage.
"""
import argparse
import concurrent.futures
import datetime
import json
import socket
import ssl
import sys

__version__ = "1.0.0"
__version__ = "1.1.0"


def parse_target(text, default_port=443):
Expand Down Expand Up @@ -50,6 +52,44 @@ def fetch_not_after(host, port, timeout=10):
return tls.getpeercert()["notAfter"]


def fetch_cert(host, port, timeout=10):
"""Return the peer certificate dict (verified TLS connection)."""
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=timeout) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as tls:
return tls.getpeercert()


def _name(rdns):
"""Readable name from the getpeercert() subject/issuer structure."""
flat = {k: v for rdn in rdns or () for k, v in rdn}
return flat.get("commonName") or flat.get("organizationName") or ""


def inspect(target, warn=30, crit=7, fetch=fetch_cert, now=None, timeout=10):
"""Full result dict for one target. Never raises on network or certificate errors."""
res = {"target": target, "status": "ERROR", "days_left": None, "not_after": None,
"subject": None, "issuer": None, "san": [], "detail": ""}
try:
host, port = parse_target(target)
try:
cert = fetch(host, port, timeout)
except TypeError: # injected fetchers that take only (host, port)
cert = fetch(host, port)
days = days_left(cert["notAfter"], now)
except ssl.SSLCertVerificationError as exc:
res.update(status="INVALID", detail="certificate verification failed: %s" % exc.verify_message)
return res
except (OSError, ValueError, KeyError, TypeError) as exc:
res["detail"] = str(exc)
return res
res.update(status=classify(days, warn, crit), days_left=round(days, 2), not_after=cert["notAfter"],
subject=_name(cert.get("subject")), issuer=_name(cert.get("issuer")),
san=[v for k, v in cert.get("subjectAltName", ()) if k == "DNS"],
detail="%.1f day(s) left" % days)
return res


def check(target, warn=30, crit=7, fetch=fetch_not_after, now=None):
"""Return (status, detail) for one target. Never raises on network errors."""
try:
Expand All @@ -62,12 +102,15 @@ def check(target, warn=30, crit=7, fetch=fetch_not_after, now=None):
return classify(days, warn, crit), "%.1f day(s) left" % days


def main(argv=None):
def main(argv=None, _fetch=fetch_cert):
ap = argparse.ArgumentParser(description="Check TLS certificate expiry.")
ap.add_argument("targets", nargs="*", help="host or host:port")
ap.add_argument("-f", "--file", help="file with one target per line (# comments ok)")
ap.add_argument("--warn", type=int, default=30, help="warning threshold in days")
ap.add_argument("--crit", type=int, default=7, help="critical threshold in days")
ap.add_argument("--timeout", type=float, default=10, help="connect/handshake timeout in seconds")
ap.add_argument("--workers", type=int, default=8, help="hosts to check in parallel (default 8)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
ap.add_argument("--version", action="version", version=__version__)
args = ap.parse_args(argv)

Expand All @@ -83,12 +126,18 @@ def main(argv=None):
ap.print_usage(sys.stderr)
return 2

bad = 0
for t in targets:
status, detail = check(t, args.warn, args.crit)
if status != "OK":
bad += 1
print("%-9s %-40s %s" % (status, t, detail))
if args.crit >= args.warn:
print("certwatch: --crit (%d) must be lower than --warn (%d)" % (args.crit, args.warn), file=sys.stderr)
return 2
workers = max(1, min(args.workers, len(targets)))
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
results = list(pool.map(lambda t: inspect(t, args.warn, args.crit, _fetch, None, args.timeout), targets))
bad = sum(1 for r in results if r["status"] != "OK")
if args.json:
print(json.dumps(results, indent=2))
else:
for r in results:
print("%-9s %-40s %s" % (r["status"], r["target"], r["detail"]))
return 1 if bad else 0


Expand Down
29 changes: 29 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[project]
name = "certwatch"
version = "1.1.0"
description = "TLS certificate expiry checker for your own hosts: parallel, JSON output with issuer and SANs, cron-friendly."
readme = "README.md"
requires-python = ">=3.9"
license = {text = "MIT"}
authors = [{name = "TPOALOS"}]
keywords = ["tls", "ssl", "certificate-expiry", "monitoring"]
classifiers = [
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Security",
]

[project.urls]
Homepage = "https://github.com/TPOALOS/certwatch"

[project.scripts]
certwatch = "certwatch:main"

[tool.setuptools]
py-modules = ["certwatch"]
112 changes: 112 additions & 0 deletions test_certwatch.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import contextlib
import io
import json
import os
import socket
import ssl
Expand Down Expand Up @@ -78,5 +81,114 @@ def test_unreachable_local_port(self):
self.assertEqual(certwatch.main(["localhost:1"]), 1)


def cert(not_after, cn="example.com", issuer="Test CA", san=("example.com", "www.example.com")):
return {"notAfter": not_after, "subject": ((("commonName", cn),),), "issuer": ((("organizationName", issuer),),),
"subjectAltName": tuple(("DNS", n) for n in san) + (("IP Address", "10.0.0.1"),)}


def run_main(*argv, fetch):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = certwatch.main(list(argv), _fetch=fetch)
return code, out.getvalue(), err.getvalue()


class InspectTests(unittest.TestCase):
def test_details_extracted(self):
r = certwatch.inspect("example.com", fetch=lambda h, p, t: cert("Jan 1 00:00:00 2031 GMT"), now=NOW)
self.assertEqual((r["status"], r["subject"], r["issuer"]), ("OK", "example.com", "Test CA"))
self.assertEqual(r["san"], ["example.com", "www.example.com"]) # IP SANs are not DNS names
self.assertGreater(r["days_left"], 90)

def test_legacy_two_argument_fetcher_still_works(self):
r = certwatch.inspect("h", fetch=lambda h, p: cert("Jan 1 00:00:00 2031 GMT"), now=NOW)
self.assertEqual(r["status"], "OK")

def test_errors_become_results(self):
def boom(h, p, t):
raise socket.timeout("timed out")
r = certwatch.inspect("h", fetch=boom)
self.assertEqual((r["status"], r["days_left"]), ("ERROR", None))
self.assertIn("timed out", r["detail"])

def test_verification_failure_is_invalid(self):
def bad(h, p, t):
e = ssl.SSLCertVerificationError()
e.verify_message = "self signed certificate"
raise e
r = certwatch.inspect("h", fetch=bad)
self.assertEqual(r["status"], "INVALID")
self.assertIn("self signed", r["detail"])

def test_bad_port_is_error_not_crash(self):
self.assertEqual(certwatch.inspect("host:notaport", fetch=lambda *a: {})["status"], "ERROR")

def test_missing_not_after_is_error(self):
self.assertEqual(certwatch.inspect("h", fetch=lambda h, p, t: {})["status"], "ERROR")

def test_unexpected_type_error_in_fetcher_is_still_a_result(self):
def broken(h, p, t=None):
raise TypeError("boom")
self.assertEqual(certwatch.inspect("h", fetch=broken)["status"], "ERROR")

def test_name_helper(self):
self.assertEqual(certwatch._name(None), "")
self.assertEqual(certwatch._name(((("organizationName", "Org"),),)), "Org")


class CliTests(unittest.TestCase):
FUTURE = "Jan 1 00:00:00 2099 GMT"
PAST = "Jan 1 00:00:00 2001 GMT"

def fetch(self, host, port, timeout):
return cert(self.PAST if host.startswith("old") else self.FUTURE, cn=host)

def test_json_output_and_order_preserved(self):
targets = ["ok%d.example.com" % i for i in range(5)] + ["old.example.com"]
code, out, _ = run_main(*targets, "--json", fetch=self.fetch)
data = json.loads(out)
self.assertEqual(code, 1)
self.assertEqual([d["target"] for d in data], targets)
self.assertEqual(data[-1]["status"], "EXPIRED")

def test_all_ok_exit_zero(self):
self.assertEqual(run_main("a.example.com", "b.example.com", fetch=self.fetch)[0], 0)

def test_text_output_unchanged(self):
_, out, _ = run_main("a.example.com", fetch=self.fetch)
self.assertTrue(out.startswith("OK a.example.com"))

def test_timeout_is_passed_through(self):
seen = []
run_main("a.example.com", "--timeout", "3.5", fetch=lambda h, p, t: seen.append(t) or cert(self.FUTURE))
self.assertEqual(seen, [3.5])

def test_workers_flag_runs_in_parallel_without_losing_results(self):
targets = ["h%d.example.com" % i for i in range(20)]
code, out, _ = run_main(*targets, "--workers", "5", "--json", fetch=self.fetch)
self.assertEqual(code, 0)
self.assertEqual(len(json.loads(out)), 20)

def test_workers_zero_or_negative_still_works(self):
self.assertEqual(run_main("a.example.com", "--workers", "0", fetch=self.fetch)[0], 0)

def test_crit_must_be_below_warn(self):
code, _, err = run_main("a.example.com", "--warn", "5", "--crit", "10", fetch=self.fetch)
self.assertEqual(code, 2)
self.assertIn("--crit", err)

def test_file_targets_and_comments(self):
import tempfile
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "hosts.txt")
with open(p, "w") as fh:
fh.write("# production\na.example.com # web\n\nold.example.com:8443\n")
code, out, _ = run_main("-f", p, "--json", fetch=self.fetch)
self.assertEqual([d["target"] for d in json.loads(out)], ["a.example.com", "old.example.com:8443"])

def test_no_targets_is_usage_error(self):
self.assertEqual(run_main(fetch=self.fetch)[0], 2)


if __name__ == "__main__":
unittest.main()
Loading