Skip to main content
Menu
Advisories

Mock Server evaluates #(...) in a body read through karate.request (bypass of GHSA-2c85-rfcc-g74j)

GHSA-4CCW-FVX9-7QPJPublished Updated GitHub

Description

The Karate Mock Server exposes karate.request as a JavaScript property on the karate object inside mock features. That accessor returns the parsed HTTP request body as a fresh Map/List without wrapping the value with markRequestDerived(...), the trust tag that advisory GHSA-2c85-rfcc-g74j introduced in v2.1.0 for every engine-level request binding. When a mock feature assigns karate.request to a variable or returns it as a response, Karate recursively evaluates any embedded #(...) expression it carries. An unauthenticated attacker who can reach the mock server over the network can place #(karate.exec('...')) inside the HTTP request body, achieving arbitrary OS command execution with the privileges of the JVM. This is the same class of eval injection fixed in GHSA-2c85-rfcc-g74j, exercised through a parallel accessor the fix did not cover.

Root Cause

Advisory GHSA-2c85-rfcc-g74j (fixed in v2.1.0) introduced a trust boundary: attacker-controlled values derived from the current mock request are tagged with markRequestDerived(...), and StepExecutor.processEmbeddedExpressions short-circuits for tagged values so their #(...) substrings are returned as inert data instead of being passed to runtime.eval(...). The fix was applied comprehensively to every engine-level request binding registered in MockHandler.initRuntime() (lines 193 through 273 at v2.1.3), including the engine variable named request.

Karate also exposes a parallel JavaScript accessor, karate.request, through KarateJs.jsGet("request"). That accessor dispatches to KarateJs.getRequest(), which never applies markRequestDerived:

// karate-core/src/main/java/io/karatelabs/core/KarateJs.java (v2.1.3)
case "request" -> getRequest();                                 // line 1320

private Object getRequest() {                                   // line 1055
    if (mockHandler == null) {
        logger.warn("karate.request is only available in mock context");
        return null;
    }
    io.karatelabs.http.HttpRequest request = mockHandler.getCurrentRequest();
    return request != null ? request.getBodyConverted() : null; // line 1061 — no markRequestDerived
}

The engine-level request binding, by contrast, wraps the identical body:

// karate-core/src/main/java/io/karatelabs/core/MockHandler.java:254-255 (v2.1.3)
engine.put("request", (JsLazy) () ->
    currentRequest != null ? markRequestDerived(runtime, currentRequest.getBodyConverted()) : null);

HttpRequest.getBodyConverted() returns a fresh Map/List on every call (HttpRequest.java:443-448, which delegates to HttpUtils.fromBytes). Because ScenarioRuntime.isRequestDerived is identity-based for containers and string-equality-based for strings (ScenarioRuntime.java:1725-1730), a fresh unmarked Map is treated as trusted feature-authored data. The embedded-expression evaluator at StepExecutor.java:3405 then does not short-circuit, and processEmbeddedString at StepExecutor.java:3487-3490 passes any #(...) string value to runtime.eval. The result is an eval sink reachable from attacker-controlled HTTP body bytes.

Impact

An unauthenticated remote attacker who can reach the mock server over the network and whose target mock feature assigns or returns karate.request can execute arbitrary operating system commands under the privileges of the JVM running the mock. The commands flow through karate.exec(...), which creates ProcessBuilder and ProcessHandle instances directly (see Attack Chain, step 6); it is not gated by javaBridgeEnabled, which only controls Java interop through Java.type(...). The default configuration is vulnerable: javaBridgeEnabled is false by default and does not block this path, and requestExpressionsEnabled is false by default but relies on markRequestDerived tagging to short-circuit evaluation, and the whole point of this report is that the tagging is missing on this accessor.

Demonstrated capability is arbitrary command execution, which grants read and write access to any file or environment variable accessible to the mock process and the ability to disrupt it. Observed in this review by source-level verification of the full chain, not by live execution.

The Karate project's SECURITY.md and docs/MOCKS.md state that the mock server is intended for trusted networks only and that network-reachable variants of GHSA-2c85-rfcc-g74j are triaged as defense-in-depth. The gap reported here breaks a specific protection the fix for GHSA-2c85-rfcc-g74j introduced, so remediation restores a documented default-safe guarantee for the mock server.

Proof of Concept

The PoC uses a minimal mock feature that references karate.request (the JS property on the karate object) and sends a JSON body containing a Karate embedded expression. The mock is started on localhost:18080 for demonstration. Any Karate v2 runtime with karate-core on the classpath is sufficient; no additional dependencies are required.

Vulnerable mock feature (echo-mock.feature):

Feature: Echo mock

  Scenario: pathMatches('/echo')
    * def body = karate.request
    * def response = body

Start the mock server (any invocation that loads karate-core 2.1.0 through 2.1.3 and launches MockServer with this feature):

java -cp "<karate-core-and-runtime-classpath>" io.karatelabs.cli.Main mock -p 18080 -m echo-mock.feature

Exploit request:

POST /echo HTTP/1.1
Host: localhost:18080
Content-Type: application/json
Content-Length: 55

{"result": "#(karate.exec('sh -c id>/tmp/karate_poc'))"}

Observed outcome on a vulnerable installation: /tmp/karate_poc contains the output of id, demonstrating OS command execution as the user running the mock JVM. The HTTP response body also reflects the result of the evaluated expression.

Negative control: replace karate.request with the engine-level variable request in the feature (* def body = request). The same payload is returned as literal text and /tmp/karate_poc is not created, confirming that the engine-level binding is correctly tagged by markRequestDerived while the JS accessor is not.

Attack Chain

  1. Exposure: The mock server is started via MockServer.Builder.start() (karate-core/src/main/java/io/karatelabs/core/MockServer.java:338-343) or the karate mock CLI. It binds HttpServer.start(port, sslContext, handler) (HttpServer.java:90) to a TCP port with MockHandler as the sole request function; no authentication filter, IP allowlist, or TLS client-certificate check sits in front of it in code.
  2. Control: The attacker sends POST /<path matched by the mock scenario> with Content-Type: application/json and a body such as {"result": "#(karate.exec('id'))"}. HttpRequest.getBodyConverted() (karate-core/src/main/java/io/karatelabs/http/HttpRequest.java:443-448) parses the body into a fresh LinkedHashMap via HttpUtils.fromBytes; the attacker fully controls key names and string values.
  3. Path: The matched mock scenario evaluates a Karate expression that references karate.request, for example * def body = karate.request. StepExecutor.evalKarateExpression (karate-core/src/main/java/io/karatelabs/core/StepExecutor.java:1898-1905) evaluates the expression as JS, which dispatches through KarateJs.jsGet("request") (karate-core/src/main/java/io/karatelabs/core/KarateJs.java:1320) to getRequest() (lines 1055-1061). The accessor returns the parsed body unchanged.
  4. Guard: StepExecutor.processEmbeddedExpressions runs on the returned value and checks !runtime.isRequestExpressionsEnabled() && runtime.isRequestDerived(value) at StepExecutor.java:3405. For the fresh Map returned by getRequest(), the identity set requestDerived does not contain it (ScenarioRuntime.java:1725-1727) and requestDerivedStrings is empty because the engine-level request JsLazy was never resolved for this request. The guard returns false; recursion continues into every map entry.
  5. Primitive: For each attacker string value, processEmbeddedString (StepExecutor.java:3487-3490) detects the #(...) form, strips the wrapper, and invokes runtime.eval(expr).
  6. Result: runtime.eval("karate.exec('id')") resolves exec through KarateJs.jsGet (KarateJs.java:1299) to the exec() implementation (KarateJs.java:822-841), which creates a ProcessBuilder, calls ProcessHandle.start(builder.build()), and executes the OS command. No javaBridgeEnabled check is on this path; javaBridgeEnabled only gates engine-level Java.type(...) interop (KarateJsBase.java:110-119). The command runs as the mock JVM user, yielding full read/write/exec capability on files and processes accessible to that user.

Bypass Evidence

The protection tested is the markRequestDerived / isRequestDerived tagging that advisory GHSA-2c85-rfcc-g74j introduced in v2.1.0 as the default-safe guarantee for mock request data (documented in docs/MOCKS.md:13). The strongest refutation attempted was that requestDerivedStrings might already contain the attacker payload (populated by another engine binding during the same request cycle, so even the unmarked karate.request Map would route strings through a tagged set). This fails on inspection: requestDerivedStrings is populated exclusively by ScenarioRuntime.markRequestDerived(Object) (ScenarioRuntime.java:1704-1721), which is called only from the markRequestDerived(runtime, ...) helper inside the JsLazy lambdas registered in MockHandler.initRuntime(). Those lambdas are lazy and resolve only when the matching engine variable is read. A mock feature that uses karate.request (and does not touch request, requestHeaders, requestParams, bodyPath, headerValue, or paramValue) never resolves any of them, so the string set stays empty. clearRequestDerived() (ScenarioRuntime.java:1647-1657) also clears both sets at the start of each request.

A second refutation was that getBodyConverted() might return an object instance already present in the identity set. HttpRequest.getBodyConverted() (HttpRequest.java:443-448) delegates to HttpUtils.fromBytes(body, false, rt) on every invocation, which produces a new LinkedHashMap from the raw bytes; two calls return structurally equal but identity-distinct objects, and the IdentityHashMap-backed requestDerived set (ScenarioRuntime.java:123-124) cannot match a separately created Map.

Finally, no additional karate.* JS accessor returning mock request data without markRequestDerived wrapping was found. A full read of KarateJs.jsGet (KarateJs.java:1256-1343) shows that karate.request is the only accessor returning attacker-controlled mock request data; karate.prevRequest reflects the mock's own outgoing HTTP calls (set from StepExecutor.java:2329), not incoming attacker traffic. The gap is specific to KarateJs.getRequest().

This is reported as an incomplete fix of GHSA-2c85-rfcc-g74j (published 2026-06-18): the fix added markRequestDerived wrapping to the engine-level request bindings but did not extend it to the parallel karate.request JS accessor. The subsequent unreleased commit 151d38c (addressing GHSA-rwf2-w5fv-w3g5) added markRequestDerived to three further engine bindings (pathParams, requestUrlBase, requestMethod) but likewise did not touch KarateJs.getRequest().

Affected Versions

  • Ecosystem: maven
  • Package: io.karatelabs:karate-core
  • Confirmed affected range: >= 2.1.0, <= 2.1.3
  • Latest release checked: 2.1.3 (Maven Central)
  • Fix status: not fixed

The upper bound is verified directly against the Maven Central artifact and the tagged source: git show v2.1.3:karate-core/src/main/java/io/karatelabs/core/KarateJs.java shows the unprotected getRequest() at lines 1049-1056 of that file, matching the HEAD source. HEAD (fff0899, four commits past v2.1.3) is also unfixed, including after the unreleased commit 151d38c that addresses GHSA-rwf2-w5fv-w3g5. The lower bound 2.1.0 is the first release in which markRequestDerived was introduced (as the fix for GHSA-2c85-rfcc-g74j); before 2.1.0 the engine-level request bindings themselves were vulnerable and are covered by that advisory, so the bypass through KarateJs.getRequest() is only materially distinct from GHSA-2c85-rfcc-g74j from 2.1.0 onwards. The 2.1.x line published to Maven Central contains 2.1.0, 2.1.1, 2.1.2, and 2.1.3; all four are expected to carry the gap, but direct per-version artifact inspection was performed only for 2.1.3.

Suggested Fix

Restore the markRequestDerived invariant on the karate.request accessor so that the JS property returns the same tagged value as the engine-level request binding. Wrap the return value of KarateJs.getRequest() with markRequestDerived(runtime, ...) using the active ScenarioRuntime, or have the accessor delegate to the engine-level request variable (which already carries the tag). The fix must also cover any future JS accessor that exposes mock request data: a regression test that submits #(karate.exec(...)) through the body, headers, and query parameters and asserts that karate.request returns the payload as inert data would make the invariant executable rather than implicit.

As an interim mitigation for operators who cannot upgrade, avoid referencing karate.request in mock features; use the engine-level request variable instead, which is correctly tagged. Keep javaBridgeEnabled and requestExpressionsEnabled at their defaults. The project's stated deployment model, keeping the mock server off untrusted networks, remains the primary defense until the accessor is tagged.

---

Reported by zx (GitHub: @manus-pi).

----

Severity

Low. The Karate Mock Server is developer test tooling, documented for trusted networks only and never for untrusted clients (see SECURITY.md). Exploiting this also requires a mock feature that reads the body through the karate.request accessor rather than the documented request variable, and then assigns or returns it. The attacker doesn't control that and can't discover it. The report was verified by reading the source, not by running it. This is an incomplete-fix variant of GHSA-2c85-rfcc-g74j, GHSA-m82q-jgc3-9gc9 and GHSA-rwf2-w5fv-w3g5, all published as Low, and the same weighting applies.

Fixed in 2.1.4:

  • karate.request reads the body through the same binding as request, so it is treated as request data. An embedded #(...) in it stays inert unless configure requestExpressionsEnabled = true.
  • As defense-in-depth, process execution (karate.exec(), karate.fork()) now follows javaBridgeEnabled and is off by default in a mock, like Java interop. An expression that reaches evaluation through some other path can no longer run OS commands unless a trusted mock opts in with configure javaBridgeEnabled = true.

Tracked in #3067.

Affected versions

References

GitHub · karatelabs/karate