Repository navigation
fix(security): close TPA red-team holes in the rug-pull gate and detect engine (RT-01..RT-07) - #1596
Merged
Merged
Conversation
…atch (RT-01) The change gate's description-match fallback auto-approved any input-schema change whose description stayed byte-identical, in every trust mode except scan. A sneaky rug pull that only adds a parameter (an exfiltration sink) was silently approved in the default manual mode (red-team EXP-2b). The fallback now applies only when the stored and live input schemas are structurally identical (same property set, required set, types and constraints; only required-list order may differ). Any structural change falls through to the change gate and is held as changed.
…T-02) The scan-mode change gate re-scanned a changed contract and auto-approved it on a clean verdict. Paraphrased rug pulls scan clean, so an off-corpus pull was silently approved with no operator signal (red-team EXP-6). A changed contract is now always held as changed under trust_mode scan. The scan still runs to record hold evidence (cleared on a clean verdict), a warn log names the held change, and the mark-changed path emits the usual tool_description_changed activity event. The changed-to-approved invariant no longer accepts the scan reason. New tools stay scan-gated. Docs, Web UI and CLI help describe the new policy.
An annotation-only flip (destructive -> readOnly-lying) with a byte-identical description and schema kept the same contract hash, so the change gate never fired and read-gated routing trusted the lie (red-team EXP-5). The approval hash now includes the effective readOnly/destructive/idempotent/ openWorld hints when they differ from the MCP defaults, so default-hint tools keep their hash byte-for-byte. Records get HashSchemaVersion 4 (AnnotationHashSchemaVersion). Pre-v4 approvals migrate through the formula-change path by re-hashing the stored contract with the stored hint snapshot; an uncaptured (nil) snapshot counts as unknown and is accepted, so existing approvals survive the upgrade without re-review. Content-match, description-match and revert paths also require matching hints.
Discovery skipped quarantined servers entirely. After a restart that re-applied quarantined:true, the armed upstream stayed connected for inspection while its stale stage-1 approval remained the recorded state for the whole quarantine window (red-team EXP-2a). Reactive discovery (connect and tools/list_changed) for a connected quarantined server now hash-compares its live contracts against the approval records through the existing inspection-capture path: changes are marked changed and new tools filed pending, bound to the current connection generation, and nothing reaches the search index. It never requests an inspection exemption or a connection of its own.
…RT-06) The scan's tool export is its own tools/list, which a malicious server can answer differently from the list discovery ingested. A TOCTOU server auto-baselined a poisoned contract while the scan saw a clean one and reported clean (red-team EXP-4). The scanner gains an optional ingestedToolContractsProvider capability; the server's provider returns the contracts on the tool-approval records (current and, for changed records, the approved one). Any ingested contract the live export does not reproduce is appended to tools.json and logged as a divergence, so the verdict covers what the proxy actually trusted. Export counts, names and hashes still describe the live export.
Spell the zero-width payload runes as escape sequences (same bytes) and use a tagged switch for the staged calendar description.
The capture replacement tests install persist hooks after the runtime has started; the RT-05 connect-time verification shares that persist path and raced with the hook assignment under -race. Disable the verification in those tests, as already done for the relist test.
…-03) A changed lock adopted from a pre-105 collapsed record carries no previous annotation snapshot but is stamped at the current hash version, so the revert check read it as default hints and kept a genuinely reverted tool held. The revert check now skips a nil snapshot, and the mark-changed path records an explicit empty snapshot when the approved hints were hashed, so annotation flips still cannot be reverted by default.
…aseline (RT-05) Only a previously trusted server has approved contracts that can go stale while it is re-quarantined. A never-approved quarantined server keeps an uncaptured review until an operator or scan inspects it, as the review snapshot contract (UX-02) and TestE2E_InspectQuarantined expect.
…, RT-03 review) Schema equivalence now walks only subschema positions, so a "required" member inside const/enum/default/examples or a vendor keyword is compared as data. Every pre-v4 hash shortcut (hash match, formula migration, output-schema backfill, legacy sibling adoption) first checks the stored annotation snapshot, so a known hint flip is held. A changed record with no previous annotation snapshot only reverts when the live hints are the MCP defaults, and the backfill stores a snapshot matching its hash.
…explicit discovery Name the list_changed discovery callback so a test can drive it, and split the RT-05 regression into a connect-time case with no explicit refresh and a notification-driven contract change.
…or (RT-06 review) The scanner-facing tool export and the stored ingested contracts carry output schemas, the divergence key includes the output schema, and a failed lookup of the ingested contracts exports nothing instead of a live-only list.
…seded (RT-05 review)
…d an approved baseline
…ail closed on tools.json write errors (RT-06 review) The scan export skipped the ingested-contract lookup when the live tools/list was empty or errored, and a serialization or write failure returned a zero-count success. A source-backed or manual scan then read whatever tools.json the source dir already held. The stored contracts are now read independently of the live export, tools.json is always rewritten (an empty list included), a write or serialization failure aborts the scan, and a live export that keeps failing with nothing ingested aborts Pass 1 and records a failed Pass 2 instead of scanning a stale file.
…02/RT-06 review) A -> held B -> held C stayed recorded as B, so review output and the ingested-contract scan input went stale. The Current* snapshot now follows the live contract while ApprovedHash and the Previous* evidence of the approved contract are kept, so the record stays changed and a revert is still recognised.
… (RT-05 review) A tools/list_changed notification (or connect callback) that hit the in-progress dedup was dropped. For a quarantined server periodic discovery never runs, so a contract armed after the in-flight run listed its tools kept a stale approval indefinitely. Triggers are now recorded and the in-flight owner runs a bounded follow-up. The list_changed test no longer retries the trigger, and a deterministic single-notification test asserts the follow-up verification.
EXP-2a now holds only when both rug-pulled tools are held, reports a hole when either stays approved and is inconclusive otherwise. The suite exits non-zero on any hole or inconclusive result except the deferred EXP-3 detector hole. An IMAGE override is written into every generated config's isolation blocks (refusing configs that are not Docker-isolated with no network), and run-tpa-lab-docker.sh refuses an override its fixed config would not run. The predicates live in scripts/lib/tpa-lab-verdicts.sh and are tested from tests/tpa-attack-lab.
…-01, RT-03 review) A CurrentHash the runtime recomputes now records its formula version (CurrentHashSchemaVersion), and an approval that copies it into ApprovedHash takes that version, so a legacy pending or held record refreshed under the hint-aware formula no longer keeps the unknown-hints wildcard after approval. A revert stamps the current version. An empty stored description, input schema or output schema is a wildcard only on records that predate complete contract capture; from the output-schema hash version on it is the declared contract, so an added (possibly poisoned) output schema or description is held in manual and scan modes instead of being migrated or content-matched. The revert check compares the output schema literally.
…T-05 review) An owner that reaches the coalesced follow-up cap hands a still-pending trigger to a fresh worker after a short delay instead of dropping it, so a notification burst that ends with an armed contract on a quarantined server is still verified. The continuation stops on shutdown. Notification-owned follow-ups run with a fresh runtime-scoped timeout instead of the original notification's expiring context.
…t it (RT-06 review) The in-process baseline scanner analyses the exact tools.json document the service exported, carried in memory on the scan request, instead of re-reading it from a source dir an upstream may be able to write. Docker scanners still read the mounted file, and their result is discarded when it no longer matches the snapshot before or after the run. A Pass-2 supply-chain audit whose tool export fails no longer records a failed job: scanners that may analyse tool metadata are failed with an explicit reason while metadata-independent ones (trivy-mcp) still run.
…e, pin the lab data dir EXP-2b now requires a successful unquarantine, a non-quarantined server, evidence that post-unquarantine discovery ran and held tools absent from the index before it reports HOLDS. Only a recognised clean/warnings EXP-3 verdict is the deferred detector hole; an unreadable report is INCONCLUSIVE and fails the suite. run-tpa-lab-docker.sh runs from the project root and refuses a config whose data_dir resolves elsewhere.
…d refuse a busy port without killing Sol r9 P2 follow-ups for the TPA lab scripts: - scan_report_verdict no longer promotes a nested finding's threat_level to the report verdict; a missing or unrecognised top-level aggregate verdict is unknown, so EXP-4 and the baseline runner cannot pass on it. - Both lab scripts wait for tpa-lab-attacker AND tpa-lab-victim by name and fail on a readiness or stability timeout instead of scanning a half-connected lab. - The suite preflight refuses a busy port 8081 and kills nothing (the old machine-wide pkill could hit unrelated lab daemons).
…d references in lab configs, refuse any busy lab port
- revertedToPreviousContract: an empty PreviousSchema is no longer a
wildcard; the revert is proven only when the live contract hashes to the
ApprovedHash under the current formula (RT-01, review round 10 P1)
- lab_config_check_isolation refuses ${env:...}/${keyring:...} references
in server entries and docker_isolation, which the daemon resolves at
launch (review round 10 P1)
- run-tpa-lab-docker.sh refuses any listener on 8081 via lab_port_busy
before creating state or starting the daemon (review round 10 P2)
- record round-10 follow-ups and fresh red-team results
Brings in SEC-01 (detect-engine de-obfuscation, confusable folding and paraphrase/multilingual soft families) and the other main merges. Conflict resolution and follow-ups for this branch's gate semantics: - docs/features/security-quarantine.md: keep the RT-02 scan-mode row and describe the RT-01/RT-03 gate (structural input-schema changes, added output schemas, added descriptions and hint flips are all held); the input-schema-only, absent-to-present output schema and empty-description exceptions documented on main no longer apply to captured records. - Flip main's three "known gap" pins (manual input-schema-only change, absent-to-present output schema, empty-to-present description) to assert the change is held. - SEC-01 scan-mode corpus test: the benign wording edit is now held as well (RT-02: a changed contract is never scan-approved); hostile variants must also carry non-clean scan hold evidence.
…(RT-04, RT-07)
Builds on SEC-01 (de-obfuscation, confusable folding, paraphrase and
multilingual soft families) and closes only the gaps it left:
- Mixed-script homoglyphs reach the HARD tier: a third phrase view folds
only words that mix Latin with look-alike letters, keeping spacing,
punctuation, quotes and negation, so position classification stays
truthful. Negated matches and the leet/spacing de-obfuscated view stay
review-only, as SEC-01 decided.
- Destination-anchored exfiltration (HARD): an exfil verb plus an explicit
URL or e-mail destination (defanged hxxps://, [.] included) and a secret
attached by an inclusion word or named before the destination.
- Credential-file-to-argument (HARD): reading ~/.ssh, ~/.aws, .env and
similar files into a named field/parameter/argument.
- Data-sink parameters by shape (SOFT): an unexplained free-text parameter
whose own description asks for data stored alongside the operation or for
the user's conversation, prompt or environment; no longer name-list only.
- New SOFT directive families: paraphrased and German/French/Spanish secrecy
imperatives, recipient hijack to a hard-coded number/address/wallet, and
conversation harvest.
- RT-07 position fixes: a possessive or contraction apostrophe no longer
counts as an open quote, and the verb of a leading temporal clause
("Before reporting, ...") no longer makes the directive descriptive.
- Fix stemmed plural targets (passphrases, messages) the families missed.
Same-name collisions with a rewritten description stay out of scope (owner
decision MCP-3520 in shadowing.go).
The lab follows: the mutants profile (EXP-3) must now scan dangerous and
the suite no longer allows an EXP-3 hole; the stage-3 facade wording is
re-worded so EXP-6 still proves that a clean-scanning changed contract is
held. The real-world benign corpora (527 + 45 tools) show no tool with a
worse verdict; the SEC-01 corpus gains an rt04 split with dangerous/held
expectations and benign controls.
Deploying mcpproxy-docs with
|
| Latest commit: |
68e64d5
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://995e0f92.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://feat-tpa-attack-lab.mcpproxy-docs.pages.dev |
| return nil, logs, fmt.Errorf("in-process scanner %s: no source dir with exported tool definitions", s.ID) | ||
| } | ||
| toolsPath := filepath.Join(req.SourceDir, "tools.json") | ||
| fileData, err := os.ReadFile(toolsPath) |
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 38280113846 --repo smart-mcp-proxy/mcpproxy-go
|
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…nt findings, bound exfil windows to one sentence, keep possessives inside quotes (Sol r12)
- Lab preflight: the daemon's encoding/json matches config keys
case-insensitively (last match wins), so {"command":"/lab","Command":
"docker"} passed preflight and ran docker unwrapped. The isolation and
data_dir checks now re-key objects by case-folded names and refuse
colliding keys.
- EXP-6/6b require the trust_mode: scan gate's own log line for each tool.
The new EXP-6c sends an overt pull to a trusted scan-mode server and
requires the persisted held_reason/held_verdict/held_signals.
- EXP-3 checks the current job's per-mutant findings: hard for M01/M03, any
finding for M02/M04/M06. The aggregate verdict alone no longer holds.
- Detect: the destination-to-secret and credential-file-to-argument windows
cross a dot inside a token but not a sentence-ending period. A destination
no longer swallows the period. The stemmer keeps a possessive "'s", and
oddQuoteCount never treats an apostrophe inside a word as a quote mark, so
a quoted example with possessives keeps its example-position discount.
Three new not_dangerous corpus controls.
- Docs: document the pre-v4 unknown-hints exception in the upgrade wildcard
and qualify the annotation-flip guarantee.
…a smuggled credential, and let longer prohibitions keep mixed-script overrides review-only (Sol r13)
- Credential-file-to-argument: key files (id_rsa, id_ed25519, .aws/credentials,
.netrc, .pgpass, /etc/shadow, ...) placed in a parameter stay HARD. Config
sources that also hold ordinary settings (~/.ssh, .env, ~/.aws, kubeconfig,
docker config, /etc/passwd, keychain) are HARD only when the moved value is
the file itself ("it", "its contents") or a secret (API key, token,
password, private key). "Load ~/.ssh/config and pass the host alias in the
host field" and "Read .env and put the configured timezone in the timezone
parameter" are no longer HARD.
- negatedBefore allows up to seven words between the negation and the match
("Do not under any circumstances ...", "You must never, even if the user
asks, ..."). A contrast or coordinated directive ("just", "but", "and",
"then", ...) ends its reach, and idioms such as "no matter what" or "do not
hesitate to" do not count, so affirmative mixed-script overrides stay HARD.
- Six new not_dangerous corpus controls.
…ial-file tier, match possessive secrecy, refuse shared cache volumes in the lab, print a PID-scoped cleanup hint (Sol r14)
…be the file, keep negated credential-file directives review-only on every view, refuse a custom isolation registry in the lab preflight (Sol r15)
…ent step review-only, require a hard finding for both EXP-4 poisoned tools (Sol r16)
…gated placement step review-only in the named-secret pronoun family, mask credential basenames inside non-secret file names (Sol r17)
…t please/also right after a negation as part of the prohibition (Sol r18)
…t families, so explicit metadata placement stays off HARD and a later secret becomes the referent (Sol r19)
…tching, pin tools.json as a regular file for the whole Docker scanner run (Sol r20)
- A metadata-only placement ("put its length in the size field") no longer
hides a later "put it in the notes field": the possessive pronoun is
masked instead of rejecting the match, so the regexp reaches the later
placement. The reject hook is removed.
- A secret noun excluded from the placement ("not the API key", "never the
secret", "instead of the token") is masked, so it is not the payload.
- Docker scanners: tools.json must be a regular file before the run, stay the
same file during it (watched every 20ms) and after it; a symlink retargeted
or a file swapped in mid-run fails closed. Real-Docker tests included.
Resolve tool_quarantine.go: the gate reads policy from storage (D16) and keeps scan mode holding changed contracts; checkToolApprovalsHeld serves the discovery pass under the approval lock. Pass the instance commit generation through quarantined-contract verification so a superseded instance's capture is dropped.
…ent Docker scanners (Sol r20) The exported tool-definitions snapshot was bind-mounted over <source>/tools.json inside the upstream-writable source dir, so a symlink there decided where the snapshot landed and retargeting it after the container started handed the scanner other metadata. A scanner that reads tool metadata now mounts a copy made through os.Root (symlinks copied as symlinks, special files skipped, size-capped, fail closed over the cap) with the snapshot written as a regular tools.json. The pin and watcher remain as tampering evidence. Adds a real-Docker regression test that retargets the link around container start.
…opying a scanner source (Sol r21) A directory swapped for a FIFO after its Lstat blocked the staging copy forever; directories are now opened non-blocking and checked after open, and staging stops on context cancellation. A source dir that contains the proxy data dir (a working dir of HOME) copied the staging area into itself; that directory is now skipped by identity.
…b readiness check Since Spec 116 the supervisor disconnects a quarantined upstream about a second after its boot connect, so the lab scripts' 'connected on 3 consecutive polls' readiness never held for a quarantined config. An upstream now counts as settled when it is connected, or quarantined with no error after the daemon log shows its MCP connect.
| if pinned == nil { | ||
| return "" | ||
| } | ||
| cur, err := os.Lstat(filepath.Join(req.SourceDir, "tools.json")) |
| return nil, nil | ||
| } | ||
| path := filepath.Join(req.SourceDir, "tools.json") | ||
| linfo, err := os.Lstat(path) |
| if !linfo.Mode().IsRegular() { | ||
| return nil, fmt.Errorf("exported tool definitions (tools.json) are not a regular file (a symlink or special file); the result is discarded") | ||
| } | ||
| f, err := os.Open(path) |
This was referenced Oct 12, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A Docker-isolated TPA attack lab red-teamed the rug-pull gate and the offline detect engine end to end (
docs/research/2026-10-11-tpa-attack-lab/). This PR adds the lab and fixes the seven findings fromllm-report.md.Rug-pull gate (
internal/runtime,internal/storage,internal/security/scanner,internal/server)trust_mode: scan, a changed contract is never auto-approved, even when the scan is clean (maintainer policy). The scan still runs and its verdict is recorded as hold evidence. New tools stay scan-gated.readOnly/destructive/idempotent/openWorld) are now part of the approval hash, with a migration that does not force re-review.Detect engine (
internal/security/detect), on top of SEC-01 (#1588)Merge with main: main had three "known gap" tests (input-schema-only change in manual mode, absent-to-present output schema, empty-to-present description). This branch closes all three, so those tests now assert the hold, and
docs/features/security-quarantine.mdis updated to match.Post-fix results
All upstreams in these runs are Docker-isolated: distroless image,
network_mode: none, read-only rootfs, all caps dropped.Offline harness (
go run ./cmd/tpa-redteam):False positives:
rt04corpus split: all 7 benign near-misses stay clean, and both quoted/negated examples stay non-dangerous.scan-eval --gate: recall 1.0, 0 FP on 26 benign and 21 hard negatives.Details:
docs/research/2026-10-11-tpa-attack-lab/end-to-end-experiments.md("Post-fix results" and "RT-04 / RT-07 after merging SEC-01").Verification
Behavior changes
manualandscantrust modes, every contract change is now held, including input-schema edits, added output schemas or descriptions, and annotation flips. Inscanmode a clean verdict no longer approves a changed contract.dangerous.🤖 Generated with Claude Code