maplewatch-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maplewatch/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """maplewatch: check Canadian Cyber Centre advisories against the software you actually run.
2
+
3
+ Unofficial. Not affiliated with or endorsed by the Canadian Centre for Cyber Security,
4
+ the Communications Security Establishment, or the Government of Canada.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ ATTRIBUTION = (
10
+ "Source: Canadian Centre for Cyber Security (cyber.gc.ca). maplewatch is an unofficial tool, "
11
+ "not affiliated with or endorsed by the Government of Canada. Always confirm with the linked advisory."
12
+ )
@@ -0,0 +1,200 @@
1
+ """Advisory model and parsing of the Cyber Centre's advisory HTML into products, version rules and CVEs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from urllib.parse import urljoin, urlparse
8
+
9
+ from bs4 import BeautifulSoup
10
+
11
+ from .text import clean, norm_name
12
+ from .versions import Rule, parse_rules
13
+
14
+ SITE = "https://www.cyber.gc.ca"
15
+ SERIAL_RE = re.compile(r"\b([A-Z]{2}\d{2}-\d{1,5})\b")
16
+ CVE_RE = re.compile(r"\bCVE-\d{4}-\d{4,7}\b")
17
+ _KIND = {"AV": "advisory", "AL": "alert", "IN": "information", "TR": "technical report"}
18
+
19
+
20
+ @dataclass
21
+ class Product:
22
+ name: str
23
+ rules: list[Rule] = field(default_factory=list)
24
+
25
+
26
+ @dataclass
27
+ class Advisory:
28
+ serial: str
29
+ title: str
30
+ url: str
31
+ lang: str
32
+ published: str # ISO date, YYYY-MM-DD
33
+ vendor: str = ""
34
+ products: list[Product] = field(default_factory=list)
35
+ cves: list[str] = field(default_factory=list)
36
+ references: list[dict[str, str]] = field(default_factory=list)
37
+ intro: str = ""
38
+
39
+ @property
40
+ def kind(self) -> str:
41
+ return _KIND.get(self.serial[:2], "other")
42
+
43
+ def summary(self) -> dict[str, object]:
44
+ return {
45
+ "serial": self.serial,
46
+ "kind": self.kind,
47
+ "title": self.title,
48
+ "published": self.published,
49
+ "vendor": self.vendor,
50
+ "products": [p.name for p in self.products][:20],
51
+ "cves": self.cves[:20],
52
+ "url": self.url,
53
+ }
54
+
55
+ def details(self) -> dict[str, object]:
56
+ return {
57
+ **self.summary(),
58
+ "intro": self.intro,
59
+ "affected": [{"product": p.name, "versions": [r.raw for r in p.rules]} for p in self.products],
60
+ "references": self.references,
61
+ }
62
+
63
+
64
+ def _safe_link(href: str | None) -> str | None:
65
+ if not href:
66
+ return None
67
+ url = urljoin(SITE, href.strip())
68
+ if urlparse(url).scheme not in ("http", "https") or len(url) > 500:
69
+ return None
70
+ return url
71
+
72
+
73
+ # "Webmail – versions prior to 1.6.15": product, dash, version wording (older advisories, 2016 to mid-2026)
74
+ _FLAT = re.compile(
75
+ r"^(?P<name>.+?)\s+[–—-]\s+(?P<rule>(?:versions?|all|prior|before|toutes|multiples?|antérieures|v?\d).*)$", re.I
76
+ )
77
+
78
+
79
+ # A version line mentions a number or a version word. Alerts sometimes nest instructions instead
80
+ # ("Check macOS systems for ..."), and those must not become fake products.
81
+ _VERSIONISH = re.compile(
82
+ r"\d+\.\d|\b(?:v|versions?|release|build|r)\s*\d|^(?:all|tous|toutes)\b|"
83
+ r"\b(?:prior\s+to|before|multiple|multiples|antérieures?|all\s+versions|toutes\s+les\s+versions)\b",
84
+ re.I,
85
+ )
86
+
87
+
88
+ def _rules(texts: list[str]) -> list[Rule]:
89
+ out: list[Rule] = []
90
+ for t in texts[:30]:
91
+ if len(t) <= 160 and _VERSIONISH.search(t):
92
+ out.extend(parse_rules(t))
93
+ return out
94
+
95
+
96
+ def _looks_like_product(name: str) -> bool:
97
+ """'GitLab', 'Grafana MCP Server': yes. 'If the malicious version of Nx Console is present:': no."""
98
+ return 0 < len(name) <= 120 and not name.endswith((":", ".", "?")) and len(name.split()) <= 12
99
+
100
+
101
+ def _add(products: list[Product], name: str, rules: list[Rule]) -> None:
102
+ if not rules or not _looks_like_product(name):
103
+ return
104
+ for p in products: # the same product on several lines = several release lines of one product
105
+ if p.name.lower() == name.lower():
106
+ p.rules.extend(rules)
107
+ return
108
+ products.append(Product(name, rules))
109
+
110
+
111
+ def parse_body(html: str) -> tuple[list[Product], list[str], list[dict[str, str]], str]:
112
+ """Products with their version rules, CVE ids, reference links and the intro sentence."""
113
+ soup = BeautifulSoup(html or "", "html.parser")
114
+ body = soup.select_one(".field--name-body") or soup
115
+ products: list[Product] = []
116
+ # Newer layout: <ul><li>Product<ul><li>Prior to 1.2</li></ul></li></ul>.
117
+ # Older layout: <ul><li>Product – versions prior to 1.2</li></ul>.
118
+ # Reference links live in a separate <ul class="list-unstyled"> and are skipped here.
119
+ for ul in body.find_all("ul"):
120
+ if "list-unstyled" in (ul.get("class") or []) or ul.find_parent("li") is not None:
121
+ continue
122
+ for li in ul.find_all("li", recursive=False):
123
+ nested = li.find("ul")
124
+ if nested is not None:
125
+ name = clean(" ".join(str(t) for t in li.find_all(string=True, recursive=False)), 200)
126
+ if name:
127
+ _add(products, name, _rules([clean(v.get_text(" "), 200) for v in nested.find_all("li")]))
128
+ elif m := _FLAT.match(clean(li.get_text(" "), 400)):
129
+ _add(products, clean(m.group("name"), 200), _rules([clean(m.group("rule"), 200)]))
130
+ if len(products) >= 60:
131
+ break
132
+ text = body.get_text(" ")
133
+ cves = list(dict.fromkeys(CVE_RE.findall(text + " " + " ".join(a.get("href", "") for a in body.find_all("a")))))
134
+ refs = []
135
+ for a in body.select("ul.list-unstyled a")[:15]:
136
+ link = _safe_link(a.get("href"))
137
+ if link:
138
+ refs.append({"title": clean(a.get_text(" "), 160), "url": link})
139
+ intro = ""
140
+ for p in body.find_all("p"):
141
+ t = clean(p.get_text(" "), 600)
142
+ if t and not t.lower().startswith(("serial number", "numéro de série")):
143
+ intro = t
144
+ break
145
+ return products, cves[:50], refs, intro
146
+
147
+
148
+ _TITLE_VENDOR = [
149
+ re.compile(r"^(?:\[[^\]]*\]\s*)?(?P<v>.+?)\s+security\s+(?:advisor|bulletin|update)", re.I),
150
+ re.compile(
151
+ r"^(?:\[[^\]]*\]\s*)?(?:Avis|Bulletin|Mise à jour)s?\s+de\s+sécurité\s+"
152
+ r"(?:de\s+la\s+|de\s+l'|du\s+|des\s+|de\s+|d')?(?P<v>.+?)\s*(?:\(|[–—]|$)",
153
+ re.I,
154
+ ),
155
+ ]
156
+
157
+
158
+ def title_vendor(title: str) -> str:
159
+ """'GitLab security advisory (AV26-1168)' -> 'gitlab'; 'Avis de sécurité de GitLab (AV26-1168)' -> 'gitlab'."""
160
+ for pattern in _TITLE_VENDOR:
161
+ if m := pattern.match(title):
162
+ return norm_name(m.group("v"))[:60]
163
+ return ""
164
+
165
+
166
+ def _serial(value: object) -> str:
167
+ return clean(value, 24).replace("–", "-").replace("—", "-").replace(" ", "")
168
+
169
+
170
+ def _vendor(subject: object, title: str) -> str:
171
+ """The title wins: the archive's subject tag is sometimes wrong (a GitHub incident tagged 'gitlab')."""
172
+ if from_title := title_vendor(title):
173
+ return from_title
174
+ v = norm_name(clean(subject, 80)) if subject else ""
175
+ return "" if v == "other" else v
176
+
177
+
178
+ def from_archive_item(item: dict, lang: str) -> Advisory | None:
179
+ """One entry of /api/cccs/threats/v1/get (the archive behind the advisories page)."""
180
+ serial = _serial(item.get("serial_number"))
181
+ title = clean(item.get("title"), 300)
182
+ if not SERIAL_RE.fullmatch(serial or "") and (m := SERIAL_RE.search(_serial(title).replace("(", " "))):
183
+ serial = m.group(1)
184
+ if not SERIAL_RE.fullmatch(serial or ""):
185
+ return None
186
+ body = item.get("body")
187
+ html = "".join(body) if isinstance(body, list) else str(body or "")
188
+ products, cves, refs, intro = parse_body(html)
189
+ return Advisory(
190
+ serial=serial,
191
+ title=title,
192
+ url=_safe_link(item.get("url")) or SITE,
193
+ lang=lang,
194
+ published=str(item.get("date_created") or item.get("date_modified") or "")[:10],
195
+ vendor=_vendor(item.get("subject"), title),
196
+ products=products,
197
+ cves=cves,
198
+ references=refs,
199
+ intro=intro,
200
+ )
@@ -0,0 +1,192 @@
1
+ """What you run: a stack file, CycloneDX SBOMs, and (optionally) live Docker containers.
2
+
3
+ Every location comes from environment variables set by whoever installs the server, never from
4
+ tool arguments. The model can't point maplewatch at an arbitrary file or host.
5
+ MAPLEWATCH_STACK path to stack.yaml (or .json)
6
+ MAPLEWATCH_SBOM comma-separated paths to CycloneDX JSON files
7
+ MAPLEWATCH_DOCKER "1" to read running containers (GET requests only)
8
+ DOCKER_HOST unix:///var/run/docker.sock (default) or tcp://socket-proxy:2375
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ import httpx
20
+ import yaml
21
+
22
+ from .text import clean, norm_name
23
+ from .versions import version_key
24
+
25
+ MAX_FILE_BYTES = 5 * 1024 * 1024
26
+ MAX_ITEMS = 5000
27
+
28
+
29
+ @dataclass
30
+ class Software:
31
+ name: str
32
+ version: str | None
33
+ source: str
34
+ aliases: list[str] = field(default_factory=list)
35
+ detail: str = ""
36
+
37
+ def names(self) -> set[str]:
38
+ return {n for n in (norm_name(x) for x in [self.name, *self.aliases]) if len(n) >= 3}
39
+
40
+ def as_dict(self) -> dict[str, object]:
41
+ return {
42
+ "name": self.name,
43
+ "version": self.version,
44
+ "source": self.source,
45
+ "detail": self.detail,
46
+ "comparable_version": version_key(self.version) is not None,
47
+ }
48
+
49
+
50
+ def _read(path: str) -> str:
51
+ p = Path(path).expanduser()
52
+ if p.stat().st_size > MAX_FILE_BYTES:
53
+ raise ValueError(f"{p.name} is larger than {MAX_FILE_BYTES // 1024 // 1024} MB")
54
+ return p.read_text(encoding="utf-8")
55
+
56
+
57
+ def load_stack_file(path: str) -> list[Software]:
58
+ """stack.yaml: either `software: [{name, version, aliases}]` or a plain `name: version` mapping."""
59
+ data = yaml.safe_load(_read(path)) if not path.endswith(".json") else json.loads(_read(path))
60
+ rows = data.get("software", data) if isinstance(data, dict) else data
61
+ out: list[Software] = []
62
+ if isinstance(rows, dict):
63
+ rows = [{"name": k, "version": v} for k, v in rows.items()]
64
+ for row in rows or []:
65
+ if isinstance(row, dict) and row.get("name"):
66
+ aliases = row.get("aliases") or []
67
+ out.append(
68
+ Software(
69
+ name=clean(row["name"], 120),
70
+ version=clean(row.get("version"), 60) or None,
71
+ source="stack file",
72
+ aliases=[clean(a, 120) for a in aliases if isinstance(a, str)][:10],
73
+ )
74
+ )
75
+ return out[:MAX_ITEMS]
76
+
77
+
78
+ def load_sbom(path: str) -> list[Software]:
79
+ """CycloneDX JSON (`syft -o cyclonedx-json`, `trivy --format cyclonedx`, ...)."""
80
+ data = json.loads(_read(path))
81
+ out = []
82
+ for c in data.get("components", [])[:MAX_ITEMS]:
83
+ if isinstance(c, dict) and c.get("name"):
84
+ group = clean(c.get("group"), 80)
85
+ out.append(
86
+ Software(
87
+ name=clean(c["name"], 120),
88
+ version=clean(c.get("version"), 60) or None,
89
+ source="sbom",
90
+ aliases=[f"{group} {c['name']}"] if group else [],
91
+ detail=Path(path).name,
92
+ )
93
+ )
94
+ return out
95
+
96
+
97
+ # ---------- Docker ----------
98
+ _VERSION_ENV = re.compile(r"^(?:([A-Z0-9_]+)_)?VERSION=(v?\d[\w.\-+]*)$")
99
+
100
+
101
+ def _image_names(image: str) -> tuple[str, list[str]]:
102
+ """'lscr.io/linuxserver/radarr:5.2' -> ('radarr', ['linuxserver radarr'])."""
103
+ repo = image.split("@")[0]
104
+ if ":" in repo.rsplit("/", 1)[-1]:
105
+ repo = repo.rsplit(":", 1)[0]
106
+ parts = repo.split("/")
107
+ if "." in parts[0] or ":" in parts[0] or parts[0] == "localhost":
108
+ parts = parts[1:] # drop the registry host
109
+ name = parts[-1] if parts else repo
110
+ return name, [" ".join(parts)] if len(parts) > 1 else []
111
+
112
+
113
+ def _image_tag(image: str) -> str | None:
114
+ last = image.split("@")[0].rsplit("/", 1)[-1]
115
+ return last.rsplit(":", 1)[1] if ":" in last else None
116
+
117
+
118
+ def docker_client() -> httpx.Client:
119
+ host = os.environ.get("DOCKER_HOST", "unix:///var/run/docker.sock")
120
+ if host.startswith("unix://"):
121
+ return httpx.Client(
122
+ transport=httpx.HTTPTransport(uds=host[len("unix://") :]), base_url="http://docker", timeout=10.0
123
+ )
124
+ if host.startswith("tcp://"):
125
+ return httpx.Client(base_url="http://" + host[len("tcp://") :], timeout=10.0)
126
+ raise ValueError("DOCKER_HOST must be unix:// or tcp:// (point tcp at a read-only socket proxy)")
127
+
128
+
129
+ def discover_docker(client: httpx.Client) -> list[Software]:
130
+ """Running containers. Only two GET endpoints are used: /containers/json and /images/{id}/json."""
131
+ out: list[Software] = []
132
+ containers = client.get("/containers/json").raise_for_status().json()
133
+ seen: set[str] = set()
134
+ for c in containers[:200]:
135
+ image = clean(c.get("Image"), 200)
136
+ image_id = str(c.get("ImageID", ""))
137
+ if not image or image_id in seen or not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id):
138
+ continue
139
+ seen.add(image_id)
140
+ info = client.get(f"/images/{image_id}/json").raise_for_status().json()
141
+ config = info.get("Config") or {}
142
+ labels = config.get("Labels") or {}
143
+ name, aliases = _image_names(image)
144
+ title = clean(labels.get("org.opencontainers.image.title"), 120)
145
+ version, how = None, ""
146
+ if v := clean(labels.get("org.opencontainers.image.version"), 60):
147
+ version, how = v, "image label"
148
+ if version is None:
149
+ key = norm_name(name).replace(" ", "_").upper()
150
+ for env in config.get("Env") or []:
151
+ m = _VERSION_ENV.match(str(env)[:200])
152
+ if m and (m.group(1) or "APP") in (key, "APP"): # N8N_VERSION for n8n, APP_VERSION, VERSION
153
+ version, how = m.group(2), "env " + str(env).split("=", 1)[0]
154
+ break
155
+ tag = _image_tag(image)
156
+ if version is None and tag and version_key(tag) is not None:
157
+ version, how = tag, "image tag"
158
+ out.append(
159
+ Software(
160
+ name=title or name,
161
+ version=version,
162
+ source="docker",
163
+ aliases=[name, *aliases] if title else aliases,
164
+ detail=f"{image} (version from {how})" if version else f"{image} (no version found: pin a tag)",
165
+ )
166
+ )
167
+ return out
168
+
169
+
170
+ def load_inventory() -> tuple[list[Software], list[str]]:
171
+ """Everything configured, plus problems worth telling the user about."""
172
+ items: list[Software] = []
173
+ problems: list[str] = []
174
+ if path := os.environ.get("MAPLEWATCH_STACK"):
175
+ try:
176
+ items += load_stack_file(path)
177
+ except (OSError, ValueError, yaml.YAMLError) as exc:
178
+ problems.append(f"stack file: {exc}")
179
+ for path in filter(None, (os.environ.get("MAPLEWATCH_SBOM") or "").split(",")):
180
+ try:
181
+ items += load_sbom(path.strip())
182
+ except (OSError, ValueError) as exc:
183
+ problems.append(f"SBOM {Path(path).name}: {exc}")
184
+ if os.environ.get("MAPLEWATCH_DOCKER") == "1":
185
+ try:
186
+ with docker_client() as client:
187
+ items += discover_docker(client)
188
+ except (httpx.HTTPError, OSError, ValueError) as exc:
189
+ problems.append(f"docker: {exc}")
190
+ if not items and not problems:
191
+ problems.append("nothing configured: set MAPLEWATCH_STACK, MAPLEWATCH_SBOM or MAPLEWATCH_DOCKER=1")
192
+ return items[:MAX_ITEMS], problems
maplewatch/matcher.py ADDED
@@ -0,0 +1,86 @@
1
+ """Which advisories touch which software you run, and how sure we are."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ from .advisories import Advisory, Product
9
+ from .inventory import Software
10
+ from .text import norm_name
11
+ from .versions import evaluate
12
+
13
+ Confidence = Literal["exact", "likely", "possible"]
14
+
15
+
16
+ def _contains(haystack: str, needle: str) -> bool:
17
+ """Whole-word match: 'grafana' is in 'grafana enterprise', not in 'grafanalib'."""
18
+ return f" {needle} " in f" {haystack} "
19
+
20
+
21
+ def name_match(sw: Software, product: Product, advisory: Advisory) -> Confidence | None:
22
+ prod = norm_name(product.name)
23
+ vendor = advisory.vendor
24
+ names = sw.names()
25
+ if prod in names or (vendor and f"{vendor} {prod}" in names):
26
+ return "exact"
27
+ for n in names:
28
+ if vendor and n == vendor and advisory.kind == "advisory":
29
+ return "likely" # e.g. software 'roundcube', advisory by Roundcube for product 'Webmail'
30
+ if _contains(prod, n):
31
+ return "likely" if vendor and (_contains(n, vendor) or _contains(vendor, n)) else "possible"
32
+ return None
33
+
34
+
35
+ @dataclass
36
+ class Finding:
37
+ status: Literal["affected", "check"]
38
+ software: Software
39
+ advisory: Advisory
40
+ product: Product
41
+ confidence: Confidence
42
+ reason: str
43
+
44
+ def as_dict(self) -> dict[str, object]:
45
+ return {
46
+ "status": self.status,
47
+ "software": self.software.name,
48
+ "installed_version": self.software.version,
49
+ "found_in": self.software.source,
50
+ "advisory": self.advisory.serial,
51
+ "title": self.advisory.title,
52
+ "published": self.advisory.published,
53
+ "product_in_advisory": self.product.name,
54
+ "affected_versions": [r.raw for r in self.product.rules][:10],
55
+ "name_match": self.confidence,
56
+ "why": self.reason,
57
+ "url": self.advisory.url,
58
+ }
59
+
60
+
61
+ def check(software: list[Software], advisories: list[Advisory]) -> tuple[list[Finding], int]:
62
+ """Findings (affected or needs a human look) and how many name matches were ruled out by version."""
63
+ findings: list[Finding] = []
64
+ ruled_out = 0
65
+ for adv in advisories:
66
+ for sw in software:
67
+ best: Finding | None = None
68
+ for product in adv.products:
69
+ conf = name_match(sw, product, adv)
70
+ if conf is None:
71
+ continue
72
+ verdict, reason = evaluate(sw.version, product.rules)
73
+ if verdict == "not_affected":
74
+ ruled_out += 1
75
+ continue
76
+ status = "affected" if verdict == "affected" and conf != "possible" else "check"
77
+ if conf == "possible":
78
+ reason = f"name only partly matches '{product.name}'. {reason}"
79
+ f = Finding(status, sw, adv, product, conf, reason)
80
+ if best is None or (f.status == "affected" and best.status != "affected"):
81
+ best = f
82
+ if best:
83
+ findings.append(best)
84
+ findings.sort(key=lambda f: f.advisory.published, reverse=True) # newest first...
85
+ findings.sort(key=lambda f: f.status != "affected") # ...with confirmed hits on top (sort is stable)
86
+ return findings, ruled_out