diff --git a/README.md b/README.md index 02e7c84..85aa67e 100644 --- a/README.md +++ b/README.md @@ -66,4 +66,8 @@ CI проверяет Python 3.12 и 3.13; для каждой версии пу В `facts` поле `type=exploitation_evidence` отделяет сведения о публичном PoC (`public_poc`) от наблюдения эксплуатации (`observed_in_wild`). `none_reported` относится только к оценке CISA на указанную дату. [CISA SSVC](https://github.com/cisagov/vulnrichment) читается из CVE ADP. Из каталога [Exploit-DB](https://www.exploit-db.com/about-exploit-db) индексируются явные CVE и самая ранняя дата публикации в каталоге; явная ссылка на такую публикацию в CVE JSON остаётся отдельным свидетельством. Записи без явного CVE не привязываются по сходству заголовков. Эти сигналы не подтверждают применимость к устройству. `source_refs` включает бюллетени, помеченные издателем PDF и патчи конкретных GitHub-коммитов. Содержимое вложений не скачивается. +MCP-ресурс `vuln://catalogs/exploitdb` показывает время и статус проверки **обоих** CSV. Для `files_exploits.csv` выводится число уникальных привязанных CVE; для `files_shellcodes.csv` только суммарное число строк. Второй CSV обновляется независимо, не сохраняется как набор записей и не создаёт сведений о применимости к устройствам. + +Производители оборудования: [Palo Alto Networks](https://security.paloaltonetworks.com/api) и [Schneider Electric](https://www.se.com/ww/en/work/support/cybersecurity/security-notifications/). Для поиска используйте название продукта и известную версию или номер бюллетеня (`PAN-SA-…`, `SEVD-…`, `SESB-…`). Сведения об исправлении относятся к соответствующему продукту и ветке выпуска. + Отдельный [VulnCheck KEV](https://docs.vulncheck.com/community/vulncheck-kev/faq) не опрашивается: для него требуется Community-аккаунт. Его нельзя подменять CISA KEV или считать отсутствие доступа отрицательным результатом. diff --git a/src/vuln_mcp/search.py b/src/vuln_mcp/search.py index daf5fc8..f76829f 100644 --- a/src/vuln_mcp/search.py +++ b/src/vuln_mcp/search.py @@ -25,6 +25,8 @@ _CVE = re.compile(r'CVE-[0-9]{4}-[0-9]{4,}', re.I) _GHSA = re.compile(r'GHSA-(?:[a-z0-9]{4}-){2}[a-z0-9]{4}', re.I) _SSA = re.compile(r'SSA-[0-9]+', re.I) _VAR = re.compile(r'VAR-[a-z0-9][a-z0-9._-]*', re.I) +_PAN_ID = re.compile(r'PAN-SA-[0-9]{4}-[0-9]{4}', re.I | re.ASCII) +_SCHNEIDER_ID = re.compile(r'(?:SEVD|SESB)-[0-9]{4}-[0-9]{3}-[0-9]{2}', re.I | re.ASCII) _CATALOG_ID = re.compile(r'(?:VU#[0-9]{1,12}|ZDI-[0-9]{2}-[0-9]{1,6})', re.I | re.ASCII) _NATIVE = re.compile(r'[a-z0-9][a-z0-9_.:+-]{0,199}', re.I | re.ASCII) _OSV = re.compile(r'(?:PYSEC|OSV|GO|RUSTSEC|RUBYSEC|RUBYGEMS|NPM|DLA|DSA|USN|SUSE|openSUSE-SU|ALSA|ALAS|RHSA|RLSA|ELSA|MGASA|CURL|GSD|MAL|BIT|GMS|PUB|PSF|HSEC|CGA|JENKINS|ANDROID|DEBIAN|UBUNTU|OSS-FUZZ)-[a-z0-9][a-z0-9_.:+ -]*', re.I | re.ASCII) @@ -38,8 +40,9 @@ _UNSAFE_REF = re.compile(r'(?:exploit-db|packetstorm|metasploit|/exploits?/|(?:^ _UNSAFE_PROSE = re.compile(r'```|<[^>]+>|(?:^|\n)\s*(?:[$>#] |(?:curl|wget|python3?|powershell|bash|sh)\s+)|\b(?:proof.of.concept|exploit code)\s*:', re.I) _ALLOWED_REFS = {'repository', 'fix_commit', 'release', 'vendor_advisory', 'advisory_pdf', 'fix_patch'} _SCORE_SOURCES = {'kev', 'epss'} -_INDEX_SOURCES = ('cvelist', 'osv', 'siemens', 'msrc', 'zdi', 'certcc', 'projectzero') -_PRIORITY = {'siemens': 0, 'msrc': 0, 'osv': 1, 'nvd': 2, 'circl': 3} +_INDEX_SOURCES = ('cvelist', 'osv', 'siemens', 'msrc', 'zdi', 'certcc', 'projectzero', 'paloalto', 'industrial') +_DEVICE_PUBLISHERS = {'siemens', 'msrc', 'paloalto', 'industrial'} +_PRIORITY = {**dict.fromkeys(_DEVICE_PUBLISHERS, 0), 'osv': 1, 'nvd': 2, 'circl': 3} _PAGE = 20 _LOCAL_PAGE = 100 _CAP = 1000 @@ -48,7 +51,7 @@ _CURSOR_LIMIT = 128 def _id(value: str) -> str: - if _CVE.fullmatch(value) or _SSA.fullmatch(value) or _VAR.fullmatch(value) or _CATALOG_ID.fullmatch(value): + if any(p.fullmatch(value) for p in (_CVE, _SSA, _VAR, _CATALOG_ID, _PAN_ID, _SCHNEIDER_ID)): return value.upper() if _GHSA.fullmatch(value): return 'GHSA-' + value[5:].lower() @@ -137,7 +140,7 @@ def _query(value: str, asset: AssetFacts | None) -> Query: return Query('cpe', text, text) if _COMMIT.fullmatch(text): return Query('commit', text.lower(), text.lower()) - if any(pattern.fullmatch(text) for pattern in (_CVE, _GHSA, _SSA, _VAR, _OSV, _CATALOG_ID)): + if any(pattern.fullmatch(text) for pattern in (_CVE, _GHSA, _SSA, _VAR, _OSV, _CATALOG_ID, _PAN_ID, _SCHNEIDER_ID)): return Query('id', _id(text), _id(text)) if _contains_address(text): raise ValueError('invalid_query') @@ -351,6 +354,10 @@ def _has_id(group: Group, wanted: str) -> bool: def _base_checks(native_id: str) -> set[Check]: + if _SCHNEIDER_ID.fullmatch(native_id): + return {Check('industrial', native_id.upper())} + if _PAN_ID.fullmatch(native_id): + return {Check('paloalto', native_id.upper())} if _CATALOG_ID.fullmatch(native_id): return {Check('certcc', native_id.upper())} if native_id.upper().startswith('VU#') else set() if _OSV.fullmatch(native_id) and (':' in native_id or ' ' in native_id): @@ -376,10 +383,10 @@ def _checks(group: Group) -> set[Check]: ident = _id(doc.native_id) if not (_NATIVE.fullmatch(ident) or _OSV.fullmatch(ident)): continue - if doc.source in {'osv', 'circl'}: + if doc.source in {'osv', 'circl', 'paloalto'}: planned.add(Check(doc.source, ident)) - elif doc.source in {'siemens', 'msrc'}: - if doc.source == 'siemens': + elif doc.source in {'siemens', 'msrc', 'industrial'}: + if doc.source in {'siemens', 'industrial'}: planned.discard(Check(doc.source, ident)) planned.add(Check(doc.source, ident, doc.url)) return planned @@ -459,7 +466,7 @@ class WithProvenance: def _trusted_refs(doc: Doc, issue: Issue) -> Iterable[dict[str, Any]]: - if doc.source in {'siemens', 'msrc'} and (url := _source_url(doc.url)): + if doc.source in _DEVICE_PUBLISHERS and (url := _source_url(doc.url)): yield {'type': 'vendor_advisory', 'url': url} if doc.source in {'zdi', 'certcc', 'projectzero'} and (url := _source_url(doc.url)): yield {'type': 'publisher_advisory' if doc.source != 'projectzero' else 'publisher_tracker', 'url': url} @@ -482,7 +489,7 @@ def _claim_coverage(group: Group, checked: dict[Check, ProviderPage], index: dic for check in _checks(group): actual = checked.get(check) if actual is None and check.url is not None: - actual = checked.get(Check(check.source, check.native_id)) if check.source == 'siemens' else None + actual = checked.get(Check(check.source, check.native_id)) if check.source in {'siemens', 'industrial'} else None if actual is not None: statuses.append(actual.status) for claim in group.claims: @@ -614,6 +621,10 @@ def _render(group: Group, query: Query, asset: Asset, coverage: list[Status], in for product in issue.products: origin = provenance | {'publisher': product['publisher']} if product.get('publisher') else provenance products.add(_explanatory_values(product), origin) + if doc.source == 'paloalto' and asset.version: + from .sources.feed_paloalto import paloalto_fix_matches + if not paloalto_fix_matches(product, asset.version): + continue same, absent = product_match(product, asset) if same: matches = True @@ -625,7 +636,7 @@ def _render(group: Group, query: Query, asset: Asset, coverage: list[Status], in if not absent and doc.source != 'nvd': verdict = product_status(product, asset) if verdict != 'unknown': - verdicts.append((2 if doc.source in {'siemens', 'msrc'} else 1, verdict)) + verdicts.append((2 if doc.source in _DEVICE_PUBLISHERS else 1, verdict)) if not absent: versions.update(fixed_candidates(product)) elif query.kind == 'id' and not asset.explicit: @@ -635,6 +646,10 @@ def _render(group: Group, query: Query, asset: Asset, coverage: list[Status], in if doc.source == 'nvd' and matches and nvd_affected(issue.facts.get('configurations'), asset, issue.products): verdicts.append((1, 'affected')) for fix in issue.fixes: + if doc.source == 'paloalto' and asset.version: + from .sources.feed_paloalto import paloalto_fix_matches + if not paloalto_fix_matches(fix, asset.version): + continue targets = set(fix.get('product_ids') or ()) if fix.get('product_id'): targets.add(fix['product_id']) @@ -642,6 +657,8 @@ def _render(group: Group, query: Query, asset: Asset, coverage: list[Status], in continue details = _prose(fix.get('details')) remediation = {'details': details, 'category': fix.get('category'), 'product_ids': sorted(targets)} + if doc.source == 'paloalto' and fix.get('scope'): + remediation['scope'] = fix['scope'] if url := _source_url(fix.get('url')): remediation['url'] = url if isinstance(version := fix.get('version'), str) and version: @@ -717,6 +734,18 @@ class Search: session.local_offset = stop if stop < min(_CAP, len(session.local_rows)) else None return offset, docs + async def exploitdb_catalogs(self) -> dict: + files = {} + for filename, source, metric, key in ( + ('files_exploits.csv', 'exploitdb', 'unique_cves', 'count'), + ('files_shellcodes.csv', 'exploitdb_inventory', 'records', 'records'), + ): + state = await self._store.state(source) + status = _index_status(source, state) + files[filename] = {metric: state['checkpoint'].get(key), 'status': status.status, + 'last_checked': status.as_of, 'stale': status.stale} + return files + async def _states(self) -> dict[str, Status]: return {source: _index_status(source, await self._store.state(source)) for source in (*_INDEX_SOURCES, 'kev', 'epss', 'exploitdb')} @@ -725,12 +754,12 @@ class Search: for check in sorted(wanted, key=lambda key: (key.source, key.native_id, key.url or '')): if check in checked: continue - if check.source == 'siemens' and check.url is not None and Check('siemens', check.native_id) in checked: - direct = checked[Check('siemens', check.native_id)] + if check.source in {'siemens', 'industrial'} and check.url is not None and Check(check.source, check.native_id) in checked: + direct = checked[Check(check.source, check.native_id)] if any(doc.url == check.url for doc in direct.docs): checked[check] = direct continue - if check.source == 'siemens' and check.url is None and any( + if check.source in {'siemens', 'industrial'} and check.url is None and any( other.source == check.source and other.native_id == check.native_id and other.url is not None for other in wanted ): @@ -899,6 +928,13 @@ class Search: discovery_status.append(index['certcc' if request.text.startswith('VU#') else 'zdi']) else: discover = _discovery(request) + if request.kind == 'text': + from .sources.feed_paloalto import paloalto_query + if product := paloalto_query(request.text, asset): + discover['paloalto'] = ('product', product) + name, version = product + canonical = (asset or AssetFacts()).model_copy(update={'product': name, 'version': version}) + target = make_asset('text', name, canonical) if session is None: session = Cursor(binding, generation, 0, {source: None for source in discover}) async with asyncio.TaskGroup() as tasks: @@ -906,7 +942,8 @@ class Search: source: tasks.create_task(self._page(source, *discover[source], deadline, continuation)) for source, continuation in session.offsets.items() } - local = tasks.create_task(self._local_page(request.text, session)) if session.local_offset is not None else None + local_query = product[0] if 'paloalto' in discover else request.text + local = tasks.create_task(self._local_page(local_query, session)) if session.local_offset is not None else None states = tasks.create_task(self._states()) index = states.result() discovery_status = [index[source] for source in _INDEX_SOURCES] @@ -928,7 +965,7 @@ class Search: for pos, doc in enumerate(provider.docs): observations.append(Observation(doc, 'live', session.pages * _LOCAL_PAGE + pos, provider.cacheable)) known = Check(doc.source, _id(doc.native_id)) - if doc.source not in {'siemens', 'msrc'}: + if doc.source not in _DEVICE_PUBLISHERS: checked[known] = provider.model_copy(update={'docs': [doc], 'continuation': None}) elif session.offsets[source] is None: session.offsets.pop(source) diff --git a/src/vuln_mcp/server.py b/src/vuln_mcp/server.py index 3917cef..4736a2e 100644 --- a/src/vuln_mcp/server.py +++ b/src/vuln_mcp/server.py @@ -32,8 +32,11 @@ class AdvisoryServer(MCPServer): def build_server(settings: Settings) -> MCPServer: + active: Search | None = None + @asynccontextmanager async def lifespan(_: MCPServer) -> AsyncIterator[Search]: + nonlocal active async with AsyncExitStack() as stack: store = Store(settings.data_dir) await store.open() @@ -50,8 +53,10 @@ def build_server(settings: Settings) -> MCPServer: if inventory and settings.proxy_list_refresh_minutes: refresh = group.create_task(refresh_proxy_list(settings, http.update_proxies), name="proxy-list") try: - yield Search(store, http.live) + active = Search(store, http.live) + yield active finally: + active = None background.cancel() if refresh is not None: refresh.cancel() @@ -75,6 +80,13 @@ def build_server(settings: Settings) -> MCPServer: service = ctx.request_context.lifespan_context return await service.get_advisory(id) + @server.resource("vuln://catalogs/exploitdb", mime_type="application/json") + async def exploitdb_catalogs() -> dict: + """Coverage and freshness for both Exploit-DB CSV inventories.""" + if active is None: + raise RuntimeError("Server is not running") + return await active.exploitdb_catalogs() + return server diff --git a/src/vuln_mcp/sources/feed_exploitdb.py b/src/vuln_mcp/sources/feed_exploitdb.py index c5f2f6e..7846bdc 100644 --- a/src/vuln_mcp/sources/feed_exploitdb.py +++ b/src/vuln_mcp/sources/feed_exploitdb.py @@ -9,6 +9,7 @@ from .feeds_common import FeedStage, FeedState, IndexFeedHttp, RefreshResult, co from .parsers import InvalidData CATALOG = 'https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv' +SHELLCODE_CATALOG = 'https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_shellcodes.csv' ABOUT = 'https://www.exploit-db.com/about-exploit-db' _CVE = re.compile(r'(? int: + # Consume the CSV structure only; do not persist or expose individual records. + with path.open(encoding='utf-8-sig', newline='') as stream: + rows = csv.reader(stream, strict=True) + fields = next(rows, []) + if len(set(fields)) != len(fields) or not {'id', 'date_published', 'size'} <= set(fields): + raise InvalidData('unexpected secondary catalogue columns') + count = 0 + for row in rows: + if len(row) != len(fields): + raise InvalidData('incomplete secondary catalogue row') + count += 1 + if not count: + raise InvalidData('empty secondary catalogue') + return count + + +async def refresh_exploitdb_inventory(state: FeedState, *, http: IndexFeedHttp, staging: FeedStage) -> RefreshResult: + path = staging.directory / 'inventory.csv' + validators = state.validators if state.checkpoint.get('records') else {} + status, headers = await http.download('exploitdb_inventory', SHELLCODE_CATALOG, path, + headers=conditional(validators), limit=16 * 1024**2) + if status == 304 and validators: + return RefreshResult(state.checkpoint, state.validators) + if status != 200: + raise InvalidData('secondary catalogue not downloaded') + records = await worker(_catalog_size, path) + return RefreshResult({'records': records}, response_validators(headers)) diff --git a/src/vuln_mcp/sources/feed_industrial.py b/src/vuln_mcp/sources/feed_industrial.py new file mode 100644 index 0000000..2384af3 --- /dev/null +++ b/src/vuln_mcp/sources/feed_industrial.py @@ -0,0 +1,220 @@ +"""Schneider Electric CPCERT's public CSAF directory.""" + +from __future__ import annotations + +import csv +import re +from collections.abc import Mapping, Sequence +from datetime import datetime +from pathlib import Path +from typing import Protocol +from urllib.parse import urlsplit + +from pydantic import ValidationError + +from ..models import Doc, ProviderPage, Status, utc_now +from ..transport import HttpError +from .feeds_common import (BATCH_SIZE, JSON_LIMIT, MANIFEST_LIMIT, RECORD_LIMIT, FeedStage, + FeedState, IndexFeedHttp, RefreshResult, conditional, instant, + read_json, response_validators, worker) +from .parsers import InvalidData, parse + +_SOURCE = "industrial" +_HOST = "www.se.com" +_DIRECTORY_PATH = "/.well-known/csaf/" +_DIRECTORY = f"https://{_HOST}{_DIRECTORY_PATH}" +_METADATA = f"{_DIRECTORY}provider-metadata.json" +_CHANGES = f"{_DIRECTORY}changes.csv" +_PUBLISHER = "Schneider Electric CPCERT" +_NAMESPACES = { + "https://www.se.com/ww/en", + "https://www.se.com/ww/en/work/support/cybersecurity/security-notifications.jsp", +} +_ID = re.compile(r"(?:SEVD|SESB)-([0-9]{4})-[0-9]{3}-[0-9]{2}", re.ASCII | re.IGNORECASE) +_FILE = re.compile(r"([0-9]{4})/((?:sevd|sesb)-\1-[0-9]{3}-[0-9]{2})\.json", re.ASCII) +_ATTACHMENT = re.compile(r"\.(?:pdf|docx?|xlsx?|pptx?|zip|gz|7z|exe|msi|sh|ps1|py|bin|asc)$", re.I) + + +class _LiveHttp(Protocol): + async def json( + self, source: str, url: str, *, deadline: float, + ) -> tuple[object, Mapping[str, str]]: ... + + +def allowed(host: str, path: str, *, live: bool) -> bool: + if host != _HOST or not path.startswith(_DIRECTORY_PATH): + return False + relative = path.removeprefix(_DIRECTORY_PATH) + return _FILE.fullmatch(relative) is not None or ( + not live and relative in {"provider-metadata.json", "changes.csv"} + ) + + +def _object(value: object) -> dict: + if not isinstance(value, dict): + raise InvalidData("expected Schneider CSAF object") + return value + + +def _check_publisher(raw: object) -> None: + publisher = _object(raw) + namespace = publisher.get("namespace") + if (publisher.get("name") != _PUBLISHER or publisher.get("category") != "vendor" + or not isinstance(namespace, str) or namespace not in _NAMESPACES): + raise InvalidData("unexpected Schneider CSAF publisher") + + +def _check_metadata(raw: object) -> None: + metadata = _object(raw) + if (metadata.get("metadata_version") not in ("2.0", "2.1") + or metadata.get("canonical_url") != _METADATA + or metadata.get("list_on_CSAF_aggregators") is not True): + raise InvalidData("unsupported Schneider provider metadata") + _check_publisher(metadata.get("publisher")) + distributions = metadata.get("distributions") + if not isinstance(distributions, list) or not any( + isinstance(item, dict) and item.get("directory_url") in (_DIRECTORY, _DIRECTORY.rstrip("/")) + for item in distributions + ): + raise InvalidData("Schneider public advisory directory is missing") + + +def _manifest(path: Path) -> dict[str, datetime]: + entries: dict[str, datetime] = {} + with path.open(encoding="utf-8-sig", newline="") as stream: + for count, row in enumerate(csv.reader(stream, strict=True), start=1): + if count > RECORD_LIMIT or len(row) != 2 or not (match := _FILE.fullmatch(row[0])): + raise InvalidData("invalid Schneider changes.csv row") + native, revision = match[2].upper(), instant(row[1]) + if entries.setdefault(native, revision) != revision: + raise InvalidData("conflicting Schneider manifest revision") + if not entries: + raise InvalidData("empty Schneider changes.csv") + return entries + + +def _advisory_target(value: object) -> tuple[str, str]: + if not isinstance(value, str) or not (match := _ID.fullmatch(value)): + raise InvalidData("unsupported Schneider advisory ID") + return value.upper(), f"{_DIRECTORY}{match[1]}/{value.lower()}.json" + + +def _advisory(raw: object, native: str, url: str) -> Doc: + data = _object(raw) + document = _object(data.get("document")) + _check_publisher(document.get("publisher")) + if document.get("category") != "csaf_security_advisory": + raise InvalidData("unexpected Schneider CSAF category") + tlp = _object(_object(document.get("distribution")).get("tlp")) + if tlp.get("label") not in ("WHITE", "CLEAR"): + raise InvalidData("Schneider advisory is not publicly distributable") + tracking = _object(document.get("tracking")) + if _advisory_target(tracking.get("id"))[0] != native: + raise InvalidData("Schneider tracking ID does not match the requested advisory") + instant(tracking.get("current_release_date")) + + # Do not pass vulnerability narratives, attachments, or external references + # through this vendor adapter. Keep public IDs, product scopes, and remediation. + vulnerabilities = data.get("vulnerabilities") + if not isinstance(vulnerabilities, list) or not vulnerabilities: + raise InvalidData("missing Schneider vulnerability records") + issues = [] + for item in vulnerabilities: + issue = _object(item) + issues.append({key: issue[key] for key in ("cve", "product_status", "remediations") if key in issue}) + doc = parse(_SOURCE, { + "document": {key: document[key] for key in ("csaf_version", "publisher", "title", "tracking") + if key in document}, + "product_tree": data.get("product_tree", {}), + "vulnerabilities": issues, + }, url) + for issue in doc.issues: + for fix in issue.fixes: + if fix_url := fix.get("url"): + parts = urlsplit(fix_url) + host = parts.hostname or "" + official = host in {"se.com", "schneider-electric.com"} or host.endswith( + (".se.com", ".schneider-electric.com")) + if (not official or parts.path.rstrip("/").casefold() == "/files" + or _ATTACHMENT.search(parts.path.rstrip("/"))): + del fix["url"] + return doc + + +def _read_advisory(path: Path, native: str, url: str, revision: datetime) -> Doc: + doc = _advisory(read_json(path), native, url) + if instant(doc.updated) < revision: + raise InvalidData("Schneider advisory predates the catalog revision") + return doc + + +async def refresh_industrial(state: FeedState, *, http: IndexFeedHttp, staging: FeedStage) -> RefreshResult: + previous = state.checkpoint.get("manifest") + if not previous: + metadata, _ = await http.json(_SOURCE, _METADATA) + await worker(_check_metadata, metadata) + validators = conditional(state.validators.get("manifest")) if previous else {} + path = staging.directory / "changes.csv" + status, headers = await http.download(_SOURCE, _CHANGES, path, headers=validators, limit=MANIFEST_LIMIT) + if status == 304 and validators: + return RefreshResult(state.checkpoint, state.validators) + if status != 200: + raise InvalidData("Schneider changes.csv was not downloaded") + current = await worker(_manifest, path) + old = await worker(_manifest, staging.artifact_path(previous)) if previous else {} + if any(entry in current and current[entry] < revision for entry, revision in old.items()): + raise InvalidData("Schneider catalog revision regressed") + # An overlay cannot express a removed bulletin. Replace in that case so it + # cannot remain an active finding under its old revision. + replace = not previous or not old.keys() <= current.keys() + changed = current if replace else {entry: revision for entry, revision in current.items() + if old.get(entry) != revision} + digest = await staging.artifact(path) + doc_path = staging.directory / "advisory.json" + batch: list[Doc] = [] + for native in sorted(changed, key=changed.__getitem__, reverse=True): + _, url = _advisory_target(native) + status, _ = await http.download(_SOURCE, url, doc_path, limit=JSON_LIMIT) + if status != 200: + raise InvalidData("Schneider advisory was not downloaded") + doc = await worker(_read_advisory, doc_path, native, url, changed[native]) + doc.artifact = await staging.artifact(doc_path) + batch.append(doc) + if len(batch) == BATCH_SIZE: + await staging.add("base", batch) + batch = [] + if batch: + await staging.add("base", batch) + return RefreshResult( + {"manifest": digest}, state.validators | {"manifest": response_validators(headers)}, + {"base": "replace" if replace else "overlay"} if changed else {}, artifacts=[digest], + ) + + +async def lookup_industrial( + kind: str, value: str | Sequence[str] | Mapping[str, str], *, http: _LiveHttp, + deadline: float, continuation: str | None = None, +) -> ProviderPage: + try: + if continuation is not None: + raise InvalidData("Schneider advisory detail is not paginated") + if kind == "id": + native, url = _advisory_target(value) + elif kind == "url" and isinstance(value, tuple) and len(value) == 2: + native, url = _advisory_target(value[0]) + if value[1] != url: + raise InvalidData("unexpected Schneider advisory URL") + else: + raise InvalidData("unsupported Schneider live lookup") + raw, headers = await http.json(_SOURCE, url, deadline=deadline) + doc = await worker(_advisory, raw, native, url) + except HttpError as exc: + if exc.status == "not_found": + return ProviderPage(status=Status(source=_SOURCE, as_of=utc_now())) + return ProviderPage(cacheable=False, status=Status(source=_SOURCE, status=exc.status, retry_at=exc.retry_at)) + except (InvalidData, ValidationError): + return ProviderPage(cacheable=False, status=Status(source=_SOURCE, status="invalid_data")) + cacheable = not any(token.partition("=")[0].strip().casefold() == "no-store" + for key, value in headers.items() if key.casefold() == "cache-control" + for token in value.split(",")) + return ProviderPage(docs=[doc], cacheable=cacheable, status=Status(source=_SOURCE, as_of=doc.checked_at)) diff --git a/src/vuln_mcp/sources/feed_paloalto.py b/src/vuln_mcp/sources/feed_paloalto.py new file mode 100644 index 0000000..3c16d62 --- /dev/null +++ b/src/vuln_mcp/sources/feed_paloalto.py @@ -0,0 +1,446 @@ +"""Defensive advisory metadata from Palo Alto Networks' public JSON API.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping +from pathlib import Path +from typing import Protocol +from urllib.parse import urlencode + +from ..models import AssetFacts, Doc, Issue, ProviderPage, Status, utc_now +from ..transport import HttpError +from .feeds_common import ( + MANIFEST_LIMIT, FeedStage, FeedState, IndexFeedHttp, RefreshResult, conditional, + instant, response_validators, stage_batches, worker, +) +from .parsers import InvalidData + +_SOURCE = "paloalto" +_PUBLISHER = "Palo Alto Networks" +_HOST = "security.paloaltonetworks.com" +_ORIGIN = f"https://{_HOST}" +_LISTING = _ORIGIN + "/json" +_ID = re.compile(r"(?:PAN-SA-[0-9]{4}-[0-9]{4}|CVE-[0-9]{4}-[0-9]{4,12})", re.ASCII | re.I) +_LABEL = re.compile(r"[\w][\w .,&+()/:'_-]{0,159}") +_RELEASE = re.compile(r"[0-9]{1,9}(?:\.[0-9]{1,9}){0,4}(?:-h[0-9]{1,9})?", re.ASCII) +_BRANCH = re.compile(r"[0-9]{1,9}\.[0-9]{1,9}", re.ASCII) +_BOUND = re.compile(r"(<=|<|>=)\s+([0-9.]+(?:-h[0-9]+)?)", re.ASCII) +_NEUTRAL_CONFIGURATION = re.compile( + r"(?:n/a|none|not applicable|no special configuration is required(?: to be affected by this issue)?)\.?", re.I, +) +_INDEX_LIMIT = 100 +_LIVE_LIMIT = 20 +_MAX_PAGES = 100 +_PRODUCT_ALIASES = { + "PAN-OS": ("PAN OS", "PANOS", "Palo Alto PAN-OS", "Palo Alto Networks PAN-OS"), + "PAN-OS Firewall": ("PAN OS Firewall",), + "GlobalProtect App": ("GlobalProtect", "Global Protect", "GlobalProtect Client"), + "GlobalProtect UWP App": ("GlobalProtect UWP",), + "Cloud NGFW": ("Cloud Next-Generation Firewall",), + "Cortex XDR Agent": ("XDR Agent",), + **dict.fromkeys(( + "AutoFocus", "Bridgecrew", "Checkov by Prisma Cloud", "Cortex Cloud", "Cortex XDR", + "Cortex XDR Broker VM", "Cortex Xpanse", "Cortex XSIAM", "Cortex XSOAR", "Demisto", + "Expedition", "Panorama", "Prisma Access", "Prisma Access Agent", "Prisma Browser", + "Prisma Cloud", "Prisma Cloud Compute", "Prisma SD-WAN", "Prisma SD-WAN ION", + "Strata Cloud Manager", "Traps", "User-ID Agent", "WildFire Cloud", + "WildFire Appliance (WF-500)", "WildFire Appliance WF-500 and WF-500-B", + ), ()), +} +_VENDOR_ALIASES = ("Palo Alto", "paloaltonetworks") +_PRODUCTS = {alias.casefold(): name for name, aliases in _PRODUCT_ALIASES.items() for alias in (name, *aliases)} + + +class _LiveHttp(Protocol): + async def json( + self, source: str, url: str, *, params: dict[str, str] | None = None, deadline: float, + ) -> tuple[object, Mapping[str, str]]: ... + + +def allowed(host: str, path: str, *, live: bool) -> bool: + if host != _HOST: + return False + if path == "/json": + return True + return live and path.startswith("/json/") and _ID.fullmatch(path[6:]) is not None + + +def _release(value: object) -> str | None: + return value if isinstance(value, str) and _RELEASE.fullmatch(value) else None + + +def _query_product(text: str) -> tuple[str, str | None] | None: + text = " ".join(text.split()) + if name := _PRODUCTS.get(text.casefold()): + return name, None + label, _, suffix = text.rpartition(" ") + if (name := _PRODUCTS.get(label.casefold())) and (version := _release(suffix)): + return name, version + return None + + +def paloalto_query(text: str, asset: AssetFacts | None = None) -> tuple[str, str | None] | None: + """Return a recognized catalog product and validated optional release for discovery.""" + if asset and asset.vendor and asset.vendor.casefold() not in { + label.casefold() for label in (_PUBLISHER, *_VENDOR_ALIASES) + }: + return None + supplied = _query_product(asset.product) if asset and asset.product else None + inline = _query_product(text) + product = supplied or inline + if product is None or supplied and inline and supplied[0] != inline[0]: + return None + name, version = product + if inline and inline[1]: + if version and version != inline[1]: + return None + version = inline[1] + if asset and asset.version: + explicit = _release(asset.version) + if explicit is None or version and explicit != version: + return None + version = explicit + return name, version + + +def paloalto_fix_matches(item: Mapping[str, object], version: str | None) -> bool: + """Whether a scoped publisher fix can be shown for an asset's release.""" + if "status" in item and item["status"] != "fixed": + return True + scope = item.get("scope") + if version is None: + return True + if not isinstance(scope, str) or not _release(version): + return False + release = version.partition("-h")[0] + return release == scope or release.startswith(scope + ".") + + +def _obj(value: object) -> dict[str, object]: + if not isinstance(value, dict): + raise InvalidData("expected Palo Alto advisory object") + return value + + +def _array(value: object) -> list[object]: + if not isinstance(value, list): + raise InvalidData("expected Palo Alto advisory list") + return value + + +def _strings(value: object) -> list[str]: + result = [] + for item in _array(value): + if not isinstance(item, str): + raise InvalidData("expected Palo Alto advisory label") + result.append(item.strip()) + return result + + +def _id(value: object) -> str: + if not isinstance(value, str) or not _ID.fullmatch(value): + raise InvalidData("invalid Palo Alto advisory identifier") + return value.upper() + + +def _product_name(label: str) -> str: + if not _LABEL.fullmatch(label) or "://" in label: + raise InvalidData("invalid Palo Alto product label") + return _PRODUCTS.get(label.casefold(), label) + + +def _identity(name: str) -> dict[str, object]: + return {"name": name, "vendor": [_PUBLISHER, *_VENDOR_ALIASES], "product_id": name, + "model": list(_PRODUCT_ALIASES.get(name, ())), "status": "unknown"} + + +def _branch(version: str) -> str | None: + components = version.partition("-h")[0].split(".") + return ".".join(components[:2]) if len(components) >= 3 else None + + +def _add_fix(issue: Issue, product: dict[str, object], release: str, scope: str) -> None: + version = product | {"version": release, "scope": scope, "status": "fixed"} + if version not in issue.products: + issue.products.append(version) + issue.fixes.append({"version": release, "scope": scope, "product_id": product["product_id"], + "category": "vendor_fix"}) + + +def _fix_scope(release: str, branch: str) -> str: + base, sep, _ = release.partition("-h") + return base if sep else branch + + +def _plain_bound(issue: Issue, product: dict[str, object], start: str, operator: str, end: str) -> None: + branch = _branch(start) + if branch and branch == _branch(end) and "-" not in start and "-" not in end: + key = "lessThan" if operator == "<" else "lessThanOrEqual" + issue.products.append(product | {"version": start, "scheme": "INTDOT", "range": {key: end}, + "scope": branch, "status": "affected"}) + + +def _new_issue(native: str, date: object = None) -> Issue: + issue = Issue(id=native, refs=[{"type": "vendor_advisory", "url": f"{_ORIGIN}/{native}"}]) + if date: + issue.facts["published"] = instant(date).isoformat() + return issue + + +def _document(issue: Issue, names: list[str], updated: object, *, rejected: bool = False) -> Doc: + title = f"{issue.id}: {', '.join(names)}" if names else issue.id + return Doc(source=_SOURCE, native_id=issue.id, publisher=_PUBLISHER, url=f"{_ORIGIN}/{issue.id}", + title=title[:240], updated=instant(updated).isoformat() if updated else None, + state="rejected" if rejected else "published", issues=[issue]) + + +def _listing_doc(raw: object) -> Doc: + row = _obj(raw) + issue = _new_issue(_id(row.get("ID")), row.get("date")) + labels = sorted(set(_strings(row.get("product"))), key=lambda label: (-len(label), label)) + products = {label: _identity(_product_name(label)) for label in labels if label} + issue.products.extend(products.values()) + if all(key in row for key in ("version", "affected", "fixed")): + versions, affected, fixes = (_strings(row[key]) for key in ("version", "affected", "fixed")) + # A historical record has uneven columns; none of its positional scopes are reliable. + if len(versions) == len(affected) == len(fixes): + for label, fixed in zip(versions, fixes, strict=True): + for name, product in products.items(): + if label.startswith(name + " "): + break + else: + continue + branch = label[len(name) + 1:] + if _BRANCH.fullmatch(branch) is None: + continue + bounds = [_BOUND.fullmatch(clause.strip()) for clause in fixed.split(",")] + if any(bound is None for bound in bounds): + continue + for bound in bounds: + if bound and bound[1] == ">=" and (release := _release(bound[2])) and _branch(release) == branch: + _add_fix(issue, product, release, _fix_scope(release, branch)) + names = list(dict.fromkeys(str(product["name"]) for product in products.values())) + return _document(issue, names, row.get("updated")) + + +def _listing_docs(raw: object) -> list[Doc]: + docs = [_listing_doc(row) for row in _array(raw)] + if len(docs) != len({doc.native_id for doc in docs}): + raise InvalidData("duplicate Palo Alto advisory identifier") + return docs + + +def _has_configurations(cna: dict[str, object]) -> bool: + for value in _array(cna.get("configurations", [])): + text = _obj(value).get("value") + if not isinstance(text, str): + return True + if text.strip() and not _NEUTRAL_CONFIGURATION.fullmatch(text.strip()): + return True + return False + + +def _related_cves(cna: dict[str, object], native: str) -> list[str]: + related: dict[str, None] = {} + for value in _array(cna.get("references", [])): + row = _obj(value) + url = row.get("url") + if not isinstance(url, str) or "vendor-advisory" not in _strings(row.get("tags", [])): + continue + if not url.startswith(_ORIGIN + "/"): + continue + identifier = url[len(_ORIGIN) + 1:] + if identifier.startswith("CVE-") and _ID.fullmatch(identifier) and identifier != native: + related[identifier] = None + return list(related) + + +def _detail_doc(raw: object, expected: str) -> Doc: + record = _obj(raw) + schema = record.get("dataVersion") + if record.get("dataType") != "CVE_RECORD" or not isinstance(schema, str) or not re.fullmatch(r"5\.\d+(?:\.\d+)?", schema): + raise InvalidData("unsupported Palo Alto advisory format") + meta = _obj(record.get("cveMetadata")) + native = _id(meta.get("cveId")) + state = meta.get("state") + if native != expected or state not in ("PUBLISHED", "REJECTED"): + raise InvalidData("unexpected Palo Alto advisory identity or state") + cna = _obj(_obj(record.get("containers")).get("cna")) + provider = _obj(cna.get("providerMetadata", {})) + published = meta.get("datePublished") or cna.get("datePublic") + updated = meta.get("dateUpdated") or provider.get("dateUpdated") or published + issue = _new_issue(native, published) + if state == "REJECTED": + return _document(issue, [], updated, rejected=True) + constrained = _has_configurations(cna) + if related := _related_cves(cna, native): + issue.facts["related"] = related + products: dict[str, dict[str, object]] = {} + scoped: set[str] = set() + for value in _array(cna.get("affected")): + row = _obj(value) + label = row.get("product") + if not isinstance(label, str): + raise InvalidData("invalid Palo Alto product label") + name = _product_name(label.strip()) + product = products.setdefault(name, _identity(name)) + if any(row.get(key) for key in ("platforms", "modules", "programFiles", "programRoutines")): + scoped.add(name) + continue + for value in _array(row.get("versions", [])): + entry = _obj(value) + status = entry.get("status") + start = _release(entry.get("version")) + relation = next((key for key in ("lessThan", "lessThanOrEqual") if key in entry), None) + end = _release(entry.get(relation)) if relation else None + changes = [_obj(change) for change in _array(entry.get("changes", []))] + if start and relation is None and not changes and status in ("affected", "unaffected") and start != "0": + if not constrained or status == "unaffected": + issue.products.append(product | {"version": start, "status": + "affected" if status == "affected" else "not_affected"}) + if start and end and status == "affected" and not constrained and ( + not changes or (relation == "lessThan" and changes == [{"at": end, "status": "unaffected"}]) + ): + _plain_bound(issue, product, start, "<" if relation == "lessThan" else "<=", end) + if start and status == "affected": + for change in changes: + release = _release(change.get("at")) + if release is None or change.get("status") != "unaffected": + continue + branch = _branch(release) + if branch and (_branch(start) == branch or start == "0"): + _add_fix(issue, product, release, _fix_scope(release, branch)) + # These are exact publisher-listed affected releases, not a continuous interval. + if not constrained: + names = sorted(products, key=len, reverse=True) + for entry in _strings(cna.get("x_affectedList", [])): + for name in names: + if entry.startswith(name + " ") and (version := _release(entry[len(name) + 1:])): + if name not in scoped: + affected = products[name] | {"version": version, "status": "affected"} + if affected not in issue.products: + issue.products.append(affected) + break + issue.products[:0] = products.values() + return _document(issue, list(products), updated) + + +async def refresh_paloalto(state: FeedState, *, http: IndexFeedHttp, staging: FeedStage) -> RefreshResult: + """Stage a complete listing from direct HTTP, without retaining publisher prose.""" + validators: dict[str, dict[str, str]] = {} + docs: dict[str, Doc] = {} + unchanged: list[int] = [] + path = staging.directory / "paloalto-listing.json" + + async def fetch(page: int, request_headers: Mapping[str, str]) -> list[Doc] | None: + url = f"{_LISTING}?{urlencode({'sort': '-updated', 'limit': _INDEX_LIMIT, 'page': page})}" + status, headers = await http.download(_SOURCE, url, path, headers=request_headers, + limit=MANIFEST_LIMIT) + if status == 304 and request_headers: + validators[str(page)] = state.validators[str(page)] + return None + if status != 200: + raise InvalidData("Palo Alto catalog page not downloaded") + validators[str(page)] = response_validators(headers) + return await worker(_read_listing, path) + + def add(rows: list[Doc]) -> None: + for doc in rows: + if doc.native_id in docs: + raise InvalidData("Palo Alto catalog pages overlap") + docs[doc.native_id] = doc + + try: + prior_pages = state.checkpoint.get("pages", 0) + for page in range(1, _MAX_PAGES + 1): + headers = conditional(state.validators.get(str(page))) if not docs and page <= prior_pages else {} + rows = await fetch(page, headers) + if rows is None: + unchanged.append(page) + if page == prior_pages: + return RefreshResult(state.checkpoint, validators) + continue + for previous in unchanged: + reloaded = await fetch(previous, {}) + if reloaded is None or len(reloaded) != _INDEX_LIMIT: + raise InvalidData("Palo Alto catalog changed during refresh") + add(reloaded) + unchanged.clear() + add(rows) + if len(rows) < _INDEX_LIMIT: + if not docs: + raise InvalidData("empty Palo Alto catalog") + await stage_batches(staging, "base", docs.values()) + return RefreshResult({"pages": page, "records": len(docs)}, validators, {"base": "replace"}) + raise InvalidData("Palo Alto catalog page limit exceeded") + finally: + await worker(path.unlink, missing_ok=True) + + +def _read_listing(path: Path) -> list[Doc]: + with path.open("rb") as stream: + content = stream.read(MANIFEST_LIMIT + 1) + if len(content) > MANIFEST_LIMIT: + raise InvalidData("Palo Alto catalog page exceeds byte limit") + docs = _listing_docs(json.loads(content)) + if len(docs) > _INDEX_LIMIT: + raise InvalidData("Palo Alto catalog page exceeds record limit") + return docs + + +def _cacheable(headers: Mapping[str, str]) -> bool: + return not any(part.partition("=")[0].strip().lower() == "no-store" + for key, value in headers.items() if key.lower() == "cache-control" + for part in value.split(",")) + + +async def lookup_paloalto( + kind: str, value: object, *, http: _LiveHttp, deadline: float, continuation: str | None = None, +) -> ProviderPage: + """Look up an exact advisory or a bounded page of product candidates via LiveHttp.""" + try: + next_page = None + if kind == "id" and continuation is None: + native = _id(value) + raw, headers = await http.json(_SOURCE, f"{_LISTING}/{native}", deadline=deadline) + docs = [await worker(_detail_doc, raw, native)] + elif kind == "product" and isinstance(value, tuple) and len(value) == 2: + product, version = value + if not isinstance(product, str) or product not in _PRODUCT_ALIASES or version is not None and not _release(version): + raise InvalidData("invalid Palo Alto catalog query") + if continuation is not None and not re.fullmatch(r"[1-9][0-9]{0,2}", continuation): + raise InvalidData("invalid Palo Alto catalog continuation") + page = int(continuation) if continuation is not None else 1 + if page > _MAX_PAGES: + raise InvalidData("Palo Alto catalog continuation exceeds page limit") + params = {"product": product, "sort": "-updated"} + if version is not None: + params["version"] = f"{product} {version}" + else: + params.update(limit=str(_LIVE_LIMIT), page=str(page)) + raw, headers = await http.json(_SOURCE, _LISTING, params=params, deadline=deadline) + rows = await worker(_listing_docs, raw) + # The version filter can return the whole result set regardless of page/limit. + start = (page - 1) * _LIVE_LIMIT if version is not None else 0 + if version is None and len(rows) > _LIVE_LIMIT: + raise InvalidData("Palo Alto catalog ignored page size") + docs = [doc for doc in rows[start:start + _LIVE_LIMIT] + if any(row.get("name") == product for issue in doc.issues for row in issue.products)] + more = len(rows) > start + _LIVE_LIMIT if version is not None else len(rows) == _LIVE_LIMIT + if more: + if page == _MAX_PAGES: + return ProviderPage(docs=docs, cacheable=_cacheable(headers), + status=Status(source=_SOURCE, status="invalid_data")) + next_page = str(page + 1) + else: + raise InvalidData("invalid Palo Alto lookup kind") + return ProviderPage(docs=docs, continuation=next_page, cacheable=_cacheable(headers), + status=Status(source=_SOURCE, as_of=utc_now())) + except HttpError as error: + if kind == "id" and error.status == "not_found": + return ProviderPage(status=Status(source=_SOURCE, as_of=utc_now())) + return ProviderPage(status=Status(source=_SOURCE, status=error.status, retry_at=error.retry_at)) + except (InvalidData, ValueError): + return ProviderPage(status=Status(source=_SOURCE, status="invalid_data")) diff --git a/src/vuln_mcp/sources/live.py b/src/vuln_mcp/sources/live.py index 44d50ba..ff07f28 100644 --- a/src/vuln_mcp/sources/live.py +++ b/src/vuln_mcp/sources/live.py @@ -350,6 +350,12 @@ async def lookup( """Query an applicable official endpoint through the supplied live transport.""" detail = False try: + if source == "paloalto": + from .feed_paloalto import lookup_paloalto + return await lookup_paloalto(kind, value, http=http, deadline=deadline, continuation=continuation) + if source == "industrial": + from .feed_industrial import lookup_industrial + return await lookup_industrial(kind, value, http=http, deadline=deadline, continuation=continuation) if source == "certcc" and kind == "id": from .feed_certcc import lookup_certcc return await lookup_certcc(_string(value), http=http, deadline=deadline) diff --git a/src/vuln_mcp/sources/parsers.py b/src/vuln_mcp/sources/parsers.py index ffab946..6e801f0 100644 --- a/src/vuln_mcp/sources/parsers.py +++ b/src/vuln_mcp/sources/parsers.py @@ -633,7 +633,7 @@ def parse(source: str, raw: object, url: str) -> Doc: return _osv(obj, url) if source == "nvd": return _nvd(obj, url) - if source in {"siemens", "msrc"}: + if source in {"siemens", "msrc", "industrial"}: return _csaf(source, obj, url) if source == "circl": return _variot(obj, url) diff --git a/src/vuln_mcp/store.py b/src/vuln_mcp/store.py index 1731597..bacd681 100644 --- a/src/vuln_mcp/store.py +++ b/src/vuln_mcp/store.py @@ -795,7 +795,8 @@ class Store: @asynccontextmanager async def staging(self, source: str) -> AsyncIterator[Staging]: stage = Staging(self, source, uuid4().hex) - if source not in {"cvelist", "osv", "siemens", "msrc", "kev", "epss", "exploitdb", "projectzero", "certcc", "zdi"}: + if source not in {"cvelist", "osv", "siemens", "msrc", "kev", "epss", "exploitdb", "exploitdb_inventory", + "projectzero", "certcc", "zdi", "paloalto", "industrial"}: raise ValueError("source has no index feed") try: await self._write(stage._start) diff --git a/src/vuln_mcp/sync.py b/src/vuln_mcp/sync.py index b61c092..5899c3d 100644 --- a/src/vuln_mcp/sync.py +++ b/src/vuln_mcp/sync.py @@ -16,7 +16,9 @@ from typing import Protocol from zipfile import BadZipFile from .sources.feed_certcc import refresh_certcc -from .sources.feed_exploitdb import refresh_exploitdb +from .sources.feed_exploitdb import refresh_exploitdb, refresh_exploitdb_inventory +from .sources.feed_paloalto import refresh_paloalto +from .sources.feed_industrial import refresh_industrial from .sources.feed_projectzero import refresh_projectzero from .sources.feed_zdi import refresh_zdi from .sources.feeds_bulk import refresh_cvelist, refresh_osv @@ -47,6 +49,9 @@ _FEEDS: dict[str, _Feed] = { "certcc": refresh_certcc, "projectzero": refresh_projectzero, "exploitdb": refresh_exploitdb, + "exploitdb_inventory": refresh_exploitdb_inventory, + "paloalto": refresh_paloalto, + "industrial": refresh_industrial, } diff --git a/src/vuln_mcp/transport.py b/src/vuln_mcp/transport.py index ee5f015..fdbda82 100644 --- a/src/vuln_mcp/transport.py +++ b/src/vuln_mcp/transport.py @@ -160,6 +160,14 @@ def _get_allowed(source: str, host: str, path: str, *, live: bool, previous: str # Import lazily: feed parsers also consume this transport's data contracts. if source == "exploitdb": return not live and host == "gitlab.com" and path == "/exploit-database/exploitdb/-/raw/main/files_exploits.csv" + if source == "exploitdb_inventory": + return not live and host == "gitlab.com" and path == "/exploit-database/exploitdb/-/raw/main/files_shellcodes.csv" + if source == "paloalto": + from .sources.feed_paloalto import allowed + return allowed(host, path, live=live) + if source == "industrial": + from .sources.feed_industrial import allowed + return allowed(host, path, live=live) if not live and source == "zdi": from .sources.feed_zdi import allowed return allowed(host, path) @@ -497,6 +505,7 @@ class _Sender: path: Path | None = None, allow_304: bool = True, ) -> _Response: + publisher = 'exploitdb' if source == 'exploitdb_inventory' else source route: _Route | None = routing if isinstance(routing, _Route) else None if isinstance(routing, _ProxyPool) and not routing.routes: raise HttpError("proxy_unavailable") @@ -508,7 +517,7 @@ class _Sender: async with asyncio.timeout(max(0, deadline - monotonic())): while True: try: - async with self.gate.slot(source, live, deadline): + async with self.gate.slot(publisher, live, deadline): if isinstance(routing, _ProxyPool): if route is None or route.retired: route = routing.take() @@ -519,7 +528,7 @@ class _Sender: route.in_flight += 1 try: response = await self._send( - source, route, url, method, body, headers, limit, path, live=live + publisher, route, url, method, body, headers, limit, path, live=live ) finally: route.in_flight -= 1 diff --git a/tests/test_exploitdb.py b/tests/test_exploitdb.py index f1463d7..f5eb7a3 100644 --- a/tests/test_exploitdb.py +++ b/tests/test_exploitdb.py @@ -1,4 +1,6 @@ import pytest +from vuln_mcp.store import Store +from vuln_mcp.sync import Sync from vuln_mcp.sources.feed_exploitdb import _dates from vuln_mcp.sources.parsers import InvalidData @@ -17,3 +19,36 @@ def test_truncated_csv_cannot_replace_snapshot(tmp_path): path.write_text('codes,date_published\nCVE-2024-1000\n') with pytest.raises(InvalidData): _dates(path) + + +@pytest.fixture +def anyio_backend(): + return 'asyncio' + + +@pytest.mark.anyio +async def test_secondary_csv_keeps_only_count_and_never_adds_cve_evidence(tmp_path): + from vuln_mcp.sources.feed_exploitdb import SHELLCODE_CATALOG + + class Wire: + calls = 0 + + async def download(self, source, url, path, *, headers, limit): + assert source == 'exploitdb_inventory' and url == SHELLCODE_CATALOG + self.calls += 1 + if self.calls == 2: + assert headers == {'If-None-Match': 'r1'} + return 304, {} + path.write_text('id,date_published,size,codes\n1,2024-01-01,15,CVE-2024-1234\n' + if self.calls == 1 else 'unexpected\n') + return 200, {'etag': 'r1'} + + async with Store(tmp_path) as store: + sync = Sync(store, Wire()) + assert await sync.refresh_once('exploitdb_inventory') + assert await sync.refresh_once('exploitdb_inventory') + assert not await sync.refresh_once('exploitdb_inventory') + state = await store.state('exploitdb_inventory') + assert state['checkpoint'] == {'records': 1} and state['status'] == 'invalid_data' + assert not await store.by_id('CVE-2024-1234') + assert (await store.state('exploitdb'))['status'] == 'initializing' diff --git a/tests/test_feed_recovery.py b/tests/test_feed_recovery.py index 6407517..1738cd0 100644 --- a/tests/test_feed_recovery.py +++ b/tests/test_feed_recovery.py @@ -147,7 +147,8 @@ def scores(day: str, rows: str = f"{CVE},0.13,0.25\n") -> bytes: @asynccontextmanager async def scheduler(store: Store, sync: Sync, *, active: set[str]) -> AsyncIterator[None]: - for source in {"cvelist", "osv", "siemens", "msrc", "kev", "epss", "zdi", "certcc", "projectzero", "exploitdb"} - active: + for source in {"cvelist", "osv", "siemens", "msrc", "kev", "epss", "zdi", "certcc", "projectzero", "exploitdb", + "paloalto", "industrial", "exploitdb_inventory"} - active: await store.checked(source) task = asyncio.create_task(sync.run()) try: diff --git a/tests/test_industrial.py b/tests/test_industrial.py new file mode 100644 index 0000000..037426a --- /dev/null +++ b/tests/test_industrial.py @@ -0,0 +1,228 @@ +"""Wire fixtures reduced from Schneider Electric CPCERT's public CSAF directory.""" + +from copy import deepcopy +from time import monotonic +from types import SimpleNamespace + +import httpx +import pytest + +from vuln_mcp.sources.feed_industrial import allowed, lookup_industrial +from vuln_mcp.sources.live import lookup +from vuln_mcp.store import Store +from vuln_mcp.sync import Sync +from vuln_mcp.transport import HttpClients + +_ROOT = "https://www.se.com/.well-known/csaf/" +_METADATA = _ROOT + "provider-metadata.json" +_MANIFEST = _ROOT + "changes.csv" +_NATIVE = "SEVD-2025-252-01" +_BULLETIN = "SESB-2021-347-01" +_ADVISORY_URL = _ROOT + "2025/sevd-2025-252-01.json" +_BULLETIN_URL = _ROOT + "2021/sesb-2021-347-01.json" +_INITIAL = "2026-10-13T07:00:00Z" +_REVISED = "2026-11-14T07:00:00Z" +_BULLETIN_REVISION = "2025-11-20T05:00:00Z" +_CVE = "CVE-2025-7746" + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def _metadata() -> dict: + return { + "metadata_version": "2.0", + "canonical_url": _METADATA, + "role": "csaf_trusted_provider", + "list_on_CSAF_aggregators": True, + "mirror_on_CSAF_aggregators": False, + "distributions": [{"directory_url": _ROOT}], + "publisher": {"category": "vendor", "name": "Schneider Electric CPCERT", + "namespace": "https://www.se.com/ww/en"}, + } + + +def _advisory(native: str, revision: str, cve: str = _CVE, *, details: str = "Apply the mitigation.") -> dict: + return { + "document": { + "csaf_version": "2.0", "category": "csaf_security_advisory", + "title": "Altivar Process Communication Modules security notice", + "publisher": { + "category": "vendor", "name": "Schneider Electric CPCERT", + "namespace": "https://www.se.com/ww/en/work/support/cybersecurity/security-notifications.jsp", + }, + "tracking": {"id": native, "current_release_date": revision.replace("Z", ".000Z")}, + "distribution": {"tlp": {"label": "WHITE"}}, + "references": [{"category": "external", "url": "https://public.example/attachment.pdf", + "summary": "Archive attachment"}], + }, + "product_tree": {"branches": [{ + "category": "vendor", "name": "Schneider Electric", + "branches": [{ + "category": "product_name", "name": "Altivar Process Communication Modules", + "branches": [{ + "category": "product_version_range", "name": "vers:all/*", + "product": {"product_id": "26", "name": "Altivar Process Communication Modules All Versions", + "product_identification_helper": {"model_numbers": ["VW3A3721"]}}, + }], + }], + }]}, + "vulnerabilities": [{ + "cve": cve, + "notes": [{"category": "description", "text": "Vulnerability narrative omitted by this adapter."}], + "product_status": {"known_affected": ["26"]}, + "remediations": [ + {"category": "mitigation", "details": details, "product_ids": ["26"], + "url": "https://www.se.com/ww/en/download/document/PRODUCT_GUIDE/"}, + {"category": "workaround", "details": "Follow the documented workaround.", + "product_ids": ["26"], "url": "https://www.se.com/public/attachment.pdf"}, + {"category": "mitigation", "details": "Review the device configuration.", + "product_ids": ["26"], "url": "https://public.example/technical-report"}, + ], + }], + } + + +def _manifest(advisory_revision: str, *, include_bulletin: bool = True) -> bytes: + advisory = f'"2025/sevd-2025-252-01.json","{advisory_revision}"\r\n' + bulletin = f'"2021/sesb-2021-347-01.json","{_BULLETIN_REVISION}"\r\n' + return (advisory + (bulletin if include_bulletin else "")).encode() + + +@pytest.mark.anyio +async def test_schneider_catalog_refresh_and_live_revalidation(tmp_path, monkeypatch) -> None: + advisory = _advisory(_NATIVE, _INITIAL) + bulletin = _advisory(_BULLETIN, _BULLETIN_REVISION, "CVE-2021-9001") + manifest, etag = _manifest(_INITIAL), '"catalog-1"' + calls: list[tuple[str, str, str | None]] = [] + original_client = httpx.AsyncClient + + def make_client(*, proxy: str | None, trust_env: bool) -> httpx.AsyncClient: + assert not trust_env + route = "proxy" if proxy else "direct" + + def respond(request: httpx.Request) -> httpx.Response: + url = str(request.url) + validator = request.headers.get("If-None-Match") + calls.append((route, url, validator)) + if url == _MANIFEST: + if etag == validator: + return httpx.Response(304) + return httpx.Response(200, content=manifest, headers={"ETag": etag}) + if url == _METADATA: + return httpx.Response(200, json=_metadata()) + if url == _BULLETIN_URL: + return httpx.Response(200, json=bulletin) + assert url == _ADVISORY_URL + if route == "proxy": + if validator == '"advisory"': + return httpx.Response(304, headers={"ETag": '"advisory"'}) + return httpx.Response(200, json=advisory, headers={"ETag": '"advisory"'}) + return httpx.Response(200, json=advisory) + + return original_client(transport=httpx.MockTransport(respond), trust_env=False) + + monkeypatch.setattr(httpx, "AsyncClient", make_client) + settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy") + async with Store(tmp_path) as store, HttpClients(settings, store) as clients: + sync = Sync(store, clients.index) + assert await sync.refresh_once("industrial") + [doc] = await store.by_id(_CVE) + assert (doc.native_id, doc.publisher, doc.url) == (_NATIVE, "Schneider Electric CPCERT", _ADVISORY_URL) + [issue] = doc.issues + assert issue.summary == "" + assert issue.refs == [{"type": "vendor_advisory", "url": _ADVISORY_URL}] + [product] = issue.products + assert (product["model"], product["range"], product["status"]) == ("VW3A3721", "vers:all/*", "affected") + assert issue.fixes[0]["product_ids"] == ["26"] + assert issue.fixes[0]["url"] == "https://www.se.com/ww/en/download/document/PRODUCT_GUIDE/" + assert all("url" not in fix for fix in issue.fixes[1:]) + assert await store.by_id(_BULLETIN) + + cold = await lookup("industrial", "id", _NATIVE.lower(), http=clients.live, deadline=monotonic() + 5) + checked = await lookup("industrial", "url", (_NATIVE, _ADVISORY_URL), + http=clients.live, deadline=monotonic() + 5) + assert cold.status.status == checked.status.status == "ok" + assert cold.docs[0].issues == checked.docs[0].issues == doc.issues + assert await sync.refresh_once("industrial") + assert calls == [("direct", _METADATA, None), ("direct", _MANIFEST, None), + ("direct", _ADVISORY_URL, None), ("direct", _BULLETIN_URL, None), + ("proxy", _ADVISORY_URL, None), ("proxy", _ADVISORY_URL, '"advisory"'), + ("direct", _MANIFEST, '"catalog-1"')] + + state = await store.state("industrial") + manifest, etag = _manifest(_REVISED), '"catalog-2"' + assert not await sync.refresh_once("industrial") # The document still carries the preceding revision. + failed = await store.state("industrial") + assert failed["status"] == "invalid_data" + assert failed["checkpoint"] == state["checkpoint"] and failed["validators"] == state["validators"] + assert (await store.by_id(_CVE))[0].issues[0].fixes[0]["details"] == "Apply the mitigation." + + advisory = _advisory(_NATIVE, _REVISED, details="Apply the revised mitigation.") + assert await sync.refresh_once("industrial") + assert calls[-2:] == [("direct", _MANIFEST, '"catalog-1"'), ("direct", _ADVISORY_URL, None)] + assert (await store.by_id(_CVE))[0].issues[0].fixes[0]["details"] == "Apply the revised mitigation." + assert await store.by_id(_BULLETIN) + + manifest, etag = _manifest(_REVISED, include_bulletin=False), '"catalog-3"' + assert await sync.refresh_once("industrial") + assert not await store.by_id(_BULLETIN) + assert await store.by_id(_CVE) + + +@pytest.mark.parametrize(("host", "path", "index", "live"), [ + ("www.se.com", "/.well-known/csaf/provider-metadata.json", True, False), + ("www.se.com", "/.well-known/csaf/changes.csv", True, False), + ("www.se.com", "/.well-known/csaf/2025/sevd-2025-252-01.json", True, True), + ("www.se.com", "/.well-known/csaf/2021/sesb-2021-347-01.json", True, True), + ("www.se.com", "/.well-known/csaf/2024/sevd-2025-252-01.json", False, False), + ("www.se.com", "/.well-known/csaf/2025/vde-2025-252.json", False, False), + ("www.se.com", "/.well-known/csaf/2025/sevd-2025-252-01.json.zip", False, False), + ("www.se.com", "/files/2025/sevd-2025-252-01.json", False, False), + ("www.se.com.example", "/.well-known/csaf/2025/sevd-2025-252-01.json", False, False), +]) +def test_schneider_allowlist(host: str, path: str, index: bool, live: bool) -> None: + assert allowed(host, path, live=False) is index + assert allowed(host, path, live=True) is live + + +@pytest.mark.anyio +@pytest.mark.parametrize(("kind", "value"), [ + ("id", "CVE-2025-7746"), + ("id", "VDE-2025-123"), + ("id", _ADVISORY_URL), + ("url", (_BULLETIN, _ADVISORY_URL)), + ("url", (_NATIVE, _ADVISORY_URL + "?download=true")), + ("url", (_NATIVE, _ADVISORY_URL.replace("www.se.com", "subdomain.example"))), +]) +async def test_schneider_rejects_unregistered_detail_targets(kind, value) -> None: + class Unreachable: + async def json(self, *args, **kwargs): + pytest.fail("invalid target must not make an HTTP request") + + page = await lookup_industrial(kind, value, http=Unreachable(), deadline=monotonic() + 5) + assert page.status.status == "invalid_data" and not page.docs + + +@pytest.mark.anyio +@pytest.mark.parametrize("defect", ["publisher", "tracking_id", "distribution"]) +async def test_schneider_rejects_misattributed_or_nonpublic_details(defect: str) -> None: + result = deepcopy(_advisory(_BULLETIN, _BULLETIN_REVISION)) + document = result["document"] + if defect == "publisher": + document["publisher"]["namespace"] = "https://third-party.example" + elif defect == "tracking_id": + document["tracking"]["id"] = _NATIVE + else: + document["distribution"]["tlp"]["label"] = "AMBER" + + class Publisher: + async def json(self, source: str, url: str, *, deadline: float): + assert source == "industrial" + assert url == _BULLETIN_URL + return result, {} + + page = await lookup_industrial("id", _BULLETIN, http=Publisher(), deadline=monotonic() + 5) + assert page.status.status == "invalid_data" and not page.docs diff --git a/tests/test_paloalto.py b/tests/test_paloalto.py new file mode 100644 index 0000000..963a584 --- /dev/null +++ b/tests/test_paloalto.py @@ -0,0 +1,274 @@ +"""Palo Alto JSON wire shapes, defensive scope, and atomic index publication.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import pytest + +from vuln_mcp.matching import make_asset, product_match, product_status +from vuln_mcp.models import AssetFacts +from vuln_mcp.sources import feed_paloalto +from vuln_mcp.sources.feed_paloalto import allowed, lookup_paloalto, paloalto_fix_matches, paloalto_query +from vuln_mcp.store import Store +from vuln_mcp.sync import Sync +from vuln_mcp.transport import HttpError + +ORIGIN = "https://security.paloaltonetworks.com" +HOST = "security.paloaltonetworks.com" +CATALOG = ORIGIN + "/json" +NATIVE = "PAN-SA-2024-0013" +CVE = "CVE-2024-2551" +DATE = "2024-11-20T08:00:00.000Z" +IGNORED = "fixture text outside the advisory metadata contract" + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def listing(identifier: str, **fields: object) -> dict[str, object]: + return {"ID": identifier, "product": ["PAN-OS"], "date": DATE, "updated": DATE, + "problem": IGNORED, "solution": IGNORED, **fields} + + +def detail(identifier: str, **fields: object) -> dict[str, object]: + # PAN uses CVE_RECORD even when its native ID is a non-CVE advisory ID. + return {"dataType": "CVE_RECORD", "dataVersion": "5.0", + "cveMetadata": {"cveId": identifier, "state": "PUBLISHED"}, + "containers": {"cna": { + "providerMetadata": {"dateUpdated": DATE}, "datePublic": DATE, + "affected": [], "descriptions": [{"lang": "en", "value": IGNORED}], + "solutions": [{"lang": "en", "value": IGNORED}], "exploits": [IGNORED], + "references": [{"url": "https://example.invalid/attachment", "tags": ["exploit"]}], + **fields, + }}} + + +class LiveWire: + def __init__(self, reply: object, headers: Mapping[str, str] | None = None) -> None: + self.reply = reply + self.headers = {} if headers is None else headers + self.requests: list[tuple[str, str, dict[str, str], float]] = [] + + async def json(self, source: str, url: str, *, params: dict[str, str] | None = None, + deadline: float) -> tuple[object, Mapping[str, str]]: + self.requests.append((source, url, params or {}, deadline)) + if isinstance(self.reply, HttpError): + raise self.reply + return self.reply, self.headers + + +@pytest.mark.parametrize(("text", "asset", "expected"), [ + ("PANOS", None, ("PAN-OS", None)), + ("Palo Alto Networks PAN-OS 11.2.4-h2", None, ("PAN-OS", "11.2.4-h2")), + ("VPN", AssetFacts(product="GlobalProtect", version="6.2.4"), ("GlobalProtect App", "6.2.4")), + ("PAN-OS", AssetFacts(vendor="Another Vendor"), None), + ("PAN-OS 11.2.4", AssetFacts(product="PAN OS", version="11.2.5"), None), + ("PAN-OS", AssetFacts(version="secret?branch=11"), None), + ("unknown operating system", None, None), +]) +def test_only_known_product_filters_and_release_syntax_are_forwarded( + text: str, asset: AssetFacts | None, expected: tuple[str, str | None] | None, +) -> None: + assert paloalto_query(text, asset) == expected + + +@pytest.mark.anyio +async def test_version_lookup_uses_vendor_product_qualified_version_and_continues() -> None: + rows = [listing(f"CVE-2024-{n:04}") for n in range(3000, 3022)] + wire = LiveWire(rows, {"Cache-Control": "public, no-store"}) + query = ("PAN-OS", "11.2.4") + first = await lookup_paloalto("product", query, http=wire, deadline=42) + assert first.status.status == "ok" and first.continuation == "2" and not first.cacheable + assert [doc.native_id for doc in first.docs] == [f"CVE-2024-{n:04}" for n in range(3000, 3020)] + assert all(IGNORED not in doc.model_dump_json() for doc in first.docs) + second = await lookup_paloalto("product", query, http=wire, deadline=43, continuation=first.continuation) + assert [doc.native_id for doc in second.docs] == ["CVE-2024-3020", "CVE-2024-3021"] + assert second.continuation is None + assert wire.requests == [ + ("paloalto", CATALOG, {"product": "PAN-OS", "sort": "-updated", "version": "PAN-OS 11.2.4"}, deadline) + for deadline in (42, 43) + ] + + +@pytest.mark.anyio +async def test_product_only_uses_vendor_pages() -> None: + wire = LiveWire([listing(f"CVE-2024-{n:04}") for n in range(3000, 3020)]) + first = await lookup_paloalto("product", ("PAN-OS", None), http=wire, deadline=42) + assert len(first.docs) == 20 and first.continuation == "2" + wire.reply = [listing(NATIVE)] + second = await lookup_paloalto("product", ("PAN-OS", None), http=wire, deadline=42, continuation=first.continuation) + assert [doc.native_id for doc in second.docs] == [NATIVE] and second.continuation is None + assert [request[2] for request in wire.requests] == [ + {"product": "PAN-OS", "sort": "-updated", "limit": "20", "page": page} for page in ("1", "2") + ] + + +@pytest.mark.anyio +async def test_exact_publisher_advisory_uses_official_id_and_never_exports_raw_content() -> None: + wire = LiveWire(detail(NATIVE, affected=[{"vendor": "Palo Alto Networks", "product": "PAN-OS", + "versions": [{"version": "All", "status": "unaffected"}]}])) + result = await lookup_paloalto("id", NATIVE.lower(), http=wire, deadline=42) + assert result.status.status == "ok" + [doc] = result.docs + [issue] = doc.issues + assert (doc.native_id, doc.publisher, doc.url, doc.updated) == ( + NATIVE, "Palo Alto Networks", ORIGIN + "/" + NATIVE, "2024-11-20T08:00:00+00:00", + ) + assert issue.id == NATIVE and not issue.aliases and not issue.fixes + assert issue.refs == [{"type": "vendor_advisory", "url": doc.url}] + assert doc.artifact is None and IGNORED not in doc.model_dump_json() + assert "example.invalid" not in doc.model_dump_json() + assert wire.requests == [("paloalto", f"{CATALOG}/{NATIVE}", {}, 42)] + + +@pytest.mark.anyio +async def test_native_advisory_only_reports_official_cve_links_as_related() -> None: + wire = LiveWire(detail(NATIVE, references=[ + {"url": f"{ORIGIN}/{CVE}", "tags": ["vendor-advisory"]}, + {"url": "https://example.invalid/CVE-2024-9999", "tags": ["vendor-advisory"]}, + {"url": f"{ORIGIN}/CVE-2024-8888/attachment", "tags": ["vendor-advisory"]}, + ])) + result = await lookup_paloalto("id", NATIVE, http=wire, deadline=42) + [doc] = result.docs + [issue] = doc.issues + assert issue.id == NATIVE and not issue.aliases + assert issue.facts["related"] == [CVE] + + +@pytest.mark.anyio +async def test_detail_does_not_apply_another_branch_fix_or_treat_later_builds_as_fixed() -> None: + wire = LiveWire(detail(CVE, affected=[ + {"vendor": "Palo Alto Networks", "product": "PAN-OS", "versions": [ + {"version": "11.0.0", "lessThan": "11.0.5", "status": "affected", "versionType": "custom", + "changes": [{"at": "11.0.5", "status": "unaffected"}]}, + {"version": "10.2.0", "lessThan": "10.2.4-h6", "status": "affected", "versionType": "custom", + "changes": [{"at": "10.2.4-h6", "status": "unaffected"}, + {"at": "10.2.5", "status": "unaffected"}]}, + ]}, + {"vendor": "Palo Alto Networks", "product": "Cloud NGFW", "versions": [ + {"version": "All", "status": "unaffected"}, + ]}, + ], configurations=[{"lang": "en", "value": "No special configuration is required to be affected by this issue."}], + x_affectedList=["PAN-OS 11.0.4", "PAN-OS 10.2.4-h5"])) + result = await lookup_paloalto("id", CVE, http=wire, deadline=42) + [doc] = result.docs + [issue] = doc.issues + assert doc.native_id == issue.id == CVE + assert [(fix["product_id"], fix["version"], fix["scope"]) for fix in issue.fixes] == [ + ("PAN-OS", "11.0.5", "11.0"), ("PAN-OS", "10.2.4-h6", "10.2.4"), ("PAN-OS", "10.2.5", "10.2"), + ] + assert [fix["version"] for fix in issue.fixes if paloalto_fix_matches(fix, "11.0.4")] == ["11.0.5"] + assert [fix["version"] for fix in issue.fixes if paloalto_fix_matches(fix, "10.2.5")] == ["10.2.5"] + + def verdicts(version: str) -> set[str]: + asset = make_asset("text", "PAN OS", AssetFacts(version=version)) + return {product_status(row, asset) for row in issue.products if product_match(row, asset) == (True, set())} - {"unknown"} + + assert verdicts("10.2.4-h5") == {"affected"} + assert verdicts("10.2.4-h6") == {"fixed"} + assert verdicts("11.0.4") == {"affected"} + assert verdicts("11.0.3") == {"affected"} + assert verdicts("11.0.5") == {"fixed"} + assert verdicts("11.0.6") == set() + assert verdicts("11.1.0") == set() + + +@pytest.mark.anyio +async def test_misaligned_vendor_table_does_not_attribute_other_branch_fixes() -> None: + wire = LiveWire([listing(CVE, version=["PAN-OS 11.0"], affected=["< 11.0.5"], + fixed=[">= 11.0.5", ">= 11.1.0"])]) + result = await lookup_paloalto("product", ("PAN-OS", "11.0.4"), http=wire, deadline=42) + [doc] = result.docs + [issue] = doc.issues + assert not issue.fixes + assert {row["status"] for row in issue.products} == {"unknown"} + + +@pytest.mark.anyio +async def test_detail_does_not_assume_configuration_requirements() -> None: + wire = LiveWire(detail(CVE, affected=[{ + "vendor": "Palo Alto Networks", "product": "PAN-OS", + "versions": [{"version": "11.0.0", "lessThan": "11.0.5", "status": "affected", + "changes": [{"at": "11.0.5", "status": "unaffected"}]}], + }], configurations=[{"lang": "en", "value": IGNORED}], x_affectedList=["PAN-OS 11.0.4"])) + result = await lookup_paloalto("id", CVE, http=wire, deadline=42) + [doc] = result.docs + [issue] = doc.issues + assert IGNORED not in doc.model_dump_json() + assert {row["status"] for row in issue.products} == {"unknown", "fixed"} + + +@pytest.mark.anyio +async def test_lookup_reports_missing_and_wrong_schema_differently() -> None: + missing = await lookup_paloalto("id", NATIVE, http=LiveWire(HttpError("not_found")), deadline=42) + wrong = await lookup_paloalto("id", NATIVE, http=LiveWire(detail(CVE)), deadline=42) + limited = await lookup_paloalto("id", NATIVE, http=LiveWire(HttpError("rate_limited", DATE)), deadline=42) + assert missing.status.status == "ok" and not missing.docs + assert wrong.status.status == "invalid_data" and not wrong.docs + assert limited.status.status == "rate_limited" and limited.status.retry_at == DATE + + +class IndexWire: + def __init__(self, pages: dict[int, tuple[int, object]]) -> None: + self.pages = pages + self.requests: list[tuple[int, dict[str, str]]] = [] + + async def download(self, source: str, url: str, path: Path, *, headers: Mapping[str, str] | None = None, + limit: int) -> tuple[int, Mapping[str, str]]: + parsed = urlsplit(url) + assert source == "paloalto" and parsed.scheme == "https" and parsed.netloc == HOST and parsed.path == "/json" + params = parse_qs(parsed.query) + assert params["sort"] == ["-updated"] and params["limit"] == ["2"] + page = int(params["page"][0]) + self.requests.append((page, dict(headers or {}))) + status, payload = self.pages[page] + if status == 200: + body = json.dumps(payload).encode("utf-8") + assert len(body) <= limit + path.write_bytes(body) + return status, {"ETag": f'"page-{page}"'} + + async def json(self, *_args: object, **_kwargs: object) -> tuple[object, Mapping[str, str]]: + raise AssertionError("index refresh should stream only its fixed listing pages") + + +@pytest.mark.anyio +async def test_index_is_conditional_and_atomic_across_catalog_pages( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(feed_paloalto, "_INDEX_LIMIT", 2) + wire = IndexWire({1: (200, [listing(NATIVE), listing(CVE)]), 2: (200, [listing("CVE-2024-3033")])}) + async with Store(tmp_path) as store: + sync = Sync(store, wire) + assert await sync.refresh_once("paloalto") + generation = await store.generation() + [doc] = await store.by_id(NATIVE) + assert doc.native_id == NATIVE and doc.artifact is None + assert await store.by_id("CVE-2024-3033") + wire.pages = {1: (304, None), 2: (304, None)} + assert await sync.refresh_once("paloalto") + assert await store.generation() == generation + assert wire.requests[-2:] == [(1, {"If-None-Match": '"page-1"'}), (2, {"If-None-Match": '"page-2"'})] + wire.pages = {1: (200, [listing(NATIVE), listing("CVE-2024-4044")]), 2: (200, [listing(NATIVE)])} + assert not await sync.refresh_once("paloalto") + assert await store.generation() == generation + assert not await store.by_id("CVE-2024-4044") + assert await store.by_id("CVE-2024-3033") + + +def test_allowlist_excludes_unapproved_origins_paths_and_document_routes() -> None: + for live in (True, False): + assert allowed(HOST, "/json", live=live) + assert not allowed(HOST + ".example.invalid", "/json", live=live) + assert not allowed(HOST, "/api", live=live) + assert not allowed(HOST, f"/{NATIVE}", live=live) + assert not allowed(HOST, f"/json/{NATIVE}/attachment", live=live) + assert not allowed(HOST, "/json/../private", live=live) + assert allowed(HOST, f"/json/{NATIVE}", live=True) + assert allowed(HOST, f"/json/{CVE}", live=True) diff --git a/tests/test_search.py b/tests/test_search.py index e3de807..c882434 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -148,7 +148,8 @@ async def _publish(store: Store, source: str, docs: list[Doc]) -> None: async def _ready(store: Store) -> None: - for source in ('cvelist', 'osv', 'siemens', 'msrc', 'kev', 'epss', 'zdi', 'certcc', 'projectzero', 'exploitdb'): + for source in ('cvelist', 'osv', 'siemens', 'msrc', 'kev', 'epss', 'zdi', 'certcc', 'projectzero', 'exploitdb', + 'paloalto', 'industrial', 'exploitdb_inventory'): await store.checked(source, {'as_of': datetime.now(UTC).date().isoformat()}) diff --git a/tests/test_stdio.py b/tests/test_stdio.py index 193ab95..4ce0291 100644 --- a/tests/test_stdio.py +++ b/tests/test_stdio.py @@ -1,4 +1,5 @@ """Exercise the installed stdio entrypoint, its private cache and process lock.""" +import json import os import sys @@ -28,8 +29,11 @@ async def seed(path): async with store.staging("cvelist") as stage: await stage.add("base", docs) await stage.publish({}, layers={"base": "replace"}) - for source in ("cvelist", "osv", "msrc", "siemens", "kev", "epss", "zdi", "certcc", "projectzero", "exploitdb"): + for source in ("cvelist", "osv", "msrc", "siemens", "kev", "epss", "zdi", "certcc", "projectzero", "exploitdb", + "paloalto", "industrial", "exploitdb_inventory"): await store.checked(source, {}) + await store.checked('exploitdb', {'count': 17}) + await store.checked('exploitdb_inventory', {'records': 23}) finally: await store.close() @@ -46,6 +50,10 @@ async def test_stdio_hybrid_pagination_and_offline_evidence(tmp_path): tools = {tool.name: tool for tool in (await client.list_tools()).tools} assert set(tools) == {"search", "get_advisory"} assert set(tools["search"].input_schema["properties"]) == {"query", "asset", "cursor"} + inventory = await client.read_resource('vuln://catalogs/exploitdb') + stats = json.loads(inventory.contents[0].text) + assert stats['files_exploits.csv']['unique_cves'] == 17 + assert stats['files_shellcodes.csv']['records'] == 23 first = (await client.call_tool("search", {"query": "ExampleOS"})).structured_content assert first["partial"] and first["next_cursor"] assert any(status["status"] == "proxy_unavailable" for status in first["sources"])