#!/usr/bin/env python3 """Check a whole fleet with CVEfocus and keep the history yourself (CVEfocus stores nothing). Put one inventory file per server in a folder, named __.txt (or just .txt when you don't group by customer). Each file is the output of the CVEfocus collection command for that server (Linux or Windows), gathered however you like: your RMM, Ansible, scp, a shared folder. export CVEFOCUS_KEY=cvf_live_... python3 cvefocus_fleet.py ./inventories ./cvefocus-results --provider "Your MSP name" Try it in one command on any Linux machine (it adds this machine as a server of "Test client", checks it, and writes the report; it asks for your API key if CVEFOCUS_KEY isn't set): curl -sSf https://cvefocus.com/tools/cvefocus_fleet.py | python3 - --this-machine "Test client" Each run writes, in the results folder: results-.json the full fleet result (per server, per customer, fleet totals) report--.html a printable Fleet Vulnerability Status Report per customer (open, Print -> PDF), ready to send to that customer state.json each server's finding keys, sent back next run as `previous`, so the next result lists what is new and what was resolved Run it daily from cron or Windows Task Scheduler. Python 3.8+, standard library only. """ from __future__ import annotations import argparse import getpass import json import socket import subprocess import os import sys import re import time import urllib.error import urllib.parse import urllib.request from itertools import groupby from datetime import datetime, timezone from pathlib import Path API = os.environ.get("CVEFOCUS_API", "https://api.cvefocus.com") def post(path: str, body: dict, key: str) -> tuple[int, bytes]: req = urllib.request.Request(f"{API}{path}", data=json.dumps(body).encode(), method="POST", headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=300) as resp: return resp.status, resp.read() except urllib.error.HTTPError as e: return e.code, e.read() def post_with_retry(path: str, body: dict, key: str) -> bytes: for attempt in range(5): status, data = post(path, body, key) if status == 200: return data if status == 429 and b"too many requests" in data: time.sleep(65) # per-minute limit: wait for the next minute continue sys.exit(f"CVEfocus returned {status}: {data[:500].decode(errors='replace')}") sys.exit("CVEfocus kept refusing for rate limits; try a smaller --batch") # Which packages running programs have loaded and whether they listen on the network (same as the docs). LINUX_EXPOSURE = r'''echo CVEFOCUS_EXPOSURE=host; T=$(mktemp -d); for f in /proc/net/tcp /proc/net/tcp6 /proc/net/udp /proc/net/udp6; do awk -v f="$f" 'function hx(s,i,r){for(i=1;i<=length(s);i++)r=r*16+index("0123456789ABCDEF",substr(s,i,1))-1;return r} NR>1 && (($4=="0A" && f~/tcp/) || ($4=="07" && f~/udp/ && $3~/^0+:0000$/)) {split($2,a,":"); c=(a[1]~/^0+$/)?"any":(a[1]~/7F$/ || a[1]=="00000000000000000000000001000000")?"lo":"ip"; print "L", $10, (f~/tcp/?"tcp":"udp"), c, hx(a[2])}' $f 2>/dev/null; done > $T/s; for p in /proc/[0-9]*; do grep -qE 'docker|containerd|kubepods|libpod|lxc' $p/cgroup 2>/dev/null && continue; q=${p#/proc/}; c=$(tr ' ' _ 2>/dev/null < $p/comm) || continue; ls -l $p/fd 2>/dev/null | sed -n "s/.*socket:\[\([0-9]*\)\].*/S $q \1/p"; { readlink $p/exe; awk '$6 ~ /^\// {print $6}' $p/maps; } 2>/dev/null | sed "s|^|F $q $c |"; done | sort -u > $T/p; { if [ -d /var/lib/dpkg/info ]; then awk 'FNR==1{p=FILENAME; sub(/.*\//,"",p); sub(/\.list$/,"",p); sub(/:.*/,"",p)} {print "P", $0, p}' /var/lib/dpkg/info/*.list; else rpm -qa --qf '[P %{FILENAMES} %{NAME}\n]'; fi; cat $T/s $T/p; } 2>/dev/null | awk 'function k(x){return (x~/^\/usr\/(lib|lib64|bin|sbin)\//)?substr(x,5):x} $1=="P"{o[k($2)]=$3; next} $1=="L"{s[$2]=$3" "$4" "$5; next} $1=="S"{if($3 in s){split(s[$3],z," "); l=(z[2]=="lo")?2:3; if(l>v[$2])v[$2]=l; w[$2]=w[$2] (w[$2]==""?"":",") z[3] "/" z[1] (z[2]=="lo"?"@lo":"")}; next} $1=="F"{m[$2]=$3; if(k($4) in o) u[o[k($4)] SUBSEP $2]=1} END{split("running local network",n," "); for(x in u){split(x,y,SUBSEP); l=v[y[2]]; if(l<1)l=1; if(l>b[y[1]]){b[y[1]]=l; d[y[1]]=m[y[2]] (w[y[2]]==""?"":":" w[y[2]])}} for(x in b) print "CVEFOCUS_USE=" x, n[b[x]], d[x]}' | sort; rm -rf $T''' # Anonymous system token (same as the docs): a hash of /etc/machine-id, made on the machine; the ID isn't sent. LINUX_ID = r'''[ -r /etc/machine-id ] && printf 'CVEFOCUS_SYSTEM=%s\n' "$(printf 'cvefocus:%s' "$(cat /etc/machine-id)" | sha256sum | cut -c1-32)"''' # Java runtimes unpacked from an archive: version and vendor from each "release" file (same as the docs). LINUX_JDK = r'''for f in /opt/*/release /opt/*/*/release /usr/local/*/release /usr/java/*/release /usr/lib/jvm/*/release; do [ -f "$f" ] && awk -F'"' -v d="${f%/release}" '/^JAVA_VERSION=/{v=$2} /^IMPLEMENTOR=/{i=$2} END{if(v!="")print "CVEFOCUS_JDK=" v, d, i}' "$f"; done 2>/dev/null''' # The same read-only collection command as https://cvefocus.com/docs (Linux), for --this-machine. LINUX_COLLECT = ( "cat /etc/os-release; uname -r; " # A one-way hash of this machine's ID, so the plan counts distinct systems without knowing which machine it is + LINUX_ID + "; " "if command -v dpkg-query >/dev/null; then " "dpkg-query -W -f='${Package} ${Version} ${Architecture} ${source:Package} ${Priority} ${Section}\\n'; else " "rpm -qa --qf '%{NAME} %{EPOCHNUM}:%{VERSION}-%{RELEASE} %{ARCH} %{SOURCERPM} %{MODULARITYLABEL}\\n'; fi; " + LINUX_JDK + "; " 'echo "CVEFOCUS_UID=$(id -u)"; ' ) + LINUX_EXPOSURE def collect_this_machine(folder: Path, customer: str) -> Path: """Write this machine's inventory as __.txt, like an RMM script would.""" if not Path("/etc/os-release").exists(): sys.exit("--this-machine works on Linux; on other systems, collect inventories as the docs describe.") folder.mkdir(parents=True, exist_ok=True) safe = "".join(c if c.isalnum() or c in " ._-" else "-" for c in customer).strip() or "client" path = folder / f"{safe}__{socket.gethostname().split('.')[0]}.txt" out = subprocess.run(["sh", "-c", LINUX_COLLECT], capture_output=True, text=True, check=False).stdout path.write_text(out) print(f"Collected this machine into {path}") return path def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("inventories", type=Path, nargs="?", default=Path("cvefocus-inventories"), help="folder of __.txt files (default: ./cvefocus-inventories)") ap.add_argument("results", type=Path, nargs="?", default=Path("cvefocus-results"), help="folder for results, reports and state.json (default: ./cvefocus-results)") ap.add_argument("--this-machine", metavar="CUSTOMER", help="first add this Linux machine to the inventories folder, as a server of CUSTOMER") ap.add_argument("--batch", type=int, default=25, help="servers per call (max 100; keep within your plan's requests per minute)") ap.add_argument("--provider", default=os.environ.get("CVEFOCUS_PROVIDER", ""), help="your company name, printed on the reports next to the account email") ap.add_argument("--key-file", type=Path, help="read the API key from this file instead of CVEFOCUS_KEY") ap.add_argument("--stale-days", type=float, default=3, help="warn about inventory files not updated for this many days (default 3)") ap.add_argument("--no-report", action="store_true", help="skip the printable reports") args = ap.parse_args() key = args.key_file.read_text().strip() if args.key_file else os.environ.get("CVEFOCUS_KEY") if not key: try: key = getpass.getpass("Your CVEfocus API key (free at https://cvefocus.com/start): ").strip() except (EOFError, OSError): key = "" if not key: sys.exit("Set CVEFOCUS_KEY to your API key first (or use --key-file).") if args.this_machine: collect_this_machine(args.inventories, args.this_machine) args.results.mkdir(parents=True, exist_ok=True) state_file = args.results / "state.json" state = json.loads(state_file.read_text()) if state_file.exists() else {} servers = [] for f in sorted(args.inventories.glob("*.txt")): age = (time.time() - f.stat().st_mtime) / 86400 if age > args.stale_days: print(f"warning: {f.name} was last updated {age:.0f} days ago (server offline or decommissioned?)", file=sys.stderr) customer, _, server_id = f.stem.rpartition("__") raw = f.read_bytes() text = raw.decode("utf-16") if raw.startswith((b"\xff\xfe", b"\xfe\xff")) else raw.decode("utf-8-sig", "replace") entry = {"server_id": server_id, "customer": customer, "inventory": text} if f.stem in state: entry["previous"] = state[f.stem] servers.append((f.stem, entry)) if not servers: sys.exit(f"No .txt inventories in {args.inventories}") servers.sort(key=lambda s: (s[1]["customer"], s[0])) stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") batch = max(1, min(args.batch, 100)) results, reports = [], [] # Batch per customer, so each customer gets its own report to send. for customer, group in groupby(servers, key=lambda s: s[1]["customer"]): group = list(group) parts = range(0, len(group), batch) for n, i in enumerate(parts, 1): chunk = group[i:i + batch] body = {"servers": [e for _, e in chunk]} if args.provider: body["provider"] = args.provider result = json.loads(post_with_retry("/v1/fleet/check", body, key)) results.append(result) for (stem, _), s in zip(chunk, result["servers"]): state[stem] = s["finding_keys"] if not args.no_report: query = "format=report" + (f"&customer={urllib.parse.quote(customer)}" if customer else "") name = re.sub(r"[^\w.-]+", "-", customer).strip("-") or "servers" suffix = "" if len(parts) == 1 else f"-part{n}" reports.append((f"report-{stamp}-{name}{suffix}.html", post_with_retry(f"/v1/fleet/check?{query}", body, key).decode())) (args.results / f"results-{stamp}.json").write_text(json.dumps(results, indent=2)) for name, html in reports: (args.results / name).write_text(html) state_file.write_text(json.dumps(state)) for result in results: for c in result["customers"]: by = c["by_priority"] print(f"{c['customer'] or '(no customer)'}: {c['servers']} servers, act now {by['act_now']}, " f"this week {by['this_week']}, new since last run {c['changes']['new']}, " f"resolved {c['changes']['resolved']}") print(f"Saved results{'' if args.no_report else f' and {len(reports)} report(s)'} to {args.results}") if __name__ == "__main__": main()