惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
M
MIT News - Artificial intelligence
美团技术团队
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
有赞技术团队
有赞技术团队
L
LangChain Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
S
SegmentFault 最新的问题
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
B
Blog
I
InfoQ

NodeJS Security & NodeJS Secure Coding's Blog

Hardening Your npm and pnpm Configs in the Age of Shai-Hulud Argument Injection vulnerability in git-blame@1.4.0 Argument Injection vulnerability in `gits@0.1.8` Command Injection vulnerability in `@fab1o/git@1.4.0` Command Injection vulnerability in `git-contributors` via unsanitized CLI arguments Command Injection vulnerability in `git-q@0.0.3` Command injection vulnerability via unsanitized CLI arguments in touxing/fast-git-clone Command Injection vulnerability in `willitmerge@0.2.1` A Directory Traversal Vulnerability I found in Mastra AI Frameworks MCP Server Mastering NPX: A Cheatsheet for npm and Node.js Power Users Mitigate Supply Chain Security with DevContainers and 1Password for Node.js Local Development The Tale of the Vulnerable MCP Database Server Bad Security Defaults in Mastra AI Frameworks Templates SQL Injection and Bypassing "Read-Only" Mode in Xata's MCP Server Security Advisory for qix npm supply-chain compromise affecting debug and billions of weekly download users How to Mitigate SQL Bypass in MCP Servers Argument Injection Vulnerability in ggit How to Bypass Access Control in PostgreSQL in Simple PSQL MCP Server for SQL Injection Command Injection Flaws in ggit: Unveiling a Vulnerability Command Injection Vulnerability in Create MCP Server STDIO Tool Exposes System Monitoring Functions GitHub Kanban MCP Server Command Injection Vulnerability Threatens Developer Workflows Critical Command Injection Flaw in iOS Simulator MCP Server Exposes Development Environments Command Injection Vulnerability Discovered in Codehooks MCP Server: A Critical Security Analysis SSRF Shenanigans in safe-axios: Redirects Open the Backdoor SSRF Vulnerability in safe-axios: Unintended Public Address Classification Bypassing SSRF Safeguards in ssrfcheck: A Case of Incomplete Denylists Don't Be Fooled by Multicast, SSRF Bypass in private-ip Node.js Authentication from Lucia to Better Auth Bypassing SSRF Protection in nossrf: When Your Safeguards Become Loopholes Vue CLI Security Fix to Mitigate NPM Binary Planting
Enhancing MCP Server Security: A Guide to Using execFile
2025-09-05 · via NodeJS Security & NodeJS Secure Coding's Blog

In the world of Node.js applications, security is paramount, especially when dealing with user inputs that could potentially be exploited. This is even more so important when building agentic workflows using the Model Context Protocol (MCP) servers. This guide I wrote focuses on securing the MCP Server against command injection vulnerabilities by replacing the unsafe exec function with execFile. By the end of this tutorial, you’ll have a more secure MCP Server implementation, reducing the risk of malicious command execution.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Node.js: Current LTS version installed.
  • Familiarity with Node.js child process APIs: Understanding of exec and execFile.

Understanding the Vulnerability

Command injection vulnerabilities occur when an application passes unsafe user input to a system shell. In the MCP Server, the which-app-on-port tool uses the exec function, which is vulnerable to such attacks. Here’s a snippet of the vulnerable code:

server.tool("which-app-on-port", { port: z.number() }, async ({ port }) => {

const result = await new Promise<ProcessInfo>((resolve, reject) => {

exec(`lsof -t -i tcp:${port}`, (error, pidStdout) => {

if (error) {

reject(error);

return;

}

const pid = pidStdout.trim();

exec(`ps -p ${pid} -o comm=`, (error, stdout) => {

if (error) {

reject(error);

return;

}

resolve({ command: stdout.trim(), pid });

});

});

});

});

Exploitation Example

An attacker could exploit this by injecting shell commands through the port parameter, such as ; rm -rf /tmp;#, leading to arbitrary command execution on the server.

Secure Coding Practices

Why exec is Unsafe

The exec function spawns a shell and executes the command within that shell, making it susceptible to injection attacks. This is particularly dangerous when user input is concatenated directly into the command string.

How execFile Mitigates Risks

As a replacement to the unsafe Node.js exec API, developers should consider execFile to execute a file directly without spawning a shell, thus preventing shell interpretation of the command and its arguments. This makes it a safer alternative for executing system commands with user input.

Implementing the Fix

Let’s replace exec with execFile in the MCP Server to mitigate the command injection vulnerability.

Step 1: Replace exec with execFile

First, update the which-app-on-port tool to use execFile:

server.tool("which-app-on-port", { port: z.number() }, async ({ port }) => {

const result = await new Promise<ProcessInfo>((resolve, reject) => {

execFile('lsof', ['-t', '-i', `tcp:${port}`], (error, pidStdout) => {

if (error) {

reject(error);

return;

}

const pid = pidStdout.trim();

execFile('ps', ['-p', pid, '-o', 'comm='], (error, stdout) => {

if (error) {

reject(error);

return;

}

resolve({ command: stdout.trim(), pid });

});

});

});

});

Why this matters: By using execFile, we eliminate the risk of shell command injection, as the command and its arguments are passed as separate parameters.

Step 2: Verify the Implementation

To ensure the vulnerability is resolved, test the tool with various inputs:

node server.js

# Test with a valid port

curl http://localhost:3000/which-app-on-port?port=8080

# Test with a malicious input

curl http://localhost:3000/which-app-on-port?port=8080;touch /tmp/pwned;#

Expected Output: The server should only execute the lsof and ps commands without interpreting the malicious input.

Broader Security Implications

Securing your MCP Server is just one step in maintaining a robust security posture. Here are some ongoing practices to consider:

  • Regular Security Audits: Periodically review your code for vulnerabilities.
  • Input Validation: Always validate and sanitize user inputs.
  • Dependency Management: Keep your dependencies up to date to avoid known vulnerabilities.

Conclusion

By replacing exec with execFile, you’ve taken a significant step towards securing your MCP Server against command injection attacks. This change not only protects your application but also aligns with best practices in secure coding.

  • Next Steps:
    • Implement similar security practices in other projects.
    • Follow on X/Twitter for new guides and security research.
    • Explore more code examples and related work on GitHub.