Vulnerability DatabaseGHSA-hwjc-hcp6-3fhx

GHSA-hwjc-hcp6-3fhx: 
Rust vulnerability analysis and mitigation

Out-of-bounds read in napi-rs: AsyncGenerator error paths pass non-NUL-terminated Rust strings to napi_throw_error

Report metadata

FieldValue
Packagenapi-rs (Rust / Node-API bindings, source on GitHub, pkg:github/napi-rs/napi-rs; affected code in crates/napi)
Repositoryhttps://github.com/napi-rs/napi-rs
Componentnapi::bindgen_runtime::async_iterator — generator_next / generator_return / generator_throw callbacks
Vulnerability classOut-of-bounds read (heap over-read leading to information disclosure into a JS-visible error)
CWECWE-125
Severity (reporter assessment)High
Verified againstCommit cda88ea649a2e182e0b6f7ec9cb8a6db7758b47d only. Other commits and released versions were not verified.
API surfacePublic documented API: a class implementing napi::bindgen_prelude::AsyncGenerator, exposed through the napi-rs iterator attribute (the verified reproduction used #[napi(async_iterator)])
Affected in default configurationYes. Any exported AsyncGenerator with a typed Next/Return conversion is affected. No non-standard usage or configuration is needed. The reproduction enabled the crate features async and napi4.

Summary

On argument-conversion failure, and on promise-spawn failure, the AsyncGenerator callbacks in async_iterator.rs pass format!("{}", e.status).as_ptr(), e.status.as_ref().as_ptr() and e.reason.as_ptr() directly to sys::napi_throw_error. The Node-API declaration of that function (crates/sys/src/functions.rs:323) takes *const c_char NUL-terminated C strings. Rust String and &str buffers are not NUL-terminated, so Node's strlen reads past the end of the heap allocation. The bytes it reads beyond the end become part of the thrown error's message and code. On the consumer side, any JavaScript caller can trigger this by passing a wrongly-typed argument to next() or return() on an exported async iterator. For example, passing a string where the addon declares type Next = i32 makes FromNapiValue fail before any addon generator logic runs. Affected throw sites in async_iterator.rs at cda88ea:

  • generator_next: Next conversion error -> non-NUL status and reason pointers, lines 336-340
  • generator_return: Return conversion error -> non-NUL status and reason pointers, lines 396-400
  • generator_return: promise-spawn error branch -> status.as_ref() (&'static str) and reason String, lines 422-426
  • generator_throw: promise-spawn error branch -> same pattern, lines 497-501 For comparison, direct throws elsewhere in the crate that are C-string-safe pass C-string literals. (Specific sibling line references were not collected.) The synchronous iterator support has a similar direct-throw pattern. That is out of scope here: async_iterator.rs has its own direct throw calls and needs its own fix.

Impact

A remote JavaScript caller (any code that can call the iterator's methods) causes a native heap out-of-bounds read inside napi_throw_error. In the verified reproduction, adjacent heap bytes (glibc malloc chunk metadata) showed up in the JS-visible e.message. There was also a second over-read while setting e.code. If the read crosses into an unmapped page, the Node process can crash. Without this bug, an invalid argument gives a bounded JavaScript exception or rejected promise whose text matches the Rust error. With it, the same routine invalid call reads native memory past the string's length and exposes it to JavaScript. What gets disclosed depends on the allocator and the heap layout. Scoring note: we did not compute a CVSS vector. Exploitability, and the value of the disclosed bytes, depend on whether the consuming addon exposes an AsyncGenerator to untrusted JavaScript input and on heap layout. Addons that do not implement AsyncGenerator, or whose async iterators are never reachable with attacker-chosen arguments, are not affected by this path.

Preconditions

  1. The consuming addon exports a class that implements napi::bindgen_prelude::AsyncGenerator through the public napi-rs iterator support.
  2. The generator declares a fallible typed Next and/or Return (for example type Next = i32). This is the standard, documented usage pattern, not a non-default option.
  3. The attacker can call next() or return() on the iterator with an arbitrary JavaScript value, such as a string where a number is expected.
  4. T::Next::from_napi_value / T::Return::from_napi_value returns Err (the reproduction got status NumberExpected). Alternatively, the spawn-failure branches in generator_return / generator_throw are reached. No non-standard usage, monkey-patching or unusual configuration is needed. AsyncGenerator is a public bindgen iterator surface. We found no documentation saying callers must pass only trusted, valid JS input, or permitting native C-string over-reads.

Data flow

  1. Source: an attacker-chosen JS value arrives as the iterator method's argv[0] (async_iterator.rs:332, async_iterator.rs:392).
  2. Propagation: T::Next::from_napi_value / T::Return::from_napi_value rejects the wrong-typed value and returns a napi::Error whose status and reason are Rust strings (async_iterator.rs:332-334, async_iterator.rs:392-394).
  3. Sink: the raw byte pointers are passed as C strings: sys::napi_throw_error(env, format!("{}", e.status).as_ptr().cast(), e.reason.as_ptr().cast()) (async_iterator.rs:336-340, async_iterator.rs:396-400). The spawn-error variants using e.status.as_ref().as_ptr() are at async_iterator.rs:422-426 and async_iterator.rs:497-501. The callee expects *const c_char (functions.rs:323).
  4. Reachability: these callbacks are production runtime code, wired up for classes exported with napi-rs iterator support. A consumer reaches them through it[Symbol.asyncIterator]().next(x) / .return(x) or await it.next(x) (async_iterator.rs:332-501).

Vulnerable code

crates/napi/src/bindgen_runtime/async_iterator.rs, conversion-error branch (generator_next, around lines 336-340; the same shape is at 396-400) at cda88ea649a2e182e0b6f7ec9cb8a6db7758b47d:

Err(e) => {
  unsafe {
    sys::napi_throw_error(
      env,
      format!("{}", e.status).as_ptr().cast(), // SINK: String bytes, no NUL terminator
      e.reason.as_ptr().cast(),                // SINK: String bytes, no NUL terminator
    )
  };
  None
}

The spawn-error branches at lines 422-426 and 497-501 follow the same pattern, passing e.status.as_ref().as_ptr() (a &'static str, also not NUL-terminated) in place of the format! result.

Reproduction

Verified dynamically at commit cda88ea649a2e182e0b6f7ec9cb8a6db7758b47d with Node 24.22.1 on Linux/glibc, using a minimal cdylib addon built against crates/napi (features async, napi4).

// Minimal addon: an AsyncGenerator with a typed Next.
// Trait signature taken from the finding; exact form may need adjusting to the commit under test.
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi(async_iterator)]
pub struct AsyncNumbers;
#[napi]
impl AsyncGenerator for AsyncNumbers {
  type Yield = u32;
  type Next = i32;
  type Return = ();
  fn next(&mut self, _: Option<i32>) -> impl std::future::Future<Output = Option<u32>> + Send {
    async { Some(1) }
  }
}
// Trigger: pass a wrongly-typed value to next().
const addon = require('./index.node');
(async () => {
  const it = new addon.AsyncNumbers()[Symbol.asyncIterator]();
  try { await it.next('x'); } catch (e) { console.log(e.code, e.message, e.message.length); }
})();
// Run under: valgrind --tool=memcheck node repro.js

Observed:

  • The thrown e.message was 57 characters long, while the Rust reason string was 56 bytes. The extra trailing byte was 0x21 / 0x51 (glibc malloc chunk-size metadata of the adjacent chunk): heap bytes leaked into the JS-visible error.
  • Valgrind memcheck: Invalid read of size 1 at strlen by napi_throw_error <- generator_next_fn (async_iterator.rs:336) ... Address is 0 bytes after a block of size 56 alloc'd (the reason String).
  • A second invalid read in set_error_code: 0 bytes after a block of size 14 alloc'd (the format!-ed status code NumberExpected). The generator_return conversion path and the spawn-error branches have the same code pattern by inspection. Only the generator_next conversion path was exercised dynamically.
  • Expected: a bounded JS conversion error / rejected promise whose message and code exactly match the Rust reason and status, with no native reads past the string lengths.
  • Actual: strlen reads past the end of both heap buffers, and the bytes it over-reads appear in the thrown error's message.

Suggested remediation

Never pass a Rust String/&str pointer where Node-API expects a C string. Convert to an owned CString (handling embedded NULs), or use the crate's existing length-bounded JS error construction.

Err(e) => {
  // Strip interior NULs so CString::new cannot fail, then pass NUL-terminated buffers.
  let code = std::ffi::CString::new(format!("{}", e.status).replace('\0', ""))
    .expect("NULs removed");
  let msg = std::ffi::CString::new(e.reason.replace('\0', ""))
    .expect("NULs removed");
  unsafe { sys::napi_throw_error(env, code.as_ptr(), msg.as_ptr()) };
  None
}

A second form, matching the crate's own idiom, is to turn the napi::Error into a JS error through the crate's existing error-to-JS conversion, which builds JS strings with explicit lengths. That avoids C strings entirely. (We have not verified the exact helper name at this commit.) Notes:

  • Apply the same change to all four sites: 336-340, 396-400, 422-426 and 497-501. In the spawn-error branches e.status.as_ref() is a &'static str and is equally unterminated.
  • Factoring this into one small helper (for example "throw this napi::Error as a JS error") would keep the four branches consistent.
  • The analogous direct-throw pattern in the synchronous iterator support needs a separate, independent fix. It is not covered by this patch.
  • Throw sites that already pass C-string literals are safe and need no change. Suggested regression test, next to the existing async-iterator tests: export an AsyncGenerator with type Next = i32, call next('x'), and assert that e.code === 'NumberExpected' and that e.message equals the expected Rust reason exactly (same length, no trailing bytes). Also run the case under valgrind or ASan and assert there are no invalid reads. Add the equivalent case for return('x').

Maintainer Triage & Remediation Notes

  • Status: Confirmed on main (fb1c6d46). Fix merged in commit 95ee412973f32a45a24211b64df059b83fc5c7b6 ("Merge commit from fork", 2026-11-22) and shipped in napi 3.16.3 (2026-11-23). All 7 raw sys::napi_throw_error sites in async_iterator.rs and iterator.rs now route through JsError::from(e).throw_into(env) (length-bounded napi_create_string_utf8), conversion and set_generator_value error paths return early via Result<sys::napi_value>, and pending exception identity is preserved while closing [[GeneratorState]] in generator_throw_fn.
  • Affected versions:
    • AsyncGenerator (crates/napi/src/bindgen_runtime/async_iterator.rs, 4 sites): napi >= 3.0.0-alpha.25, <= 3.16.2 (introduced in 98cb7671 / PR #2418).
    • Synchronous Generator / ScopedGenerator (crates/napi/src/bindgen_runtime/iterator.rs, 3 identical sibling sites): napi >= 2.4.0, <= 3.16.2 (introduced in a3356264 / PR #1166).
  • Fix summary:
    1. Replaced all 7 raw sys::napi_throw_error calls across both async_iterator.rs and iterator.rs with JsError::from(e).throw_into(env) (length-bounded napi_create_string_utf8, avoiding heap / .rodata over-reads, 0x1 empty-reason SIGSEGV, and interior-NUL truncation).
    2. Fixed argument-conversion and set_generator_value error paths in generator_next / generator_return / generator_throw to return early via Result<sys::napi_value> instead of falling through to invoke g.next(None) or Node-API with a pending exception.
    3. Preserved pending exception identity while closing [[GeneratorState]] in iterator.rs::generator_throw_fn.

Source: NVD

Related Rust vulnerabilities:

CVE ID

Severity

Score

Technologies

Component name

CISA KEV exploit

Has fix

Published date

GHSA-9q5v-84p5-m3p2HIGH7.1
  • Rust logoRust
  • termaxa
NoYesNov 26, 2026
GHSA-hwjc-hcp6-3fhxHIGHN/A
  • Rust logoRust
  • napi
NoYesNov 26, 2026
GHSA-7qh9-r57w-m46cHIGHN/A
  • Rust logoRust
  • napi
NoYesNov 26, 2026
GHSA-94v8-9f79-j8qfLOWN/A
  • Rust logoRust
  • frink-core
NoYesNov 25, 2026
GHSA-xj2w-fm6g-f5pjLOWN/A
  • Rust logoRust
  • frink-core
NoYesNov 25, 2026

Free Vulnerability Assessment

Benchmark your Cloud Security Posture

Evaluate your cloud security practices across 9 security domains to benchmark your risk level and identify gaps in your defenses.

Request assessment

Additional Wiz resources

Get a personalized demo

Ready to see Wiz in action?

"Best User Experience I have ever seen, provides full visibility to cloud workloads."
David EstlickCISO
"Wiz provides a single pane of glass to see what is going on in our cloud environments."
Adam FletcherChief Security Officer
"We know that if Wiz identifies something as critical, it actually is."
Greg PoniatowskiHead of Threat and Vulnerability Management