Select published exploit artifacts and report exploitation preconditions
This commit is contained in:
1 parent
5d1e5d2cac
commit
dbcd91eae0
35 files changed
+1916
-21
No files matched your search
@@ -10,3 +10,4 @@ dist/
|
||||
.coverage.*
|
||||
coverage.xml
|
||||
htmlcov/
|
||||
tmpwork/
|
||||
@@ -28,6 +28,25 @@ MCPHub may prefix tool names, for example `vuln-search_guides` and `vuln-get_gui
|
||||
|
||||
VEX statements from the supplied document are scoped to `bom-ref` and labeled `supplied_bom`; they do not override independent publisher evidence. Unsupported ranges or missing versions do not establish that a component is safe. An empty result is not a clean bill of health.
|
||||
|
||||
## Exploitation evidence
|
||||
|
||||
Every hit carries two fields for planning an attempt. The MCP never executes anything and never contacts the target; it supplies the artifact, the preconditions, and the observable that separates success from a blind response.
|
||||
|
||||
`exploit_refs` lists published artifacts, ordered `exploit_db` then `metasploit_module` then `poc_repo` then `detection_template`, deduplicated, capped at 20:
|
||||
|
||||
| Type | Source |
|
||||
| --- | --- |
|
||||
| `exploit_db` | Exploit-DB, with `edb_id`, `exploit_type`, `platform`, `verified`, `tags`. Remote and verified entries rank first. |
|
||||
| `metasploit_module` | Module path and platform from the Metasploit metadata. |
|
||||
| `poc_repo` | Public proof-of-concept repositories referenced for that CVE. |
|
||||
| `detection_template` | ProjectDiscovery nuclei template and its protocol, for establishing presence before selecting an artifact. |
|
||||
|
||||
`exploitation` reports published preconditions from the record itself: `automatable` and `technical_impact` from CISA SSVC, `cvss_av`, `cvss_pr` and `cvss_ui` from the CVSS vector, and `component_role` (`application`, `operating_system`, `hardware`) from the CPE part. Absent keys mean the publisher said nothing.
|
||||
|
||||
None of this confirms the queried build. A detection template hit is not a working exploit; a referenced repository is not tested code; `automatable: yes` says nothing about reachability from your position. Confirm the version constraint first, then the artifact, then the observable.
|
||||
|
||||
The Metasploit mapping comes from an 11 MB publisher index. A cold process reports `initializing` for that source on the first search and refreshes it in the background; the next search uses it. Every warm lookup still revalidates the index with a conditional request, so a changed or removed module appears immediately.
|
||||
|
||||
## Run
|
||||
|
||||
Use Python 3.12+ with SQLite FTS5, uv, and a local disk. From the project directory:
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Through a local test cache, request the same page with two test accounts whose profiles contain distinct values. Verify that each response contains only that account's profile data. Inspect the actual `Cache-Control` and `Vary` headers, not just the configuration.
|
||||
|
||||
**Exploitation.** Needs a shared cache such as a CDN or reverse proxy in front of an authenticated page, a signed-in victim, and a response whose headers still permit storage. The operator requests the page as one account, then as an unauthenticated or second account, and compares the bodies. Success is the second response carrying the first account's profile values inside otherwise plausible markup; a missing hit indicator such as `X-Cache`, `Age`, or `CF-Cache-Status` makes the result blind and proves nothing. Limited to personalized responses behind a shared cache: a private browser cache alone is never exposed.
|
||||
|
||||
**Fix.** Keep personalized responses out of shared caches. Use `Cache-Control: private` when storage in a user's own cache is acceptable, or `Cache-Control: no-store` when the response must not be stored. Cache public resources separately.
|
||||
|
||||
[MDN: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Replace the process launcher with a test function that records arguments without running anything. Submit a valid name containing spaces and verify that the launcher receives the fixed executable path and the unchanged name as a single argument. Verify that an input that fails validation never reaches the launcher.
|
||||
|
||||
**Exploitation.** Needs attacker-influenced data reaching either a shell string or the argument vector of a child process, plus one side channel the operator can read. The operator submits a value carrying shell syntax or an option-like prefix and looks for the process's own effect: echoed command output, a new file, an outbound DNS or HTTP callback, or a measurable delay. Success is an effect the application cannot produce alone; a plain `200` with an unchanged body is blind and needs a callback or a timing baseline. Limited by the sink, because shell-less array invocation allows only option injection, and a host without outbound network removes callbacks.
|
||||
|
||||
**Fix.** Prefer a library function. If a subprocess is necessary, use a fixed executable and pass an argument array without a shell. Separate options from data using the program's documented conventions, and run with only the privileges it needs.
|
||||
|
||||
[OWASP: OS Command Injection Defense](https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Use a local test client to compare response headers for an approved origin and the unapproved origin `https://outside.example`. Verify that the unapproved origin receives no CORS permission to read the response with credentials. If the response varies by origin, verify that it includes `Vary: Origin`.
|
||||
|
||||
**Exploitation.** Needs a browser session on the victim, a credentialed endpoint returning private data, and a policy that reflects the requesting origin. The operator serves a page from an unapproved origin, fetches the endpoint with credentials, and reads the body from that page. Success is the script reading data the origin should not see, observable in the page itself; a preflight that merely returns `200` while the body stays unreadable is blind. Limited to browser-enforced reads, so a plain command-line client never proves it, and an endpoint without cookies or with an explicit allowlist for the tested origin is unaffected.
|
||||
|
||||
**Fix.** Allow only the exact schemes, hosts, and ports that need access. Permit credentials only where needed and leave CORS disabled on routes that do not need cross-origin reads.
|
||||
|
||||
[MDN: CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** In a local test application, submit the same operation with a valid token for the current test session, without a token, and with a token for a different test session. Verify that only the first case is accepted and that rejected requests do not write to the database.
|
||||
|
||||
**Exploitation.** Needs cookie-based authentication, a state-changing route that accepts a simple cross-site request, and a victim with an active session. The operator loads a page on another origin or forges the request without a token, then checks the server-side record from a separate authenticated session. Success is a persisted change confirmed out of band; a success page rendered after a blind submission may still be a no-op. Limited to cookie authentication, since header or token APIs are immune, and a strict `SameSite` policy narrows the window without closing it.
|
||||
|
||||
**Fix.** Enable the framework's CSRF protection and set an appropriate `SameSite` cookie policy. Where CSRF protection does not apply, such as signed webhooks, verify the request with the appropriate mechanism instead.
|
||||
|
||||
[OWASP: CSRF Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Pass three plain data fixtures to the validator: a valid object, one with an unrecognized type label, and one with an extra field. Count calls to the object factory and verify that invalid input is rejected before a domain object is created.
|
||||
|
||||
**Exploitation.** Needs an attacker-supplied serialized blob such as a cookie, queue message, or import file, and a sink that reconstructs objects before validating them. The operator swaps the type label or injects an unexpected field and watches which branch the application takes. Success is instantiation of a different class, a handler side effect, or an applied change; a generic server error is only blind evidence. Limited by the format, since data-only encodings confine abuse to logic and code-level impact needs an accepted class or gadget.
|
||||
|
||||
**Fix.** Use a data format with an explicit schema and a fixed set of accepted types. Validate the data before constructing domain objects; never let a request select arbitrary classes.
|
||||
|
||||
[OWASP: Deserialization](https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Submit a small valid image and a plain text file with the same declared image type. Verify that the image is accepted and the text file is rejected without being stored. Test uploads at and just above the size limit, and verify that rejected uploads leave no partial file behind.
|
||||
|
||||
**Exploitation.** Needs an authenticated upload route, a storage location the operator can retrieve, and ideally a handler that serves files back. The operator uploads a file whose name and declared type satisfy the checks while the content is another format, then requests the stored file. Success is the file being stored, retrievable, and handled as its real content by a server parser or a browser; storage without retrieval is blind. Limited to delivery, because impact needs the path reachable or the handler active, and an inert download endpoint yields only stored-content attacks.
|
||||
|
||||
**Fix.** Accept only required formats and validate the contents with a parser for the expected format. Use server-generated names and store uploads outside executable and public application directories.
|
||||
|
||||
[OWASP: File Upload](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** In a test database, submit a valid display name in a profile update, along with a synthetic role field. Inspect the stored record and verify that the role did not change, whether the handler rejects the entire request or ignores the extra field.
|
||||
|
||||
**Exploitation.** Needs a create or update route that binds request fields wholesale to a record and at least one server-controlled field such as a role, tenant, or verified flag. The operator adds that field beyond what the interface sends and re-fetches the record through the API. Success is the persisted value changed while legitimate fields stayed intact; an echo of the input without a persisted change is blind. Limited to fields outside a strict input contract, and a handler with an explicit allowlist simply ignores the extra key.
|
||||
|
||||
**Fix.** Use a separate input model for each operation and explicitly map the fields it may change. Populate server-controlled values from trusted context.
|
||||
|
||||
[OWASP: Mass Assignment](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Seed a test database with distinct documents for two tenants. Verify that an authorized user can read their own tenant's document but cannot read or update the other tenant's document. Check that the denied update leaves the stored record unchanged.
|
||||
|
||||
**Exploitation.** Needs two identities in scope, stable record identifiers, and authentication as the only gate. The operator authenticates as the second identity and substitutes a first identity's identifier on a read and on a write. Success is a `200` carrying the other tenant's data, or a write landing in the other record and verifiable by its owner; an empty success shell is blind. Limited to object scope, the identifier format is irrelevant, and a route that also filters by tenant in the query stays safe even with guessable IDs.
|
||||
|
||||
**Fix.** Enforce record scope in the data query or a shared access policy. Apply the same rules to attachments and background jobs.
|
||||
|
||||
[OWASP: Authorization](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Call the handler in a local test client with redirect following disabled. For an approved internal route, assert the exact `Location` value. For `https://outside.example/`, assert rejection or an exact, safe internal fallback.
|
||||
|
||||
**Exploitation.** Needs a destination parameter consumed after sign-in, a callback, or a link, without a server-side allowlist. The operator requests the handler with an external destination and redirect following disabled, then reads `Location`. Success is an exact `Location` on a foreign host, provable from that single response, while following redirects makes it blind. Limited to reach, since it matters only when chained with a token or sign-in flow, and a path-only variation inside the same origin is not a finding.
|
||||
|
||||
**Fix.** Accept a short destination ID and resolve it to a route on the server. When an external destination is necessary, allow only the exact origins and paths the integration needs.
|
||||
|
||||
[OWASP: Unvalidated Redirects](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Capture a test account's reset link in a local mail sink without sending email. Verify that a token is rejected after a successful reset. Use a controlled clock to test expiration, and verify that only one of two simultaneous redemption attempts succeeds.
|
||||
|
||||
**Exploitation.** Needs a reachable reset flow, an attacker-requestable token, and a delivery sink to observe it. The operator requests two resets, redeems one, then replays the consumed link; separately, it races two redemptions of a single token. Success is a second use that still sets a password, or both parallel redemptions taking effect, visible as the password changing twice. A form that accepts submission while login still fails is blind. Limited to token handling, a single-use token is safe only when consumption is atomic with the change, and no mail sink blocks verification.
|
||||
|
||||
**Fix.** Generate tokens with a cryptographically secure random source, give them a short lifetime, and consume them in the same transaction as the password change. Return the same neutral response for known and unknown email addresses.
|
||||
|
||||
[OWASP: Forgot Password](https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Create an allowed directory and a neighboring directory under a temporary test root. Verify that the path policy accepts a fixture file inside the allowed directory and denies a fixture file outside it, including when reached through a symbolic link inside the allowed directory. Assert that denied files are not opened or modified.
|
||||
|
||||
**Exploitation.** Needs a filename or path parameter that reaches a file read or write, plus knowledge of the directory layout. The operator supplies relative escapes, an absolute path, or a link placed inside the allowed directory, and asserts on known fixture content. Success is content from outside the permitted root appearing in the response, unambiguous because the fixture is known; a default or empty body is blind. Limited to sink direction, since a read-only endpoint discloses only readable files and a write-only import overwrites outside the root invisibly.
|
||||
|
||||
**Fix.** Prefer opaque file IDs. When paths are necessary, use filesystem-aware containment checks and open files in a way that prevents a link from being swapped between the check and the open.
|
||||
|
||||
[MITRE: CWE-22](https://cwe.mitre.org/data/definitions/22.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Use a unique synthetic token and a test transport to exercise both success and failure. Verify that the collected logs contain neither the token nor the authorization header, while still retaining the expected error code and request ID.
|
||||
|
||||
**Exploitation.** Needs a request carrying credentials and a log sink with broader readership or longer retention than the data. The operator sends a unique synthetic secret and greps every rail: application, proxy, dependency, and error handler. Success is that exact value in a stored log; a structured entry that omits it is blind until its full format is read. Limited to exposure rather than execution, filtering the primary logger does nothing for dependency output, and a sink with the same readership and retention as the data adds little.
|
||||
|
||||
**Fix.** Log only explicitly approved fields. Do not serialize entire requests, environment variables, or exceptions from upstream services into logs.
|
||||
|
||||
[OWASP: Logging](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Start with an anonymous session in a local test client, then sign in to a test account and verify that the session ID changes. Verify that the old ID cannot access authenticated routes and that the new session is invalid after sign-out.
|
||||
|
||||
**Exploitation.** Needs a session ID the attacker can set or learn before authentication, and an application that keeps it afterwards. The operator uses a chosen ID anonymously, lets the victim sign in, then replays the ID. Success is the same ID now serving the victim's authenticated data, and an unchanged `Set-Cookie` after sign-in is the tell; a `200` on the account page may be a cached copy and is blind. Limited to flows where the pre-auth ID is attacker-visible and the server does not rotate it.
|
||||
|
||||
**Fix.** Rotate the session ID and invalidate the old one when authentication or privileges change. Set both absolute and idle timeouts, and revoke sessions on the server when required.
|
||||
|
||||
[OWASP: Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** In a data access test, search for the fixture surnames `Smith` and `O'Brien`. Inspect the driver calls to verify that the SQL template stays the same and that only the bound parameter changes. Verify that both names match literally in a test database.
|
||||
|
||||
**Exploitation.** Needs a value that reaches query text and a route with visible data or errors. The operator sends a matched boolean pair around an otherwise valid filter and compares row counts or error text. Success is the pair diverging, or a syntax error exposing the statement; identical pages are blind and need a timing baseline. Limited by building style, since an ORM on bound queries is immune except in raw fragments, and second-order values surface only later through stored data.
|
||||
|
||||
**Fix.** Bind values through the database driver's parameter API rather than escaping them manually. Apply the same review to background reports and data exports.
|
||||
|
||||
[OWASP: SQL Injection Prevention](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Replace DNS and HTTP with test implementations that make no network calls. Assert that the HTTP test transport receives a request for an approved destination, but none for an unapproved destination, whether specified directly or returned in a simulated redirect.
|
||||
|
||||
**Exploitation.** Needs a server-side fetch of an operator-supplied URL and a destination reachable from the server but not from the browser. The operator points the field at an internal host and port and at an external collaborator. Success is internal content reflected back, or a callback that arrives while the browser stays away; missing output with only latency differences is blind. Limited to outbound capability, an allowlist narrows it, and redirects or DNS rebinding defeat naive string checks.
|
||||
|
||||
**Fix.** Accept a registered source ID instead of a URL when possible. Enforce outbound restrictions in both the application and the network, and never forward credentials when the destination changes.
|
||||
|
||||
[OWASP: SSRF Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Render `A < B & C` in a component test. Verify that the DOM contains the exact text and that the value creates no child elements. For rich text, verify that the rendered tags and attributes conform to the allowed set.
|
||||
|
||||
**Exploitation.** Needs the input reflected or stored into an HTML context and a browser to render it. The operator sets a marker value and checks whether rendering produces a node or literal characters. Success is a created element or a script-side effect such as a dialog or a collaborator callback visible in the DOM; the escaped marker in the source is only the blind variant. Limited to rendering, framework auto-escaping covers text nodes but not attributes and URLs, and a strict CSP blunts execution without fixing the sink.
|
||||
|
||||
**Fix.** Use context-appropriate output encoding and restrict link schemes. Content Security Policy (CSP) adds protection but does not replace safe rendering.
|
||||
|
||||
[OWASP: XSS Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
**Local check.** Use a test resolver that records calls without accessing files or the network. Verify that a simple XML document parses and that a fixture requiring a disallowed external resource is rejected before the resolver is called.
|
||||
|
||||
**Exploitation.** Needs XML parsing with DTD processing enabled and a resolver the parser may reach. The operator supplies a document with an external entity and watches for a resolved value or a collaborator callback. Success is known local file content inside the parsed result, or a request originating from the server rather than the browser; a parser error naming the entity is the blind case. Limited by configuration, JSON-only endpoints are immune, and the entity type decides between file disclosure and network reach.
|
||||
|
||||
**Fix.** Explicitly disable DTDs and external entities when they are not needed. Load only trusted local schemas and limit document size and nesting depth.
|
||||
|
||||
[OWASP: XML External Entity Prevention](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html)
|
||||
@@ -81,6 +81,8 @@ class Hit(Model):
|
||||
issues: list[dict[str, Any]] = Field(default_factory=list)
|
||||
remediations: list[dict[str, Any]] = Field(default_factory=list)
|
||||
source_refs: list[dict[str, Any]] = Field(default_factory=list)
|
||||
exploit_refs: list[dict[str, Any]] = Field(default_factory=list)
|
||||
exploitation: dict[str, Any] | None = None
|
||||
facts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
coverage: list[Status] = Field(default_factory=list)
|
||||
|
||||
|
||||
+65
-5
@@ -47,6 +47,11 @@ _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'}
|
||||
_EXPLOIT_SOURCES = ('pocs', 'nuclei', 'metasploit')
|
||||
_EXPLOIT_ORDER = {'exploit_db': 0, 'metasploit_module': 1, 'poc_repo': 2, 'detection_template': 3}
|
||||
_EXPLOIT_KEYS = ('automatable', 'technical_impact', 'cvss_av', 'cvss_pr', 'cvss_ui', 'component_role')
|
||||
_EXPLOIT_CAP = 20
|
||||
_CLAIM_CHECK_SOURCES = {'osv', 'circl', 'paloalto', 'redhat', 'web', 'fortinet', 'android', *_EXPLOIT_SOURCES}
|
||||
_INDEX_SOURCES = ('cvelist', 'osv', 'siemens', 'msrc', 'zdi', 'certcc', 'projectzero', 'paloalto', 'industrial', 'web', 'android', 'fortinet')
|
||||
_DEVICE_PUBLISHERS = {'siemens', 'msrc', 'paloalto', 'industrial', 'web', 'android', 'fortinet', 'redhat'}
|
||||
_FIX_SCOPES = {'paloalto': paloalto_fix_matches, 'fortinet': fortinet_fix_matches, 'web': web_branch_matches}
|
||||
@@ -380,7 +385,7 @@ def _base_checks(native_id: str, asset: Asset | None = None) -> set[Check]:
|
||||
return set()
|
||||
ident = _id(native_id)
|
||||
if _CVE.fullmatch(ident):
|
||||
checks = {Check(source, ident) for source in ('cvelist', 'nvd', 'epss', 'circl', 'certcc')}
|
||||
checks = {Check(source, ident) for source in ('cvelist', 'nvd', 'epss', 'circl', 'certcc', *_EXPLOIT_SOURCES)}
|
||||
if asset is not None and redhat_asset(asset):
|
||||
checks.add(Check('redhat', ident))
|
||||
return checks
|
||||
@@ -403,7 +408,7 @@ def _checks(group: Group, asset: Asset | None = None) -> set[Check]:
|
||||
ident = _id(doc.native_id)
|
||||
if not (_NATIVE.fullmatch(ident) or _OSV.fullmatch(ident)):
|
||||
continue
|
||||
if doc.source in {'osv', 'circl', 'paloalto', 'redhat', 'web', 'fortinet', 'android'}:
|
||||
if doc.source in _CLAIM_CHECK_SOURCES:
|
||||
planned.add(Check(doc.source, ident))
|
||||
elif doc.source in {'siemens', 'msrc', 'industrial'}:
|
||||
if doc.source in {'siemens', 'industrial'}:
|
||||
@@ -455,6 +460,55 @@ def _source_url(value: Any) -> str | None:
|
||||
return value if parts.scheme == 'https' and parts.hostname else None
|
||||
|
||||
|
||||
def _exploit_url(value: Any) -> str | None:
|
||||
"""Publication URLs an exploit tracker owns; the ref filter would drop most of them."""
|
||||
if not isinstance(value, str) or not value:
|
||||
return None
|
||||
try:
|
||||
parts = _url_parts(value)
|
||||
except ValueError:
|
||||
return None
|
||||
if parts.scheme != 'https' or parts.port not in {None, 443} or not _HOST.fullmatch(parts.hostname or ''):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _exploit_refs(group: Group) -> list[dict[str, Any]]:
|
||||
selected: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for claim in group.claims:
|
||||
values = claim.issue.facts.get('exploit_refs')
|
||||
if not isinstance(values, list):
|
||||
continue
|
||||
for value in values:
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
kind = value.get('type')
|
||||
if not isinstance(kind, str) or kind not in _EXPLOIT_ORDER:
|
||||
continue
|
||||
url = _exploit_url(value.get('url'))
|
||||
if url is None:
|
||||
continue
|
||||
selected.setdefault((kind, url), dict(value) | {'type': kind, 'url': url})
|
||||
return sorted(selected.values(), key=lambda ref: (_EXPLOIT_ORDER[ref['type']], ref['url']))[:_EXPLOIT_CAP]
|
||||
|
||||
|
||||
def _exploitation(group: Group) -> dict[str, Any] | None:
|
||||
merged: dict[str, Any] = {}
|
||||
for claim in group.claims:
|
||||
values = claim.issue.facts.get('exploitation')
|
||||
if not isinstance(values, dict):
|
||||
continue
|
||||
for key in _EXPLOIT_KEYS:
|
||||
value = values.get(key)
|
||||
if not (value is None or isinstance(value, str)):
|
||||
continue
|
||||
if key not in merged or merged[key] is None:
|
||||
merged[key] = value
|
||||
if not merged:
|
||||
return None
|
||||
return {key: merged.get(key) for key in _EXPLOIT_KEYS}
|
||||
|
||||
|
||||
def _prose(value: Any) -> str:
|
||||
if not isinstance(value, str) or _UNSAFE_PROSE.search(value):
|
||||
return ''
|
||||
@@ -506,7 +560,8 @@ def _trusted_refs(doc: Doc, issue: Issue) -> Iterable[dict[str, Any]]:
|
||||
|
||||
def _claim_coverage(group: Group, checked: dict[Check, ProviderPage], index: dict[str, Status], asset: Asset | None = None) -> list[Status]:
|
||||
statuses = []
|
||||
for check in _checks(group, asset):
|
||||
planned = _checks(group, asset)
|
||||
for check in planned:
|
||||
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 in {'siemens', 'industrial'} else None
|
||||
@@ -522,6 +577,10 @@ def _claim_coverage(group: Group, checked: dict[Check, ProviderPage], index: dic
|
||||
if _CVE.fullmatch(group.id):
|
||||
statuses.append(index['kev'])
|
||||
statuses.append(index['exploitdb'])
|
||||
answered = {status.source for status in statuses}
|
||||
for source in _EXPLOIT_SOURCES:
|
||||
if any(check.source == source for check in planned) and source not in answered:
|
||||
statuses.append(index[source])
|
||||
if index['msrc'].status != 'ok' and index['msrc'].as_of is None:
|
||||
statuses.append(index['msrc'])
|
||||
return _collapse(statuses)
|
||||
@@ -716,7 +775,8 @@ def _render(group: Group, query: Query, asset: Asset, coverage: list[Status], in
|
||||
match_reason=_finding_reason(group, query, asset), record_state=record_state, applicability=applicability,
|
||||
missing_fields=sorted(missing), evidence=evidence, fixed_versions=sorted(versions),
|
||||
kev=scored.get('kev'), epss=scored.get('epss'), issues=issues.values(), remediations=fixes.values(),
|
||||
source_refs=refs.values(), facts=facts.values(), coverage=coverage,
|
||||
source_refs=refs.values(), exploit_refs=_exploit_refs(group), exploitation=_exploitation(group),
|
||||
facts=facts.values(), coverage=coverage,
|
||||
)
|
||||
|
||||
|
||||
@@ -769,7 +829,7 @@ class Search:
|
||||
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')}
|
||||
return {source: _index_status(source, await self._store.state(source)) for source in (*_INDEX_SOURCES, 'kev', 'epss', 'exploitdb', *_EXPLOIT_SOURCES)}
|
||||
|
||||
async def _run_checks(self, wanted: set[Check], checked: dict[Check, ProviderPage], deadline: float) -> list[Observation]:
|
||||
plans: dict[str, list[Check]] = defaultdict(list)
|
||||
|
||||
@@ -11,28 +11,69 @@ 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'
|
||||
EXPLOIT = 'https://www.exploit-db.com/exploits/'
|
||||
_CVE = re.compile(r'(?<![\w-])CVE-[0-9]{4}-[0-9]{4,}(?![\w-])', re.ASCII | re.I)
|
||||
_PUBLICATION_COLUMNS = {'codes', 'date_published'}
|
||||
_REF_COLUMNS = {'id', 'type', 'platform', 'verified', 'tags'}
|
||||
_TYPE_ORDER = ('remote', 'webapps', 'local', 'dos')
|
||||
_TYPES = frozenset(_TYPE_ORDER) | {'shellcode', 'papers', 'hardware'}
|
||||
_OTHER = len(_TYPE_ORDER)
|
||||
REF_LIMIT = 8
|
||||
|
||||
|
||||
def _dates(path: Path) -> dict[str, str]:
|
||||
def _sorted_refs(refs: list[dict]) -> list[dict]:
|
||||
ordered = sorted(refs, key=lambda ref: (_TYPE_ORDER.index(ref['exploit_type'])
|
||||
if ref['exploit_type'] in _TYPE_ORDER else _OTHER,
|
||||
0 if ref['verified'] else 1,
|
||||
-date.fromisoformat(ref['_day']).toordinal(),
|
||||
-int(ref['edb_id'])))
|
||||
return [{key: value for key, value in ref.items() if key != '_day'} for ref in ordered[:REF_LIMIT]]
|
||||
|
||||
|
||||
def _catalog(path: Path) -> tuple[dict[str, str], dict[str, list[dict]]]:
|
||||
dates: dict[str, str] = {}
|
||||
refs: dict[str, dict[str, dict]] = {}
|
||||
with path.open(encoding='utf-8-sig', newline='') as stream:
|
||||
rows = csv.reader(stream, strict=True)
|
||||
columns = next(rows, [])
|
||||
if len(columns) != len(set(columns)) or not {'codes', 'date_published'} <= set(columns):
|
||||
known = set(columns)
|
||||
if len(columns) != len(known) or not _PUBLICATION_COLUMNS <= known:
|
||||
raise InvalidData('unrecognized publication catalogue columns')
|
||||
if not _REF_COLUMNS & known:
|
||||
refs = None # type: ignore[assignment]
|
||||
elif not _REF_COLUMNS <= known:
|
||||
raise InvalidData('unrecognized exploit catalogue columns')
|
||||
codes, published = columns.index('codes'), columns.index('date_published')
|
||||
if refs is not None:
|
||||
edb_id, kind = columns.index('id'), columns.index('type')
|
||||
platform, verified, tags = columns.index('platform'), columns.index('verified'), columns.index('tags')
|
||||
for row in rows:
|
||||
if len(row) != len(columns):
|
||||
raise InvalidData('incomplete publication catalogue row')
|
||||
for match in _CVE.finditer(row[codes]):
|
||||
ident = match[0].upper()
|
||||
day = date.fromisoformat(row[published]).isoformat()
|
||||
day = date.fromisoformat(row[published]).isoformat()
|
||||
idents = [match[0].upper() for match in _CVE.finditer(row[codes])]
|
||||
for ident in idents:
|
||||
if ident not in dates or day < dates[ident]:
|
||||
dates[ident] = day
|
||||
if refs is None:
|
||||
continue
|
||||
number, exploit_type = row[edb_id].strip(), row[kind].strip().lower()
|
||||
if not number.isdigit() or exploit_type not in _TYPES:
|
||||
continue
|
||||
ref = {'type': 'exploit_db', 'url': EXPLOIT + number, 'edb_id': number,
|
||||
'exploit_type': exploit_type, 'platform': row[platform].strip(),
|
||||
'verified': row[verified].strip() == '1',
|
||||
'tags': list(dict.fromkeys(tag.strip() for tag in row[tags].split(',') if tag.strip())),
|
||||
'_day': day}
|
||||
for ident in idents:
|
||||
refs.setdefault(ident, {}).setdefault(ref['url'], ref)
|
||||
if not dates:
|
||||
raise InvalidData('empty publication catalogue')
|
||||
return dates
|
||||
return dates, {ident: _sorted_refs(list(values.values())) for ident, values in (refs or {}).items()}
|
||||
|
||||
|
||||
def _dates(path: Path) -> dict[str, str]:
|
||||
return _catalog(path)[0]
|
||||
|
||||
|
||||
async def refresh_exploitdb(state: FeedState, *, http: IndexFeedHttp, staging: FeedStage) -> RefreshResult:
|
||||
@@ -43,11 +84,12 @@ async def refresh_exploitdb(state: FeedState, *, http: IndexFeedHttp, staging: F
|
||||
return RefreshResult(state.checkpoint, state.validators)
|
||||
if status != 200:
|
||||
raise InvalidData('publication catalogue not downloaded')
|
||||
dates = await worker(_dates, path)
|
||||
dates, refs = await worker(_catalog, path)
|
||||
docs = (Doc(source='exploitdb', native_id=ident, publisher='Exploit-DB', url=ABOUT, title=ident,
|
||||
issues=[Issue(id=ident, facts={'exploitation_evidence': [
|
||||
{'publisher': 'Exploit-DB', 'status': 'public_poc', 'catalog': 'Exploit-DB', 'date': day}
|
||||
]})]) for ident, day in dates.items())
|
||||
], **({'exploit_refs': refs[ident]} if ident in refs else {})})])
|
||||
for ident, day in dates.items())
|
||||
await stage_batches(staging, 'base', docs)
|
||||
return RefreshResult({'count': len(dates)}, response_validators(headers), {'base': 'replace'})
|
||||
|
||||
@@ -79,4 +121,4 @@ async def refresh_exploitdb_inventory(state: FeedState, *, http: IndexFeedHttp,
|
||||
if status != 200:
|
||||
raise InvalidData('secondary catalogue not downloaded')
|
||||
records = await worker(_catalog_size, path)
|
||||
return RefreshResult({'records': records}, response_validators(headers))
|
||||
return RefreshResult({'records': records}, response_validators(headers))
|
||||
@@ -0,0 +1,281 @@
|
||||
"""CVE references in Rapid7's published Metasploit module metadata.
|
||||
|
||||
The only machine-readable, keyless CVE-to-module mapping is the bundled
|
||||
``db/modules_metadata_base.json`` generated by the framework's release
|
||||
tooling. It is a snapshot of module declarations on ``master``, not of the
|
||||
build an operator inspects: a hit says that a module exists and lists the CVE,
|
||||
never that the module was executed against that build. Each reference therefore
|
||||
carries the module's own ``mod_time``, the index revision (ETag), the fetch time
|
||||
and ``verified_against_build: False``.
|
||||
|
||||
Every lookup revalidates the index through the live route with a conditional
|
||||
GET, so a changed or removed module is visible immediately. The parsed mapping
|
||||
is reused only for an unchanged validator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import weakref
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from time import monotonic
|
||||
from typing import Any, Protocol
|
||||
|
||||
from ..models import Doc, Issue, ProviderPage, Status
|
||||
from ..transport import HttpError
|
||||
from .feeds_common import worker
|
||||
from .parsers import InvalidData
|
||||
|
||||
_SOURCE = "metasploit"
|
||||
_PUBLISHER = "Rapid7 Metasploit Framework"
|
||||
_HOST = "raw.githubusercontent.com"
|
||||
_INDEX_PATH = "/rapid7/metasploit-framework/master/db/modules_metadata_base.json"
|
||||
_INDEX_URL = f"https://{_HOST}{_INDEX_PATH}"
|
||||
_INDEX_URL_HTML = "https://github.com/rapid7/metasploit-framework/blob/master/db/modules_metadata_base.json"
|
||||
_INDEX_NAME = "db/modules_metadata_base.json"
|
||||
_BLOB = "https://github.com/rapid7/metasploit-framework/blob/master/"
|
||||
_CVE = re.compile(r"CVE-[0-9]{4}-[0-9]{4,}", re.ASCII | re.I)
|
||||
# A module path must be a single relative, ASCII file below modules/.
|
||||
_PATH = re.compile(r"modules/(?:[A-Za-z0-9_.+-]+/)+[A-Za-z0-9_.+-]+\.rb", re.ASCII)
|
||||
_MAX_PATH = 512
|
||||
_MAX_PLATFORM = 128
|
||||
_MAX_UPDATED = 64
|
||||
_MAX_RANK = 1000
|
||||
# The artefact is large, so it is fetched in the background with its own budget.
|
||||
_REFRESH_SECONDS = 60.0
|
||||
_TTL = 3600.0
|
||||
_WAIT_SECONDS = 2.0
|
||||
|
||||
|
||||
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:
|
||||
"""Only the generated metadata index is fetched; module files stay display-only."""
|
||||
return live and host == _HOST and path == _INDEX_PATH
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Module:
|
||||
module_path: str
|
||||
platform: str | None
|
||||
rank: int | None
|
||||
updated: str | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _State:
|
||||
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||
validator: str | None = None
|
||||
mapping: dict[str, tuple[_Module, ...]] | None = None
|
||||
task: asyncio.Task | None = None
|
||||
last: str | None = None
|
||||
retry_at: str | None = None
|
||||
no_store: bool = False
|
||||
|
||||
|
||||
# One parsed index per live transport. A fake http in tests gets its own state.
|
||||
_states: weakref.WeakKeyDictionary[object, _State] = weakref.WeakKeyDictionary()
|
||||
_fallback: dict[int, _State] = {}
|
||||
|
||||
|
||||
def _state(http: object) -> _State:
|
||||
try:
|
||||
state = _states.get(http)
|
||||
if state is None:
|
||||
state = _State()
|
||||
_states[http] = state
|
||||
return state
|
||||
except TypeError: # Objects without weak references still get isolated state.
|
||||
state = _fallback.get(id(http))
|
||||
if state is None:
|
||||
state = _State()
|
||||
_fallback[id(http)] = state
|
||||
return state
|
||||
|
||||
|
||||
def _text(value: object, limit: int) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
text = " ".join(value.split())
|
||||
return text[:limit] if text else None
|
||||
|
||||
|
||||
def _path(value: object) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
raw = value.strip()
|
||||
if not raw.startswith("/modules/") or len(raw) > _MAX_PATH:
|
||||
return None
|
||||
relative = raw[1:]
|
||||
if _PATH.fullmatch(relative) is None:
|
||||
return None
|
||||
if any(part in {".", ".."} for part in relative.split("/")):
|
||||
return None
|
||||
return relative
|
||||
|
||||
|
||||
def _rank(value: object) -> int | None:
|
||||
# Metasploit publishes ranks as integers (0 manual .. 600 excellent).
|
||||
if type(value) is not int or not 0 <= value <= _MAX_RANK:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _module(raw: dict[str, Any], module_path: str) -> _Module:
|
||||
return _Module(module_path, _text(raw.get("platform"), _MAX_PLATFORM),
|
||||
_rank(raw.get("rank")), _text(raw.get("mod_time"), _MAX_UPDATED))
|
||||
|
||||
|
||||
def _parse(raw: object) -> dict[str, tuple[_Module, ...]]:
|
||||
if not isinstance(raw, dict):
|
||||
raise InvalidData("expected a Metasploit metadata object")
|
||||
found: dict[str, dict[str, _Module]] = {}
|
||||
for entry in raw.values():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
module_path = _path(entry.get("path"))
|
||||
references = entry.get("references")
|
||||
if module_path is None or not isinstance(references, list):
|
||||
continue
|
||||
cves = {
|
||||
reference.strip().upper() for reference in references
|
||||
if isinstance(reference, str) and _CVE.fullmatch(reference.strip())
|
||||
}
|
||||
if not cves:
|
||||
continue
|
||||
module = _module(entry, module_path)
|
||||
for cve in cves:
|
||||
found.setdefault(cve, {}).setdefault(module_path, module)
|
||||
if not found:
|
||||
raise InvalidData("Metasploit metadata carries no CVE references")
|
||||
return {
|
||||
cve: tuple(sorted(modules.values(), key=lambda item: (
|
||||
-(item.rank if item.rank is not None else -1), item.module_path)))
|
||||
for cve, modules in found.items()
|
||||
}
|
||||
|
||||
|
||||
def _no_store(headers: Mapping[str, str]) -> bool:
|
||||
return any(
|
||||
part.partition("=")[0].strip().casefold() == "no-store"
|
||||
for key, value in headers.items() if key.casefold() == "cache-control"
|
||||
for part in value.split(",")
|
||||
)
|
||||
|
||||
|
||||
def _empty(cacheable: bool = True, *, status: str = "ok", retry_at: str | None = None) -> ProviderPage:
|
||||
return ProviderPage(
|
||||
cacheable=cacheable,
|
||||
status=Status(source=_SOURCE, status=status, retry_at=retry_at,
|
||||
as_of=datetime.now(UTC).isoformat() if status == "ok" else None),
|
||||
)
|
||||
|
||||
|
||||
def _document(cve: str, modules: tuple[_Module, ...], fetched: str, validator: str | None) -> Doc:
|
||||
refs = []
|
||||
for module in modules:
|
||||
reference: dict[str, Any] = {
|
||||
"type": "metasploit_module",
|
||||
"url": _BLOB + module.module_path,
|
||||
"module_path": module.module_path,
|
||||
"index": _INDEX_NAME,
|
||||
"index_snapshot": True,
|
||||
"index_fetched_at": fetched,
|
||||
"verified_against_build": False,
|
||||
}
|
||||
if module.platform is not None:
|
||||
reference["platform"] = module.platform
|
||||
if module.rank is not None:
|
||||
reference["rank"] = module.rank
|
||||
if module.updated is not None:
|
||||
reference["module_updated_at"] = module.updated
|
||||
if validator is not None:
|
||||
reference["index_revision"] = validator
|
||||
refs.append(reference)
|
||||
dated = [module.updated for module in modules if module.updated is not None]
|
||||
return Doc(
|
||||
source=_SOURCE, native_id=cve, publisher=_PUBLISHER, url=_INDEX_URL_HTML,
|
||||
title=f"Metasploit Framework modules referencing {cve}", updated=max(dated, default=None),
|
||||
issues=[Issue(id=cve, facts={"exploit_refs": refs})],
|
||||
)
|
||||
|
||||
|
||||
async def lookup_metasploit(
|
||||
kind: str, value: str, *, http: _LiveHttp, deadline: float, continuation: str | None = None,
|
||||
) -> ProviderPage:
|
||||
"""Revalidate the index for a warm process; warm it in the background when cold."""
|
||||
cve = value.upper() if isinstance(value, str) and value.isascii() else ""
|
||||
if kind != "id" or continuation is not None or _CVE.fullmatch(cve) is None:
|
||||
return _empty(cacheable=False, status="invalid_data")
|
||||
state = _state(http)
|
||||
if state.mapping is None:
|
||||
await _cold(state, http, deadline)
|
||||
else:
|
||||
async with state.lock:
|
||||
await _fetch(state, http, deadline, fresh=False)
|
||||
return _result(state, cve)
|
||||
|
||||
|
||||
async def _cold(state: _State, http: _LiveHttp, deadline: float) -> None:
|
||||
"""One shared download. The task carries its own budget and outlives the search."""
|
||||
async with state.lock:
|
||||
if state.task is None:
|
||||
state.task = asyncio.create_task(_fetch(state, http, monotonic(), fresh=True))
|
||||
task = state.task
|
||||
wait = deadline - monotonic()
|
||||
if wait <= 0:
|
||||
# Callers pass either an absolute monotonic deadline or a bare budget.
|
||||
wait = _WAIT_SECONDS
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(task), wait)
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
# Still downloading: report the state rather than stall the search.
|
||||
pass
|
||||
|
||||
|
||||
async def _fetch(state: _State, http: _LiveHttp, deadline: float, *, fresh: bool) -> None:
|
||||
"""Conditional GET plus parse. The previous mapping survives any failure."""
|
||||
try:
|
||||
raw, headers = await http.json(
|
||||
_SOURCE, _INDEX_URL, deadline=deadline, budget=_REFRESH_SECONDS if fresh else None,
|
||||
)
|
||||
state.no_store = _no_store(headers)
|
||||
validator = headers.get("ETag") or headers.get("Last-Modified")
|
||||
state.retry_at = None
|
||||
if state.mapping is not None and validator is not None and validator == state.validator:
|
||||
state.last = "ok"
|
||||
return
|
||||
state.mapping = await worker(_parse, raw)
|
||||
state.validator, state.last = validator, "ok"
|
||||
except HttpError as exc:
|
||||
state.retry_at = exc.retry_at
|
||||
# The framework may drop the generated artefact without releasing modules.
|
||||
state.last = "ok" if exc.status == "not_found" else exc.status
|
||||
if exc.status == "not_found":
|
||||
state.mapping = {}
|
||||
except InvalidData:
|
||||
state.last = "invalid_data"
|
||||
finally:
|
||||
state.task = None
|
||||
|
||||
|
||||
def _result(state: _State, cve: str) -> ProviderPage:
|
||||
mapping = state.mapping
|
||||
if mapping is None:
|
||||
return _empty(cacheable=False, status=state.last or "initializing", retry_at=state.retry_at)
|
||||
# A failed revision is not adopted, but its status still describes this check.
|
||||
failed = state.last not in (None, "ok")
|
||||
modules = () if failed else mapping.get(cve, ())
|
||||
fetched = datetime.now(UTC).isoformat()
|
||||
return ProviderPage(
|
||||
docs=[_document(cve, modules, fetched, state.validator)] if modules else [],
|
||||
cacheable=not state.no_store and not failed,
|
||||
status=Status(source=_SOURCE, as_of=fetched, status=state.last or "ok", retry_at=state.retry_at),
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""ProjectDiscovery nuclei-templates detection coverage for a CVE.
|
||||
|
||||
Templates sit at a deterministic per-CVE path, so a bounded ordered probe is
|
||||
cheaper than downloading and caching the whole recursive tree listing. Only
|
||||
the protocol directories that actually carry a ``cves`` tree are probed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from datetime import UTC, datetime
|
||||
from time import monotonic
|
||||
from typing import Protocol
|
||||
|
||||
from ..models import Doc, Issue, ProviderPage, Status
|
||||
from ..transport import HttpError
|
||||
from .parsers import InvalidData
|
||||
|
||||
_SOURCE = "nuclei"
|
||||
_HOST = "raw.githubusercontent.com"
|
||||
_ORIGIN = "https://" + _HOST
|
||||
_REPOSITORY = "/projectdiscovery/nuclei-templates/main/"
|
||||
_PUBLISHER = "ProjectDiscovery nuclei-templates"
|
||||
# Ordered by observed prevalence; dns/ and file/ have no cves/ tree.
|
||||
_PROTOCOLS = ("http", "network", "javascript", "headless")
|
||||
_MAX_PROBES = len(_PROTOCOLS)
|
||||
_LIMIT = 1024 * 1024
|
||||
_CVE = re.compile(r"CVE-[0-9]{4}-[0-9]{4,12}", re.ASCII | re.I)
|
||||
_PATH = re.compile(
|
||||
rf"/projectdiscovery/nuclei-templates/main/(?:{'|'.join(_PROTOCOLS)})/cves/"
|
||||
rf"[0-9]{{4}}/CVE-[0-9]{{4}}-[0-9]{{4,12}}\.yaml",
|
||||
re.ASCII,
|
||||
)
|
||||
_ID = re.compile(r"id:[ \t]*(.+?)\s*$")
|
||||
_NAME = re.compile(r"\s+name:[ \t]*(.+?)\s*$")
|
||||
|
||||
|
||||
class _LiveHttp(Protocol):
|
||||
async def bytes(
|
||||
self, source: str, url: str, *, deadline: float, limit: int,
|
||||
) -> tuple[bytes, Mapping[str, str]]: ...
|
||||
|
||||
|
||||
def allowed(host: str, path: str, *, live: bool) -> bool:
|
||||
return live and host == _HOST and _PATH.fullmatch(path) is not None
|
||||
|
||||
|
||||
def _scalar(value: str) -> str:
|
||||
text = value.strip()
|
||||
if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"":
|
||||
text = text[1:-1]
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def _template(raw: bytes, cve: str) -> dict[str, str] | None:
|
||||
"""Read only the top-level id and info name; the rest of the YAML is noise."""
|
||||
if len(raw) > _LIMIT:
|
||||
return None
|
||||
try:
|
||||
text = raw.decode("utf-8").lstrip("\ufeff")
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
identifier: str | None = None
|
||||
name: str | None = None
|
||||
in_info = False
|
||||
for line in text.splitlines():
|
||||
if not line:
|
||||
continue
|
||||
if line[:1] in {" ", "\t"}:
|
||||
if in_info and name is None and (match := _NAME.fullmatch(line)):
|
||||
name = _scalar(match[1]) or None
|
||||
continue
|
||||
if (match := _ID.fullmatch(line)) is not None and identifier is None:
|
||||
identifier = _scalar(match[1]).split(" ", 1)[0]
|
||||
in_info = line.split("#", 1)[0].strip() == "info:"
|
||||
if identifier is None or identifier.casefold() != cve.casefold():
|
||||
return None
|
||||
return {"name": name or cve}
|
||||
|
||||
|
||||
def _url(protocol: str, cve: str) -> str:
|
||||
year = cve[4:8]
|
||||
return f"{_ORIGIN}{_REPOSITORY}{protocol}/cves/{year}/{cve}.yaml"
|
||||
|
||||
|
||||
def _doc(cve: str, ref: dict[str, str]) -> Doc:
|
||||
return Doc(
|
||||
source=_SOURCE, native_id=cve, publisher=_PUBLISHER, url=ref["url"], title=ref["template_name"],
|
||||
issues=[Issue(id=cve, facts={"exploit_refs": [ref]})],
|
||||
)
|
||||
|
||||
|
||||
async def lookup_nuclei(
|
||||
kind: str, value: object, *, http: _LiveHttp, deadline: float, continuation: str | None = None,
|
||||
) -> ProviderPage:
|
||||
"""Probe the fixed protocol order and stop at the first matching template."""
|
||||
if kind != "id" or continuation is not None or not isinstance(value, str) or not _CVE.fullmatch(value):
|
||||
return ProviderPage(status=Status(source=_SOURCE, status="invalid_data"))
|
||||
cve = value.upper()
|
||||
docs: list[Doc] = []
|
||||
probed = 0
|
||||
while probed < _MAX_PROBES:
|
||||
if deadline - monotonic() <= 0.05:
|
||||
return ProviderPage(docs=docs, cacheable=False,
|
||||
status=Status(source=_SOURCE, status="timeout" if not docs else "ok"))
|
||||
protocol = _PROTOCOLS[probed]
|
||||
probed += 1
|
||||
url = _url(protocol, cve)
|
||||
try:
|
||||
raw, _ = await http.bytes(_SOURCE, url, deadline=deadline, limit=_LIMIT)
|
||||
except HttpError as exc:
|
||||
if exc.status == "not_found":
|
||||
continue
|
||||
return ProviderPage(docs=docs, cacheable=False,
|
||||
status=Status(source=_SOURCE, status=exc.status, retry_at=exc.retry_at))
|
||||
except InvalidData:
|
||||
return ProviderPage(docs=docs, cacheable=False,
|
||||
status=Status(source=_SOURCE, status="invalid_data"))
|
||||
parsed = _template(raw, cve)
|
||||
if parsed is None:
|
||||
continue
|
||||
docs.append(_doc(cve, {
|
||||
"type": "detection_template", "url": url, "protocol": protocol,
|
||||
"template_name": parsed["name"],
|
||||
}))
|
||||
break
|
||||
return ProviderPage(docs=docs, status=Status(source=_SOURCE, as_of=datetime.now(UTC).isoformat()))
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Community proof-of-concept repositories that merely exist alongside a CVE.
|
||||
|
||||
Neither index verifies that the code runs; the adapter only reports that a
|
||||
repository was listed for the exact CVE.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import Any, Protocol
|
||||
|
||||
from ..models import Doc, Issue, ProviderPage, Status, utc_now
|
||||
from ..transport import HttpError
|
||||
from .parsers import InvalidData
|
||||
|
||||
_SOURCE = "pocs"
|
||||
_HOST = "raw.githubusercontent.com"
|
||||
_POCS = "/nomi-sec/PoC-in-GitHub/master"
|
||||
_TRICKEST = "/trickest/cve/main"
|
||||
_BASE = f"https://{_HOST}"
|
||||
_CVE = re.compile(r"CVE-([0-9]{4})-([0-9]{4,})", re.I | re.ASCII)
|
||||
_ANY_CVE = re.compile(r"CVE-([0-9]{4})-[0-9]{4,}", re.I | re.ASCII)
|
||||
_REPO_URL = re.compile(r"https://github\.com/([A-Za-z0-9_.-]{1,100})/([A-Za-z0-9_.-]{1,100})(?:\.git)?/?")
|
||||
_LISTED = re.compile(r"^[-*]\s+(?:\[[^\]\n]*\]\(\s*)?(https://github\.com/[^\s)]+)\)?\s*$")
|
||||
_HEADING = re.compile(r"^#{1,6}\s+\[?(CVE-[0-9]{4}-[0-9]{4,})\]?", re.I | re.M)
|
||||
_GITHUB = re.compile(r"^#{1,6}\s+Github\s*$", re.I | re.M)
|
||||
_HEADING_ANY = re.compile(r"^#{1,6}\s", re.M)
|
||||
_JSON_PATH = re.compile(rf"{_POCS}/([0-9]{{4}})/CVE-([0-9]{{4}})-[0-9]{{4,}}\.json")
|
||||
_MD_PATH = re.compile(rf"{_TRICKEST}/([0-9]{{4}})/CVE-([0-9]{{4}})-[0-9]{{4,}}\.md")
|
||||
_MAX_REFS = 10
|
||||
_LIMIT = 8 * 1024**2
|
||||
|
||||
__all__ = ["allowed", "lookup_pocs"]
|
||||
|
||||
|
||||
class _LiveHttp(Protocol):
|
||||
async def bytes(
|
||||
self, source: str, url: str, *, deadline: float, limit: int,
|
||||
) -> tuple[bytes, Mapping[str, str]]: ...
|
||||
|
||||
|
||||
def allowed(host: str, path: str, *, live: bool) -> bool:
|
||||
if not live or host != _HOST:
|
||||
return False
|
||||
for pattern in (_JSON_PATH, _MD_PATH):
|
||||
match = pattern.fullmatch(path)
|
||||
if match is not None and match[1] == match[2]:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _repo(value: object) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
match = _REPO_URL.fullmatch(value.strip())
|
||||
if match is None:
|
||||
return None
|
||||
return f"https://github.com/{match[1]}/{match[2]}"
|
||||
|
||||
|
||||
def _wrong_year(text: str, year: str) -> bool:
|
||||
# A generic repository may cover several CVEs; drop only mismatched identities.
|
||||
years = [match[1] for match in _ANY_CVE.finditer(text)]
|
||||
return bool(years) and year not in years
|
||||
|
||||
|
||||
def _ref(repo: str, stars: object = None) -> dict[str, Any]:
|
||||
ref: dict[str, Any] = {"type": "poc_repo", "url": repo + "/blob/HEAD", "repo": repo}
|
||||
if type(stars) is int and stars >= 0:
|
||||
ref["stars"] = stars
|
||||
return ref
|
||||
|
||||
|
||||
def _json_refs(raw: bytes, year: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
text = raw.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
raise InvalidData("PoC JSON is not UTF-8") from None
|
||||
if text.lstrip()[:1] not in {"[", "{"}:
|
||||
return [] # An HTML or plain error page makes no structural claim.
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except ValueError:
|
||||
raise InvalidData("PoC JSON is not parseable") from None
|
||||
if not isinstance(data, list):
|
||||
raise InvalidData("unexpected PoC JSON shape")
|
||||
refs = []
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
raise InvalidData("unexpected PoC JSON entry")
|
||||
name = row.get("full_name") if isinstance(row.get("full_name"), str) else row.get("name")
|
||||
if isinstance(name, str) and _wrong_year(name, year):
|
||||
continue
|
||||
repo = _repo(row.get("html_url"))
|
||||
if repo is not None:
|
||||
refs.append(_ref(repo, row.get("stargazers_count", row.get("stars"))))
|
||||
return refs
|
||||
|
||||
|
||||
def _markdown_refs(raw: bytes, cve: str, year: str) -> list[dict[str, Any]]:
|
||||
text = raw.decode("utf-8", "replace")
|
||||
heading = _HEADING.search(text)
|
||||
if heading is None and _GITHUB.search(text) is None:
|
||||
return []
|
||||
if heading is not None and heading[1].upper() != cve:
|
||||
raise InvalidData("trickest page is for another CVE")
|
||||
section = _GITHUB.search(text)
|
||||
if section is None:
|
||||
return []
|
||||
rest = text[section.end():]
|
||||
stop = _HEADING_ANY.search(rest)
|
||||
body = rest[:stop.start()] if stop is not None else rest
|
||||
refs = []
|
||||
for line in body.splitlines():
|
||||
listed = _LISTED.match(line.strip())
|
||||
if listed is None:
|
||||
continue
|
||||
repo = _repo(listed[1])
|
||||
if repo is not None and not _wrong_year(repo, year):
|
||||
refs.append(_ref(repo))
|
||||
if not refs:
|
||||
raise InvalidData("empty trickest repository section")
|
||||
return refs
|
||||
|
||||
|
||||
def _unique(parts: list[tuple[str, str, list[dict[str, Any]]]]) -> list[tuple[str, str, list[dict[str, Any]]]]:
|
||||
"""Keep both publishers represented instead of letting the first fill the cap."""
|
||||
seen: set[str] = set()
|
||||
kept: list[list[dict[str, Any]]] = [[] for _ in parts]
|
||||
cursors = [0] * len(parts)
|
||||
while len(seen) < _MAX_REFS:
|
||||
progressed = False
|
||||
for position, (_, _, refs) in enumerate(parts):
|
||||
while cursors[position] < len(refs):
|
||||
ref = refs[cursors[position]]
|
||||
cursors[position] += 1
|
||||
key = ref["repo"].casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
kept[position].append(ref)
|
||||
progressed = True
|
||||
break
|
||||
if len(seen) >= _MAX_REFS:
|
||||
break
|
||||
if not progressed:
|
||||
break
|
||||
return [(publisher, url, refs) for (publisher, url, _), refs in zip(parts, kept, strict=True)]
|
||||
|
||||
|
||||
async def lookup_pocs(
|
||||
kind: str, value: object, *, http: _LiveHttp, deadline: float, continuation: str | None = None,
|
||||
) -> ProviderPage:
|
||||
"""Read both community indexes for exactly one CVE, through the live route only."""
|
||||
invalid = ProviderPage(cacheable=False, status=Status(source=_SOURCE, status="invalid_data"))
|
||||
if kind != "id" or continuation is not None or not isinstance(value, str):
|
||||
return invalid
|
||||
match = _CVE.fullmatch(value.strip())
|
||||
if match is None:
|
||||
return invalid
|
||||
cve, year = match[0].upper(), match[1]
|
||||
|
||||
fetched: list[tuple[str, str, list[dict[str, Any]]]] = []
|
||||
failed = False
|
||||
failure: HttpError | None = None
|
||||
sources: tuple[tuple[str, str, str, Callable[[bytes], list[dict[str, Any]]]], ...] = (
|
||||
(_POCS, ".json", "nomi-sec/PoC-in-GitHub", lambda raw: _json_refs(raw, year)),
|
||||
(_TRICKEST, ".md", "trickest/cve", lambda raw: _markdown_refs(raw, cve, year)),
|
||||
)
|
||||
for prefix, suffix, publisher, parser in sources:
|
||||
url = f"{_BASE}{prefix}/{year}/{cve}{suffix}"
|
||||
try:
|
||||
raw, _ = await http.bytes(_SOURCE, url, deadline=deadline, limit=_LIMIT)
|
||||
refs = await asyncio.to_thread(parser, raw)
|
||||
except HttpError as exc:
|
||||
if exc.status != "not_found":
|
||||
failed = True
|
||||
failure = failure or exc
|
||||
continue
|
||||
except (InvalidData, ValueError, RecursionError):
|
||||
failed = True
|
||||
continue
|
||||
if refs:
|
||||
doc_url = f"https://github.com/{publisher}/blob/HEAD/{year}/{cve}{suffix}"
|
||||
fetched.append((publisher, doc_url, refs))
|
||||
|
||||
kept = _unique(fetched)
|
||||
docs = [
|
||||
Doc(source=_SOURCE, native_id=cve, publisher=publisher, title=cve, url=doc_url,
|
||||
issues=[Issue(id=cve, facts={"exploit_refs": refs})])
|
||||
for publisher, doc_url, refs in kept if refs
|
||||
]
|
||||
if docs:
|
||||
return ProviderPage(docs=docs, status=Status(source=_SOURCE, as_of=utc_now()))
|
||||
if failure is not None:
|
||||
return ProviderPage(cacheable=False,
|
||||
status=Status(source=_SOURCE, status=failure.status, retry_at=failure.retry_at))
|
||||
if failed:
|
||||
return invalid
|
||||
return ProviderPage(status=Status(source=_SOURCE, as_of=utc_now()))
|
||||
@@ -362,6 +362,11 @@ async def lookup(
|
||||
if source == "web":
|
||||
from .feed_web import lookup_web
|
||||
return await lookup_web(kind, value, http=http, deadline=deadline, continuation=continuation)
|
||||
if source in {"pocs", "nuclei", "metasploit"}:
|
||||
from . import feed_metasploit, feed_nuclei, feed_pocs
|
||||
module = {"pocs": feed_pocs, "nuclei": feed_nuclei, "metasploit": feed_metasploit}[source]
|
||||
function = getattr(module, f"lookup_{source}")
|
||||
return await function(kind, value, http=http, deadline=deadline, continuation=continuation)
|
||||
if source == "paloalto":
|
||||
from .feed_paloalto import lookup_paloalto
|
||||
return await lookup_paloalto(kind, value, http=http, deadline=deadline, continuation=continuation)
|
||||
|
||||
@@ -188,6 +188,50 @@ def _ssvc(metric: dict[str, Any], cve: str) -> dict[str, str] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _ssvc_profile(metric: dict[str, Any]) -> dict[str, str]:
|
||||
"""The two CISA decision points that bound how much operator work exploitation takes."""
|
||||
other = metric.get("other")
|
||||
content = other.get("content") if isinstance(other, dict) and other.get("type") == "ssvc" else None
|
||||
if not isinstance(content, dict) or not isinstance(content.get("options"), list):
|
||||
return {}
|
||||
found: dict[str, str] = {}
|
||||
for option in content["options"]:
|
||||
if not isinstance(option, dict):
|
||||
continue
|
||||
for key, field in (("automatable", "Automatable"), ("technical_impact", "Technical Impact")):
|
||||
value = option.get(field)
|
||||
if isinstance(value, str) and len(value) <= 24:
|
||||
found.setdefault(key, value)
|
||||
return found
|
||||
|
||||
|
||||
_CVSS_FIELDS = {"AV": "cvss_av", "PR": "cvss_pr", "UI": "cvss_ui"}
|
||||
_CPE_ROLES = {"a": "application", "o": "operating_system", "h": "hardware"}
|
||||
|
||||
|
||||
def _vector_profile(vector: object) -> dict[str, str]:
|
||||
"""Path and interaction requirements, read from the beginning of the CVSS vector."""
|
||||
if not isinstance(vector, str) or len(vector) > 160:
|
||||
return {}
|
||||
found: dict[str, str] = {}
|
||||
for part in vector.split("/")[:8]:
|
||||
metric, _, value = part.partition(":")
|
||||
field = _CVSS_FIELDS.get(metric.upper())
|
||||
if field and value and len(value) <= 8:
|
||||
found.setdefault(field, value)
|
||||
return found
|
||||
|
||||
|
||||
def _note_profile(issue: "Issue", profile: dict[str, str]) -> None:
|
||||
"""Merge only absent keys: a later publisher never overwrites an earlier assertion."""
|
||||
if not profile:
|
||||
return
|
||||
target = issue.facts.setdefault("exploitation", {})
|
||||
if isinstance(target, dict):
|
||||
for key, value in profile.items():
|
||||
target.setdefault(key, value)
|
||||
|
||||
|
||||
def _refs(raw: object) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for value in _array(raw):
|
||||
@@ -298,6 +342,15 @@ def _cve(source: str, raw: dict[str, Any], url: str) -> Doc:
|
||||
origin = _str(provider.get("shortName") or provider.get("orgId") or publisher)
|
||||
issue.products.extend(row for product in _array(value.get("affected", []))
|
||||
for row in _cve_product(_obj(product), origin))
|
||||
# CPE part separates a directly exposed component from its platform.
|
||||
for product in issue.products:
|
||||
part = product.get("cpe_part")
|
||||
if part is None:
|
||||
listed = product.get("cpes")
|
||||
if isinstance(listed, list) and listed and isinstance(listed[0], str):
|
||||
part = _cpe(listed[0]).get("cpe_part")
|
||||
if role := _CPE_ROLES.get(str(part)):
|
||||
_note_profile(issue, {"component_role": role})
|
||||
issue.refs.extend(dict(ref, publisher=origin) for ref in _refs(value.get("references", [])))
|
||||
if any(_publication_reference(row.get("url")) for row in value.get("references", [])):
|
||||
signal = _compact(status="public_poc", publisher=origin, catalog="Exploit-DB",
|
||||
@@ -309,13 +362,16 @@ def _cve(source: str, raw: dict[str, Any], url: str) -> Doc:
|
||||
if isinstance(cwe, str) and re.fullmatch(r"CWE-\d+", cwe):
|
||||
issue.facts["cwe"].append({"id": cwe, "publisher": origin})
|
||||
for metric in _array(value.get("metrics", [])):
|
||||
raw_metric = _obj(metric)
|
||||
if value is not cna and provider.get("orgId") == "134c704f-9b21-4f2e-91b3-4a467353bcc0":
|
||||
assessment = _ssvc(_obj(metric), cve)
|
||||
assessment = _ssvc(raw_metric, cve)
|
||||
if assessment:
|
||||
issue.facts.setdefault("exploitation_evidence", []).append(assessment)
|
||||
for key, score in _obj(metric).items():
|
||||
_note_profile(issue, _ssvc_profile(raw_metric))
|
||||
for key, score in raw_metric.items():
|
||||
if key.startswith("cvssV") and (fact := _cvss(_obj(score), origin)):
|
||||
issue.facts["cvss"].append(fact)
|
||||
_note_profile(issue, _vector_profile(fact.get("vector")))
|
||||
for impact in _array(value.get("impacts", [])):
|
||||
row = _obj(impact)
|
||||
prose = _localized(row.get("descriptions", []))
|
||||
|
||||
@@ -176,6 +176,10 @@ def _get_allowed(source: str, host: str, path: str, *, live: bool, previous: str
|
||||
if source == "fortinet":
|
||||
from .sources.feed_fortinet import allowed
|
||||
return allowed(host, path, live=live)
|
||||
if source in {"pocs", "nuclei", "metasploit"} and live:
|
||||
from .sources import feed_metasploit, feed_nuclei, feed_pocs
|
||||
module = {"pocs": feed_pocs, "nuclei": feed_nuclei, "metasploit": feed_metasploit}[source]
|
||||
return module.allowed(host, path, live=live)
|
||||
if source == "paloalto":
|
||||
from .sources.feed_paloalto import allowed
|
||||
return allowed(host, path, live=live)
|
||||
@@ -734,9 +738,10 @@ class LiveHttp:
|
||||
async def json(
|
||||
self, source: str, url: str, *, params: _Params | None = None,
|
||||
body: Mapping[str, Any] | None = None, deadline: float | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
headers: Mapping[str, str] | None = None, budget: float | None = None,
|
||||
) -> tuple[Any, httpx.Headers]:
|
||||
deadline = _deadline(deadline, _LIVE_SECONDS)
|
||||
# A background refresh of a large artefact needs more than the per-search cap.
|
||||
deadline = monotonic() + budget if budget is not None else _deadline(deadline, _LIVE_SECONDS)
|
||||
method = "POST" if body is not None else "GET"
|
||||
requested = _parsed_url(source, url, True, method, params)
|
||||
outbound = _headers(headers, "application/json")
|
||||
|
||||
+85
-1
@@ -1,9 +1,15 @@
|
||||
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.feed_exploitdb import _catalog, _dates
|
||||
from vuln_mcp.sources.parsers import InvalidData
|
||||
|
||||
HEADER = 'id,file,description,date_published,type,platform,date_added,date_updated,tags,codes,verified\n'
|
||||
|
||||
|
||||
def _row(edb_id, day, kind, codes, verified='0', platform='Linux', tags=''):
|
||||
return f'{edb_id},f,Example,{day},{kind},{platform},{day},{day},{tags},{codes},{verified}\n'
|
||||
|
||||
|
||||
def test_publication_dates_require_explicit_cve_and_keep_earliest(tmp_path):
|
||||
path = tmp_path / 'catalog.csv'
|
||||
@@ -52,3 +58,81 @@ async def test_secondary_csv_keeps_only_count_and_never_adds_cve_evidence(tmp_pa
|
||||
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'
|
||||
|
||||
|
||||
def test_exploit_refs_prefer_type_then_verified_then_newest(tmp_path):
|
||||
path = tmp_path / 'catalog.csv'
|
||||
path.write_text(HEADER
|
||||
+ _row(10, '2024-01-01', 'remote', 'CVE-2024-1000', '1', tags='Metasploit')
|
||||
+ _row(11, '2024-05-01', 'webapps', 'CVE-2024-1000', '1')
|
||||
+ _row(12, '2024-06-01', 'local', 'CVE-2024-1000', '1')
|
||||
+ _row(13, '2024-07-01', 'dos', 'CVE-2024-1000', '1')
|
||||
+ _row(14, '2024-09-01', 'remote', 'CVE-2024-1000')
|
||||
+ _row(15, '2024-03-01', 'remote', 'CVE-2024-1000', '1', tags='Metasploit'))
|
||||
dates, refs = _catalog(path)
|
||||
assert dates == {'CVE-2024-1000': '2024-01-01'}
|
||||
[ref] = [refs['CVE-2024-1000']]
|
||||
assert [item['edb_id'] for item in ref] == ['15', '10', '14', '11', '12', '13']
|
||||
assert ref[0] == {'type': 'exploit_db', 'url': 'https://www.exploit-db.com/exploits/15',
|
||||
'edb_id': '15', 'exploit_type': 'remote', 'platform': 'Linux',
|
||||
'verified': True, 'tags': ['Metasploit']}
|
||||
|
||||
|
||||
def test_exploit_refs_dedup_by_url_and_cap_per_cve(tmp_path):
|
||||
path = tmp_path / 'catalog.csv'
|
||||
rows = ''.join(_row(100 + number, f'2024-01-{number:02d}', 'remote', 'CVE-2024-1000',
|
||||
'1' if number <= 2 else '0') for number in range(1, 13))
|
||||
path.write_text(HEADER + _row(101, '2023-12-31', 'remote', 'CVE-2024-1000', '1') + rows)
|
||||
_, refs = _catalog(path)
|
||||
found = refs['CVE-2024-1000']
|
||||
assert len(found) == 8
|
||||
assert len({item['url'] for item in found}) == 8
|
||||
assert [item['edb_id'] for item in found] == ['102', '101', '112', '111', '110', '109', '108', '107']
|
||||
|
||||
|
||||
def test_exploit_ref_fans_out_to_every_listed_cve_and_skips_unknown_type(tmp_path):
|
||||
path = tmp_path / 'catalog.csv'
|
||||
path.write_text(HEADER
|
||||
+ _row(20, '2024-01-01', 'local', 'CVE-2024-2000; CVE-2024-2001')
|
||||
+ _row(21, '2024-01-02', 'unranked', 'CVE-2024-2000')
|
||||
+ _row('bad', '2024-01-03', 'remote', 'CVE-2024-2000'))
|
||||
dates, refs = _catalog(path)
|
||||
assert dates == {'CVE-2024-2000': '2024-01-01', 'CVE-2024-2001': '2024-01-01'}
|
||||
assert refs['CVE-2024-2000'] == refs['CVE-2024-2001']
|
||||
[ref] = refs['CVE-2024-2000']
|
||||
assert ref['edb_id'] == '20' and ref['exploit_type'] == 'local'
|
||||
|
||||
|
||||
def test_catalogue_with_partial_ref_columns_or_broken_row_fails(tmp_path):
|
||||
partial = tmp_path / 'partial.csv'
|
||||
partial.write_text('codes,date_published,id\nCVE-2024-1000,2024-01-01,1\n')
|
||||
with pytest.raises(InvalidData):
|
||||
_catalog(partial)
|
||||
broken = tmp_path / 'broken.csv'
|
||||
broken.write_text(HEADER + _row(1, '2024-01-01', 'remote', 'CVE-2024-1000')[:-4] + '\n')
|
||||
with pytest.raises(InvalidData):
|
||||
_catalog(broken)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_refresh_publishes_refs_alongside_publication_evidence(tmp_path):
|
||||
from vuln_mcp.sources.feed_exploitdb import CATALOG
|
||||
|
||||
class Wire:
|
||||
async def download(self, source, url, path, *, headers, limit):
|
||||
assert source == 'exploitdb' and url == CATALOG and not headers
|
||||
path.write_text(HEADER
|
||||
+ _row(30, '2024-02-01', 'remote', 'CVE-2024-3000', '1')
|
||||
+ _row(31, '2024-01-01', 'webapps', 'CVE-2024-3000;CVE-2024-3001'))
|
||||
return 200, {'etag': 'v1'}
|
||||
|
||||
async with Store(tmp_path) as store:
|
||||
sync = Sync(store, Wire())
|
||||
assert await sync.refresh_once('exploitdb')
|
||||
[doc] = await store.by_id('CVE-2024-3000')
|
||||
[issue] = doc.issues
|
||||
assert [ref['edb_id'] for ref in issue.facts['exploit_refs']] == ['30', '31']
|
||||
assert issue.facts['exploitation_evidence'][0]['date'] == '2024-01-01'
|
||||
[other] = await store.by_id('CVE-2024-3001')
|
||||
assert [ref['edb_id'] for ref in other.issues[0].facts['exploit_refs']] == ['31']
|
||||
assert len(other.issues[0].facts['exploit_refs']) == 1
|
||||
@@ -0,0 +1,147 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from vuln_mcp.matching import make_asset
|
||||
from vuln_mcp.models import AssetFacts, Doc, Issue, Status
|
||||
from vuln_mcp.search import Claim, Group, Observation, _base_checks, _claim_coverage, _query, _render
|
||||
|
||||
CVE = 'CVE-2025-43715'
|
||||
OTHER = 'CVE-2025-43999'
|
||||
GHSA = 'GHSA-abcd-1234-wxyz'
|
||||
EDB = 'https://www.exploit-db.com/exploits/51001'
|
||||
MSF = 'https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/linux/http/cve_2025_43715.rb'
|
||||
POC = 'https://github.com/example/poc-cve-2025-43715'
|
||||
TEMPLATE = 'https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/main/http/cves/2025/CVE-2025-43715.yaml'
|
||||
|
||||
|
||||
def _claim(source: str, native: str, facts: dict, *, url: str | None = None, state: str = 'published') -> Claim:
|
||||
doc = Doc(source=source, native_id=native, publisher=source, url=url or f'https://example.test/{native}',
|
||||
title=native, state=state, issues=[Issue(id=native, facts=facts)])
|
||||
return Claim(Observation(doc, 'live'), doc.issues[0])
|
||||
|
||||
|
||||
def _group(*claims: Claim) -> Group:
|
||||
group = Group(CVE)
|
||||
group.claims.extend(claims)
|
||||
return group
|
||||
|
||||
|
||||
def _index() -> dict[str, Status]:
|
||||
return {source: Status(source=source, status='initializing') for source in
|
||||
('kev', 'exploitdb', 'msrc', 'pocs', 'nuclei', 'metasploit')}
|
||||
|
||||
|
||||
def _hit(group: Group, asset: AssetFacts | None = None):
|
||||
query = _query(CVE, None)
|
||||
target = make_asset('id', CVE, asset)
|
||||
return _render(group, query, target, [], _index())
|
||||
|
||||
|
||||
def test_refs_are_ordered_by_type_then_url() -> None:
|
||||
group = _group(
|
||||
_claim('pocs', CVE, {'exploit_refs': [{'type': 'poc_repo', 'url': POC}]}),
|
||||
_claim('nuclei', CVE, {'exploit_refs': [{'type': 'detection_template', 'url': TEMPLATE}]}),
|
||||
_claim('metasploit', CVE, {'exploit_refs': [{'type': 'metasploit_module', 'url': MSF}]}),
|
||||
_claim('exploitdb', CVE, {'exploit_refs': [{'type': 'exploit_db', 'url': EDB, 'edb_id': '51001'}]}),
|
||||
)
|
||||
assert [(ref['type'], ref['url']) for ref in _hit(group).exploit_refs] == [
|
||||
('exploit_db', EDB), ('metasploit_module', MSF), ('poc_repo', POC), ('detection_template', TEMPLATE),
|
||||
]
|
||||
|
||||
|
||||
def test_refs_dedup_by_type_and_url_and_keep_extra_fields() -> None:
|
||||
group = _group(
|
||||
_claim('exploitdb', CVE, {'exploit_refs': [
|
||||
{'type': 'exploit_db', 'url': EDB, 'edb_id': '51001', 'verified': True},
|
||||
{'type': 'exploit_db', 'url': EDB, 'edb_id': '51001'},
|
||||
]}),
|
||||
_claim('pocs', CVE, {'exploit_refs': [
|
||||
{'type': 'poc_repo', 'url': POC},
|
||||
{'type': 'poc_repo', 'url': POC},
|
||||
]}),
|
||||
)
|
||||
refs = _hit(group).exploit_refs
|
||||
assert [ref['url'] for ref in refs] == [EDB, POC]
|
||||
assert refs[0]['edb_id'] == '51001' and refs[0]['verified'] is True
|
||||
|
||||
|
||||
def test_refs_are_capped() -> None:
|
||||
urls = [f'https://www.exploit-db.com/exploits/{51000 + number}' for number in range(30)]
|
||||
group = _group(_claim('exploitdb', CVE, {'exploit_refs': [{'type': 'exploit_db', 'url': url} for url in urls]}))
|
||||
refs = _hit(group).exploit_refs
|
||||
assert len(refs) == 20
|
||||
assert refs[0]['url'] == urls[0]
|
||||
|
||||
|
||||
def test_unsafe_refs_are_dropped() -> None:
|
||||
unsafe = [
|
||||
{'type': 'exploit_db', 'url': EDB}, # exploit-db path would fail the source-ref filter
|
||||
{'type': 'poc_repo', 'url': 'http://github.com/example/insecure'},
|
||||
{'type': 'poc_repo', 'url': 'https://user:secret@github.com/example/userinfo'},
|
||||
{'type': 'poc_repo', 'url': 'https://github.com:8443/example/port'},
|
||||
{'type': 'poc_repo', 'url': 'not-a-url'},
|
||||
{'type': 'poc_repo', 'url': 'https:///no-host'},
|
||||
{'type': 'writeup', 'url': POC},
|
||||
{'type': 'poc_repo'},
|
||||
{'url': POC},
|
||||
'string-entry',
|
||||
]
|
||||
hit = _hit(_group(_claim('pocs', CVE, {'exploit_refs': unsafe})))
|
||||
assert hit.exploit_refs == [{'type': 'exploit_db', 'url': EDB}]
|
||||
assert hit.source_refs == []
|
||||
|
||||
|
||||
def test_exploitation_passthrough() -> None:
|
||||
values = {'automatable': 'yes', 'technical_impact': 'remote code execution', 'cvss_av': 'N',
|
||||
'cvss_pr': 'N', 'cvss_ui': 'N', 'component_role': 'management interface'}
|
||||
hit = _hit(_group(_claim('metasploit', CVE, {'exploitation': values})))
|
||||
assert hit.exploitation == values
|
||||
|
||||
|
||||
def test_exploitation_fills_missing_keys_and_skips_foreign_values() -> None:
|
||||
group = _group(
|
||||
_claim('metasploit', CVE, {'exploitation': {'automatable': 'yes', 'cvss_av': 'N', 'cvss_pr': 7}}),
|
||||
_claim('pocs', CVE, {'exploitation': {'technical_impact': 'denial of service', 'cvss_av': 'L',
|
||||
'component_role': None}}),
|
||||
)
|
||||
hit = _hit(group)
|
||||
assert hit.exploitation == {
|
||||
'automatable': 'yes', 'technical_impact': 'denial of service', 'cvss_av': 'N',
|
||||
'cvss_pr': None, 'cvss_ui': None, 'component_role': None,
|
||||
}
|
||||
assert _hit(_group(_claim('pocs', CVE, {}))).exploitation is None
|
||||
|
||||
|
||||
def test_verdict_and_fixes_are_unchanged() -> None:
|
||||
product = {'publisher': 'Siemens', 'name': 'Ctrl', 'model': 'M1', 'status': 'affected',
|
||||
'versions': ['1.3.0'], 'events': [{'introduced': '0'}, {'fixed': '1.3.1'}]}
|
||||
plain = _group(_claim('cvelist', CVE, {}, url='https://www.cve.org/CVERecord?id=' + CVE))
|
||||
plain.claims[0].issue.products.append(product)
|
||||
enriched = _group(
|
||||
_claim('cvelist', CVE, {}, url='https://www.cve.org/CVERecord?id=' + CVE),
|
||||
_claim('pocs', CVE, {'exploit_refs': [{'type': 'poc_repo', 'url': POC}],
|
||||
'exploitation': {'automatable': 'yes'}}),
|
||||
)
|
||||
enriched.claims[0].issue.products.append(product)
|
||||
asset = AssetFacts(product='M1', version='1.3.0')
|
||||
left, right = _hit(plain, asset), _hit(enriched, asset)
|
||||
assert (left.applicability, left.fixed_versions, left.match_reason) == ('affected', ['1.3.1'], 'exact_id')
|
||||
assert (right.applicability, right.fixed_versions, right.match_reason) == \
|
||||
(left.applicability, left.fixed_versions, left.match_reason)
|
||||
assert right.source_refs == left.source_refs
|
||||
assert right.exploit_refs == [{'type': 'poc_repo', 'url': POC}]
|
||||
|
||||
|
||||
def test_exploit_checks_are_scheduled_for_cves_only() -> None:
|
||||
planned = {(check.source, check.native_id) for check in _base_checks(CVE)}
|
||||
assert {('pocs', CVE), ('nuclei', CVE), ('metasploit', CVE)} <= planned
|
||||
assert all(check.native_id == CVE for check in _base_checks(CVE) if check.source in {'pocs', 'nuclei', 'metasploit'})
|
||||
assert {check.source for check in _base_checks(GHSA)} == {'osv', 'circl'}
|
||||
assert {check.source for check in _base_checks(OTHER)} >= {'pocs', 'nuclei', 'metasploit'}
|
||||
|
||||
|
||||
def test_unrun_exploit_checks_expose_coverage() -> None:
|
||||
hit = _hit(_group(_claim('cvelist', CVE, {})))
|
||||
assert hit.coverage == []
|
||||
statuses = _claim_coverage(_group(_claim('cvelist', CVE, {})), {}, _index())
|
||||
for source in ('pocs', 'nuclei', 'metasploit'):
|
||||
assert any(status.source == source and status.status == 'initializing' for status in statuses)
|
||||
@@ -0,0 +1,374 @@
|
||||
"""The upstream Metasploit metadata index is the only CVE-to-module authority."""
|
||||
|
||||
import asyncio
|
||||
from time import monotonic
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from vuln_mcp.models import ProviderPage
|
||||
from vuln_mcp.sources import feed_metasploit
|
||||
from vuln_mcp.sources.feed_metasploit import allowed, lookup_metasploit
|
||||
from vuln_mcp.transport import HttpError
|
||||
|
||||
INDEX = "https://raw.githubusercontent.com/rapid7/metasploit-framework/master/db/modules_metadata_base.json"
|
||||
BLOB = "https://github.com/rapid7/metasploit-framework/blob/master/"
|
||||
FLASH = "CVE-2021-44228"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
class FakeHttp:
|
||||
def __init__(self, *responses: object) -> None:
|
||||
self.responses = list(responses)
|
||||
self.calls: list[tuple[str, str, float]] = []
|
||||
|
||||
async def json(self, source: str, url: str, *, deadline: float, budget: float | None = None):
|
||||
self.calls.append((source, url, deadline))
|
||||
item = self.responses.pop(0)
|
||||
if isinstance(item, BaseException):
|
||||
raise item
|
||||
body, headers = item
|
||||
return body, httpx.Headers(headers)
|
||||
|
||||
|
||||
def _module(path: str, references: list[str], **extra: object) -> dict:
|
||||
return {"path": path, "references": references, **extra}
|
||||
|
||||
|
||||
def _index(*modules: dict) -> dict:
|
||||
return {f"module_{number}": module for number, module in enumerate(modules)}
|
||||
|
||||
|
||||
def _response(body: dict, etag: str = '"revision-1"') -> tuple[dict, dict]:
|
||||
return body, {"ETag": etag}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("host", "path", "live", "expected"), [
|
||||
("raw.githubusercontent.com", "/rapid7/metasploit-framework/master/db/modules_metadata_base.json", True, True),
|
||||
("raw.githubusercontent.com", "/rapid7/metasploit-framework/master/db/modules_metadata_base.json", False, False),
|
||||
("raw.githubusercontent.com", "/rapid7/metasploit-framework/master/db/modules_metadata.json", True, False),
|
||||
("github.com", "/rapid7/metasploit-framework/blob/master/db/modules_metadata_base.json", True, False),
|
||||
("raw.githubusercontent.com", "/rapid7/metasploit-framework/master/modules/exploits/a/b.rb", True, False),
|
||||
])
|
||||
def test_allowlist_is_live_index_only(host: str, path: str, live: bool, expected: bool) -> None:
|
||||
assert allowed(host, path, live=live) is expected
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_exact_references_map_to_validated_module_refs() -> None:
|
||||
body = _index(
|
||||
_module("/modules/exploits/multi/http/apache_log4j.rb", [FLASH, "URL-https://example.test"],
|
||||
platform="Java,Unix,Windows", rank=600, mod_time="2024-03-02 10:00:00 +0000"),
|
||||
_module("/modules/auxiliary/scanner/http/log4shell_scanner.rb", [FLASH.lower()],
|
||||
platform="", rank=300),
|
||||
_module("/modules/exploits/windows/http/other.rb", ["CVE-2019-0001"], rank=500),
|
||||
)
|
||||
http = FakeHttp(_response(body))
|
||||
page = await lookup_metasploit("id", "cve-2021-44228", http=http, deadline=10.0)
|
||||
assert page.status.status == "ok" and page.cacheable
|
||||
assert len(page.docs) == 1
|
||||
doc = page.docs[0]
|
||||
assert doc.source == "metasploit" and doc.native_id == FLASH
|
||||
assert doc.url == "https://github.com/rapid7/metasploit-framework/blob/master/db/modules_metadata_base.json"
|
||||
refs = doc.issues[0].facts["exploit_refs"]
|
||||
assert [ref["module_path"] for ref in refs] == [
|
||||
"modules/exploits/multi/http/apache_log4j.rb",
|
||||
"modules/auxiliary/scanner/http/log4shell_scanner.rb",
|
||||
]
|
||||
first, second = refs
|
||||
assert first["type"] == "metasploit_module"
|
||||
assert first["url"] == BLOB + first["module_path"]
|
||||
assert first["platform"] == "Java,Unix,Windows" and first["rank"] == 600
|
||||
assert first["module_updated_at"] == "2024-03-02 10:00:00 +0000"
|
||||
assert first["index"] == "db/modules_metadata_base.json"
|
||||
assert first["index_snapshot"] is True
|
||||
assert first["index_revision"] == '"revision-1"'
|
||||
assert first["verified_against_build"] is False
|
||||
assert second["url"] == BLOB + second["module_path"]
|
||||
assert "platform" not in second and second["rank"] == 300
|
||||
assert all(ref["index_fetched_at"] for ref in refs)
|
||||
assert doc.updated == "2024-03-02 10:00:00 +0000"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_absent_cve_is_empty_success() -> None:
|
||||
http = FakeHttp(_response(_index(_module("/modules/exploits/a/b.rb", ["CVE-2020-1111"]))))
|
||||
page = await lookup_metasploit("id", "CVE-2020-2222", http=http, deadline=10.0)
|
||||
assert page.status.status == "ok" and not page.docs
|
||||
assert page.status.as_of is not None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_missing_index_is_empty_success_not_an_error() -> None:
|
||||
http = FakeHttp(HttpError("not_found"))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert page.status.status == "ok" and not page.docs
|
||||
assert page.cacheable
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rank_is_emitted_only_for_published_integer() -> None:
|
||||
body = _index(
|
||||
_module("/modules/exploits/a/int.rb", [FLASH], rank=0),
|
||||
_module("/modules/exploits/a/string.rb", [FLASH], rank="400"),
|
||||
_module("/modules/exploits/a/bool.rb", [FLASH], rank=True),
|
||||
_module("/modules/exploits/a/none.rb", [FLASH], rank=None),
|
||||
_module("/modules/exploits/a/high.rb", [FLASH], rank=1001),
|
||||
)
|
||||
http = FakeHttp(_response(body))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
refs = page.docs[0].issues[0].facts["exploit_refs"]
|
||||
names = [ref["module_path"].rsplit("/", 1)[-1] for ref in refs]
|
||||
ranks = {name: ref.get("rank") for name, ref in zip(names, refs)}
|
||||
assert ranks == {"int.rb": 0, "string.rb": None, "bool.rb": None, "none.rb": None, "high.rb": None}
|
||||
# A published manual rank still precedes modules whose rank is unknown.
|
||||
assert names == ["int.rb", "bool.rb", "high.rb", "none.rb", "string.rb"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_invalid_paths_are_skipped_but_valid_siblings_survive() -> None:
|
||||
body = _index(
|
||||
_module("/modules/exploits/good/one.rb", [FLASH]),
|
||||
_module("modules/exploits/no-leading-slash.rb", [FLASH]),
|
||||
_module("/modules/../escape.rb", [FLASH]),
|
||||
_module("/modules/exploits/../../escape.rb", [FLASH]),
|
||||
_module("/modules//double.rb", [FLASH]),
|
||||
_module("/modules/exploits/not_ruby.txt", [FLASH]),
|
||||
_module("/modules/exploits/back\\slash.rb", [FLASH]),
|
||||
_module("https://evil.test/modules/x/y.rb", [FLASH]),
|
||||
_module("/modules/exploits/space here/x.rb", [FLASH]),
|
||||
_module("/modules/exploits/deep/ok/two.rb", [FLASH]),
|
||||
_module(None, [FLASH]),
|
||||
_module("/modules/exploits/missing_refs.rb", "CVE-2020-0001"),
|
||||
)
|
||||
http = FakeHttp(_response(body))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
paths = [ref["module_path"] for ref in page.docs[0].issues[0].facts["exploit_refs"]]
|
||||
assert paths == ["modules/exploits/deep/ok/two.rb", "modules/exploits/good/one.rb"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_broken_entries_are_skipped_independently() -> None:
|
||||
body = {
|
||||
"scalar": "not an object",
|
||||
"empty_refs": _module("/modules/exploits/a/empty.rb", []),
|
||||
"mixed_refs": _module("/modules/exploits/a/mixed.rb", ["URL-https://example.test", 7]),
|
||||
"valid": _module("/modules/exploits/a/valid.rb", [FLASH]),
|
||||
"valid_refs": _module("/modules/exploits/a/valid2.rb", ["CVE-2019-0001", FLASH, 7]),
|
||||
"untyped_refs": {"path": "/modules/exploits/a/untyped.rb", "references": "CVE-2019-0002"},
|
||||
}
|
||||
http = FakeHttp(_response(body))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert [ref["module_path"] for ref in page.docs[0].issues[0].facts["exploit_refs"]] == [
|
||||
"modules/exploits/a/valid.rb",
|
||||
"modules/exploits/a/valid2.rb",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_module_named_for_another_cve_does_not_match() -> None:
|
||||
body = {
|
||||
"exploit/a/CVE-2020-1111": {
|
||||
"name": "CVE-2020-1111 named module",
|
||||
"fullname": "exploit/a/CVE-2020-1111",
|
||||
"ref_name": "a/CVE-2020-1111",
|
||||
"path": "/modules/exploits/a/wrong.rb",
|
||||
"references": ["CVE-2020-2222"],
|
||||
},
|
||||
"exploit/a/prefix": _module("/modules/exploits/a/prefix.rb", ["CVE-2020-12345"]),
|
||||
}
|
||||
http = FakeHttp(_response(body), _response(body), _response(body))
|
||||
wrong = await lookup_metasploit("id", "CVE-2020-1111", http=http, deadline=10.0)
|
||||
assert not wrong.docs
|
||||
matches = await lookup_metasploit("id", "CVE-2020-2222", http=http, deadline=10.0)
|
||||
assert [ref["module_path"] for ref in matches.docs[0].issues[0].facts["exploit_refs"]] == [
|
||||
"modules/exploits/a/wrong.rb"
|
||||
]
|
||||
prefix = await lookup_metasploit("id", "CVE-2020-1234", http=http, deadline=10.0)
|
||||
assert not prefix.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(("kind", "value", "continuation"), [
|
||||
("ids", FLASH, None),
|
||||
("id", FLASH, "next"),
|
||||
("id", "CVE-21-1", None),
|
||||
("id", "GHSA-aaaa-bbbb-cccc", None),
|
||||
("id", "CVE-2021-44228x", None),
|
||||
])
|
||||
async def test_invalid_inputs_do_not_touch_the_network(kind: str, value: str, continuation: str | None) -> None:
|
||||
http = FakeHttp()
|
||||
page: ProviderPage = await lookup_metasploit(kind, value, http=http, deadline=10.0,
|
||||
continuation=continuation)
|
||||
assert page.status.status == "invalid_data" and not page.docs and not page.cacheable
|
||||
assert http.calls == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_unchanged_revision_reuses_the_parsed_index(monkeypatch) -> None:
|
||||
body = _index(_module("/modules/exploits/a/b.rb", [FLASH], rank=500))
|
||||
http = FakeHttp(_response(body), _response(body))
|
||||
calls = 0
|
||||
original = feed_metasploit._parse
|
||||
|
||||
def counting(raw: object):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original(raw)
|
||||
|
||||
monkeypatch.setattr(feed_metasploit, "_parse", counting)
|
||||
first = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
second = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert calls == 1
|
||||
assert len(http.calls) == 2
|
||||
first_ref = first.docs[0].issues[0].facts["exploit_refs"][0]
|
||||
second_ref = second.docs[0].issues[0].facts["exploit_refs"][0]
|
||||
assert {key: value for key, value in first_ref.items() if key != "index_fetched_at"} == {
|
||||
key: value for key, value in second_ref.items() if key != "index_fetched_at"
|
||||
}
|
||||
assert first_ref["index_fetched_at"] != second_ref["index_fetched_at"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_missing_validator_reparses_rather_than_trusting_stale_bytes(monkeypatch) -> None:
|
||||
old = _index(_module("/modules/exploits/a/old.rb", [FLASH]))
|
||||
new = _index(_module("/modules/exploits/a/new.rb", [FLASH]))
|
||||
http = FakeHttp(_response(old, '"rev"'), (new, {}))
|
||||
calls = 0
|
||||
original = feed_metasploit._parse
|
||||
|
||||
def counting(raw: object):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original(raw)
|
||||
|
||||
monkeypatch.setattr(feed_metasploit, "_parse", counting)
|
||||
await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
second = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert calls == 2
|
||||
assert second.docs[0].issues[0].facts["exploit_refs"][0]["module_path"].endswith("new.rb")
|
||||
assert second.docs[0].issues[0].facts["exploit_refs"][0].get("index_revision") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_http_without_weak_references_still_gets_isolated_state() -> None:
|
||||
class Slotted:
|
||||
__slots__ = ()
|
||||
|
||||
async def json(self, source: str, url: str, *, deadline: float, budget: float | None = None):
|
||||
return _index(_module("/modules/exploits/a/b.rb", [FLASH])), httpx.Headers({"ETag": '"s"'})
|
||||
|
||||
one, two = Slotted(), Slotted()
|
||||
first = await lookup_metasploit("id", FLASH, http=one, deadline=10.0)
|
||||
second = await lookup_metasploit("id", FLASH, http=two, deadline=10.0)
|
||||
again = await lookup_metasploit("id", FLASH, http=one, deadline=10.0)
|
||||
assert first.docs and second.docs and again.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_changed_revision_is_reflected_on_the_next_call() -> None:
|
||||
old = _index(_module("/modules/exploits/a/old.rb", [FLASH], rank=300))
|
||||
new = _index(_module("/modules/exploits/a/new.rb", [FLASH], rank=600, platform="Unix"))
|
||||
http = FakeHttp(_response(old, '"rev-1"'), _response(new, '"rev-2"'))
|
||||
first = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
second = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert first.docs[0].issues[0].facts["exploit_refs"][0]["module_path"].endswith("old.rb")
|
||||
ref = second.docs[0].issues[0].facts["exploit_refs"][0]
|
||||
assert ref["module_path"].endswith("new.rb") and ref["rank"] == 600
|
||||
assert ref["index_revision"] == '"rev-2"'
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_broken_index_is_invalid_data_and_keeps_the_last_mapping() -> None:
|
||||
http = FakeHttp(
|
||||
_response(_index(_module("/modules/exploits/a/b.rb", [FLASH]))),
|
||||
_response([], '"rev-2"'),
|
||||
_response(_index(_module("/modules/exploits/a/c.rb", [FLASH])), '"rev-3"'),
|
||||
)
|
||||
ok = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert ok.docs
|
||||
broken = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert broken.status.status == "invalid_data" and not broken.cacheable and not broken.docs
|
||||
# The failed revision is not adopted; a later valid revision replaces it.
|
||||
again = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert again.status.status == "ok"
|
||||
assert again.docs[0].issues[0].facts["exploit_refs"][0]["module_path"].endswith("c.rb")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_without_any_cve_entry_is_invalid_data() -> None:
|
||||
http = FakeHttp(_response({}, '"empty"'))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert page.status.status == "invalid_data" and not page.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_no_store_response_makes_the_page_uncacheable() -> None:
|
||||
http = FakeHttp((_index(_module("/modules/exploits/a/b.rb", [FLASH])),
|
||||
{"ETag": '"rev"', "Cache-Control": "private, no-store"}))
|
||||
page = await lookup_metasploit("id", FLASH, http=http, deadline=10.0)
|
||||
assert page.docs and not page.cacheable
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("error", [
|
||||
HttpError("rate_limited", "2030-01-01T00:00:00+00:00"),
|
||||
HttpError("unavailable"),
|
||||
HttpError("timeout"),
|
||||
HttpError("access_denied"),
|
||||
HttpError("invalid_data"),
|
||||
])
|
||||
async def test_transport_errors_keep_their_status(error: HttpError) -> None:
|
||||
page = await lookup_metasploit("id", FLASH, http=FakeHttp(error), deadline=10.0)
|
||||
assert page.status.status == error.status and not page.docs and not page.cacheable
|
||||
assert page.status.retry_at == error.retry_at
|
||||
|
||||
class SlowHttp(FakeHttp):
|
||||
"""A cold download that outlives the caller's wait."""
|
||||
|
||||
def __init__(self, *responses: object) -> None:
|
||||
super().__init__(*responses)
|
||||
self.gate = asyncio.Event()
|
||||
self.started = asyncio.Event()
|
||||
self.budgets: list[float | None] = []
|
||||
|
||||
async def json(self, source: str, url: str, *, deadline: float, budget: float | None = None):
|
||||
self.budgets.append(budget)
|
||||
self.started.set()
|
||||
await self.gate.wait()
|
||||
return await super().json(source, url, deadline=deadline, budget=budget)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_cold_download_reports_initializing_then_serves_the_warmed_index() -> None:
|
||||
http = SlowHttp(*[_response(_index(_module("/modules/exploits/a/b.rb", [FLASH])))] * 2)
|
||||
cold = await lookup_metasploit("id", FLASH, http=http, deadline=monotonic() + 0.05)
|
||||
assert cold.status.status == "initializing" and not cold.docs and not cold.cacheable
|
||||
assert http.budgets[0] is not None, "a cold refresh must carry its own budget"
|
||||
|
||||
http.gate.set()
|
||||
async with asyncio.timeout(5):
|
||||
while not feed_metasploit._state(http).mapping:
|
||||
await asyncio.sleep(0.01)
|
||||
warm = await lookup_metasploit("id", FLASH, http=http, deadline=monotonic() + 5)
|
||||
assert warm.docs[0].issues[0].facts["exploit_refs"][0]["module_path"].endswith("b.rb")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_concurrent_cold_calls_share_one_download() -> None:
|
||||
http = SlowHttp(*[_response(_index(_module("/modules/exploits/a/b.rb", [FLASH])))] * 2)
|
||||
deadline = monotonic() + 0.05
|
||||
results = await asyncio.gather(
|
||||
lookup_metasploit("id", FLASH, http=http, deadline=deadline),
|
||||
lookup_metasploit("id", FLASH, http=http, deadline=deadline),
|
||||
lookup_metasploit("id", FLASH, http=http, deadline=deadline),
|
||||
)
|
||||
http.gate.set()
|
||||
while not feed_metasploit._state(http).mapping:
|
||||
await asyncio.sleep(0.01)
|
||||
assert [page.status.status for page in results] == ["initializing"] * 3
|
||||
assert len(http.calls) == 1
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Detection-template coverage from the public nuclei-templates repository."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from collections.abc import Mapping
|
||||
from time import monotonic
|
||||
|
||||
import pytest
|
||||
|
||||
from vuln_mcp.sources.feed_nuclei import _PROTOCOLS, allowed, lookup_nuclei
|
||||
from vuln_mcp.transport import HttpError
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
CVE = "CVE-2021-41773"
|
||||
BASE = "https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/main/"
|
||||
|
||||
|
||||
def url(protocol: str, cve: str = CVE) -> str:
|
||||
return f"{BASE}{protocol}/cves/{cve[4:8]}/{cve}.yaml"
|
||||
|
||||
|
||||
def template(cve: str = CVE, name: str = "Apache 2.4.49 - Path Traversal") -> bytes:
|
||||
return (f"id: {cve}\n\ninfo:\n name: {name}\n author: daffainfo\n severity: high\n description: |\n"
|
||||
f" line one\n\n line two\n").encode()
|
||||
|
||||
|
||||
class Wire:
|
||||
def __init__(self) -> None:
|
||||
self.replies: dict[str, deque[tuple[int, bytes, str | None]]] = {}
|
||||
self.requests: list[tuple[str, float]] = []
|
||||
|
||||
def put(self, address: str, body: bytes = b"", *, status: int = 200,
|
||||
retry_at: str | None = None) -> None:
|
||||
self.replies.setdefault(address, deque()).append((status, body, retry_at))
|
||||
|
||||
async def bytes(
|
||||
self, source: str, address: str, *, deadline: float, limit: int,
|
||||
) -> tuple[bytes, Mapping[str, str]]:
|
||||
assert source == "nuclei"
|
||||
self.requests.append((address, deadline))
|
||||
queued = self.replies.get(address)
|
||||
status, body, retry_at = queued.popleft() if queued else (404, b"", None)
|
||||
if status == 404:
|
||||
raise HttpError("not_found")
|
||||
if status != 200:
|
||||
raise HttpError("unavailable" if status >= 500 else "access_denied", retry_at)
|
||||
assert len(body) <= limit
|
||||
return body, {"cache-control": "max-age=300"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def refs(page) -> list[dict[str, str]]:
|
||||
assert len(page.docs) == 1
|
||||
[issue] = page.docs[0].issues
|
||||
return issue.facts["exploit_refs"]
|
||||
|
||||
|
||||
async def test_http_template_is_a_detection_ref() -> None:
|
||||
wire = Wire()
|
||||
body = (b"---\nid: CVE-2021-41773\ninfo:\n name: \"Apache: Path Traversal\"\n"
|
||||
b" severity: high\n")
|
||||
wire.put(url("http"), body)
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
|
||||
assert page.status.status == "ok" and page.continuation is None
|
||||
[doc] = page.docs
|
||||
assert (doc.source, doc.native_id, doc.publisher) == ("nuclei", CVE, "ProjectDiscovery nuclei-templates")
|
||||
assert doc.url == url("http")
|
||||
assert refs(page) == [{
|
||||
"type": "detection_template", "url": url("http"), "protocol": "http",
|
||||
"template_name": "Apache: Path Traversal",
|
||||
}]
|
||||
assert [address for address, _ in wire.requests] == [url("http")]
|
||||
|
||||
|
||||
async def test_stops_at_first_protocol_hit() -> None:
|
||||
wire = Wire()
|
||||
wire.put(url("http"), status=404)
|
||||
wire.put(url("network"), template(), status=200)
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
|
||||
assert [address for address, _ in wire.requests] == [url("http"), url("network")]
|
||||
assert refs(page)[0]["protocol"] == "network"
|
||||
assert refs(page)[0]["template_name"] == "Apache 2.4.49 - Path Traversal"
|
||||
|
||||
|
||||
async def test_miss_probes_every_protocol_once_then_succeeds_empty() -> None:
|
||||
wire = Wire()
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 30)
|
||||
assert page.docs == [] and page.status.status == "ok"
|
||||
assert page.status.as_of is not None
|
||||
assert [address for address, _ in wire.requests] == [url(protocol) for protocol in _PROTOCOLS]
|
||||
assert len(wire.requests) == 4
|
||||
assert _PROTOCOLS == ("http", "network", "javascript", "headless")
|
||||
|
||||
|
||||
async def test_identifier_mismatch_and_malformed_yaml_are_skipped() -> None:
|
||||
wire = Wire()
|
||||
wire.put(url("http"), template("CVE-1999-0001"))
|
||||
wire.put(url("network"), b"\xff\xfe id: CVE-2021-41773\n")
|
||||
wire.put(url("javascript"), b"info:\n name: No identifier\n")
|
||||
wire.put(url("headless"), template(name="Real template"))
|
||||
page = await lookup_nuclei("id", CVE.lower(), http=wire, deadline=monotonic() + 5)
|
||||
assert len(wire.requests) == 4
|
||||
assert refs(page)[0]["protocol"] == "headless"
|
||||
assert page.docs[0].native_id == CVE
|
||||
assert url("headless") in page.docs[0].url
|
||||
|
||||
|
||||
async def test_missing_name_falls_back_to_identifier() -> None:
|
||||
wire = Wire()
|
||||
wire.put(url("http"), b"id: CVE-2021-41773\ninfo:\n severity: high\n")
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
|
||||
assert refs(page)[0]["template_name"] == CVE
|
||||
|
||||
|
||||
async def test_expired_deadline_makes_no_request() -> None:
|
||||
wire = Wire()
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() - 1)
|
||||
assert wire.requests == [] and page.docs == []
|
||||
assert page.status.status == "timeout"
|
||||
|
||||
|
||||
async def test_error_stops_probing_and_keeps_retry_hint() -> None:
|
||||
wire = Wire()
|
||||
wire.put(url("http"), status=404)
|
||||
wire.put(url("network"), status=500, retry_at="2026-01-01T00:00:00+00:00")
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
|
||||
assert page.docs == [] and page.status.status == "unavailable"
|
||||
assert page.status.retry_at == "2026-01-01T00:00:00+00:00"
|
||||
assert [address for address, _ in wire.requests] == [url("http"), url("network")]
|
||||
|
||||
|
||||
async def test_access_denied_is_not_treated_as_a_miss() -> None:
|
||||
wire = Wire()
|
||||
wire.put(url("http"), status=403)
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5)
|
||||
assert page.status.status == "access_denied" and len(wire.requests) == 1
|
||||
|
||||
|
||||
async def test_rejects_wrong_kind_and_malformed_identifier() -> None:
|
||||
wire = Wire()
|
||||
for kind, value in (("text", CVE), ("id", "CVE-2021-417"), ("id", "GHSA-xxxx"), ("id", 7)):
|
||||
page = await lookup_nuclei(kind, value, http=wire, deadline=monotonic() + 5)
|
||||
assert page.status.status == "invalid_data", (kind, value)
|
||||
page = await lookup_nuclei("id", CVE, http=wire, deadline=monotonic() + 5, continuation="1")
|
||||
assert page.status.status == "invalid_data"
|
||||
assert wire.requests == []
|
||||
|
||||
|
||||
def test_allowed_paths_cover_only_protocol_cve_files() -> None:
|
||||
for protocol in _PROTOCOLS:
|
||||
path = f"/projectdiscovery/nuclei-templates/main/{protocol}/cves/2021/{CVE}.yaml"
|
||||
assert allowed("raw.githubusercontent.com", path, live=True)
|
||||
assert not allowed("raw.githubusercontent.com",
|
||||
f"/projectdiscovery/nuclei-templates/main/dns/cves/2021/{CVE}.yaml", live=True)
|
||||
assert not allowed("raw.githubusercontent.com",
|
||||
f"/projectdiscovery/nuclei-templates/main/file/cves/2021/{CVE}.yaml", live=True)
|
||||
assert not allowed("raw.githubusercontent.com",
|
||||
"/projectdiscovery/nuclei-templates/main/http/cves/2021/CVE-2021-417.yaml", live=True)
|
||||
assert not allowed("raw.githubusercontent.com",
|
||||
f"/projectdiscovery/nuclei-templates/main/http/cves/2021/{CVE}.yaml", live=False)
|
||||
assert not allowed("example.invalid",
|
||||
f"/projectdiscovery/nuclei-templates/main/http/cves/2021/{CVE}.yaml", live=True)
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Both community PoC indexes, one CVE per call, through the live route only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from collections.abc import Mapping
|
||||
|
||||
import pytest
|
||||
|
||||
from vuln_mcp.sources.feed_pocs import allowed, lookup_pocs
|
||||
from vuln_mcp.transport import HttpError
|
||||
|
||||
CVE = "CVE-2021-44228"
|
||||
YEAR = "2021"
|
||||
JSON_URL = f"https://raw.githubusercontent.com/nomi-sec/PoC-in-GitHub/master/{YEAR}/{CVE}.json"
|
||||
MD_URL = f"https://raw.githubusercontent.com/trickest/cve/main/{YEAR}/{CVE}.md"
|
||||
DEADLINE = 12.5
|
||||
|
||||
|
||||
class Wire:
|
||||
def __init__(self) -> None:
|
||||
self.replies: dict[str, tuple[int, bytes]] = defaultdict(lambda: (404, b""))
|
||||
self.requests: list[tuple[str, float]] = []
|
||||
|
||||
def put(self, url: str, body: bytes) -> None:
|
||||
self.replies[url] = (200, body)
|
||||
|
||||
def fail(self, url: str, status: str) -> None:
|
||||
self.replies[url] = (-1, status.encode())
|
||||
|
||||
async def bytes(self, source: str, url: str, *, deadline: float, limit: int) -> tuple[bytes, Mapping[str, str]]:
|
||||
assert source == "pocs"
|
||||
self.requests.append((url, deadline))
|
||||
status, body = self.replies[url]
|
||||
if status == 404:
|
||||
raise HttpError("not_found")
|
||||
if status == -1:
|
||||
raise HttpError(body.decode())
|
||||
assert status == 200 and len(body) <= limit
|
||||
return body, {}
|
||||
|
||||
|
||||
def entry(owner: str, repo: str, stars: int | None = None) -> dict:
|
||||
row: dict = {"full_name": f"{owner}/{repo}", "html_url": f"https://github.com/{owner}/{repo}"}
|
||||
if stars is not None:
|
||||
row["stargazers_count"] = stars
|
||||
return row
|
||||
|
||||
|
||||
def json_body(*rows: dict) -> bytes:
|
||||
return json.dumps(list(rows)).encode()
|
||||
|
||||
|
||||
def markdown(cve: str = CVE, repos: tuple[str, ...] = ()) -> bytes:
|
||||
lines = [
|
||||
f"### [{cve}](https://nvd.nist.gov/vuln/detail/{cve})", "",
|
||||
"### Description", "Untrusted prose.", "",
|
||||
"### POC", "", "#### Reference", "- http://packetstormsecurity.com/files/1/x.html", "",
|
||||
"#### Github",
|
||||
]
|
||||
lines += [f"- {repo}" for repo in repos]
|
||||
return "\n".join(lines).encode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def refs(page) -> list[dict]:
|
||||
return [ref for doc in page.docs for issue in doc.issues for ref in issue.facts["exploit_refs"]]
|
||||
|
||||
|
||||
def test_allowed_only_accepts_live_exact_paths() -> None:
|
||||
assert allowed("raw.githubusercontent.com", JSON_URL.removeprefix("https://raw.githubusercontent.com"), live=True)
|
||||
assert allowed("raw.githubusercontent.com", MD_URL.removeprefix("https://raw.githubusercontent.com"), live=True)
|
||||
assert not allowed("raw.githubusercontent.com", JSON_URL.removeprefix("https://raw.githubusercontent.com"), live=False)
|
||||
assert not allowed("example.test", JSON_URL.removeprefix("https://raw.githubusercontent.com"), live=True)
|
||||
assert not allowed("raw.githubusercontent.com", f"/nomi-sec/PoC-in-GitHub/master/{YEAR}/{CVE}.md", live=True)
|
||||
assert not allowed("raw.githubusercontent.com", "/nomi-sec/PoC-in-GitHub/master/2020/CVE-2021-44228.json", live=True)
|
||||
assert not allowed("raw.githubusercontent.com", "/nomi-sec/PoC-in-GitHub/main/2021/CVE-2021-44228.json", live=True)
|
||||
assert not allowed("raw.githubusercontent.com", "/trickest/cve/main/2021/CVE-2021-44228.md/", live=True)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_both_indexes_missing_is_a_normal_empty_success() -> None:
|
||||
wire = Wire()
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert page.status.status == "ok" and not page.docs
|
||||
assert wire.requests == [(JSON_URL, DEADLINE), (MD_URL, DEADLINE)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_both_parsers_emit_canonical_refs_with_stars() -> None:
|
||||
wire = Wire()
|
||||
wire.put(JSON_URL, json_body(
|
||||
entry("alice", "one", 7),
|
||||
entry("bob", "two", 0),
|
||||
))
|
||||
wire.put(MD_URL, markdown(repos=("https://github.com/carol/three",)))
|
||||
page = await lookup_pocs("id", CVE.lower(), http=wire, deadline=DEADLINE)
|
||||
|
||||
assert page.status.status == "ok"
|
||||
first, second = page.docs
|
||||
assert (first.publisher, first.native_id, first.title) == ("nomi-sec/PoC-in-GitHub", CVE, CVE)
|
||||
assert first.url == f"https://github.com/nomi-sec/PoC-in-GitHub/blob/HEAD/{YEAR}/{CVE}.json"
|
||||
assert (second.publisher, second.native_id) == ("trickest/cve", CVE)
|
||||
assert second.url == f"https://github.com/trickest/cve/blob/HEAD/{YEAR}/{CVE}.md"
|
||||
assert refs(page) == [
|
||||
{"type": "poc_repo", "url": "https://github.com/alice/one/blob/HEAD",
|
||||
"repo": "https://github.com/alice/one", "stars": 7},
|
||||
{"type": "poc_repo", "url": "https://github.com/bob/two/blob/HEAD",
|
||||
"repo": "https://github.com/bob/two", "stars": 0},
|
||||
{"type": "poc_repo", "url": "https://github.com/carol/three/blob/HEAD",
|
||||
"repo": "https://github.com/carol/three"},
|
||||
]
|
||||
assert all(set(ref) <= {"type", "url", "repo", "stars"} for ref in refs(page))
|
||||
assert first.issues[0].id == second.issues[0].id == CVE
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_trickest_page_for_another_cve_is_rejected() -> None:
|
||||
wire = Wire()
|
||||
wire.put(MD_URL, markdown(cve="CVE-2020-1472", repos=("https://github.com/alice/one",)))
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert page.status.status == "invalid_data" and not page.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_json_entries_named_after_another_year_are_rejected() -> None:
|
||||
wire = Wire()
|
||||
wire.put(JSON_URL, json_body(
|
||||
entry("alice", "CVE-2020-1472-poc"),
|
||||
entry("bob", "CVE-2021-44228-and-CVE-2020-1472"),
|
||||
))
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert page.status.status == "ok"
|
||||
assert [ref["repo"] for ref in refs(page)] == ["https://github.com/bob/CVE-2021-44228-and-CVE-2020-1472"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_structural_claims_that_do_not_parse_are_invalid() -> None:
|
||||
broken = Wire()
|
||||
broken.put(JSON_URL, b'[{"full_name": "alice/one"')
|
||||
assert (await lookup_pocs("id", CVE, http=broken, deadline=DEADLINE)).status.status == "invalid_data"
|
||||
|
||||
wrong_shape = Wire()
|
||||
wrong_shape.put(JSON_URL, b'{"message": "not found"}')
|
||||
assert (await lookup_pocs("id", CVE, http=wrong_shape, deadline=DEADLINE)).status.status == "invalid_data"
|
||||
|
||||
empty_section = Wire()
|
||||
empty_section.put(MD_URL, markdown())
|
||||
page = await lookup_pocs("id", CVE, http=empty_section, deadline=DEADLINE)
|
||||
assert page.status.status == "invalid_data" and not page.docs
|
||||
|
||||
bad_entry = Wire()
|
||||
bad_entry.put(JSON_URL, b'[{"html_url": "https://github.com/alice/one"}, 5]')
|
||||
page = await lookup_pocs("id", CVE, http=bad_entry, deadline=DEADLINE)
|
||||
assert page.status.status == "invalid_data"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_plain_payloads_without_structure_are_empty_not_invalid() -> None:
|
||||
wire = Wire()
|
||||
wire.put(JSON_URL, b"<html><body>502 Bad Gateway</body></html>")
|
||||
wire.put(MD_URL, b"Rate limit exceeded")
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert page.status.status == "ok" and not page.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_duplicates_are_deduplicated_by_repository() -> None:
|
||||
wire = Wire()
|
||||
wire.put(JSON_URL, json_body(
|
||||
entry("Alice", "One"),
|
||||
entry("alice", "one"),
|
||||
))
|
||||
wire.put(MD_URL, markdown(repos=("https://github.com/ALICE/ONE", "https://github.com/bob/two")))
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert [ref["repo"] for ref in refs(page)] == ["https://github.com/Alice/One", "https://github.com/bob/two"]
|
||||
assert len(page.docs) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reference_count_is_capped_across_both_indexes() -> None:
|
||||
wire = Wire()
|
||||
wire.put(JSON_URL, json_body(*(entry("owner", f"repo{index}") for index in range(8))))
|
||||
wire.put(MD_URL, markdown(repos=tuple(f"https://github.com/other/repo{index}" for index in range(5))))
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert len(refs(page)) == 10
|
||||
assert [doc.publisher for doc in page.docs] == ["nomi-sec/PoC-in-GitHub", "trickest/cve"]
|
||||
assert len(page.docs[0].issues[0].facts["exploit_refs"]) == 5
|
||||
assert len(page.docs[1].issues[0].facts["exploit_refs"]) == 5
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_one_source_failure_keeps_the_other_refs() -> None:
|
||||
wire = Wire()
|
||||
wire.fail(JSON_URL, "timeout")
|
||||
wire.put(MD_URL, markdown(repos=("https://github.com/alice/one",)))
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert page.status.status == "ok"
|
||||
assert [doc.publisher for doc in page.docs] == ["trickest/cve"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_both_sources_failing_reports_the_error() -> None:
|
||||
wire = Wire()
|
||||
wire.fail(JSON_URL, "rate_limited")
|
||||
wire.fail(MD_URL, "timeout")
|
||||
page = await lookup_pocs("id", CVE, http=wire, deadline=DEADLINE)
|
||||
assert (page.status.status, page.status.retry_at) == ("rate_limited", None)
|
||||
assert not page.docs
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_only_one_cve_without_continuation_is_accepted() -> None:
|
||||
wire = Wire()
|
||||
for kind, value, continuation in (
|
||||
("text", CVE, None), ("id", "", None), ("id", "GHSA-1234-abcd", None),
|
||||
("id", CVE, "2"), ("id", "pkg:pypi/x@1", None),
|
||||
):
|
||||
page = await lookup_pocs(kind, value, http=wire, deadline=DEADLINE, continuation=continuation)
|
||||
assert page.status.status == "invalid_data"
|
||||
assert wire.requests == []
|
||||
@@ -19,6 +19,40 @@ def record(value, authority=CISA, subject=CVE):
|
||||
'id': subject, 'options': [{'Exploitation': value}], 'timestamp': DATE}}}]}]}}
|
||||
|
||||
|
||||
def _profile(cna_extra=None, ssvc=None, part='a'):
|
||||
raw = {'dataType': 'CVE_RECORD', 'dataVersion': '5.1', 'cveMetadata': {'cveId': CVE, 'state': 'PUBLISHED'},
|
||||
'containers': {'cna': {'providerMetadata': {'shortName': 'x'},
|
||||
'affected': [{'cpes': [f'cpe:2.3:{part}:acme:portal:1.0:*:*:*:*:*:*:*'],
|
||||
'versions': [{'version': '1.0', 'status': 'affected'}]}],
|
||||
'metrics': [{'cvssV3_1': {'vectorString': 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H',
|
||||
'baseScore': 9.8}}]} | (cna_extra or {})}}
|
||||
if ssvc:
|
||||
raw['containers']['adp'] = [{'providerMetadata': {'orgId': CISA}, 'metrics': [
|
||||
{'other': {'type': 'ssvc', 'content': {'id': CVE, 'options': ssvc}}}]}]
|
||||
return parse('cvelist', raw, 'https://www.cve.org/').issues[0].facts.get('exploitation') or {}
|
||||
|
||||
|
||||
def test_path_interaction_and_component_role_are_extracted():
|
||||
assert _profile() == {'cvss_av': 'N', 'cvss_pr': 'N', 'cvss_ui': 'N', 'component_role': 'application'}
|
||||
|
||||
|
||||
def test_cisa_decision_points_fill_only_absent_keys():
|
||||
facts = _profile(ssvc=[{'Exploitation': 'active'}, {'Automatable': 'yes'}, {'Technical Impact': 'total'}])
|
||||
assert (facts['automatable'], facts['technical_impact'], facts['cvss_av']) == ('yes', 'total', 'N')
|
||||
|
||||
|
||||
def test_platform_component_is_not_reported_as_application():
|
||||
assert _profile(part='o')['component_role'] == 'operating_system'
|
||||
|
||||
|
||||
def test_partial_vector_and_absent_ssvc_leave_keys_out():
|
||||
raw = {'dataType': 'CVE_RECORD', 'dataVersion': '5.1', 'cveMetadata': {'cveId': CVE, 'state': 'PUBLISHED'},
|
||||
'containers': {'cna': {'providerMetadata': {'shortName': 'x'}, 'metrics': [
|
||||
{'cvssV3_1': {'vectorString': 'CVSS:3.1/AV:L/AC:H', 'baseScore': 1.0}}]}}}
|
||||
facts = parse('cvelist', raw, 'https://www.cve.org/').issues[0].facts.get('exploitation')
|
||||
assert facts == {'cvss_av': 'L'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('value', 'normalized'), [('poc', 'public_poc'), ('active', 'observed_in_wild'), ('none', 'none_reported')])
|
||||
def test_publication_and_cisa_assessment_are_independent(value, normalized):
|
||||
doc = parse('cvelist', record(value), 'https://www.cve.org/')
|
||||
|
||||
+29
-2
@@ -101,8 +101,14 @@ class PublisherHTTP:
|
||||
self.osv_pages: dict[str, dict] = {}
|
||||
self.failures: dict[tuple[str, str], HttpError] = {}
|
||||
self.no_store: set[str] = set()
|
||||
# A parsed Metasploit index needs at least one CVE reference; keep it off the fixture CVEs.
|
||||
self.metasploit: dict = {'fixture/module': {
|
||||
'path': '/modules/exploits/fixture/module.rb', 'references': ['CVE-2025-0001'], 'rank': 300,
|
||||
}}
|
||||
self.templates: set[str] = set()
|
||||
|
||||
async def json(self, source: str, url: str, *, params=None, body=None, deadline=None, headers=None):
|
||||
async def json(self, source: str, url: str, *, params=None, body=None, deadline=None, headers=None,
|
||||
budget=None):
|
||||
assert deadline is not None
|
||||
params, body = params or {}, body or {}
|
||||
self.calls.append((source, url, params, body))
|
||||
@@ -132,6 +138,8 @@ class PublisherHTTP:
|
||||
for ident in params['cve'].split(',')]}
|
||||
elif source in {'siemens', 'msrc'}:
|
||||
response = self.csaf.get(url)
|
||||
elif source == 'metasploit':
|
||||
response = self.metasploit
|
||||
elif source == 'osv':
|
||||
response = self.osv_pages.get(body.get('page_token', ''), {}) if ident == 'query' else self.osv.get(ident)
|
||||
else:
|
||||
@@ -140,6 +148,20 @@ class PublisherHTTP:
|
||||
raise HttpError('not_found')
|
||||
return response, response_headers
|
||||
|
||||
async def bytes(self, source: str, url: str, *, deadline: float, limit: int):
|
||||
self.calls.append((source, url, {}, {}))
|
||||
ident = url.rsplit('/', 1)[-1]
|
||||
if failure := self.failures.get((source, ident)):
|
||||
raise failure
|
||||
if source == 'pocs':
|
||||
return (b'[]' if url.endswith('.json') else b''), {}
|
||||
if source == 'nuclei':
|
||||
cve = ident.removesuffix('.yaml')
|
||||
if cve not in self.templates:
|
||||
raise HttpError('not_found')
|
||||
return f'id: {cve}\n\ninfo:\n name: Fixture template\n'.encode(), {}
|
||||
raise AssertionError(f'unexpected publisher {source}')
|
||||
|
||||
|
||||
async def _publish(store: Store, source: str, docs: list[Doc]) -> None:
|
||||
async with store.staging(source) as stage:
|
||||
@@ -162,6 +184,7 @@ async def test_warm_exact_search_and_detail_recheck_all_publishers_and_replace_r
|
||||
http = PublisherHTTP()
|
||||
http.cves[CVE] = _cve()
|
||||
http.nvd[CVE] = _nvd(CVE)
|
||||
http.templates.add(CVE)
|
||||
http.osv[GHSA] = _osv()
|
||||
http.csaf[SA_URL] = _csaf()
|
||||
async with Store(tmp_path) as store:
|
||||
@@ -182,8 +205,12 @@ async def test_warm_exact_search_and_detail_recheck_all_publishers_and_replace_r
|
||||
assert any(fact['type'] == 'cvss' and fact['value']['publisher'] == 'nvd@nist.gov' for fact in hit.facts)
|
||||
assert any(ref['type'] == 'fix_commit' and ref['url'] == REPO and ref['commit'] == COMMIT for ref in hit.source_refs)
|
||||
assert not any('/PoC/' in ref['url'] for ref in hit.source_refs)
|
||||
assert [ref for ref in hit.exploit_refs if ref['type'] == 'detection_template'] == [
|
||||
{'type': 'detection_template', 'url': 'https://raw.githubusercontent.com/projectdiscovery/nuclei-templates'
|
||||
'/main/http/cves/2025/CVE-2025-43715.yaml', 'protocol': 'http', 'template_name': 'Fixture template'},
|
||||
]
|
||||
assert {status.source for status in hit.coverage if status.channel == 'live'} == {
|
||||
'cvelist', 'circl', 'nvd', 'epss', 'osv', 'siemens', 'certcc',
|
||||
'cvelist', 'circl', 'nvd', 'epss', 'osv', 'siemens', 'certcc', 'pocs', 'nuclei', 'metasploit',
|
||||
}
|
||||
assert not page.partial
|
||||
first = {source for source, *_ in http.calls}
|
||||
|
||||
Reference in new issue
Block a user