From 5b37f87b011a07f560bde3a35722eaddfa21743d Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sat, 15 Nov 2025 11:27:16 -0800 Subject: [PATCH 1/7] Add beginner-friendly examples section to SAFE-T1106 Added practical Python code examples demonstrating: - Simple loop detection using call history tracking - Basic loop prevention with iteration limits and convergence checks - Log pattern analysis for identifying loop indicators This addition helps beginners understand autonomous loop exploits through hands-on, runnable code examples. Signed-off-by: Satbir Singh --- techniques/SAFE-T1106/README.md | 192 ++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) diff --git a/techniques/SAFE-T1106/README.md b/techniques/SAFE-T1106/README.md index 328f7d60..eba2b1d9 100644 --- a/techniques/SAFE-T1106/README.md +++ b/techniques/SAFE-T1106/README.md @@ -44,6 +44,197 @@ This is conceptually related to application/protocol loop DoS, where two compone } ``` +### Beginner-Friendly Examples + +The following examples help beginners understand how autonomous loops work and how to detect them in practice. + +#### Example 1: Simple Loop Detection + +This Python example demonstrates how to detect when an agent is stuck in a loop by tracking repeated identical tool calls: + +```python +from collections import defaultdict +from typing import Dict, List, Tuple +import hashlib +import json + +class LoopDetector: + """Simple detector for autonomous loops in MCP tool invocations""" + + def __init__(self, max_repeats: int = 10, time_window_seconds: int = 300): + self.max_repeats = max_repeats + self.time_window = time_window_seconds + self.call_history: Dict[str, List[Tuple[int, str]]] = defaultdict(list) + + def _generate_call_hash(self, tool_name: str, args: dict) -> str: + """Create a unique hash for a tool call based on name and arguments""" + call_signature = json.dumps({"tool": tool_name, "args": args}, sort_keys=True) + return hashlib.md5(call_signature.encode()).hexdigest() + + def record_call(self, session_id: str, tool_name: str, args: dict, timestamp: int): + """Record a tool call and check if it indicates a loop""" + call_hash = self._generate_call_hash(tool_name, args) + key = f"{session_id}:{call_hash}" + + # Add timestamp to history + self.call_history[key].append(timestamp) + + # Remove old entries outside time window + cutoff = timestamp - self.time_window + self.call_history[key] = [t for t in self.call_history[key] if t > cutoff] + + # Check if we've exceeded the repeat threshold + if len(self.call_history[key]) >= self.max_repeats: + return { + "is_loop": True, + "session_id": session_id, + "tool_name": tool_name, + "repeat_count": len(self.call_history[key]), + "call_hash": call_hash + } + + return {"is_loop": False} + +# Example usage +detector = LoopDetector(max_repeats=5, time_window_seconds=60) + +# Simulate repeated identical calls (potential loop) +for i in range(6): + result = detector.record_call( + session_id="session_123", + tool_name="http.get", + args={"url": "https://api.example.com/health"}, + timestamp=1000 + i * 10 + ) + if result["is_loop"]: + print(f"⚠️ Loop detected! Tool '{result['tool_name']}' called {result['repeat_count']} times") + break +``` + +#### Example 2: Basic Loop Prevention + +This example shows a simple way to prevent loops by adding iteration limits and convergence checks: + +```python +class SafeAgentExecutor: + """Agent executor with basic loop prevention""" + + def __init__(self, max_iterations: int = 50, convergence_threshold: float = 0.01): + self.max_iterations = max_iterations + self.convergence_threshold = convergence_threshold + self.iteration_count = 0 + self.previous_results = [] + + def execute_with_guardrails(self, tool_call_func, *args, **kwargs): + """Execute a tool call with loop prevention guardrails""" + if self.iteration_count >= self.max_iterations: + raise RuntimeError(f"Maximum iterations ({self.max_iterations}) exceeded. Possible loop detected.") + + result = tool_call_func(*args, **kwargs) + self.iteration_count += 1 + + # Simple convergence check: stop if result hasn't changed significantly + if len(self.previous_results) > 0: + if self._is_converged(result, self.previous_results[-1]): + return result + + self.previous_results.append(result) + return result + + def _is_converged(self, current: dict, previous: dict) -> bool: + """Check if the result has converged (stopped changing)""" + # Simple check: compare result values + if current.get("status") == previous.get("status"): + return True + return False + + def reset(self): + """Reset the executor state""" + self.iteration_count = 0 + self.previous_results = [] + +# Example usage +def check_service_health(): + """Simulated service health check""" + return {"status": "warming_up", "message": "Service is starting..."} + +executor = SafeAgentExecutor(max_iterations=10) + +try: + for i in range(15): # Try more than max_iterations + result = executor.execute_with_guardrails(check_service_health) + print(f"Iteration {i+1}: {result}") +except RuntimeError as e: + print(f"🛑 Guardrail triggered: {e}") +``` + +#### Example 3: Recognizing Loop Patterns in Logs + +This example shows how to identify loop patterns from log entries: + +```python +import re +from collections import Counter +from typing import List + +def analyze_logs_for_loops(log_entries: List[str]) -> dict: + """Analyze log entries to detect potential autonomous loops""" + + # Patterns that suggest non-convergence + loop_indicators = [ + r"retry", + r"try again", + r"almost ready", + r"warming up", + r"in progress", + r"checking\.\.\." + ] + + # Count tool call patterns + tool_call_pattern = r'tool["\']?\s*:\s*["\']([^"\']+)["\']' + tool_calls = [] + + for entry in log_entries: + # Check for loop indicator phrases + for pattern in loop_indicators: + if re.search(pattern, entry, re.IGNORECASE): + # Extract tool name if present + match = re.search(tool_call_pattern, entry) + if match: + tool_calls.append(match.group(1)) + + # Analyze frequency + tool_counter = Counter(tool_calls) + suspicious_tools = {tool: count for tool, count in tool_counter.items() if count >= 5} + + return { + "total_loop_indicators": len(tool_calls), + "suspicious_tools": suspicious_tools, + "is_likely_loop": len(suspicious_tools) > 0 + } + +# Example log entries +sample_logs = [ + '{"tool": "http.get", "status": "warming_up", "message": "retry in 5s"}', + '{"tool": "http.get", "status": "warming_up", "message": "almost ready"}', + '{"tool": "http.get", "status": "warming_up", "message": "try again"}', + '{"tool": "http.get", "status": "warming_up", "message": "retry in 5s"}', + '{"tool": "http.get", "status": "warming_up", "message": "checking..."}', +] + +analysis = analyze_logs_for_loops(sample_logs) +if analysis["is_likely_loop"]: + print("⚠️ Potential loop detected!") + print(f" Suspicious tool calls: {analysis['suspicious_tools']}") +``` + +These examples demonstrate: +- **Detection**: How to identify when an agent is stuck in a loop +- **Prevention**: Basic guardrails to stop loops before they cause damage +- **Analysis**: How to recognize loop patterns in system logs + +For production systems, combine these approaches with the more sophisticated mitigations listed in the [Mitigation Strategies](#mitigation-strategies) section. + ### Advanced Attack Techniques - Loop amplification via parallel subtasks re-queuing on partial failure - Cross-agent cycles where delegation returns to originator after minor mutation @@ -149,5 +340,6 @@ tags: | Version | Date | Changes | Author | |---------|------------|-----------------------|------------------| | 1.0 | 2025-08-10 | Initial documentation | Sunil Dhakal | +| 1.1 | 2025-01-27 | Added beginner-friendly examples section with practical code demonstrations for loop detection, prevention, and log analysis | The SAFE-MCP Authors | From 82b64a0e63a85b80d68ad24586050dae355dc53f Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sat, 15 Nov 2025 20:11:33 -0800 Subject: [PATCH 2/7] Update version history author to Satbir Singh Signed-off-by: Satbir Singh --- techniques/SAFE-T1106/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/techniques/SAFE-T1106/README.md b/techniques/SAFE-T1106/README.md index eba2b1d9..52a939f7 100644 --- a/techniques/SAFE-T1106/README.md +++ b/techniques/SAFE-T1106/README.md @@ -340,6 +340,6 @@ tags: | Version | Date | Changes | Author | |---------|------------|-----------------------|------------------| | 1.0 | 2025-08-10 | Initial documentation | Sunil Dhakal | -| 1.1 | 2025-01-27 | Added beginner-friendly examples section with practical code demonstrations for loop detection, prevention, and log analysis | The SAFE-MCP Authors | +| 1.1 | 2025-01-27 | Added beginner-friendly examples section with practical code demonstrations for loop detection, prevention, and log analysis | Satbir Singh | From c6c45db8906db42d4f92cc3eada40ffc586ba98b Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sun, 16 Nov 2025 09:32:19 -0800 Subject: [PATCH 3/7] docs(SAFE-T1106): fix changelog date and add md5 usage note Signed-off-by: Satbir Singh --- techniques/SAFE-T1106/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/techniques/SAFE-T1106/README.md b/techniques/SAFE-T1106/README.md index 52a939f7..8e368a91 100644 --- a/techniques/SAFE-T1106/README.md +++ b/techniques/SAFE-T1106/README.md @@ -67,7 +67,11 @@ class LoopDetector: self.call_history: Dict[str, List[Tuple[int, str]]] = defaultdict(list) def _generate_call_hash(self, tool_name: str, args: dict) -> str: - """Create a unique hash for a tool call based on name and arguments""" + """Create a unique hash for a tool call based on name and arguments + + Note: MD5 is used here for non-cryptographic purposes (content identification). + For security-sensitive applications, use SHA-256 or another secure hash function. + """ call_signature = json.dumps({"tool": tool_name, "args": args}, sort_keys=True) return hashlib.md5(call_signature.encode()).hexdigest() @@ -340,6 +344,6 @@ tags: | Version | Date | Changes | Author | |---------|------------|-----------------------|------------------| | 1.0 | 2025-08-10 | Initial documentation | Sunil Dhakal | -| 1.1 | 2025-01-27 | Added beginner-friendly examples section with practical code demonstrations for loop detection, prevention, and log analysis | Satbir Singh | +| 1.1 | 2025-11-16 | Added beginner-friendly examples section with practical code demonstrations for loop detection, prevention, and log analysis | Satbir Singh | From 75778e57e6177206ee6b275da315c51732b3a66d Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sun, 16 Nov 2025 09:53:52 -0800 Subject: [PATCH 4/7] feat(SAFE-T1004): add Server Impersonation / Name-Collision technique documentation - Added comprehensive documentation for SAFE-T1004 technique - Includes attack vectors, technical details, detection methods, and mitigations - Created Sigma-format detection rule for identifying server impersonation attacks - Updated main README to link to new technique documentation This technique documents how attackers impersonate trusted MCP servers through name collision, DNS hijacking, and discovery service manipulation to gain initial access to MCP environments. Signed-off-by: Satbir Singh --- README.md | 2 +- techniques/SAFE-T1004/README.md | 303 +++++++++++++++++++++++ techniques/SAFE-T1004/detection-rule.yml | 147 +++++++++++ 3 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 techniques/SAFE-T1004/README.md create mode 100644 techniques/SAFE-T1004/detection-rule.yml diff --git a/README.md b/README.md index a6f3e9aa..280ffdd1 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ The SAFE-MCP framework defines 14 tactics that align with the MITRE ATT&CK metho | **ATK-TA0001** | **Initial Access** | [SAFE-T1001](techniques/SAFE-T1001/README.md) | Tool Poisoning Attack (TPA) | Attackers embed malicious instructions within MCP tool descriptions that are invisible to users but processed by LLMs | | ATK-TA0001 | Initial Access | [SAFE-T1002](techniques/SAFE-T1002/README.md) | Supply Chain Compromise | Distribution of backdoored MCP server packages through unofficial repositories or compromised legitimate sources | | ATK-TA0001 | Initial Access | [SAFE-T1003](techniques/SAFE-T1003/README.md) | Malicious MCP-Server Distribution | Adversary ships a trojanized server package or Docker image that users install, gaining foothold when the host registers its tools | -| ATK-TA0001 | Initial Access | SAFE-T1004 | Server Impersonation / Name-Collision | Attacker registers a server with the same name/URL as a trusted one, or hijacks discovery, so the client connects to them instead | +| ATK-TA0001 | Initial Access | [SAFE-T1004](techniques/SAFE-T1004/README.md) | Server Impersonation / Name-Collision | Attacker registers a server with the same name/URL as a trusted one, or hijacks discovery, so the client connects to them instead | | ATK-TA0001 | Initial Access | [SAFE-T1008](techniques/SAFE-T1008/README.md) | Tool Shadowing Attack | Malicious MCP servers impersonate or interfere with legitimate tools to hijack execution within MCP-based workflows through cross-server tool interference | | ATK-TA0001 | Initial Access | SAFE-T1005 | Exposed Endpoint Exploit | Misconfigured public MCP endpoints (no auth, debug on) let attackers connect, enumerate tools or trigger RCE | | ATK-TA0001 | Initial Access | SAFE-T1006 | User-Social-Engineering Install | Phishing/social posts persuade developers to "try this cool tool"; the installer silently registers dangerous capabilities | diff --git a/techniques/SAFE-T1004/README.md b/techniques/SAFE-T1004/README.md new file mode 100644 index 00000000..5d009595 --- /dev/null +++ b/techniques/SAFE-T1004/README.md @@ -0,0 +1,303 @@ +# SAFE-T1004: Server Impersonation / Name-Collision + +## Overview +**Tactic**: Initial Access (ATK-TA0001) +**Technique ID**: SAFE-T1004 +**Severity**: High +**First Observed**: Not observed in production +**Last Updated**: 2025-11-16 + +## Description +Server Impersonation / Name-Collision is an attack technique where adversaries register MCP servers with identical names, URLs, or identifiers as trusted servers, or hijack discovery mechanisms, causing clients to connect to malicious servers instead of legitimate ones. This attack exploits the trust relationships established during MCP server discovery and registration processes. + +This technique differs from supply chain compromise (SAFE-T1002) and malicious server distribution (SAFE-T1003) in that it focuses specifically on impersonating existing trusted servers rather than creating new malicious packages. Attackers leverage name collision vulnerabilities, DNS manipulation, discovery service hijacking, or registry poisoning to redirect legitimate client connections to attacker-controlled infrastructure. + +## Attack Vectors +- **Primary Vector**: Server name/URL collision in MCP server registries or discovery services +- **Secondary Vectors**: + - DNS hijacking for MCP server endpoints + - Typosquatting server names (e.g., "github-mcp" vs "github-mcp-tools", "mcp-github" vs "mcp-github-official") + - Discovery service manipulation (hijacking service discovery protocols) + - Registry poisoning attacks (injecting malicious entries into server registries) + - Man-in-the-middle during server discovery phase + - Certificate/subdomain hijacking for HTTPS endpoints + - Namespace collision in package registries (npm, PyPI, etc.) + +## Technical Details + +### Prerequisites +- Access to server registry or discovery mechanism +- Ability to host malicious MCP server +- Knowledge of target server names, URLs, or identifiers +- Understanding of MCP server discovery protocols +- Capability to manipulate DNS or network routing (for network-level attacks) + +### Attack Flow +1. **Reconnaissance Stage**: Attacker identifies target trusted MCP servers and their registration details (names, URLs, endpoints, certificates) +2. **Impersonation Preparation**: Create malicious MCP server with identical or similar identifying information +3. **Discovery Manipulation**: Hijack or poison discovery mechanism (DNS, service registry, package registry) to point to malicious server +4. **Registration Stage**: Register malicious server with colliding name/identifier in target registry +5. **Connection Interception**: Legitimate clients attempt to connect to trusted server but are redirected to malicious server +6. **Trust Exploitation**: Malicious server presents itself as trusted server, potentially using stolen or forged credentials +7. **Exploitation Stage**: Client establishes connection and grants permissions, allowing attacker to execute malicious operations +8. **Post-Exploitation**: Attacker maintains access through persistent connections or establishes backdoors + +### Example Scenario + +**DNS-Based Server Impersonation:** +```json +{ + "mcp_servers": { + "github": { + "command": "node", + "args": ["/path/to/github-mcp-server"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} +``` + +Attacker manipulates DNS resolution: +```bash +# Malicious DNS entry pointing to attacker-controlled server +github-mcp-server.example.com. 300 IN A 192.0.2.100 +# Legitimate server is at 203.0.113.50 +``` + +**Registry Name Collision Attack:** +```json +{ + "name": "mcp-github-tools", + "version": "1.0.0", + "description": "Official GitHub integration for MCP", + "author": "GitHub Inc.", + "repository": { + "type": "git", + "url": "https://github.com/github/mcp-github-tools" + }, + "main": "dist/index.js" +} +``` + +Attacker creates malicious package with similar name: +```json +{ + "name": "mcp-github-tools-official", + "version": "1.0.1", + "description": "Official GitHub integration for MCP - Enhanced", + "author": "GitHub Inc.", + "repository": { + "type": "git", + "url": "https://github.com/github-official/mcp-github-tools" + }, + "main": "dist/index.js" +} +``` + +**Discovery Service Hijacking:** +```python +# Legitimate discovery service response +{ + "servers": [ + { + "id": "github-mcp", + "name": "GitHub MCP Server", + "endpoint": "https://mcp.github.com/api", + "version": "1.0.0", + "verified": true + } + ] +} + +# Attacker poisons discovery service +{ + "servers": [ + { + "id": "github-mcp", + "name": "GitHub MCP Server", + "endpoint": "https://mcp-github.attacker.com/api", # Redirected + "version": "1.0.0", + "verified": true # Forged verification + } + ] +} +``` + +### Advanced Attack Techniques + +According to security research on service discovery and name collision attacks, attackers have developed sophisticated variations: + +1. **Subdomain Takeover**: Exploiting abandoned subdomains or DNS misconfigurations to host malicious MCP servers at trusted domains +2. **Certificate Pinning Bypass**: Using compromised or misissued certificates to impersonate HTTPS endpoints +3. **Multi-Vector Collision**: Combining name collision with DNS hijacking and registry poisoning for higher success rates +4. **Time-Based Attacks**: Registering malicious servers during maintenance windows or registry updates when verification may be relaxed + +## Impact Assessment +- **Confidentiality**: High — Attacker gains access to all data and credentials that would be accessible to the legitimate server +- **Integrity**: High — Attacker can modify, delete, or corrupt data through impersonated server access +- **Availability**: Medium — Legitimate services may be disrupted, and malicious server may provide degraded or malicious functionality +- **Scope**: Network-wide — Can affect all clients attempting to connect to the impersonated server + +### Current Status (2025) +Many MCP implementations rely on simple name-based or URL-based server identification without robust verification mechanisms. Server discovery protocols often lack cryptographic verification, making name collision attacks feasible. Organizations are beginning to implement: +- Certificate pinning for server endpoints +- Cryptographic server identity verification +- Registry validation and reputation systems +- DNS security extensions (DNSSEC) for discovery services + +## Detection Methods + +### Indicators of Compromise (IoCs) +- Unexpected server endpoint connections (IP addresses not matching known legitimate servers) +- DNS resolution anomalies (resolving to unexpected IP addresses) +- Certificate mismatches or unexpected certificate authorities +- Server metadata inconsistencies (version mismatches, unexpected capabilities) +- Unusual network traffic patterns from MCP server connections +- Failed authentication attempts from servers claiming to be trusted +- Registry entries with suspicious modification timestamps +- Discovery service responses with unexpected server endpoints + +### Detection Rules + +**Important**: The following rule is written in Sigma format and contains example patterns only. Organizations should: +- Use AI-based anomaly detection to identify novel impersonation patterns +- Regularly update detection logic based on operational telemetry +- Implement multiple layers of detection beyond pattern matching +- Consider behavioral analysis of server connections and registry changes + +```yaml +title: MCP Server Impersonation / Name Collision Detection +id: 71aa869b-65cc-47f3-ada5-d9e67337dc44 +status: experimental +description: Detects potential MCP server impersonation through name collision, DNS anomalies, and registry manipulation +author: SAFE-MCP Authors +date: 2025-11-16 +references: + - https://github.com/safe-mcp/techniques/SAFE-T1004 + - https://attack.mitre.org/techniques/T1199/ +logsource: + product: mcp + service: server_discovery +detection: + selection_dns_anomaly: + event_type: "dns_resolution" + server_name: "*" + resolved_ip|not_in: + - "known_legitimate_ips" + dns_response_time: ">5000ms" + selection_name_collision: + event_type: "server_registration" + server_name|contains: + - "github" + - "slack" + - "notion" + - "google" + server_id|endswith: + - "-official" + - "-tools" + - "-enhanced" + - "-pro" + registration_source: "unknown" + selection_certificate_mismatch: + event_type: "tls_handshake" + server_name: "*" + certificate_issuer|not_in: + - "known_trusted_cas" + certificate_fingerprint|not_in: + - "known_legitimate_certificates" + selection_registry_poisoning: + event_type: "registry_update" + server_name: "*" + endpoint_changed: true + endpoint_domain|not_contains: + - "github.com" + - "slack.com" + - "notion.so" + update_timestamp: "suspicious_hours" + selection_discovery_hijack: + event_type: "discovery_response" + server_count: ">1" + duplicate_server_ids: true + endpoint_conflict: true + condition: selection_dns_anomaly or selection_name_collision or selection_certificate_mismatch or selection_registry_poisoning or selection_discovery_hijack +falsepositives: + - Legitimate server migrations or endpoint changes + - DNS infrastructure updates + - Certificate renewals from different CAs + - Development and testing environments with local server instances +level: high +tags: + - attack.initial_access + - attack.t1199 + - safe.t1004 +``` + +### Behavioral Indicators +- Sudden changes in server endpoint IP addresses without corresponding infrastructure changes +- Multiple servers registering with similar names in short time periods +- Discovery service responses containing conflicting server information +- Clients connecting to servers with mismatched metadata (version, capabilities, author) +- Unusual geographic locations for server connections (servers appearing in unexpected regions) +- Registry modification patterns indicating bulk registration of similar-named servers + +## Mitigation Strategies + +### Preventive Controls +1. **[SAFE-M-21: Output Context Isolation](../../mitigations/SAFE-M-21/README.md)**: Implement server identity verification before establishing connections to prevent impersonation. +2. **[SAFE-M-22: Semantic Output Validation](../../mitigations/SAFE-M-22/README.md)**: Validate server metadata and capabilities against known legitimate server profiles. +3. **Certificate Pinning**: Pin TLS certificates for known legitimate MCP servers to prevent certificate-based impersonation. +4. **Server Identity Verification**: Implement cryptographic server identity verification using public key infrastructure or similar mechanisms. +5. **Registry Validation**: Enforce strict validation and reputation checks in server registries to prevent name collision attacks. +6. **DNS Security**: Use DNSSEC and DNS filtering to prevent DNS-based hijacking attacks. + +### Detective Controls +1. **[SAFE-M-11: Behavioral Monitoring](../../mitigations/SAFE-M-11/README.md)**: Monitor server connection patterns and detect anomalies in endpoint resolution. +2. **[SAFE-M-20: Anomaly Detection](../../mitigations/SAFE-M-20/README.md)**: Detect unusual server registration patterns and name collision attempts. +3. **[SAFE-M-12: Audit Logging](../../mitigations/SAFE-M-12/README.md)**: Maintain comprehensive logs of server discovery, registration, and connection events for forensic analysis. +4. **Registry Monitoring**: Continuously monitor server registries for suspicious entries, bulk registrations, and name collision attempts. + +### Response Procedures +1. **Immediate Actions**: + - Disconnect from suspected impersonated servers immediately + - Revoke any credentials or tokens that may have been exposed to malicious servers + - Block network access to identified malicious server endpoints + - Notify affected users and administrators +2. **Investigation Steps**: + - Analyze DNS resolution logs to identify hijacking attempts + - Review server registry entries for unauthorized modifications + - Examine certificate chains and TLS handshake logs for anomalies + - Correlate discovery service responses with known legitimate server information + - Identify the scope of potential data exposure through malicious server connections +3. **Remediation**: + - Remove malicious server entries from registries + - Implement stronger server identity verification mechanisms + - Update DNS configurations and enable DNSSEC where applicable + - Establish server reputation systems and whitelisting for critical servers + - Enhance discovery service security with cryptographic verification + +## Related Techniques +- [SAFE-T1002](../SAFE-T1002/README.md) – Supply Chain Compromise (related but focuses on package compromise rather than server impersonation) +- [SAFE-T1003](../SAFE-T1003/README.md) – Malicious MCP-Server Distribution (related but involves creating new malicious servers rather than impersonating existing ones) +- [SAFE-T1008](../SAFE-T1008/README.md) – Tool Shadowing Attack (related technique involving tool-level impersonation rather than server-level) +- [SAFE-T1301](../SAFE-T1301/README.md) – Cross-Server Tool Shadowing (similar concept applied at tool level) + +## References +- [Model Context Protocol Specification](https://modelcontextprotocol.io/specification) +- [OWASP Top 10 for LLM Applications](https://owasp.org/www-project-top-10-for-large-language-model-applications/) +- [MITRE ATT&CK: Trusted Relationship (T1199)](https://attack.mitre.org/techniques/T1199/) +- [OWASP: Subdomain Takeover](https://owasp.org/www-community/attacks/Subdomain_takeover) +- [RFC 6762: Multicast DNS](https://tools.ietf.org/html/rfc6762) - Service discovery protocols +- [RFC 4033: DNS Security Introduction and Requirements](https://tools.ietf.org/html/rfc4033) - DNSSEC for secure DNS + +## MITRE ATT&CK Mapping +- [T1199 - Trusted Relationship](https://attack.mitre.org/techniques/T1199/) - Exploiting trust relationships through impersonation +- [T1566.001 - Phishing: Spearphishing Attachment](https://attack.mitre.org/techniques/T1566/001/) - Related social engineering component +- [T1071.001 - Application Layer Protocol: Web Protocols](https://attack.mitre.org/techniques/T1071/001/) - HTTP/HTTPS-based server communication + +## Version History +| Version | Date | Changes | Author | +|---------|------|---------|--------| +| 1.0 | 2025-11-16 | Initial documentation | Satbir Singh | + diff --git a/techniques/SAFE-T1004/detection-rule.yml b/techniques/SAFE-T1004/detection-rule.yml new file mode 100644 index 00000000..82ed838f --- /dev/null +++ b/techniques/SAFE-T1004/detection-rule.yml @@ -0,0 +1,147 @@ +# SIGMA RULE: MCP Server Impersonation / Name Collision Detection +# WARNING: This rule contains example patterns only. Organizations should: +# - Regularly update patterns based on threat intelligence +# - Implement behavioral analysis beyond pattern matching +# - Use AI-based anomaly detection for novel attack vectors +# - Consider environment-specific customizations + +title: MCP Server Impersonation / Name Collision Detection +id: 71aa869b-65cc-47f3-ada5-d9e67337dc44 +status: experimental +description: Detects potential MCP server impersonation through name collision, DNS anomalies, and registry manipulation +author: SAFE-MCP Authors +date: 2025-11-16 +modified: 2025-11-16 +references: + - https://github.com/safe-mcp/techniques/SAFE-T1004 + - https://attack.mitre.org/techniques/T1199/ +logsource: + product: mcp + service: server_discovery + definition: | + Requires comprehensive MCP server discovery and connection logging that captures: + + Server Discovery: + - Server registration events with names, IDs, and endpoints + - Discovery service queries and responses + - Server metadata (version, author, capabilities) + - Registration timestamps and sources + + DNS Resolution: + - DNS queries for MCP server endpoints + - Resolved IP addresses and response times + - DNS server information and DNSSEC validation status + + TLS/Connection: + - TLS handshake events with certificate information + - Certificate issuer and fingerprint data + - Server endpoint connections and IP addresses + - Connection establishment timestamps + + Registry Events: + - Server registry modifications + - Endpoint changes and updates + - Bulk registration events + - Registry access patterns + + Behavioral Context: + - Geographic location of server endpoints + - Connection frequency and patterns + - Server capability mismatches + - Anomaly scores from behavioral analysis +detection: + # DNS-based impersonation detection + selection_dns_anomaly: + event_type: "dns_resolution" + server_name: "*" + resolved_ip|not_in: + - "known_legitimate_ips" + dns_response_time: ">5000ms" + + # Name collision in server registration + selection_name_collision: + event_type: "server_registration" + server_name|contains: + - "github" + - "slack" + - "notion" + - "google" + - "microsoft" + - "openai" + server_id|endswith: + - "-official" + - "-tools" + - "-enhanced" + - "-pro" + - "-premium" + registration_source: "unknown" + server_metadata|contains: + - "version_mismatch" + - "unexpected_capabilities" + + # Certificate-based impersonation + selection_certificate_mismatch: + event_type: "tls_handshake" + server_name: "*" + certificate_issuer|not_in: + - "known_trusted_cas" + certificate_fingerprint|not_in: + - "known_legitimate_certificates" + certificate_validation: "failed" + + # Registry poisoning detection + selection_registry_poisoning: + event_type: "registry_update" + server_name: "*" + endpoint_changed: true + endpoint_domain|not_contains: + - "github.com" + - "slack.com" + - "notion.so" + - "google.com" + - "microsoft.com" + update_timestamp: "suspicious_hours" + bulk_update: true + + # Discovery service hijacking + selection_discovery_hijack: + event_type: "discovery_response" + server_count: ">1" + duplicate_server_ids: true + endpoint_conflict: true + response_source: "unverified" + + # Subdomain takeover indicators + selection_subdomain_takeover: + event_type: "server_connection" + endpoint_subdomain: "*" + certificate_status: "invalid" + dns_cname: "pointing_to_external" + server_metadata: "minimal_or_missing" + + # Geographic anomaly detection + selection_geographic_anomaly: + event_type: "server_connection" + server_name: "*" + endpoint_location|not_in: + - "expected_regions" + connection_frequency: "unusual" + latency: ">threshold" + + condition: selection_dns_anomaly or selection_name_collision or selection_certificate_mismatch or selection_registry_poisoning or selection_discovery_hijack or selection_subdomain_takeover or selection_geographic_anomaly + +falsepositives: + - Legitimate server migrations or endpoint changes with proper notification + - DNS infrastructure updates and maintenance windows + - Certificate renewals from different certificate authorities + - Development and testing environments with local server instances + - Load balancer IP address changes + - CDN endpoint variations for legitimate servers + - Multi-region server deployments + +level: high +tags: + - attack.initial_access + - attack.t1199 + - safe.t1004 + From ebfac7981a8b29dcb8a4de95f7d4bfb65f5df80c Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sun, 16 Nov 2025 10:47:36 -0800 Subject: [PATCH 5/7] docs(SAFE-T1004): enhance Advanced Attack Techniques and Current Status sections - Expanded Advanced Attack Techniques with more detailed explanations - Enhanced Current Status section with specific implementation details - Improved clarity and alignment with SAFE-T1008 format Signed-off-by: Satbir Singh --- techniques/SAFE-T1004/README.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/techniques/SAFE-T1004/README.md b/techniques/SAFE-T1004/README.md index 5d009595..8958903e 100644 --- a/techniques/SAFE-T1004/README.md +++ b/techniques/SAFE-T1004/README.md @@ -129,10 +129,13 @@ Attacker creates malicious package with similar name: According to security research on service discovery and name collision attacks, attackers have developed sophisticated variations: -1. **Subdomain Takeover**: Exploiting abandoned subdomains or DNS misconfigurations to host malicious MCP servers at trusted domains -2. **Certificate Pinning Bypass**: Using compromised or misissued certificates to impersonate HTTPS endpoints -3. **Multi-Vector Collision**: Combining name collision with DNS hijacking and registry poisoning for higher success rates -4. **Time-Based Attacks**: Registering malicious servers during maintenance windows or registry updates when verification may be relaxed +1. **Subdomain Takeover**: Exploiting abandoned subdomains or DNS misconfigurations to host malicious MCP servers at trusted domains. This technique leverages expired domain registrations or misconfigured DNS records pointing to external services that attackers can claim. + +2. **Certificate Pinning Bypass**: Using compromised or misissued certificates to impersonate HTTPS endpoints. Attackers may exploit certificate authority vulnerabilities or social engineering to obtain certificates for legitimate-looking domains. + +3. **Multi-Vector Collision**: Combining name collision with DNS hijacking and registry poisoning for higher success rates. Attackers simultaneously target multiple discovery mechanisms to increase the probability of successful impersonation. + +4. **Time-Based Attacks**: Registering malicious servers during maintenance windows or registry updates when verification may be relaxed. Attackers monitor registry update schedules and exploit periods of reduced security oversight. ## Impact Assessment - **Confidentiality**: High — Attacker gains access to all data and credentials that would be accessible to the legitimate server @@ -141,11 +144,14 @@ According to security research on service discovery and name collision attacks, - **Scope**: Network-wide — Can affect all clients attempting to connect to the impersonated server ### Current Status (2025) -Many MCP implementations rely on simple name-based or URL-based server identification without robust verification mechanisms. Server discovery protocols often lack cryptographic verification, making name collision attacks feasible. Organizations are beginning to implement: -- Certificate pinning for server endpoints -- Cryptographic server identity verification -- Registry validation and reputation systems -- DNS security extensions (DNSSEC) for discovery services +Many MCP implementations rely on simple name-based or URL-based server identification without robust verification mechanisms. Server discovery protocols often lack cryptographic verification, making name collision attacks feasible. + +According to security researchers and the MCP specification, organizations are beginning to implement: +- Certificate pinning for server endpoints to prevent certificate-based impersonation +- Cryptographic server identity verification using public key infrastructure +- Registry validation and reputation systems to detect and prevent name collision attacks +- DNS security extensions (DNSSEC) for discovery services to prevent DNS hijacking +- Server whitelisting and allowlisting mechanisms for critical MCP deployments ## Detection Methods From 1c8e92abaea4f380a85f3fcc92f3a66c1d254ba8 Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sun, 16 Nov 2025 19:14:53 -0800 Subject: [PATCH 6/7] fix(SAFE-T1004): correct Related Techniques link paths Fixed relative paths to use absolute paths from repository root to resolve 404 errors in GitHub PR view. Signed-off-by: Satbir Singh --- techniques/SAFE-T1004/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/techniques/SAFE-T1004/README.md b/techniques/SAFE-T1004/README.md index 8958903e..7f8a08b5 100644 --- a/techniques/SAFE-T1004/README.md +++ b/techniques/SAFE-T1004/README.md @@ -284,10 +284,10 @@ tags: - Enhance discovery service security with cryptographic verification ## Related Techniques -- [SAFE-T1002](../SAFE-T1002/README.md) – Supply Chain Compromise (related but focuses on package compromise rather than server impersonation) -- [SAFE-T1003](../SAFE-T1003/README.md) – Malicious MCP-Server Distribution (related but involves creating new malicious servers rather than impersonating existing ones) -- [SAFE-T1008](../SAFE-T1008/README.md) – Tool Shadowing Attack (related technique involving tool-level impersonation rather than server-level) -- [SAFE-T1301](../SAFE-T1301/README.md) – Cross-Server Tool Shadowing (similar concept applied at tool level) +- [SAFE-T1002](techniques/SAFE-T1002/README.md) – Supply Chain Compromise (related but focuses on package compromise rather than server impersonation) +- [SAFE-T1003](techniques/SAFE-T1003/README.md) – Malicious MCP-Server Distribution (related but involves creating new malicious servers rather than impersonating existing ones) +- [SAFE-T1008](techniques/SAFE-T1008/README.md) – Tool Shadowing Attack (related technique involving tool-level impersonation rather than server-level) +- [SAFE-T1301](techniques/SAFE-T1301/README.md) – Cross-Server Tool Shadowing (similar concept applied at tool level) ## References - [Model Context Protocol Specification](https://modelcontextprotocol.io/specification) From 2f73911af36fdcad18ec525806d75e6d6f81fd81 Mon Sep 17 00:00:00 2001 From: Satbir Singh Date: Sun, 16 Nov 2025 19:25:21 -0800 Subject: [PATCH 7/7] fix(SAFE-T1004): use relative paths for Related Techniques links Changed from absolute paths (techniques/SAFE-TXXXX/README.md) to relative paths (../SAFE-TXXXX/README.md) to match the format used by other techniques in the repository. This ensures links work correctly when viewing files in GitHub's web interface. Signed-off-by: Satbir Singh --- techniques/SAFE-T1004/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/techniques/SAFE-T1004/README.md b/techniques/SAFE-T1004/README.md index 7f8a08b5..8958903e 100644 --- a/techniques/SAFE-T1004/README.md +++ b/techniques/SAFE-T1004/README.md @@ -284,10 +284,10 @@ tags: - Enhance discovery service security with cryptographic verification ## Related Techniques -- [SAFE-T1002](techniques/SAFE-T1002/README.md) – Supply Chain Compromise (related but focuses on package compromise rather than server impersonation) -- [SAFE-T1003](techniques/SAFE-T1003/README.md) – Malicious MCP-Server Distribution (related but involves creating new malicious servers rather than impersonating existing ones) -- [SAFE-T1008](techniques/SAFE-T1008/README.md) – Tool Shadowing Attack (related technique involving tool-level impersonation rather than server-level) -- [SAFE-T1301](techniques/SAFE-T1301/README.md) – Cross-Server Tool Shadowing (similar concept applied at tool level) +- [SAFE-T1002](../SAFE-T1002/README.md) – Supply Chain Compromise (related but focuses on package compromise rather than server impersonation) +- [SAFE-T1003](../SAFE-T1003/README.md) – Malicious MCP-Server Distribution (related but involves creating new malicious servers rather than impersonating existing ones) +- [SAFE-T1008](../SAFE-T1008/README.md) – Tool Shadowing Attack (related technique involving tool-level impersonation rather than server-level) +- [SAFE-T1301](../SAFE-T1301/README.md) – Cross-Server Tool Shadowing (similar concept applied at tool level) ## References - [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)