# Defensive MCP Server Coding: Stopping ReDoS, Indirect Prompt Injection & SSRF

> **TL;DR:** Every MCP tool that fetches URLs, parses user regexes, or reads external GitHub issues processes untrusted input. Hardening requires linear-time regex engines (Go regexp RE2), custom net.Dialer CIDR blocks against SSRF, and clear XML/JSON untrusted-data framing.

- **Canonical URL:** https://syndipath.com/en/blog/preventing-regex-redos-prompt-injection-ssrf-in-custom-mcp-tools
- **Category:** Observability & Security | **Reading Time:** 10 min

When an MCP server fetches a third-party issue or webpage, malicious hidden text inside that document can attempt indirect prompt injection—instructing the host LLM to invoke sibling tools or exfiltrate workspace files.1. Linear-Time Regular Expressions (Zero Catastrophic Backtracking)Backtracking regex engines in Node/Python can freeze an STDIO server on crafted inputs. Test patterns inside SyndiPath's Live Regex Debugger and prefer Go's guaranteed O(n) RE2 engine for server-side log and secret scanning.2. Socket-Level SSRF VerificationVerify resolved IP addresses inside net.Dialer.Control rather than pre-validating hostnames to defeat DNS-rebinding attacks—complementing defensive AI engineering research on NeuroBulletin and MDN Web Security references.

## Production Benchmark Matrix

| Metric | Baseline | Hardened | Verdict |
|---|---|---|---|
| Regex Engine Complexity | Exponential PCRE backtracking | Guaranteed O(n) RE2 / bounded input | Immune to ReDoS hangs |
| Outbound HTTP SSRF Check | Naive URL string prefix check | Post-DNS socket IP CIDR blocklist | Defeats DNS rebinding |
| Untrusted Output Wrapping | Raw concatenated prose | Structured data boundaries + read-only scope | Contains prompt injection |

## FAQ

### Why does URL hostname checking fail against DNS rebinding?
An attacker domain can resolve to a public IP during validation and flip to 127.0.0.1 or 169.254.169.254 with a 0-second TTL during the actual HTTP socket connect.

### Should MCP tools execute shell strings via sh -c?
Never pass LLM-controlled strings to sh -c or cmd /c; always pass argument arrays directly to execve / exec.Command without shell interpolation.

- External Research Reference: [Follow adversarial LLM & security benchmark publications on NeuroBulletin](https://neurobulletin.com/en)
