Skip to content
RCE Write-up Advanced

Poisoning Rhino, Then Waiting for the Callback

A PythonScript policy could leave a Rhino JSContext attached to a worker thread with class access enabled, and a later asynchronous httpClient JavaScript callback on the same worker reused that context without the per-thread security mark, allowing the callback to reach java.lang.Runtime and execute a host command. The attacker needed permission to deploy API proxy code containing both policy types.

Nikita Markevich Follow

Published on bugs.exposed

Comment

Nikita Markevich, on bugs.exposed

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 18 min read.

Context

Google Cloud Apigee runs API proxy code through a set of policies, two of which execute scripts: a JavaScript policy (Rhino) and a PythonScript policy (Jython). Both are meant to run under constrained runtimes. Rhino can expose Java classes to JavaScript, and Apigee limits that with a class shutter that admits only configured classes and packages. The JVM permission boundary is enforced through a thread-local security mark that the synchronous JavaScript step installs around shell.execute() and clears afterwards.

The feature that made this interesting is httpClient, the JavaScript object model's outbound HTTP client. A policy can send a request and supply a function to handle the response or error. Using a callback releases the JavaScript worker while the HTTP operation is pending, so it can return to the pool and service other work; a queued task invokes the function when the response is ready. The proxy flow itself does not run past every following policy during that wait: the JavaScript step installs a resume handler and returns ExecutionResult.PAUSE, and the flow resumes after the callback executor finishes its work. Releasing a worker and advancing the flow are separate operations.

The research question was whether one policy could leave Rhino in a dangerous state and a different JavaScript execution path could find that state later. The chain that answered it ran between PythonScript and an asynchronous JavaScript callback: PythonScript modified a Rhino JSContext and left it attached to a worker thread, a JavaScript policy separately registered an httpClient callback, and when that callback landed on the prepared worker it reused the modified context while the per-thread security mark was absent. The function could reach java.lang.Runtime and execute a host command.

Setup

The chain was reproduced on runtime 1-17-0-apigee-4. The prerequisite was permission to modify and deploy API proxy code containing PythonScript and JavaScript policies. Once the policies were deployed, later HTTP requests supplied the worker-pool activity needed to trigger the chain. The Rhino excerpts are pinned to version 1.7.13, and the Apigee excerpts are cleaned decompilations from the tested runtime.

Finding it

After earlier sandbox bypasses, the ordinary JavaScript policy looked exhausted. Three checks stood in the way, and the walkthrough shows them separately.

  1. The class shutter. In restricted mode, JSContext.ClassShutter.visibleToScripts admits configured classes and packages: basic value types and the Java implementation of Apigee's script-facing objects. java.lang.Runtime stays outside that surface.
  2. The wrapper hides getClass. Apigee wraps exposed Java objects in JSNativeJavaObject, and reading getClass returns NOT_FOUND instead of the reflective entry point.
  3. The thread mark. The normal JavaScript execution path sets a thread-local security mark before calling the script shell and clears it afterwards, so even resolving a dangerous Java class would not by itself grant permission to start a process.
Java
setClassShutter(new ClassShutter() {
    public boolean visibleToScripts(String className) {
        if (JSContext.this.allowClassAccess
                || JSContext.allowedClasses.contains(className)) {
            return true;
        }
        for (String p : JSContext.allowedPackages) {
            if (className.startsWith(p)) {
                return true;
            }
        }
        return false;
    }
});

With allowClassAccess=false, a class must match the configured classes or packages, and java.lang.Runtime is outside that surface.

Java
public Object get(String name, Scriptable start) {
        if (name.equals("getClass")) {
            return NOT_FOUND;
        }
        return super.get(name, start);
    }

Reading getClass returns NOT_FOUND instead of the reflective entry point.

Java
private void shellExecute(Shell shell, Binder binder,
        MessageContext messageContext) throws FlowException {
    // Service lookup, timing and exception handling omitted.
    securityPolicy.setSecurityManagerOnThread(
        true, this.javascriptStep.getContextInfo());
    shell.execute(binder);
    securityPolicy.setSecurityManagerOnThread(false, "");
}

Before shell.execute, Apigee enables its security manager on this Java thread. Resolving a Java class would still leave the JVM permission checks to satisfy.

The synchronous path offered no useful new route. The httpClient callback did, because it ran the JavaScript function later, through a different executor.

Exploitation

Step 1: follow callback registration

Registration goes through ScriptableHttpClient.buildCallBackEvent(). It creates a CallBackEvent containing the supplied function and its scope. The constructor also retains thisObj, a copied Binder containing Apigee bindings, the execution deadline and callback depth. It reads the current JSContext to collect some of those values, but does not store that parent context for later execution.

Java
private CallBackEvent buildCallBackEvent(Object callBack) {
    CallBackEvent callBackHolder = null;
    if (callBack instanceof BaseFunction) {
        BaseFunction function = (BaseFunction) callBack;
        Scriptable scope = JSContext.getCurrentContext().getTopLevelScope();
        callBackHolder = new CallBackEvent(function, scope, this, getCallBackExecutor());
        this.hasCallBacks = true;
    }
    return callBackHolder;
}
Java
public CallBackEvent(BaseFunction function, Scriptable scope, Scriptable thisObj, CallBackExecutor callBackExecutor) {
    this.function = function;
    this.scope = scope;
    this.thisObj = thisObj;
    JSContext parenJsContext = JSContext.getCurrentContext();
    this.binder = new Binder(parenJsContext.getBinder());
    this.endTimeMS = parenJsContext.getEndTimeMS();
    this.callBackExecutor = callBackExecutor;
    this.depth = callBackExecutor.getCurrentStackDepth() + 1;
}

The event retains function, scope, thisObj, a copied Binder, deadline and callback depth. parenJsContext is read here but is not stored as the callback context.

Step 2: pause the flow and queue the callback

After synchronous JavaScript returns, Apigee installs submission and resume handlers. PAUSE suspends the proxy flow and the worker can return to the pool.

Java
CallBackExecutor callBackExecutor = httpClient.getCallBackExecutor();
if (httpClient.hasCallBacks()) {
    ThreadPoolManager threadPoolManager = ThreadPoolManager.getInstance();
    Objects.requireNonNull(threadPoolManager);
    callBackExecutor.setTaskSubmitHandler(threadPoolManager::submitAsMetricsAwareTask);
    callBackExecutor.setResumeHandlerAndStart(throwable -> {
        handleResume(throwable, binder, messageContext, executionContext);
    });
    return ExecutionResult.PAUSE;
}
binder.unBindAll();
return ExecutionResult.SUCCESS;

When the HTTP work completes, the response path queues the event and decrements the in-flight count. When no operations remain and a resume handler exists, it submits pending callbacks.

Java
public void prepareToExecute(CallBackEvent callBackHolder) {
    this.callBackQueue.add(callBackHolder);
    int inFlight = this.inflightCallBackCount.decrementAndGet();
    logger.atFine().log("Adding call back callBackQueue size is %d inflight is %d", this.callBackQueue.size(), inFlight);
    this.numberOfCall.incrementAndGet();
    if (inFlight == 0 && this.resumeHandler != null) {
        submitPendingCallbacks();
    }
}
Java
private void submitPendingCallbacks() {
    if (readyToExecute() && !this.shutDown.get()) {
        logger.atFine().log(" submitPendingCallbacks");
        Runnable r = () -> {
            Throwable error = null;
            boolean finished = true;
            try {
                finished = executeJSCallBacksCode();
            } catch (Throwable e) {
                error = e;
            }
            if (finished) {
                if (this.readyToResumeFlag.compareAndSet(false, true)) {
                    this.resumeHandler.accept(error);
                } else {
                    logger.atWarning().log("Attempt to call resume handler more than once");
                }
            }
        };
        if (this.submitHandler != null) {
            this.submitHandler.accept(r);
        } else {
            r.run();
        }
    }
}

The JavaScript step configured this handler as ThreadPoolManager.submitAsMetricsAwareTask. The Runnable executes the callback queue on a selected worker, with no affinity to the registration thread. The saved function keeps its JavaScript environment and the Apigee variables needed to continue; its interpreter context comes from the worker that eventually runs the event.

Step 3: notice the missing thread mark

That did not automatically expose Java classes in a callback. CallBackExecutorImpl explicitly enters the restricted factory, so on a clean worker the function still gets a restricted context. The other boundary is the thread that carries the permission checks. The security mark around shell.execute() belongs to the thread executing that synchronous call, and Apigee clears it when the shell returns. The callback task is scheduled separately through ThreadPoolManager.submitAsMetricsAwareTask.

On the worker selected for that task, the callback executor enters Rhino and drains its event queue. CallBackEvent.execute() restores the saved binder and deadline, then calls the function directly. There is no matching installation of the JavaScript security-policy mark around that invocation.

Java
private synchronized boolean executeJSCallBacksCode() throws Throwable {
  int inFlight = 0;
  if (!this.shutDown.get()) {
    JSContextFactory factory = JSContextFactory.getRestrictedInstance();
    try {
      factory.enterContext();
      while (!this.callBackQueue.isEmpty()) {
        this.current = this.callBackQueue.poll();
        this.current.execute();
      }
      inFlight = this.inflightCallBackCount.get();
      // error handling omitted
    } finally {
      this.current = null;
      factory.exit();
    }
  }
  return inFlight == 0 && this.callBackQueue.isEmpty();
}
Java
public void execute() {
  if (this.depth > 10) {
    throw new IllegalStateException("Too many nested calls to Callbacks.");
  }
  // null-function and deadline checks omitted
  JSContext cx = JSContext.getCurrentContext();
  cx.setBinder(this.binder);
  cx.setEndTimeMS(this.endTimeMS);
  this.function.call(cx, this.scope, this.thisObj, this.args);
  clear();
}

Apigee's internal security manager uses thread-local state to decide whether to enforce its JVM permission checks. Saving the function, variables and deadline does not carry that mark to another worker. The callback could resume its application state without restoring the restriction used around an ordinary JavaScript policy. One of the two relevant checks was absent on the callback path; the class shutter still prevented a clean callback from resolving Runtime.

Step 4: open the class shutter from PythonScript

The shutter's first condition reads JSContext.allowClassAccess. When the flag is true, the filter immediately allows the requested class: the shutter remains installed, but its allowlists no longer restrict the result. The flag was mutable through a public method:

Java
public boolean setAllowClassAccess(boolean set) {
    boolean old = this.allowClassAccess;
    this.allowClassAccess = set;
    return old;
}

That setter changes the live object whose flag the shutter reads. It does not bind the change to one script invocation or arrange to restore the old value when that script finishes. The implementation supported both open and restricted context creation. JSContextFactory.makeContext() left a restricted object's flag at its constructor default of false; the open factory set it to true:

Java
protected Context makeContext() {
    JSContext ctx = new JSContext(this);
    if (this.restrictPackageAccess) {
        ctx.setInstructionObserverThreshold(this.INSTRUCTION_OBSERVER_THRESHOLD);
    } else {
        ctx.setAllowClassAccess(true);
    }
    ctx.setWrapFactory(new JSWrapFactory());
    return ctx;
}

Earlier PythonScript research had already shown a broader Java-access path, including a legacy route that accepted JavaScript resources inside that policy. The code suggests the policy may once have been intended to support both languages, although that design history could not be confirmed.

PythonScript uses Jython. From the Python seed, the researcher could reach Apigee's JSContextFactory and call the public setter on the returned context. The tested runtime's Java permission policy permitted the calls needed to obtain the factory and change the flag. That suggested a short chain: use PythonScript to open the shutter, then call Runtime.exec() from an asynchronous JavaScript callback where the thread mark was absent. One problem remained: allowClassAccess belonged to a JSContext, so the modified object had to survive long enough for a callback on the same worker to reuse it.

Step 5: keep the context attached across cleanup

A Rhino Context is associated with a Java thread. Entering one does not necessarily create a new interpreter object: Context.enter(...) first checks whether the thread already has a current context. If it does, Rhino returns that same object and increments its nesting counter.

The JavaScript step tried to clean up a prior context before preparing a fresh policy execution. Its clearJSContext() helper performed one Context.exit(), which decremented the counter. Rhino cleared the thread association only when that counter reached zero.

The seed entered the restricted factory twice from PythonScript, changed the context returned by the first entry through setAllowClassAccess(True), and deliberately omitted both exits. On an initially clean worker, the two entries raised the counter from zero to two. Returning from PythonScript left that modified object attached to the worker.

Python
factory = JSContextFactory.getRestrictedInstance()
ctx = factory.enterContext()
factory.enterContext()
ctx.setAllowClassAccess(True)

On an initially clean worker, the restricted factory creates and attaches a JSContext and its entry count becomes 1. The second call returns the already attached context and raises its entry count to 2, with no matching exits. The same JSContext now has allowClassAccess=true, and returning from the seed leaves both entries outstanding; the worker can go back to the pool with that state.

Java
protected void clearJSContext() {
    Context context = Context.getCurrentContext();
    if (context != null) {
        try {
            Context.exit();
        } catch (Exception e) {
            logger.atSevere().withCause(e).log("%s Failed to clear JS context from thread.", this.javascriptStep);
        }
    }
}

Before preparing a fresh policy, the JavaScript step calls clearJSContext. This helper performs only one exit, even when the current context has multiple outstanding entries.

Java
public static void exit()
{
    Object helper = VMBridge.instance.getThreadContextHelper();
    Context cx = VMBridge.instance.getContext(helper);
    if (cx == null) {
        throw new IllegalStateException(
            "Calling Context.exit without previous Context.enter");
    }
    if (cx.enterCount < 1) Kit.codeBug();
    if (--cx.enterCount == 0) {
        VMBridge.instance.setContext(helper, null);
        cx.factory.onContextReleased(cx);
    }
}

Rhino clears the thread association only at zero. A single cleanup exit leaves the modified context attached when the counter was 2.

Java
Context old = VMBridge.instance.getContext(helper);
if (old != null) {
  cx = old;
} else {
  if (cx == null) {
    cx = factory.makeContext();
    // initialization omitted
  }
  VMBridge.instance.setContext(helper, cx);
}
cx.enterCount++;

An attached context bypasses factory.makeContext. Entering through the restricted factory does not reset allowClassAccess; the callback executor later balances only its own increment. The existing-context branch also explains why selecting the restricted factory did not repair the flag: Rhino returned the attached object without calling makeContext(). The factory's restricted default applied when constructing a missing object, while this worker already had one with allowClassAccess=true.

Step 6: a fresh policy fails before its script runs

Ordinary JavaScript policies were sent through the pool, waiting for one to reuse a prepared worker. The expectation was that the retained context would expose Runtime. Instead, Apigee threw IllegalStateException while building the JavaScript environment, before the script body started.

The Python seed had attached a context without leaving a JavaScript invocation active. Rhino tracks that invocation separately as a top call, and helpers need its scope when converting Java values into objects in the correct JavaScript environment. RhinoExecutor.runScript() called Binder.bindAll(...) before script.exec(...). During that preparation, a content wrapper asked ScriptRuntime.getTopCallScope(cx) for the current scope. The reused context had no active top call, so the helper threw before the policy body could establish one.

This was the second reason the callback mattered. Its function and scope already existed. CallBackEvent.execute() restored the saved state and invoked that function directly, avoiding the fresh-policy binding phase that had just failed.

Step 7: the callback establishes its own top call

For an interpreted callback, InterpretedFunction.call() checks whether a top call is active. If none exists, it routes the function through ScriptRuntime.doTopCall(), which establishes the saved scope. Apigee's factory hook records it on JSContext, and the function is invoked again inside that active top call. This time Rhino reaches the interpreter. The Rhino helpers come from the 1.7.13 ContextFactory, InterpretedFunction and ScriptRuntime sources, with upstream line numbers preserved.

Java
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
          Object[] args)
{
  if (!ScriptRuntime.hasTopCall(cx)) {
    return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args, idata.isStrict);
  }
  return Interpreter.interpret(this, cx, scope, thisObj, args);
}
Java
public static Object doTopCall(Callable callable,
                Context cx, Scriptable scope,
                Scriptable thisObj, Object[] args, boolean isTopLevelStrict)
{
  if (scope == null)
    throw new IllegalArgumentException();
  if (cx.topCallScope != null) throw new IllegalStateException();

  Object result;
  cx.topCallScope = ScriptableObject.getTopLevelScope(scope);
  cx.useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE);
  boolean previousTopLevelStrict = cx.isTopLevelStrict;
  cx.isTopLevelStrict = isTopLevelStrict;
  ContextFactory f = cx.getFactory();
  try {
    result = f.doTopCall(callable, cx, scope, thisObj, args);
  } finally {
    cx.topCallScope = null;
    // Cleanup cached references
    cx.cachedXMLLib = null;
    cx.isTopLevelStrict = previousTopLevelStrict;

    if (cx.currentActivationCall != null) {
      // Function should always call exitActivationFunction
      // if it creates activation record
      throw new IllegalStateException();
    }
  }
  return result;
}
Java
protected Object doTopCall(Callable callable, Context cx,
    Scriptable scope, Scriptable thisObj, Object[] args) {
  if (cx instanceof JSContext) {
    JSContext jcx = (JSContext) cx;
    jcx.setTopLevelScope(scope);
    if (args != null) {
      notifyArgs(args, jcx);
    }
  }
  return super.doTopCall(callable, cx, scope, thisObj, args);
}
Java
protected Object doTopCall(Callable callable,
              Context cx, Scriptable scope,
              Scriptable thisObj, Object[] args)
{
  Object result = callable.call(cx, scope, thisObj, args);
  return result instanceof ConsString ? result.toString() : result;
}

The restricted factory has entered the worker's current context. The queued event already holds a function and scope. CallBackEvent.execute() restores the saved binder and deadline on this worker's JSContext, and direct function invocation avoids fresh global binding. The interpreted function detects the absent top call, and Rhino establishes one around the existing function and its saved scope. ScriptRuntime.doTopCall sets topCallScope from the saved callback scope, and the context's factory receives the call. Apigee records the saved scope on JSContext, and its superclass invokes the Callable inside the active top call; neither operation resets class access or marks this worker. The Callable is the same interpreted callback, and on the second entry hasTopCall is now true, so the interpreter runs the callback. Its context still has allowClassAccess=true, and the callback path has not installed the synchronous policy security mark. After the invocation unwinds, the executor's exit removes only its own increment; earlier leaked entries can keep the modified context attached to the worker.

The callback could now run in the context modified by PythonScript, through the path that lacked the synchronous security mark. The class shutter exposed Runtime, and the missing mark left Apigee's normal JVM permission boundary inactive for that callback invocation.

Step 8: reproduce the worker-pool race

The proof was split into two proxies because the chain needed two different scheduling roles.

Proxy A ran a normal JavaScript policy. At startup it called Context.exit() until its current worker had no Rhino context, allowing the policy to initialize normally even after earlier attempts. It then issued a delayed outbound request through httpClient. Registration saved the callback function, scope, binder, deadline, and depth while the response remained pending.

Proxy B ran the PythonScript seed. While Proxy A waited, repeated requests to Proxy B visited workers in the same pool. Each successful seed entered the restricted factory twice, set allowClassAccess=true, and returned without matching the entries. A worker could finish the request and return to the pool with the modified context still attached.

When Proxy A's outbound response arrived, Apigee queued the saved CallBackEvent as new work. The callback had no affinity to the thread that registered it. A clean worker kept Runtime hidden. A contaminated worker reused the open context, and the saved function supplied the missing top call.

Worker selection made the proof nondeterministic. In a deployment with several message processors, both proxies also had to reach the same JVM because the leaked state could not cross a process boundary. The policies, callback body, delay, and request volume were controlled; repeated requests handled the two scheduling decisions that could not be.

The model predicted three outcomes, which made useful negative controls:

  1. A callback on a clean worker could not resolve the blocked Java class.
  2. A fresh JavaScript policy on a contaminated worker failed during global binding, before its body.
  3. A saved callback on a contaminated worker entered a top call and reached the host operation.

Step 9: prove it with a shell

For the end-to-end check, the callback opened a reverse shell. Inside it, the operating-system identity of the Apigee message processor was checked:

Bash
bash-5.1$ whoami
apigee

Root cause

The failure came from the lifetime of security state, not from a single missing check. Three pieces combined:

  • allowClassAccess is a mutable flag on a live JSContext, changed through a public setter that does not bind the change to one invocation or restore the old value.
  • Rhino attaches a Context to a thread and only detaches it when the nesting counter reaches zero. The JavaScript step's clearJSContext() performed a single Context.exit(), so a context entered twice by PythonScript survived cleanup with allowClassAccess=true and was returned by a later Context.enter() without going through makeContext().
  • The synchronous JavaScript step installs the thread-local security mark around shell.execute() and clears it afterwards. The asynchronous callback executor invokes the saved function on a pool worker without installing that mark, so the JVM permission boundary was inactive for the callback.

The class shutter and the getClass wrapper were still in place, and the callback executor still entered the restricted factory. The restricted factory did not repair the flag because the attached context bypassed makeContext(), and the callback's own top-call establishment did not reset class access or mark the worker.

Impact

An attacker who could deploy both policy flows could reach host command execution as the message processor's operating-system user. The prerequisite narrowed who could exploit the issue: the ability to modify and deploy API proxy code containing PythonScript and JavaScript policies. The worker state also crossed proxy and request boundaries without travelling through a documented flow variable: Proxy B changed a Rhino object attached to a Java thread, and Proxy A's callback later consumed that state because the pool happened to select the same thread. The policy model presented those executions as separate, while the runtime let one inherit the other's interpreter authority.

Fix

A later review of the Apigee hybrid 1.17.1 runtime image found two changes aimed at the state used by this chain. The proof was not rerun against that image or a managed-runtime build, so this evidence does not establish the first fixed version or a managed-service remediation date.

Old contexts are drained before JavaScript starts

JSContext gained clearPriorContexts(), which repeatedly calls Context.exit() until the worker has no current Rhino context, with a guard against an endless loop:

Java
public static void clearPriorContexts() {
    int maxLoop = 1000;
    while (Context.getCurrentContext() != null) {
        try {
            if (maxLoop-- <= 0) {
                logger.atSevere().log(
                    "Exceeded max loop iterations clearing prior JS contexts.");
                return;
            }
            Context.exit();
        } catch (Throwable e) {
            logger.atFine().withCause(e).log("Failed to close Context");
        }
    }
}

Both JavascriptStepExecution.execute(...) and RhinoExecutor.execute(...) call this cleanup before preparing a policy. The older cleanup could remove one entry; the loop drains all outstanding entries before normal JavaScript initialization, so a worker carrying Proxy B's modified context should detach it before a fresh policy begins.

Callbacks run through an untrusted executor

ScriptableHttpClient now passes InternalMessageContext::callUntrusted into each CallBackEvent. The event uses that executor around the captured function instead of calling the function directly. The call eventually reaches SecurityPolicyServiceImpl.callUntrusted(...), which installs the thread mark when necessary, executes the callback, and clears only the mark it added:

Java
InternalSecurityManager securityManager = getSecurityManager();
boolean wasMarked = false;
if (securityManager != null) {
    wasMarked = securityManager.markedThread();
    if (!wasMarked) {
        securityManager.markThread("callUntrusted");
    }
}

V result = AccessController.doPrivileged(() -> callable.call());

if (securityManager != null && !wasMarked) {
    securityManager.clearThread();
}
return result;

This establishes the JVM permission boundary on the worker that actually executes the callback, so its authority no longer depends on the mark left on that thread by unrelated work. The bundled Rhino version remained 1.7.13, setAllowClassAccess(...) remained mutable, and the callback executor still entered a restricted context in much the same way. The repair instead enforced clean state before policy execution and explicit untrusted authority around the asynchronous function. Static inspection of hybrid 1.17.1 therefore indicates that the complete callback chain is closed.

Variants to test

  • Other asynchronous executors. Look for any path that saves a function and runs it on a pool worker without the synchronous security mark, such as other callback-based APIs. A positive result is a callback that can resolve a class the shutter should block.
  • Other mutable security flags. Search for public setters that change live interpreter state read by a filter or shutter. A positive result is a flag change that survives the script invocation and is visible to a later execution on the same thread.
  • Cleanup helpers that exit once. Audit any Context.exit() or equivalent teardown that assumes a single outstanding entry. A positive result is a context that stays attached after cleanup when entered more than once.
  • Cross-policy state on shared workers. Deploy two proxies that share a pool and have one leave interpreter state behind for the other. A positive result is the second proxy observing state it never set through a documented flow variable.
  • Fresh-policy binding failures as a signal. If a policy on a reused worker throws during environment setup before its body runs, check whether the worker carries a context with no active top call. A positive result is a reproducible IllegalStateException from the binding phase.
  • Multi-process deployments. Confirm whether leaked state can cross message processors. A positive result would be the chain working when the two proxies land on different JVMs, which the original chain could not do.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 32 min read.

What happened, in plain words

Google Cloud Apigee is a service that companies use to run small programs in front of their APIs. An API (Application Programming Interface) is the set of doors a program offers so other programs can talk to it: for example, a weather app asking a weather service "what is the temperature in London?". Apigee sits between the caller and the company's backend, and it lets developers write little pieces of code, called policies, that run on every request: check a login, add a header, fetch data from another server, and so on.

Two of those policy types run scripts: a JavaScript policy (JavaScript is the language that runs in web pages, and here it runs inside a Java program using an engine called Rhino) and a PythonScript policy (Python running inside Java through an engine called Jython). Both are supposed to run in a sandbox: a restricted playpen where the script can do its job but cannot touch the rest of the machine. Think of a sandbox like a hotel room: you can rearrange the furniture, but you cannot knock down the wall into the next room.

The researcher found a way to break out of that playpen. The trick was not one broken lock but two policies disagreeing about when a lock should be applied. A PythonScript policy could leave a shared interpreter object in a dangerous state on a worker thread (a worker is one of the threads of the server that actually runs the code). Later, an asynchronous JavaScript callback (a function that runs later, when an HTTP response arrives) could land on that same worker and inherit the dangerous state, while the usual permission check was missing. The callback could then reach java.lang.Runtime, the Java class that can start operating-system programs, and reach host command execution as the message processor's operating-system user.

The prerequisite was that the attacker could already modify and deploy API proxy code containing PythonScript and JavaScript policies. That is a real restriction: you need to be allowed to write and publish the proxy. Once the policies were deployed, later HTTP requests supplied the worker-pool activity needed to trigger the chain, though worker selection made it nondeterministic. The researcher reproduced it on runtime 1-17-0-apigee-4.

The three locks that were supposed to stop this

Before the chain, the ordinary JavaScript policy looked exhausted. Three checks stood in the way, and the walkthrough shows them separately.

  1. The class shutter. Rhino can expose Java classes to JavaScript. A Java class is a named piece of Java code, like a toolbox; java.lang.Runtime is the toolbox that can start processes. Apigee limits which classes a script can see with a filter called a class shutter. In restricted mode it admits only configured classes and packages: basic value types and the Java implementation of Apigee's script-facing objects. java.lang.Runtime stays outside that surface.
  2. The wrapper hides getClass. Java objects have a method called getClass() that tells you what class an object is; from there, reflection (a Java feature that lets code inspect and call things at runtime) can often reach other classes. Apigee wraps exposed Java objects in a class called JSNativeJavaObject, and reading getClass returns NOT_FOUND instead of the reflective entry point.
  3. The thread mark. The normal JavaScript execution path sets a thread-local security mark before calling the script shell and clears it afterwards. A thread-local value is a value that belongs to one thread only, like a wristband given to one guest. Even resolving a dangerous Java class would not by itself grant permission to start a process, because the JVM (Java Virtual Machine, the program that runs Java code) checks that wristband.

Here is the class shutter code:

Java
setClassShutter(new ClassShutter() {
    public boolean visibleToScripts(String className) {
        if (JSContext.this.allowClassAccess
                || JSContext.allowedClasses.contains(className)) {
            return true;
        }
        for (String p : JSContext.allowedPackages) {
            if (className.startsWith(p)) {
                return true;
            }
        }
        return false;
    }
});

Line by line:

  • setClassShutter(new ClassShutter() { ... }); installs a filter object that decides which Java classes a script may see.
  • public boolean visibleToScripts(String className) { is the question the filter answers: "may the script see the class named className?"
  • if (JSContext.this.allowClassAccess checks a flag on the current context. If the flag is true, the answer is yes for everything.
  • || JSContext.allowedClasses.contains(className)) { is the second half of that condition: the class is on the allowlist.
  • return true; means the class is visible.
  • for (String p : JSContext.allowedPackages) { loops over allowed package prefixes. A package is a group of related Java classes, like a folder.
  • if (className.startsWith(p)) { checks whether the class name begins with an allowed package name.
  • return true; means the class is visible because its package is allowed.
  • return false; means the class is not visible.

With allowClassAccess=false, a class must match the configured classes or packages, and java.lang.Runtime is outside that surface.

Next, the wrapper that hides getClass:

Java
public Object get(String name, Scriptable start) {
        if (name.equals("getClass")) {
            return NOT_FOUND;
        }
        return super.get(name, start);
    }

Line by line:

  • public Object get(String name, Scriptable start) { is the method that runs when a script reads a property from a wrapped Java object.
  • if (name.equals("getClass")) { checks whether the script is asking for getClass.
  • return NOT_FOUND; answers as if the property did not exist.
  • return super.get(name, start); otherwise hands the request to the normal implementation.

Reading getClass returns NOT_FOUND instead of the reflective entry point.

Finally, the thread mark around the synchronous shell call:

Java
private void shellExecute(Shell shell, Binder binder,
        MessageContext messageContext) throws FlowException {
    // Service lookup, timing and exception handling omitted.
    securityPolicy.setSecurityManagerOnThread(
        true, this.javascriptStep.getContextInfo());
    shell.execute(binder);
    securityPolicy.setSecurityManagerOnThread(false, "");
}

Line by line:

  • private void shellExecute(Shell shell, Binder binder, starts the method that runs a JavaScript policy synchronously, meaning the request waits for it to finish.
  • MessageContext messageContext) throws FlowException { is the rest of the signature; MessageContext holds the request data.
  • // Service lookup, timing and exception handling omitted. is a comment saying some code was removed for readability.
  • securityPolicy.setSecurityManagerOnThread( turns on the security manager for this thread.
  • true, this.javascriptStep.getContextInfo()); passes true (enable) and some context information.
  • shell.execute(binder); actually runs the script.
  • securityPolicy.setSecurityManagerOnThread(false, ""); turns the mark off again.

Before shell.execute, Apigee enables its security manager on this Java thread. Resolving a Java class would still leave the JVM permission checks to satisfy.

The synchronous path offered no useful new route. The httpClient callback did, because it ran the JavaScript function later, through a different executor.

Step 1: follow callback registration

httpClient is the JavaScript object model's outbound HTTP client: a way for a script to send a request to another server. A policy can send a request and supply a function to handle the response or error. Using a callback releases the JavaScript worker while the HTTP operation is pending, so it can return to the pool and service other work; a queued task invokes the function when the response is ready. Think of ordering food: you place the order, you are free to do other things, and the restaurant calls you when it is ready.

The proxy flow itself does not run past every following policy during that wait: the JavaScript step installs a resume handler and returns ExecutionResult.PAUSE, and the flow resumes after the callback executor finishes its work. Releasing a worker and advancing the flow are separate operations.

Registration goes through ScriptableHttpClient.buildCallBackEvent(). It creates a CallBackEvent containing the supplied function and its scope. The constructor also retains thisObj, a copied Binder containing Apigee bindings, the execution deadline and callback depth. It reads the current JSContext to collect some of those values, but does not store that parent context for later execution.

Java
private CallBackEvent buildCallBackEvent(Object callBack) {
    CallBackEvent callBackHolder = null;
    if (callBack instanceof BaseFunction) {
        BaseFunction function = (BaseFunction) callBack;
        Scriptable scope = JSContext.getCurrentContext().getTopLevelScope();
        callBackHolder = new CallBackEvent(function, scope, this, getCallBackExecutor());
        this.hasCallBacks = true;
    }
    return callBackHolder;
}

Line by line:

  • private CallBackEvent buildCallBackEvent(Object callBack) { starts a method that builds the saved event from the callback the script supplied.
  • CallBackEvent callBackHolder = null; prepares an empty result.
  • if (callBack instanceof BaseFunction) { checks that the supplied thing is a JavaScript function.
  • BaseFunction function = (BaseFunction) callBack; treats it as a function object.
  • Scriptable scope = JSContext.getCurrentContext().getTopLevelScope(); grabs the current top-level scope, which is the set of variables the function can see.
  • callBackHolder = new CallBackEvent(function, scope, this, getCallBackExecutor()); creates the event with the function, its scope, the HTTP client object and the executor that will run it.
  • this.hasCallBacks = true; records that this client has callbacks.
  • return callBackHolder; returns the event.
Java
public CallBackEvent(BaseFunction function, Scriptable scope, Scriptable thisObj, CallBackExecutor callBackExecutor) {
    this.function = function;
    this.scope = scope;
    this.thisObj = thisObj;
    JSContext parenJsContext = JSContext.getCurrentContext();
    this.binder = new Binder(parenJsContext.getBinder());
    this.endTimeMS = parenJsContext.getEndTimeMS();
    this.callBackExecutor = callBackExecutor;
    this.depth = callBackExecutor.getCurrentStackDepth() + 1;
}

Line by line:

  • public CallBackEvent(...) is the constructor, the code that runs when a new event is created.
  • this.function = function; saves the function.
  • this.scope = scope; saves the scope.
  • this.thisObj = thisObj; saves the object the function will see as this.
  • JSContext parenJsContext = JSContext.getCurrentContext(); reads the current interpreter context, the object that holds the script's runtime state.
  • this.binder = new Binder(parenJsContext.getBinder()); copies the binder, which holds Apigee's variables.
  • this.endTimeMS = parenJsContext.getEndTimeMS(); saves the deadline.
  • this.callBackExecutor = callBackExecutor; saves the executor.
  • this.depth = callBackExecutor.getCurrentStackDepth() + 1; records how deeply nested the callback is.

The event retains function, scope, thisObj, a copied Binder, deadline and callback depth. parenJsContext is read here but is not stored as the callback context. That detail matters later: the event does not carry the parent interpreter context with it.

Step 2: pause the flow and queue the callback

After synchronous JavaScript returns, Apigee installs submission and resume handlers. PAUSE suspends the proxy flow and the worker can return to the pool.

Java
CallBackExecutor callBackExecutor = httpClient.getCallBackExecutor();
if (httpClient.hasCallBacks()) {
    ThreadPoolManager threadPoolManager = ThreadPoolManager.getInstance();
    Objects.requireNonNull(threadPoolManager);
    callBackExecutor.setTaskSubmitHandler(threadPoolManager::submitAsMetricsAwareTask);
    callBackExecutor.setResumeHandlerAndStart(throwable -> {
        handleResume(throwable, binder, messageContext, executionContext);
    });
    return ExecutionResult.PAUSE;
}
binder.unBindAll();
return ExecutionResult.SUCCESS;

Line by line:

  • CallBackExecutor callBackExecutor = httpClient.getCallBackExecutor(); gets the object that will run callbacks.
  • if (httpClient.hasCallBacks()) { checks whether any callbacks were registered.
  • ThreadPoolManager threadPoolManager = ThreadPoolManager.getInstance(); gets the pool manager, the component that hands out worker threads.
  • Objects.requireNonNull(threadPoolManager); fails early if it is missing.
  • callBackExecutor.setTaskSubmitHandler(threadPoolManager::submitAsMetricsAwareTask); tells the executor to submit callback work to the thread pool.
  • callBackExecutor.setResumeHandlerAndStart(throwable -> { installs the code that resumes the flow when the callback finishes.
  • handleResume(throwable, binder, messageContext, executionContext); is that resume code.
  • }); closes the lambda.
  • return ExecutionResult.PAUSE; pauses the flow.
  • } closes the if.
  • binder.unBindAll(); releases the variables when there are no callbacks.
  • return ExecutionResult.SUCCESS; continues the flow normally.

When the HTTP work completes, the response path queues the event and decrements the in-flight count. When no operations remain and a resume handler exists, it submits pending callbacks.

Java
public void prepareToExecute(CallBackEvent callBackHolder) {
    this.callBackQueue.add(callBackHolder);
    int inFlight = this.inflightCallBackCount.decrementAndGet();
    logger.atFine().log("Adding call back callBackQueue size is %d inflight is %d", this.callBackQueue.size(), inFlight);
    this.numberOfCall.incrementAndGet();
    if (inFlight == 0 && this.resumeHandler != null) {
        submitPendingCallbacks();
    }
}

Line by line:

  • public void prepareToExecute(CallBackEvent callBackHolder) { starts the method that queues a finished callback.
  • this.callBackQueue.add(callBackHolder); puts the event in the queue.
  • int inFlight = this.inflightCallBackCount.decrementAndGet(); lowers the count of operations still running and stores the new value.
  • logger.atFine().log(...) writes a debug log line.
  • this.numberOfCall.incrementAndGet(); counts the call.
  • if (inFlight == 0 && this.resumeHandler != null) { checks whether nothing is left running and a resume handler exists.
  • submitPendingCallbacks(); submits the queued callbacks.
  • } closes the if.
Java
private void submitPendingCallbacks() {
    if (readyToExecute() && !this.shutDown.get()) {
        logger.atFine().log(" submitPendingCallbacks");
        Runnable r = () -> {
            Throwable error = null;
            boolean finished = true;
            try {
                finished = executeJSCallBacksCode();
            } catch (Throwable e) {
                error = e;
            }
            if (finished) {
                if (this.readyToResumeFlag.compareAndSet(false, true)) {
                    this.resumeHandler.accept(error);
                } else {
                    logger.atWarning().log("Attempt to call resume handler more than once");
                }
            }
        };
        if (this.submitHandler != null) {
            this.submitHandler.accept(r);
        } else {
            r.run();
        }
    }
}

Line by line:

  • private void submitPendingCallbacks() { starts the method that sends queued callbacks for execution.
  • if (readyToExecute() && !this.shutDown.get()) { checks that the executor is ready and not shut down.
  • logger.atFine().log(" submitPendingCallbacks"); logs the action.
  • Runnable r = () -> { creates a task, a piece of work that can be handed to a thread.
  • Throwable error = null; prepares a place for an error.
  • boolean finished = true; assumes the work will finish.
  • try { starts the guarded block.
  • finished = executeJSCallBacksCode(); runs the callbacks.
  • } catch (Throwable e) { catches any error.
  • error = e; saves it.
  • } closes the catch.
  • if (finished) { checks whether the callbacks finished.
  • if (this.readyToResumeFlag.compareAndSet(false, true)) { atomically flips a flag so the resume handler runs only once.
  • this.resumeHandler.accept(error); resumes the flow.
  • } else { if the flag was already set,
  • logger.atWarning().log("Attempt to call resume handler more than once"); logs a warning.
  • } closes the inner if.
  • } closes the outer if.
  • }; closes the task.
  • if (this.submitHandler != null) { checks whether a submit handler exists.
  • this.submitHandler.accept(r); hands the task to it.
  • } else { otherwise,
  • r.run(); runs it on the current thread.
  • } closes the if.
  • } closes the method.

The JavaScript step configured this handler as ThreadPoolManager.submitAsMetricsAwareTask. The Runnable executes the callback queue on a selected worker, with no affinity to the registration thread. In other words, the callback is not guaranteed to run on the same thread that registered it. The saved function keeps its JavaScript environment and the Apigee variables needed to continue; its interpreter context comes from the worker that eventually runs the event.

Step 3: notice the missing thread mark

That did not automatically expose Java classes in a callback. CallBackExecutorImpl explicitly enters the restricted factory, so on a clean worker the function still gets a restricted context. The other boundary is the thread that carries the permission checks. The security mark around shell.execute() belongs to the thread executing that synchronous call, and Apigee clears it when the shell returns. The callback task is scheduled separately through ThreadPoolManager.submitAsMetricsAwareTask.

On the worker selected for that task, the callback executor enters Rhino and drains its event queue. CallBackEvent.execute() restores the saved binder and deadline, then calls the function directly. There is no matching installation of the JavaScript security-policy mark around that invocation.

Java
private synchronized boolean executeJSCallBacksCode() throws Throwable {
  int inFlight = 0;
  if (!this.shutDown.get()) {
    JSContextFactory factory = JSContextFactory.getRestrictedInstance();
    try {
      factory.enterContext();
      while (!this.callBackQueue.isEmpty()) {
        this.current = this.callBackQueue.poll();
        this.current.execute();
      }
      inFlight = this.inflightCallBackCount.get();
      // error handling omitted
    } finally {
      this.current = null;
      factory.exit();
    }
  }
  return inFlight == 0 && this.callBackQueue.isEmpty();
}

Line by line:

  • private synchronized boolean executeJSCallBacksCode() throws Throwable { starts the method; synchronized means only one thread runs it at a time.
  • int inFlight = 0; prepares a counter.
  • if (!this.shutDown.get()) { checks the executor is not shut down.
  • JSContextFactory factory = JSContextFactory.getRestrictedInstance(); gets the restricted factory, the object that creates restricted interpreter contexts.
  • try { starts the guarded block.
  • factory.enterContext(); enters a context on this thread.
  • while (!this.callBackQueue.isEmpty()) { loops while callbacks are queued.
  • this.current = this.callBackQueue.poll(); takes the next event.
  • this.current.execute(); runs it.
  • } closes the loop.
  • inFlight = this.inflightCallBackCount.get(); reads the in-flight count.
  • // error handling omitted is a comment.
  • } finally { runs cleanup whatever happened.
  • this.current = null; clears the current event.
  • factory.exit(); exits the context.
  • } closes the finally.
  • } closes the if.
  • return inFlight == 0 && this.callBackQueue.isEmpty(); reports whether everything is done.
Java
public void execute() {
  if (this.depth > 10) {
    throw new IllegalStateException("Too many nested calls to Callbacks.");
  }
  // null-function and deadline checks omitted
  JSContext cx = JSContext.getCurrentContext();
  cx.setBinder(this.binder);
  cx.setEndTimeMS(this.endTimeMS);
  this.function.call(cx, this.scope, this.thisObj, this.args);
  clear();
}

Line by line:

  • public void execute() { starts the method that runs one saved callback.
  • if (this.depth > 10) { checks the nesting limit.
  • throw new IllegalStateException("Too many nested calls to Callbacks."); refuses deeper nesting.
  • } closes the if.
  • // null-function and deadline checks omitted is a comment.
  • JSContext cx = JSContext.getCurrentContext(); gets the current interpreter context on this worker.
  • cx.setBinder(this.binder); restores the saved variables.
  • cx.setEndTimeMS(this.endTimeMS); restores the deadline.
  • this.function.call(cx, this.scope, this.thisObj, this.args); calls the saved function directly.
  • clear(); cleans up.

Apigee's internal security manager uses thread-local state to decide whether to enforce its JVM permission checks. Saving the function, variables and deadline does not carry that mark to another worker. The callback could resume its application state without restoring the restriction used around an ordinary JavaScript policy. One of the two relevant checks was absent on the callback path; the class shutter still prevented a clean callback from resolving Runtime.

Step 4: open the class shutter from PythonScript

The shutter's first condition reads JSContext.allowClassAccess. When the flag is true, the filter immediately allows the requested class: the shutter remains installed, but its allowlists no longer restrict the result. The flag was mutable through a public method:

Java
public boolean setAllowClassAccess(boolean set) {
    boolean old = this.allowClassAccess;
    this.allowClassAccess = set;
    return old;
}

Line by line:

  • public boolean setAllowClassAccess(boolean set) { starts a public setter, a method that changes a value.
  • boolean old = this.allowClassAccess; remembers the previous value.
  • this.allowClassAccess = set; stores the new value.
  • return old; returns the previous value.
  • } closes the method.

That setter changes the live object whose flag the shutter reads. It does not bind the change to one script invocation or arrange to restore the old value when that script finishes. The implementation supported both open and restricted context creation. JSContextFactory.makeContext() left a restricted object's flag at its constructor default of false; the open factory set it to true:

Java
protected Context makeContext() {
    JSContext ctx = new JSContext(this);
    if (this.restrictPackageAccess) {
        ctx.setInstructionObserverThreshold(this.INSTRUCTION_OBSERVER_THRESHOLD);
    } else {
        ctx.setAllowClassAccess(true);
    }
    ctx.setWrapFactory(new JSWrapFactory());
    return ctx;
}

Line by line:

  • protected Context makeContext() { starts the method that creates a new interpreter context.
  • JSContext ctx = new JSContext(this); creates the context.
  • if (this.restrictPackageAccess) { checks whether this factory is restricted.
  • ctx.setInstructionObserverThreshold(this.INSTRUCTION_OBSERVER_THRESHOLD); sets a limit that lets the runtime watch long-running scripts.
  • } else { for an open factory,
  • ctx.setAllowClassAccess(true); opens the class shutter.
  • } closes the if.
  • ctx.setWrapFactory(new JSWrapFactory()); installs the wrapper that hides getClass.
  • return ctx; returns the context.

Earlier PythonScript research had already shown a broader Java-access path, including a legacy route that accepted JavaScript resources inside that policy. The code suggests the policy may once have been intended to support both languages, although that design history could not be confirmed.

PythonScript uses Jython. From the Python seed, the researcher could reach Apigee's JSContextFactory and call the public setter on the returned context. The tested runtime's Java permission policy permitted the calls needed to obtain the factory and change the flag. That suggested a short chain: use PythonScript to open the shutter, then call Runtime.exec() from an asynchronous JavaScript callback where the thread mark was absent. One problem remained: allowClassAccess belonged to a JSContext, so the modified object had to survive long enough for a callback on the same worker to reuse it.

Step 5: keep the context attached across cleanup

A Rhino Context is associated with a Java thread. Entering one does not necessarily create a new interpreter object: Context.enter(...) first checks whether the thread already has a current context. If it does, Rhino returns that same object and increments its nesting counter. Think of a hotel room key: if you already have the key, the front desk hands you the same key again and writes down that you now hold it twice.

The JavaScript step tried to clean up a prior context before preparing a fresh policy execution. Its clearJSContext() helper performed one Context.exit(), which decremented the counter. Rhino cleared the thread association only when that counter reached zero.

The seed entered the restricted factory twice from PythonScript, changed the context returned by the first entry through setAllowClassAccess(True), and deliberately omitted both exits. On an initially clean worker, the two entries raised the counter from zero to two. Returning from PythonScript left that modified object attached to the worker.

Python
factory = JSContextFactory.getRestrictedInstance()
ctx = factory.enterContext()
factory.enterContext()
ctx.setAllowClassAccess(True)

Line by line:

  • factory = JSContextFactory.getRestrictedInstance() gets the restricted factory.
  • ctx = factory.enterContext() enters a context and keeps a reference to it.
  • factory.enterContext() enters again, which returns the same context and raises its count to two.
  • ctx.setAllowClassAccess(True) opens the class shutter on that context.

On an initially clean worker, the restricted factory creates and attaches a JSContext and its entry count becomes 1. The second call returns the already attached context and raises its entry count to 2, with no matching exits. The same JSContext now has allowClassAccess=true, and returning from the seed leaves both entries outstanding; the worker can go back to the pool with that state.

Java
protected void clearJSContext() {
    Context context = Context.getCurrentContext();
    if (context != null) {
        try {
            Context.exit();
        } catch (Exception e) {
            logger.atSevere().withCause(e).log("%s Failed to clear JS context from thread.", this.javascriptStep);
        }
    }
}

Line by line:

  • protected void clearJSContext() { starts the cleanup helper.
  • Context context = Context.getCurrentContext(); gets the current context, if any.
  • if (context != null) { checks there is one.
  • try { starts the guarded block.
  • Context.exit(); exits once.
  • } catch (Exception e) { catches errors.
  • logger.atSevere().withCause(e).log(...) logs the failure.
  • } closes the catch.
  • } closes the if.
  • } closes the method.

Before preparing a fresh policy, the JavaScript step calls clearJSContext. This helper performs only one exit, even when the current context has multiple outstanding entries.

Java
public static void exit()
{
    Object helper = VMBridge.instance.getThreadContextHelper();
    Context cx = VMBridge.instance.getContext(helper);
    if (cx == null) {
        throw new IllegalStateException(
            "Calling Context.exit without previous Context.enter");
    }
    if (cx.enterCount < 1) Kit.codeBug();
    if (--cx.enterCount == 0) {
        VMBridge.instance.setContext(helper, null);
        cx.factory.onContextReleased(cx);
    }
}

Line by line:

  • public static void exit() starts the exit method.
  • Object helper = VMBridge.instance.getThreadContextHelper(); gets the per-thread helper object.
  • Context cx = VMBridge.instance.getContext(helper); reads the context attached to this thread.
  • if (cx == null) { checks there is one.
  • throw new IllegalStateException(...) fails if not.
  • } closes the if.
  • if (cx.enterCount < 1) Kit.codeBug(); sanity check.
  • if (--cx.enterCount == 0) { lowers the count and checks whether it reached zero.
  • VMBridge.instance.setContext(helper, null); detaches the context from the thread.
  • cx.factory.onContextReleased(cx); tells the factory.
  • } closes the if.
  • } closes the method.

Rhino clears the thread association only at zero. A single cleanup exit leaves the modified context attached when the counter was 2.

Java
Context old = VMBridge.instance.getContext(helper);
if (old != null) {
  cx = old;
} else {
  if (cx == null) {
    cx = factory.makeContext();
    // initialization omitted
  }
  VMBridge.instance.setContext(helper, cx);
}
cx.enterCount++;

Line by line:

  • Context old = VMBridge.instance.getContext(helper); reads any context already attached to the thread.
  • if (old != null) { if there is one,
  • cx = old; reuse it.
  • } else { otherwise,
  • if (cx == null) { if no context was supplied,
  • cx = factory.makeContext(); create one.
  • // initialization omitted is a comment.
  • } closes the inner if.
  • VMBridge.instance.setContext(helper, cx); attach it to the thread.
  • } closes the outer if.
  • cx.enterCount++; raise the count.

An attached context bypasses factory.makeContext. Entering through the restricted factory does not reset allowClassAccess; the callback executor later balances only its own increment. The existing-context branch also explains why selecting the restricted factory did not repair the flag: Rhino returned the attached object without calling makeContext(). The factory's restricted default applied when constructing a missing object, while this worker already had one with allowClassAccess=true.

Step 6: a fresh policy fails before its script runs

Ordinary JavaScript policies were sent through the pool, waiting for one to reuse a prepared worker. The expectation was that the retained context would expose Runtime. Instead, Apigee threw IllegalStateException while building the JavaScript environment, before the script body started.

The Python seed had attached a context without leaving a JavaScript invocation active. Rhino tracks that invocation separately as a top call, and helpers need its scope when converting Java values into objects in the correct JavaScript environment. RhinoExecutor.runScript() called Binder.bindAll(...) before script.exec(...). During that preparation, a content wrapper asked ScriptRuntime.getTopCallScope(cx) for the current scope. The reused context had no active top call, so the helper threw before the policy body could establish one.

This was the second reason the callback mattered. Its function and scope already existed. CallBackEvent.execute() restored the saved state and invoked that function directly, avoiding the fresh-policy binding phase that had just failed.

Step 7: the callback establishes its own top call

For an interpreted callback, InterpretedFunction.call() checks whether a top call is active. If none exists, it routes the function through ScriptRuntime.doTopCall(), which establishes the saved scope. Apigee's factory hook records it on JSContext, and the function is invoked again inside that active top call. This time Rhino reaches the interpreter. The Rhino helpers come from the 1.7.13 ContextFactory, InterpretedFunction and ScriptRuntime sources, with upstream line numbers preserved.

Java
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
          Object[] args)
{
  if (!ScriptRuntime.hasTopCall(cx)) {
    return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args, idata.isStrict);
  }
  return Interpreter.interpret(this, cx, scope, thisObj, args);
}

Line by line:

  • public Object call(Context cx, Scriptable scope, Scriptable thisObj, starts the method that calls a function.
  • Object[] args) is the rest of the signature.
  • { opens the body.
  • if (!ScriptRuntime.hasTopCall(cx)) { checks whether no top call is active.
  • return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args, idata.isStrict); wraps the call in a top call.
  • } closes the if.
  • return Interpreter.interpret(this, cx, scope, thisObj, args); otherwise runs the function in the interpreter.
  • } closes the method.
Java
public static Object doTopCall(Callable callable,
                Context cx, Scriptable scope,
                Scriptable thisObj, Object[] args, boolean isTopLevelStrict)
{
  if (scope == null)
    throw new IllegalArgumentException();
  if (cx.topCallScope != null) throw new IllegalStateException();

  Object result;
  cx.topCallScope = ScriptableObject.getTopLevelScope(scope);
  cx.useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE);
  boolean previousTopLevelStrict = cx.isTopLevelStrict;
  cx.isTopLevelStrict = isTopLevelStrict;
  ContextFactory f = cx.getFactory();
  try {
    result = f.doTopCall(callable, cx, scope, thisObj, args);
  } finally {
    cx.topCallScope = null;
    // Cleanup cached references
    cx.cachedXMLLib = null;
    cx.isTopLevelStrict = previousTopLevelStrict;

    if (cx.currentActivationCall != null) {
      // Function should always call exitActivationFunction
      // if it creates activation record
      throw new IllegalStateException();
    }
  }
  return result;
}

Line by line:

  • public static Object doTopCall(Callable callable, starts the method that establishes a top call.
  • Context cx, Scriptable scope, are the context and scope.
  • Scriptable thisObj, Object[] args, boolean isTopLevelStrict) are the this object, arguments and strictness flag.
  • { opens the body.
  • if (scope == null) checks the scope.
  • throw new IllegalArgumentException(); fails if it is missing.
  • if (cx.topCallScope != null) throw new IllegalStateException(); fails if a top call is already active.
  • Object result; prepares the result.
  • cx.topCallScope = ScriptableObject.getTopLevelScope(scope); records the top-level scope.
  • cx.useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE); copies a feature flag.
  • boolean previousTopLevelStrict = cx.isTopLevelStrict; remembers the strictness setting.
  • cx.isTopLevelStrict = isTopLevelStrict; sets the new one.
  • ContextFactory f = cx.getFactory(); gets the factory.
  • try { starts the guarded block.
  • result = f.doTopCall(callable, cx, scope, thisObj, args); lets the factory run the call.
  • } finally { runs cleanup.
  • cx.topCallScope = null; clears the top call.
  • // Cleanup cached references is a comment.
  • cx.cachedXMLLib = null; clears a cache.
  • cx.isTopLevelStrict = previousTopLevelStrict; restores strictness.
  • if (cx.currentActivationCall != null) { checks for a leftover activation.
  • // Function should always call exitActivationFunction is a comment.
  • // if it creates activation record is a comment.
  • throw new IllegalStateException(); fails if one is left.
  • } closes the if.
  • } closes the finally.
  • return result; returns the result.
  • } closes the method.
Java
protected Object doTopCall(Callable callable, Context cx,
    Scriptable scope, Scriptable thisObj, Object[] args) {
  if (cx instanceof JSContext) {
    JSContext jcx = (JSContext) cx;
    jcx.setTopLevelScope(scope);
    if (args != null) {
      notifyArgs(args, jcx);
    }
  }
  return super.doTopCall(callable, cx, scope, thisObj, args);
}

Line by line:

  • protected Object doTopCall(Callable callable, Context cx, starts Apigee's override.
  • Scriptable scope, Scriptable thisObj, Object[] args) { is the rest of the signature.
  • if (cx instanceof JSContext) { checks the context type.
  • JSContext jcx = (JSContext) cx; casts it.
  • jcx.setTopLevelScope(scope); records the scope on the context.
  • if (args != null) { checks arguments exist.
  • notifyArgs(args, jcx); notifies about them.
  • } closes the if.
  • } closes the outer if.
  • return super.doTopCall(callable, cx, scope, thisObj, args); delegates to the parent class.
  • } closes the method.
Java
protected Object doTopCall(Callable callable,
              Context cx, Scriptable scope,
              Scriptable thisObj, Object[] args)
{
  Object result = callable.call(cx, scope, thisObj, args);
  return result instanceof ConsString ? result.toString() : result;
}

Line by line:

  • protected Object doTopCall(Callable callable, starts the base implementation.
  • Scriptable thisObj, Object[] args) are the this object and arguments.
  • { opens the body.
  • Object result = callable.call(cx, scope, thisObj, args); calls the function.
  • return result instanceof ConsString ? result.toString() : result; converts a special string type to a normal string if needed.
  • } closes the method.

The restricted factory has entered the worker's current context. The queued event already holds a function and scope. CallBackEvent.execute() restores the saved binder and deadline on this worker's JSContext, and direct function invocation avoids fresh global binding. The interpreted function detects the absent top call, and Rhino establishes one around the existing function and its saved scope. ScriptRuntime.doTopCall sets topCallScope from the saved callback scope, and the context's factory receives the call. Apigee records the saved scope on JSContext, and its superclass invokes the Callable inside the active top call; neither operation resets class access or marks this worker. The Callable is the same interpreted callback, and on the second entry hasTopCall is now true, so the interpreter runs the callback. Its context still has allowClassAccess=true, and the callback path has not installed the synchronous policy security mark. After the invocation unwinds, the executor's exit removes only its own increment; earlier leaked entries can keep the modified context attached to the worker.

The callback could now run in the context modified by PythonScript, through the path that lacked the synchronous security mark. The class shutter exposed Runtime, and the missing mark left Apigee's normal JVM permission boundary inactive for that callback invocation.

Step 8: reproduce the worker-pool race

The proof was split into two proxies because the chain needed two different scheduling roles. A proxy here is the Apigee configuration that defines the API and its policies.

Proxy A ran a normal JavaScript policy. At startup it called Context.exit() until its current worker had no Rhino context, allowing the policy to initialize normally even after earlier attempts. It then issued a delayed outbound request through httpClient. Registration saved the callback function, scope, binder, deadline, and depth while the response remained pending.

Proxy B ran the PythonScript seed. While Proxy A waited, repeated requests to Proxy B visited workers in the same pool. Each successful seed entered the restricted factory twice, set allowClassAccess=true, and returned without matching the entries. A worker could finish the request and return to the pool with the modified context still attached.

When Proxy A's outbound response arrived, Apigee queued the saved CallBackEvent as new work. The callback had no affinity to the thread that registered it. A clean worker kept Runtime hidden. A contaminated worker reused the open context, and the saved function supplied the missing top call.

Worker selection made the proof nondeterministic. In a deployment with several message processors, both proxies also had to reach the same JVM because the leaked state could not cross a process boundary. The policies, callback body, delay, and request volume were controlled; repeated requests handled the two scheduling decisions that could not be.

The model predicted three outcomes, which made useful negative controls:

  1. A callback on a clean worker could not resolve the blocked Java class.
  2. A fresh JavaScript policy on a contaminated worker failed during global binding, before its body.
  3. A saved callback on a contaminated worker entered a top call and reached the host operation.

Step 9: prove it with a shell

For the end-to-end check, the callback opened a reverse shell. A reverse shell is a connection from the victim machine back to the attacker, giving the attacker a command prompt on that machine. Inside it, the operating-system identity of the Apigee message processor was checked:

Bash
bash-5.1$ whoami
apigee

Line by line:

  • bash-5.1$ is the shell prompt, showing the shell version.
  • whoami asks the operating system which user is running the command.
  • apigee is the answer: the message processor runs as the apigee user.

Root cause

The failure came from the lifetime of security state, not from a single missing check. Three pieces combined:

  • allowClassAccess is a mutable flag on a live JSContext, changed through a public setter that does not bind the change to one invocation or restore the old value.
  • Rhino attaches a Context to a thread and only detaches it when the nesting counter reaches zero. The JavaScript step's clearJSContext() performed a single Context.exit(), so a context entered twice by PythonScript survived cleanup with allowClassAccess=true and was returned by a later Context.enter() without going through makeContext().
  • The synchronous JavaScript step installs the thread-local security mark around shell.execute() and clears it afterwards. The asynchronous callback executor invokes the saved function on a pool worker without installing that mark, so the JVM permission boundary was inactive for the callback.

The class shutter and the getClass wrapper were still in place, and the callback executor still entered the restricted factory. The restricted factory did not repair the flag because the attached context bypassed makeContext(), and the callback's own top-call establishment did not reset class access or mark the worker.

Impact

An attacker who could deploy both policy flows could reach host command execution as the message processor's operating-system user. The prerequisite narrowed who could exploit the issue: the ability to modify and deploy API proxy code containing PythonScript and JavaScript policies. The worker state also crossed proxy and request boundaries without travelling through a documented flow variable: Proxy B changed a Rhino object attached to a Java thread, and Proxy A's callback later consumed that state because the pool happened to select the same thread. The policy model presented those executions as separate, while the runtime let one inherit the other's interpreter authority.

Fix

A later review of the Apigee hybrid 1.17.1 runtime image found two changes aimed at the state used by this chain. The proof was not rerun against that image or a managed-runtime build, so this evidence does not establish the first fixed version or a managed-service remediation date.

Old contexts are drained before JavaScript starts

JSContext gained clearPriorContexts(), which repeatedly calls Context.exit() until the worker has no current Rhino context, with a guard against an endless loop:

Java
public static void clearPriorContexts() {
    int maxLoop = 1000;
    while (Context.getCurrentContext() != null) {
        try {
            if (maxLoop-- <= 0) {
                logger.atSevere().log(
                    "Exceeded max loop iterations clearing prior JS contexts.");
                return;
            }
            Context.exit();
        } catch (Throwable e) {
            logger.atFine().withCause(e).log("Failed to close Context");
        }
    }
}

Line by line:

  • public static void clearPriorContexts() { starts the new cleanup method.
  • int maxLoop = 1000; sets a safety limit.
  • while (Context.getCurrentContext() != null) { loops while a context is attached.
  • try { starts the guarded block.
  • if (maxLoop-- <= 0) { checks the limit.
  • logger.atSevere().log(...) logs a severe message.
  • return; stops if the limit is hit.
  • } closes the if.
  • Context.exit(); exits once.
  • } catch (Throwable e) { catches errors.
  • logger.atFine().withCause(e).log("Failed to close Context"); logs them.
  • } closes the catch.
  • } closes the loop.
  • } closes the method.

Both JavascriptStepExecution.execute(...) and RhinoExecutor.execute(...) call this cleanup before preparing a policy. The older cleanup could remove one entry; the loop drains all outstanding entries before normal JavaScript initialization, so a worker carrying Proxy B's modified context should detach it before a fresh policy begins.

Callbacks run through an untrusted executor

ScriptableHttpClient now passes InternalMessageContext::callUntrusted into each CallBackEvent. The event uses that executor around the captured function instead of calling the function directly. The call eventually reaches SecurityPolicyServiceImpl.callUntrusted(...), which installs the thread mark when necessary, executes the callback, and clears only the mark it added:

Java
InternalSecurityManager securityManager = getSecurityManager();
boolean wasMarked = false;
if (securityManager != null) {
    wasMarked = securityManager.markedThread();
    if (!wasMarked) {
        securityManager.markThread("callUntrusted");
    }
}

V result = AccessController.doPrivileged(() -> callable.call());

if (securityManager != null && !wasMarked) {
    securityManager.clearThread();
}
return result;

Line by line:

  • InternalSecurityManager securityManager = getSecurityManager(); gets the security manager.
  • boolean wasMarked = false; prepares a flag.
  • if (securityManager != null) { checks it exists.
  • wasMarked = securityManager.markedThread(); checks whether this thread is already marked.
  • if (!wasMarked) { if it is not,
  • securityManager.markThread("callUntrusted"); mark it.
  • } closes the inner if.
  • } closes the outer if.
  • V result = AccessController.doPrivileged(() -> callable.call()); runs the callback with the JVM's permission checks.
  • if (securityManager != null && !wasMarked) { checks whether this code added the mark.
  • securityManager.clearThread(); clears only the mark it added.
  • } closes the if.
  • return result; returns the result.

This establishes the JVM permission boundary on the worker that actually executes the callback, so its authority no longer depends on the mark left on that thread by unrelated work. The bundled Rhino version remained 1.7.13, setAllowClassAccess(...) remained mutable, and the callback executor still entered a restricted context in much the same way. The repair instead enforced clean state before policy execution and explicit untrusted authority around the asynchronous function. Static inspection of hybrid 1.17.1 therefore indicates that the complete callback chain is closed.

Variants to test

  • Other asynchronous executors. Look for any path that saves a function and runs it on a pool worker without the synchronous security mark, such as other callback-based APIs. A positive result is a callback that can resolve a class the shutter should block.
  • Other mutable security flags. Search for public setters that change live interpreter state read by a filter or shutter. A positive result is a flag change that survives the script invocation and is visible to a later execution on the same thread.
  • Cleanup helpers that exit once. Audit any Context.exit() or equivalent teardown that assumes a single outstanding entry. A positive result is a context that stays attached after cleanup when entered more than once.
  • Cross-policy state on shared workers. Deploy two proxies that share a pool and have one leave interpreter state behind for the other. A positive result is the second proxy observing state it never set through a documented flow variable.
  • Fresh-policy binding failures as a signal. If a policy on a reused worker throws during environment setup before its body runs, check whether the worker carries a context with no active top call. A positive result is a reproducible IllegalStateException from the binding phase.
  • Multi-process deployments. Confirm whether leaked state can cross message processors. A positive result would be the chain working when the two proxies land on different JVMs, which the original chain could not do.

Glossary

  • API: the set of doors a program offers so other programs can talk to it.
  • API proxy: an Apigee configuration that defines an API and the policies that run on its requests.
  • Apigee: Google Cloud's service for running policies in front of APIs.
  • Asynchronous: work that is started now and finishes later, without the caller waiting.
  • Binder: an Apigee object that holds the variables a script can use.
  • Callback: a function supplied to run later, when an event such as an HTTP response arrives.
  • Class: a named piece of Java code, like a toolbox.
  • Class shutter: a filter that decides which Java classes a script may see.
  • Context: Rhino's object holding a script's runtime state, attached to a thread.
  • Context.enter / Context.exit: the calls that attach a context to a thread and detach it, using a nesting counter.
  • Decompilation: turning compiled code back into readable source code.
  • Flow variable: a named value that Apigee policies can read and write during a request.
  • getClass: a Java method that tells you what class an object is; a common step towards reflection.
  • HTTP: the protocol browsers and servers use to exchange requests and responses.
  • httpClient: the JavaScript object model's outbound HTTP client.
  • IllegalStateException: a Java error meaning the program was in the wrong state for an operation.
  • Java: a programming language and runtime used widely on servers.
  • JavaScript: the language that runs in web pages, also used for Apigee policies.
  • java.lang.Runtime: the Java class that can start operating-system programs.
  • JVM: Java Virtual Machine, the program that runs Java code.
  • Jython: an engine that runs Python code inside Java.
  • Message processor: the Apigee component that actually runs proxy policies.
  • Negative control: a test expected to fail, used to confirm that a success is meaningful.
  • Package: a group of related Java classes, like a folder.
  • Policy: a small piece of configuration or code that Apigee runs on a request.
  • Proxy: see API proxy.
  • PythonScript: an Apigee policy type that runs Python through Jython.
  • Reflection: a Java feature that lets code inspect and call things at runtime.
  • Reverse shell: a connection from the victim machine back to the attacker, giving a command prompt.
  • Rhino: the JavaScript engine that runs JavaScript inside Java.
  • Sandbox: a restricted playpen where code can run without touching the rest of the machine.
  • Scope: the set of variables a function can see.
  • Security manager: the component that enforces permission checks.
  • Setter: a method that changes a value.
  • Synchronous: work that the caller waits for before continuing.
  • Thread: one of the sequences of work a server runs in parallel.
  • Thread-local: a value that belongs to one thread only.
  • Top call: Rhino's record of an active JavaScript invocation, needed by helpers that convert values.
  • Worker: a thread from a pool that runs queued work.
  • Worker pool: a set of reusable threads that pick up queued tasks.

More by Nikita Markevich

View all

11 more disclosed reports, best first.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.