401 lines
18 KiB
Python
401 lines
18 KiB
Python
"""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))
|
|
# The last response repeats: a background refresh may retry past the scripted list.
|
|
item = self.responses.pop(0) if len(self.responses) > 1 else self.responses[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"]
|
|
# Rank 300 (good) outranks 600 (low), whatever the index order was.
|
|
assert [ref["module_path"] for ref in refs] == [
|
|
"modules/auxiliary/scanner/http/log4shell_scanner.rb",
|
|
"modules/exploits/multi/http/apache_log4j.rb",
|
|
]
|
|
second, first = 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}
|
|
# Nothing is graded here, so the order is alphabetical: manual rank 0 is not a grade.
|
|
assert names == ["bool.rb", "high.rb", "int.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", "expected"), [
|
|
(HttpError("rate_limited", "2030-01-01T00:00:00+00:00"), "rate_limited"),
|
|
(HttpError("unavailable"), "unavailable"),
|
|
# A timeout keeps the background retry alive, so the first call is still warming.
|
|
(HttpError("timeout"), "initializing"),
|
|
(HttpError("access_denied"), "access_denied"),
|
|
(HttpError("invalid_data"), "invalid_data"),
|
|
])
|
|
async def test_transport_errors_keep_their_status(error: HttpError, expected: str) -> None:
|
|
page = await lookup_metasploit("id", FLASH, http=FakeHttp(error), deadline=10.0)
|
|
assert page.status.status == expected 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
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_throttled_cold_route_is_retried_while_the_budget_lasts() -> None:
|
|
http = FakeHttp(
|
|
HttpError("timeout"),
|
|
HttpError("timeout"),
|
|
_response(_index(_module("/modules/exploits/a/b.rb", [FLASH]))),
|
|
)
|
|
cold = await lookup_metasploit("id", FLASH, http=http, deadline=monotonic() + 0.01)
|
|
assert cold.status.status in {"initializing", "timeout"} and not cold.docs
|
|
async with asyncio.timeout(10):
|
|
while not feed_metasploit._state(http).mapping:
|
|
await asyncio.sleep(0.01)
|
|
assert len(http.calls) == 3
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_a_warm_timeout_is_not_retried_inside_the_caller_deadline() -> None:
|
|
http = FakeHttp(_response(_index(_module("/modules/exploits/a/b.rb", [FLASH]))), HttpError("timeout"), HttpError("timeout"))
|
|
await lookup_metasploit("id", FLASH, http=http, deadline=monotonic() + 5)
|
|
page = await lookup_metasploit("id", FLASH, http=http, deadline=monotonic() + 5)
|
|
assert page.status.status == "timeout" and len(http.calls) == 2
|