Sponsored by Deepsite.site

Command Injection Vulnerability in MCP File Reader

Created By
Eliran798 months ago
A deliberately vulnerable MCP server demonstrating command injection flaws. This Python implementation shows how lack of input sanitization in file paths leads to critical security vulnerabilities allowing attackers to execute arbitrary commands. For educational purposes only - demonstrates both the vulnerability and proper security practices.
Content

Command Injection Vulnerability in MCP File Reader

This repository demonstrates a critical command injection vulnerability in a Python MCP (Model Context Protocol) server implementation. The vulnerability allows attackers to execute arbitrary shell commands on the host system by manipulating the file path parameter.

The Vulnerability

The vulnerability exists in the read_file function which is intended to read files from a "safe" directory but contains a dangerous implementation flaw:

command = f"cat {file_name}"
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)

This code is vulnerable because:

  1. It uses shell=True which invokes a shell to execute the command
  2. It directly interpolates user input (file_name) into the command string without proper sanitization
  3. It performs only superficial validation on the input path

A simple semantic difference between using quotes around the filename ('file_name') and not using quotes (file_name) exposes the entire system to command execution.

Installation

Prerequisites

  • Python 3.12 or higher
  • MCP library version 1.6.0

Setup

  1. Clone this repository:

    git clone https://github.com/Eliran79/Vulnerable-file-reader-server.git
    cd Vulnerable-file-reader-server
    
  2. Install the MCP server:

    mcp install main.py
    
  3. Configure Claude Desktop to use your MCP server by editing ~/.config/claude-desktop/claude_desktop_config.json:

    {
      "mcpServers": {
        "file-reader": {
          "command": "/ABSOLUTE/PATH/TO/uv",
          "args": [
            "--directory",
            "/data/git/file_reader_server",
            "/usr/bin/uv",
            "run,--with,mcp,mcp,run,main.py"
          ]
        }
      }
    }
    

    Be sure to replace /ABSOLUTE/PATH/TO/uv with the actual path to your uv executable and adjust the directory path if needed.

  4. Start the MCP server in development mode:

    mcp dev main.py
    

Demonstration

  1. In a separate terminal, install and run the MCP inspector:

    pip install mcp-inspector
    mcp-inspector
    
  2. Connect to the server in the MCP Inspector GUI:

    • Set Transport Type to "STDIO"
    • Set Command to: run --with mcp run main.py
    • Click "Restart"
  3. Exploit the vulnerability:

    • Go to the "Tools" tab
    • Find the "read_file" tool
    • In the "file_name" field, enter:
      /tmp/safe/test.txt; whoami
      
    • Click "Run Tool"
  4. You should see the contents of test.txt followed by your username, demonstrating successful command execution.

Additional Exploitation Examples

Here are more command injection payloads to try:

/tmp/safe/test.txt; id
/tmp/safe/test.txt; ls -la /etc
/tmp/safe/test.txt; cat /etc/passwd
/tmp/safe/test.txt; echo $(hostname)
/tmp/safe/test.txt; find / -name "*.conf" 2>/dev/null | head -5

Proper Fix

To fix this vulnerability, never use shell=True with user-provided input. Instead:

# SECURE: Use a list of arguments instead of shell=True
result = subprocess.check_output(['cat', file_name], shell=False)

# OR, if shell=True is necessary, properly quote the argument:
import shlex
result = subprocess.check_output(f"cat {shlex.quote(file_name)}", shell=True)

# AND perform proper path validation:
import os
safe_dir_resolved = os.path.abspath(SAFE_DIRECTORY)
requested_path_resolved = os.path.abspath(file_name)
if not requested_path_resolved.startswith(safe_dir_resolved):
    return f"Error: Access denied. Path traversal attempt detected."

Warning

⚠️ FOR EDUCATIONAL PURPOSES ONLY: This implementation contains deliberate security vulnerabilities. Never use this code in a production environment or on any system that contains sensitive information.

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
CursorThe AI Code Editor
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
ChatWiseThe second fastest AI chatbot™
Serper MCP ServerA Serper MCP Server
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Tavily Mcp
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Amap Maps高德地图官方 MCP Server
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
WindsurfThe new purpose-built IDE to harness magic
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
DeepChatYour AI Partner on Desktop
Playwright McpPlaywright MCP server
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.