CVEReports
CVEReports

Automated vulnerability intelligence platform. Comprehensive reports for high-severity CVEs generated by AI.

Product

  • Home
  • Sitemap
  • RSS Feed

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 CVEReports. All rights reserved.

Made with love by Amit Schendel & Alon Barad



GHSA-VWF3-4XXJ-QG6H

GHSA-VWF3-4XXJ-QG6H: Server-Side Template Injection in mcp-contextforge-gateway

Amit Schendel
Amit Schendel
Senior Security Researcher

Aug 25, 2026·7 min read·38 visits

Executive Summary (TL;DR)

Unsandboxed Jinja2 rendering and an unsafe str.format() fallback in mcp-contextforge-gateway prior to v1.0.0 permit remote code execution via crafted prompt templates.

A Server-Side Template Injection (SSTI) leading to Remote Code Execution (RCE) was discovered in the mcp-contextforge-gateway package before version 1.0.0. The vulnerability stems from an unsandboxed Jinja2 template rendering environment combined with an unsafe fallback mechanism using Python's native str.format() function. Attackers with template modification access could bypass static regex filters to execute arbitrary commands on the hosting platform.

Vulnerability Overview

The vulnerability identified as GHSA-VWF3-4XXJ-QG6H resides in the prompt templating implementation of mcp-contextforge-gateway, a component of the mcp-context-forge repository. This package provides gateway services within the ContextForge ecosystem, specifically managing system integration and prompt-based interactions. The core functionality allows users to register, manage, and render templated prompts to interact with backend models.

Because the gateway exposes APIs to register custom templates, the template rendering engine represents a significant attack surface. The system accepts user-controlled inputs during template registration and subsequent rendering operations. If the template input is not strictly validated and sanitized, it is processed directly by the rendering pipeline, exposing the application to injection attacks.

This flaw is classified under CWE-1336 (Improper Neutralization of Special Elements Used in a Template Engine) and CWE-94 (Improper Control of Generation of Code). The ultimate impact is unauthenticated or authenticated remote code execution (RCE) on the underlying host, depending on the network configuration and user authorization controls governing access to the prompt service.

Root Cause Analysis

The root cause of this vulnerability lies in the combination of an unsandboxed Jinja2 template environment, an inadequate regex-based blocklist, and an unsafe fallback mechanism in the rendering code. The primary engine responsible for rendering prompt templates was initialized using the standard jinja2.Environment class. This environment does not restrict access to Python runtime objects, allowing an executed template to traverse the Python object hierarchy and invoke arbitrary system APIs.

To prevent template injection, developers implemented a case-insensitive regex pattern scan called CONTENT_BLOCKED_TEMPLATE_PATTERNS. This static filter scanned raw template string input for dunder strings such as __class__ and __import__. However, static pattern-matching is fundamentally insufficient to block Jinja2 injection due to the engine's expressive parsing options. Attackers can bypass these filters by using hex-encoded strings, string concatenation, or attributes of objects like the request parameter to reconstruct blocked keywords at runtime.

Additionally, the rendering implementation in PromptService._render_template contained a nested try-except error handling block designed to handle rendering failures. If the Jinja2 compilation or execution failed, the engine caught the exception and automatically fell back to Python's built-in str.format() method to format the template. Since Python's native formatting engine also supports property access and arbitrary object traversal, this fallback reintroduced the vulnerability, providing an alternative execution pathway even if the primary Jinja2 rendering path was obstructed.

Code Analysis

The vulnerability was located in mcpgateway/services/prompt_service.py where the Jinja2 environment was initialized and templates were rendered. Let us examine the vulnerable implementation of the environment setup and the rendering function.

# VULNERABLE CODE PATH
from jinja2 import Environment, select_autoescape
 
def _get_jinja_env() -> Environment:
    global _JINJA_ENV
    if _JINJA_ENV is None:
        # Initializes a standard, unsandboxed Jinja2 Environment
        _JINJA_ENV = Environment(
            autoescape=select_autoescape(["html", "xml"]),
            trim_blocks=True,
            lstrip_blocks=True,
        )
    return _JINJA_ENV
 
def _render_template(self, template: str, arguments: Dict[str, str]) -> str:
    try:
        jinja_template = _compile_jinja_template(template)
        return jinja_template.render(**arguments)
    except Exception:
        try:
            # Unsafe fallback to python str.format() when Jinja rendering fails
            return template.format(**arguments)
        except Exception:
            raise PromptError("Failed to format template")

To resolve this issue, the patch transitioned the application to Jinja2's SandboxedEnvironment and hardened the exception handlers to block unsafe format fallback operations. It also introduced a multi-step pre-flight validator to inspect templates before saving them to the database.

# PATCHED CODE PATH
from jinja2.sandbox import SandboxedEnvironment
from jinja2.exceptions import SecurityError as JinjaSecurityError
 
def _get_jinja_env() -> SandboxedEnvironment:
    global _JINJA_ENV
    if _JINJA_ENV is None:
        # Transition to SandboxedEnvironment blocks unsafe attribute access
        _JINJA_ENV = SandboxedEnvironment(
            autoescape=select_autoescape(["html", "xml"]),
            trim_blocks=True,
            lstrip_blocks=True,
        )
    return _JINJA_ENV
 
def _render_template(self, template: str, arguments: Dict[str, str]) -> str:
    try:
        jinja_template = _compile_jinja_template(template)
        return jinja_template.render(**arguments)
    except JinjaSecurityError as sec_err:
        # Intercept Jinja security exceptions and terminate execution immediately
        raise PromptError(f"Failed to render template: sandbox rejected unsafe operation ({sec_err})")
    except Exception:
        try:
            # Fallback only executed for non-security related compilation errors
            return template.format(**arguments)
        except Exception:
            raise PromptError("Failed to format template")

While the transition to SandboxedEnvironment represents a significant security improvement, its complete security depends on the configuration of the sandbox. The default Jinja2 sandbox blocks attributes prefixed with underscores and certain methods like __import__. However, complex deployment setups with custom helper filters must ensure that they do not expose sensitive object references to the sandboxed scope.

Exploitation Methodology

Exploitation of this vulnerability requires the ability to register or update prompt templates in the application. Depending on the gateway's access control configurations, this could be achieved by an authenticated user with low privileges or an administrator, or via an unauthenticated endpoint if access controls are misconfigured. Once the attacker has access to template generation interfaces, they submit a malicious template payload.

To bypass the static regex scanners that block direct strings like __class__, the attacker must use obfuscated syntax. One primary mechanism uses Jinja2's attr filter paired with hexadecimal encoding. Because the regex scanner only inspects the literal template text, it does not evaluate the hex-encoded sequences at rest, allowing the payload to pass validation checks and enter the template database.

{# Payload to retrieve the class hierarchy and locate subclass references #}
{{ ""|attr("\\x5f\\x5fclass\\x5f\\x5f")|attr("\\x5f\\x5fmro\\x5f\\x5f") }}

Once the template is saved, the attacker triggers its execution via the template rendering endpoints. During execution, the unsandboxed Jinja2 environment parses the hexadecimal strings, resolves the attributes, traverses the MRO hierarchy to find the <class 'subprocess.Popen'> or <module 'os'> reference, and executes arbitrary shell commands on the host system. If an error is triggered during execution, the system may fall back to the str.format() interpreter, which allows similar object-traversal exploitation via native Python format structures.

Impact Assessment

The impact of successful exploitation is critical, potentially resulting in full remote code execution under the security context of the mcp-contextforge-gateway application process. In containerized environments, this level of access allows the attacker to execute shell commands, read application configuration secrets, retrieve internal API keys, and interact with other local containers or backend cloud services.

If the gateway process is configured to run with administrative or root privileges on the host system, the attacker can leverage the execution context to achieve persistence, escalate privileges, and compromise the host operating system. The vulnerability poses a significant risk to confidentiality, integrity, and availability because all data handled by the gateway can be read, modified, or destroyed by the attacker.

No official CVE identifier is assigned to this vulnerability because it was cataloged directly under the GitHub Security Advisory (GHSA) program as GHSA-VWF3-4XXJ-QG6H. However, its severity aligns with a CVSS v3.1 base score of 9.8 (Critical) assuming unauthenticated vector access, or 8.8 (High) if authentication is strictly enforced. The vulnerability has not yet been reported as actively exploited in the wild or listed in the CISA KEV catalog.

Remediation and Configuration Hardening

To remediate this vulnerability, organizations must upgrade mcp-contextforge-gateway to version 1.0.0 or later. This version completely replaces the default Jinja2 environment with a secure SandboxedEnvironment and updates the error handling code to abort execution upon encountering sandbox violations, preventing unsafe fallbacks to str.format().

In addition to upgrading the package, administrators must verify that template security configurations are enabled in their environment files. Confirming that CONTENT_VALIDATE_PROMPT_TEMPLATES is set to true enforces the multi-layer pre-flight template validation pipeline. This validation pipeline runs an AST syntax analysis on templates and rejects structural anomalies before saving them to the backend database.

# Recommended Security Settings
CONTENT_VALIDATE_PROMPT_TEMPLATES=true
CONTENT_PATTERN_DETECTION_ENABLED=true
CONTENT_PATTERN_VALIDATION_MODE=strict

Security teams should monitor application logging facilities for attempts to execute restricted template expressions. The patched code emits structured logs when template validation or sandbox security policies are violated. Alerts should be established to identify multiple rapid template parsing exceptions, which often indicate exploratory fuzzing or exploit payload testing.

Official Patches

IBMOfficial Pull Request fixing template injection vulnerabilities in prompt service
IBMSecurity patch applying sandboxing, pre-flight checks, and robust error fallback mechanisms

Fix Analysis (1)

Technical Appendix

CVSS Score
9.8/ 10
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H

Affected Systems

mcp-contextforge-gateway < 1.0.0mcp-context-forge integrations utilizing prompt_service templates < 1.0.0

Affected Versions Detail

Product
Affected Versions
Fixed Version
mcp-contextforge-gateway
IBM
< 1.0.01.0.0
AttributeDetail
CWE IDCWE-1336, CWE-94
Attack VectorNetwork (with template registration privileges)
CVSS v3.1 Score9.8 (Critical)
Exploit StatusProof-of-Concept
Patch StatusPatched in v1.0.0
Vulnerability ClassServer-Side Template Injection (SSTI)

MITRE ATT&CK Mapping

T1190Exploit Public-Facing Application
Initial Access
T1059Command and Scripting Interpreter
Execution
CWE-1336
Improper Neutralization of Special Elements Used in a Template Engine

The product uses a template engine but does not properly neutralize special elements in the template before it is rendered, allowing execution of arbitrary code.

Known Exploits & Detection

GitHub AdvisoryOriginal security disclosure highlighting the SSTI vulnerability and validation bypass.

References & Sources

  • [1]GitHub Advisory Database Entry
  • [2]mcp-context-forge v1.0.0 Release Notes

Attack Flow Diagram

Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

More Reports

•41 minutes ago•GHSA-4WHP-JX7J-XVRM
5.1

GHSA-4whp-jx7j-xvrm: Stored Cross-Site Scripting in Hugo Syntax Highlighter via wrapperClass

A stored Cross-Site Scripting (XSS) vulnerability in the Hugo static site generator (versions 0.140.2 prior to 0.170.0) allows content authors to inject arbitrary HTML and JavaScript into generated pages. The flaw resides in the syntax highlighting component (`markup/highlight/highlight.go`), where the `wrapperClass` option is concatenated directly into an HTML `<div class="...">` attribute without HTML entity escaping. Because shortcodes and code fence attributes bypass Goldmark's raw HTML sanitization rules, untrusted contributors in multi-author workflows can achieve client-side script execution in the browsers of site visitors.

Alon Barad
Alon Barad
0 views•9 min read
•about 3 hours ago•CVE-2026-139994
4.7

CVE-2026-139994: Cross-Site Scripting via Context-Mismatched HTML Escaping in React Router RSC Streaming Redirects

CVE-2026-139994 (GHSA-mjj8-rxh9-q8f5) is a Cross-Site Scripting (XSS) vulnerability in React Router affecting versions 7.11.0 through 7.18.3 and 8.0.0 through 8.3.1. The flaw resides in the server-side streaming handler for the unstable React Server Components (RSC) Data mode and RSC Framework mode. When a server-side redirect is triggered during an HTML stream, the framework injects an inline <meta http-equiv="refresh"> element into the response stream. Because the redirect destination URL is sanitized using an HTML body escaping utility (escapeHtml) rather than an attribute-specific encoding function, double-quote characters (") are left unescaped. An attacker who can influence the redirect URL can break out of the content attribute context, inject arbitrary attributes or HTML elements, and execute arbitrary JavaScript within the victim's browser session.

Alon Barad
Alon Barad
5 views•11 min read
•about 4 hours ago•CVE-2026-139996
7.4

CVE-2026-139996: Prototype Pollution in React Router via Vendored turbo-stream Deserializer

CVE-2026-139996 is a prototype pollution vulnerability (CWE-1321) in React Router's vendored turbo-stream deserializer, utilized in Framework mode for single-fetch transitions and client-server hydration. When unflattening serialized streams, the decoder assigns object properties using direct bracket notation (object[key] = value) rather than defining own properties via Object.defineProperty. Furthermore, the deserializer lacks integer and bounds validation on stream reference indices. An attacker capable of supplying crafted turbo-stream payloads to the deserializer can pollute Object.prototype or trigger arbitrary index dereferences, compromising application integrity and confidentiality.

Amit Schendel
Amit Schendel
4 views•9 min read
•about 5 hours ago•CVE-2026-137181
7.1

CVE-2026-137181: Incorrect Authorization via Improper Context Cancellation Propagation in OpenFGA

CVE-2026-137181 (GHSA-637h-v79h-mvqf) is an incorrect authorization vulnerability (CWE-863) in OpenFGA versions 1.10.3 through 1.22.x. The graph evaluation engine fails to distinguish between normal stream exhaustion and context cancellations or deadline exceedances during concurrent set evaluations. When resolving models using relational set operations (and, or, but not), an aborted worker branch can be evaluated as empty rather than errored, causing the engine to return unauthorized access grants (Allowed: true). When query caching is enabled, these erroneous evaluation states can be persisted to the in-memory cache, poisoning subsequent authorization checks.

Amit Schendel
Amit Schendel
4 views•9 min read
•about 6 hours ago•CVE-2026-137200
7.5

CVE-2026-137200: Denial of Service via Unhandled Upgrade Error in Engine.IO

An uncaught exception vulnerability (CWE-248) in Engine.IO versions prior to 6.6.12 allows remote unauthenticated attackers to cause a Denial of Service (DoS) against Node.js applications utilizing Engine.IO or Socket.IO. By sending an HTTP upgrade request targeting a non-Engine.IO URL path and forcibly resetting the underlying TCP connection before the internal destruction timeout expires, an attacker triggers an unhandled ECONNRESET error event on the socket object, terminating the entire Node.js runtime process.

Alon Barad
Alon Barad
6 views•10 min read
•about 7 hours ago•CVE-2026-137199
9.2

CVE-2026-137199: OS Command Injection in cross-spawn on Windows via Batch File Argument Escaping Bypass

CVE-2026-137199 (GHSA-ghv9-86vm-4v8m) is a critical OS command injection vulnerability in the Node.js cross-spawn library affecting versions prior to 6.0.7 and 7.1.0 on Windows. The vulnerability stems from incomplete metacharacter escaping when routing batch scripts (.bat and .cmd) outside of node_modules/.bin through cmd.exe, alongside flaws in file extension canonicalization, environment variable expansion, and line break handling. Attackers who control arguments passed to batch scripts can break out of argument quoting and execute arbitrary system commands.

Alon Barad
Alon Barad
5 views•15 min read