Repository navigation
Description
Preflight Checklist
- I have read the Contributing Guidelines for this project.
- I agree to follow the Code of Conduct that this project adheres to.
- I have searched the issue tracker for a bug report that matches the one I want to file, without success.
Electron Version
45.5.0
What operating system(s) are you using?
macOS
Operating System Version
macOS Tahoe 26.5.1
What arch are you using?
arm64 (including Apple Silicon)
Last Known Working Electron version
Not bisected. The code path was introduced by #52964, which (per the release notes) first shipped in v42.10.0 (#53042), v43.5.0 (#53041), v44.0.0 (#53040, from 44.0.0-beta.6) and v45.0.0-alpha.1. Releases before those (e.g. 42.9.x, 43.4.x) should not be affected, but I have not tested them.
Does the issue also appear in Chromium / Google Chrome?
No
Expected Behavior
Calling a reference to process.activateUvLoop (or process.getCPUUsage) that belongs to a subframe which has since been removed should do nothing (or throw / return undefined). The renderer should not crash.
Actual Behavior
The renderer crashes on every run:
FATAL:base/allocator/partition_alloc_support.cc:827] Detected dangling raw_ptr in unretained with id=0x…
render-process-gone { reason: 'crashed', exitCode: 5 }
This is PartitionAlloc's dangling-base::Unretained check firing: the C++ object the function is bound to has already been freed.
With that check disabled (--disable-features=PartitionAllocUnretainedDanglingPtr), the renderer goes on to use the freed memory and segfaults at 0xefefefefefefefff / 0xefefefefefefefef (PartitionAlloc's quarantine fill byte) inside electron::ElectronBindings::ActivateUVLoop / base::ProcessMetrics::GetCumulativeCPUUsage. Symbolized stacks are below.
Only nodeIntegrationInSubFrames: true and sandbox: false are required. It reproduces with the recommended contextIsolation: true and nodeIntegration: false, from a preload script.
Testcase Gist URL
Additional Information
Testcase
package.json
{
"name": "electron-bindings-uaf",
"main": "main.js"
}main.js
const { app, BrowserWindow, protocol, net } = require('electron')
const path = require('node:path')
const { pathToFileURL } = require('node:url')
// Serve index.html and child.html from one origin so the top frame's preload
// can reach the child frame's window.
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { standard: true, secure: true } }
])
app.whenReady().then(() => {
protocol.handle('app', (req) =>
net.fetch(pathToFileURL(path.join(__dirname, new URL(req.url).pathname)).toString()))
const win = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
nodeIntegrationInSubFrames: true,
sandbox: false,
preload: path.join(__dirname, 'preload.js')
}
})
win.webContents.on('render-process-gone', (_event, details) => {
console.log('render-process-gone', details)
})
win.loadURL('app://poc/index.html')
})preload.js
// Runs in every frame (nodeIntegrationInSubFrames). The top frame drives the repro.
if (process.isMainFrame) {
window.addEventListener('DOMContentLoaded', () => {
const iframe = document.createElement('iframe')
iframe.src = 'child.html'
iframe.onload = () => {
// The subframe has its own Node.js environment and its own ElectronBindings.
const activateUvLoop = iframe.contentWindow.process.activateUvLoop
activateUvLoop() // fine: the child's ElectronBindings is alive
iframe.remove() // frees the child's ElectronBindings
activateUvLoop() // use-after-free -> renderer crash
}
document.body.appendChild(iframe)
})
}index.html
<!DOCTYPE html>
<html><body><h1>parent</h1></body></html>child.html
<!DOCTYPE html>
<html><body>child</body></html>Steps: npm install [email protected] && npx electron . → the renderer crashes as soon as the iframe loads. Deleting the last activateUvLoop() call (the control) makes the crash go away.
Notes on the testcase:
- The child must be a real same-origin document.
about:blanksubframes never get a Node.js environment (ElectronRenderFrameObserver::ShouldNotifyClient), so they don't reproduce this. The customapp:scheme just makes both pages same-origin. - The same crash happens from page script with
nodeIntegration: true, contextIsolation: false, nodeIntegrationInSubFrames: true, sandbox: false, usingiframe.contentWindow.process.activateUvLoop. process.getCPUUsagefrom the removed frame crashes the same way (it is bound to the freedmetrics_).
Root cause
Links point at b5e057b on main.
-
Every subframe (and every extra main frame in the process) now gets its own
ElectronBindings.FrameEnvironmentborrows the process-lifetimeElectronBindingsonly for the first main frame; every other frame createsown_electron_bindings, which is destroyed with theFrameEnvironment:
electron_renderer_client.cc#L34-L65 -
That per-frame object is bound into JS functions with
base::Unretained.DidCreateScriptContextcallsframe_env->electron_bindings->BindTo(...)(L199), which installs:// electron_bindings.cc#L81-L83 dict.SetMethod("activateUvLoop", base::BindRepeating(&ElectronBindings::ActivateUVLoop, base::Unretained(this))); // electron_bindings.cc#L58-L60 (via BindProcess(..., metrics_.get())) process->SetMethod("getCPUUsage", base::BindRepeating(&ElectronBindings::GetCPUUsage, base::Unretained(metrics)));
-
The JS functions outlive the frame. The callback lives in a cppgc-managed
gin_helper::CallbackHolder(function_template.h#L65,#L439), so it stays alive for as long as any JS reference to the function exists, including one held by another frame. -
Removing the frame frees the object without invalidating the functions.
WillReleaseScriptContext→FreeFrameEnvironment(L255, L294) drops theFrameEnvironment, whose destructor deletesown_electron_bindings(and with itmetrics_,pending_next_ticks_andcall_next_tick_async_).env->set_can_call_into_js(false)doesn't help here, because the call goes from JS into C++. -
A later call runs on the freed object.
ActivateUVLoop(L90-L97) reads and writespending_next_ticks_and callsuv_async_send()on the freed handle (whose loop has also been freed by~NodeBindings). In the detector-off crash,std::ranges::containsloads thestd::listsentinel'snextpointer from the quarantined object (0xefefefefefefefef) and faults reading that node's value at+0x10(0xefefefefefefefff).
The child's setImmediate and process.nextTick are wrapped to call process.activateUvLoop() (lib/common/init.ts#L14-L20), so holding on to a removed frame's setImmediate should reach the same freed object. I haven't tested that path.
Regression
Before #52964 every renderer environment used the process-lifetime ElectronBindings owned by ElectronRendererClient, so Unretained(this) was safe. #52964 did not touch electron_bindings.cc; the binding site changed by one line:
- electron_bindings_->BindTo(env->isolate(), env->process_object());
+ frame_env->electron_bindings->BindTo(env->isolate(), env->process_object());That made the receiver of the existing Unretained(this) per-frame, and so shorter-lived than the JS functions bound to it.
Stack traces
Electron 45.5.0, darwin-arm64, symbolized with the official electron-v45.5.0-darwin-arm64-symbols.zip (module 4C4C449555553144A1E4E0ADB297AB1C0). These come from the page-script variant, triggered from the iframe's onload; the preload testcase produces the same FATAL.
Default build (dangling-Unretained check):
EXC_BREAKPOINT
#0 logging::LogMessage::HandleFatal(...)
#1 logging::LogMessage::Flush()
#2 logging::LogMessageFatal::~LogMessageFatal()
#5 base::internal::Invoker<...>::Run raw_ptr.h:994
#6 gin_helper::Dispatcher<void (v8::Isolate*)>::DispatchToCallback(...)
#7-#10 <V8 builtins>
#11 v8::internal::Execution::Call(...) execution.cc:492
#12 v8::Function::Call(...)
#13 blink::V8ScriptRunner::CallFunction(...)
...
#21 blink::HTMLFrameOwnerElement::DispatchLoad()
(Frame #5's symbol name shows electron::Browser::* because the linker folded identical Invoker instantiations; the dispatcher signature void (v8::Isolate*) is activateUvLoop's.)
--disable-features=PartitionAllocUnretainedDanglingPtr, activateUvLoop:
EXC_BAD_ACCESS (SIGSEGV) KERN_INVALID_ADDRESS at 0xefefefefefefefff
#0 electron::ElectronBindings::ActivateUVLoop(v8::Isolate*)
#2 gin_helper::Dispatcher<void (v8::Isolate*)>::DispatchToCallback(...)
#7 v8::internal::Execution::Call(...)
#8 v8::Function::Call(...)
#9 blink::V8ScriptRunner::CallFunction(...)
...
#17 blink::HTMLFrameOwnerElement::DispatchLoad()
--disable-features=PartitionAllocUnretainedDanglingPtr, getCPUUsage:
EXC_BAD_ACCESS (SIGSEGV) KERN_INVALID_ADDRESS at 0xefefefefefefefef
#0 base::ProcessMetrics::GetCumulativeCPUUsage() process_metrics_apple.mm:128
#1 electron::ElectronBindings::GetCPUUsage(base::ProcessMetrics*, v8::Isolate*)
#2 base::RepeatingCallback<v8::Local<v8::Value> (v8::Isolate*)>::Run(...)
#5 gin_helper::Dispatcher<v8::Local<v8::Value> (v8::Isolate*)>::DispatchToCallback(...)
#10 v8::internal::Execution::Call(...)
...
#20 blink::HTMLFrameOwnerElement::DispatchLoad()
Suggested fix
Bind the per-frame methods through a WeakPtr, so that a stale function becomes a no-op (not compiled; a sketch):
// electron_bindings.h — last member
base::WeakPtrFactory<ElectronBindings> weak_factory_{this};
// electron_bindings.cc, in BindTo()
dict.SetMethod("activateUvLoop",
base::BindRepeating(&ElectronBindings::ActivateUVLoop,
weak_factory_.GetWeakPtr()));
// getCPUUsage returns a value, so it needs an explicit check rather than
// WeakPtr cancellation:
dict.SetMethod("getCPUUsage",
base::BindRepeating(
[](base::WeakPtr<ElectronBindings> self,
v8::Isolate* isolate) -> v8::Local<v8::Value> {
if (!self)
return v8::Undefined(isolate);
return GetCPUUsage(self->metrics_.get(), isolate);
},
weak_factory_.GetWeakPtr()));The static BindProcess(..., metrics) used by the sandboxed renderer client can keep Unretained, because that client's metrics_ lives for the whole process. A regression spec could follow the testcase above: keep a removed subframe's process.activateUvLoop and call it.
Related
- [Bug]: Asynchronous onBeforeRequest handler crashes Chromium with unretained dangling ptr error for specific websites #42149 — the same
Detected dangling raw_ptr in unretainedcrash class (fromwebRequest), confirmed and fixed in fix: useBlockedRequeststruct to handlewebRequestdata #42647. - fix: illegal access errors when a same-process child window or subframe closes #52964 (backports fix: illegal access errors when a same-process child window or subframe closes #53040, fix: illegal access errors when a same-process child window or subframe closes #53041, fix: illegal access errors when a same-process child window or subframe closes #53042) — introduced the per-frame
ElectronBindings. - fix: crash when a node-integrated iframe is removed before its loop starts #53833, fix: crash when a preload removes its own iframe asynchronously #53838, fix: renderer crash after IPC to a window.open() child with its own contextIsolation #53535 — other crashes in the same per-frame environment setup/teardown path. None of them covers JS-retained
processfunctions.
Scope
- Reproduced on Electron 45.5.0, macOS 26.5.1, arm64 only. Not yet tested on Windows or Linux, or on the 42/43/44 lines.
- Only code that already has Node.js access (a preload script, or a page with
nodeIntegrationon) can get hold of the child frame'sprocessobject. WithcontextIsolation: true, web content in the main world can't reach it. I'm therefore filing this as a crash bug rather than a security report.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fields👀 Unsorted Items
Activity