Security audit of QuickJS

Open
#610 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 5 days

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
15/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
c
Domain
security

Research direction

The report names temporal/plainmonthday.c, temporal/plaindate.c, temporal/plaindatetime.c, temporal/calendar.c, intl/intl.c, intl/numberformat.c, quickjs.c, and quickjs-libc.c. Start by checking each finding against the cited function and reproducer, then run the reported sanitizer builds and relevant tests. Done means the confirmed issues are fixed and regression coverage demonstrates the triggers no longer crash, hang, overflow, or leave promises pending.

Written by the indexing model from the issue text.

Description

Security audit of QuickJS

I have created a security audit of QuickJS, using Claude Fable 5.1 model. Since this Claude AI model is
now so easily available, I will simply publish the findings here, since the information is already essentially available using Claude.

Date: 2026-11-09
Scope: Full source tree. Core engine (quickjs.c, libregexp.c, libunicode.c,
cutils.c, dtoa.c), the CLI/runtime library (quickjs-libc.c, qjs.c, qjsc.c,
run-test262.c), and the two large fork-specific additions intl/ (ECMA-402) and
temporal/ (Temporal proposal).

Method. Thirteen subsystem reviewers read the code and wrote JavaScript
proof-of-concepts; every finding below was reproduced independently against an
AddressSanitizer + UndefinedBehaviorSanitizer build (gcc). The full test262
conformance suite and the built-in test suite were run under that sanitizer build, and
the built-in tests plus Intl stress were also run under Valgrind against the normal
build to exercise the custom small-block allocator (which the ASan build compiles out
via JS_MALLOC_LARGE_BLOCKS_ONLY). Each PoC path was traced to confirm it is reachable
from the stated attacker position and that no earlier check prevents it.

Threat model. Priority 1 is attacker-controlled JavaScript run by an embedder
(e.g. qjs, or any application linking libquickjs). Priority 2 is untrusted bytecode
fed to JS_ReadObject/bjson (upstream treats bytecode as trusted). Priority 3 is
untrusted input to the CLI tools and the std/os modules.


Headline

The engine is, on the whole, carefully written: the heavily-exercised areas
(ArrayBuffer/TypedArray/DataView/Atomics including the new resizable and immutable
buffers, the fast-array and collection machinery, the parser/compiler and its bytecode
stack verifier, the rewritten regexp executor, strings/ropes, Proxy, GC) produced no
memory-safety findings
under close reading plus sanitizer-backed fuzzing, and the full
test262 run produced zero hard sanitizer errors (no heap/stack/global overflow, no
use-after-free).

Confirmed findings, most severe first

# Severity Area Reach Effect
1 High Temporal pure JS OOB read → SEGV (crash; potential info-leak)
2 High Temporal pure JS Unbounded native loop → interpreter hang (DoS)
3 High Intl pure JS Stack-buffer overflow write (1 NUL byte past buffer)
4 Medium Intl pure JS OOB heap read (crash/DoS)
5 Medium engine (async) pure JS Promises never settle → hang + unbounded retention
6 Medium libc (os, workers) pure JS OOB heap read in worker poll loop (crash/DoS)
7 Low engine (TypedArray) pure JS memcpy(dst, NULL, 0) — UB, no OOB
8 Low engine (regexp) pure JS memcpy(_, NULL, 0) — UB, no OOB
9 Low engine (Math) pure JS int64 accumulator overflow → wrong result
10 Low engine (compiler) pure JS 16-bit scope-index truncation → miscompile
11 Low Temporal / Intl pure JS / OOM int truncation + OOM-path leaks (several)
12 Low libc (dtoa) embedder API js_dtoa_max_len under-sizes (latent; not JS-reachable)
— Info bytecode untrusted bytecode unvalidated deserialized bytecode (by design)

1. High — OOB read / SEGV in PlainMonthDay.prototype.with (Temporal)
  • Location: temporal/plainmonthday.c:412 (js_plainmonthday_with) →
    temporal/plaindate.c:89 (pd_days_in_month: return days[month - 1];, a 12-element
    array with no bounds check).
  • Root cause: for an ISO-calendar PlainMonthDay with a numeric month property and
    no monthCode, the method sets month to the raw integer from the property
    ([1, INT32_MAX]) and calls ti_calendar_days_in_month(... month) before any range
    clamp. ISO dispatch reaches pd_days_in_month, which indexes days[month-1] with the
    attacker value. The sibling with methods on PlainDate/PlainDateTime/PlainYearMonth
    all clamp month first; this one does not.
  • Trigger (pure JS): Temporal.PlainMonthDay.from("01-15").with({ month: 1e9 }).
  • Verified: ASan — SEGV ... READ in pd_days_in_month plaindate.c:89. Production
    qjs --experimental — segmentation fault (exit 139) for month ≥ ~1e9. All other
    month-taking entry points were spot-tested and clamp correctly, so the bug is isolated to
    this single method.
  • Impact: at minimum a remotely-triggerable crash (DoS). The out-of-bounds word is fed
    into further date math, so an info-leak primitive cannot be excluded.
  • Fix: clamp/validate month to [1, months-in-year] (honoring the overflow option)
    before computing days-in-month, as js_plainyearmonth_with already does; additionally add
    a defensive bounds check in the shared pd_days_in_month / pd_day_of_year primitives.
2. High — unbounded native loop (hang/DoS) via non-ISO calendar + out-of-range year (Temporal)
  • Location: range check skipped in js_create_plaindatetime_with_calendar
    (temporal/plaindatetime.c:46) and js_plaindatetime_constructor
    (temporal/plaindatetime.c:251) — pdt_is_within_limits() is only called for
    CAL_ISO8601/CAL_GREGORY. Same gap in js_create_plaindate_with_calendar
    (temporal/plaindate.c:26). The uncapped year then drives the correction loops in
    ti_iso_to_islamic_civil (temporal/calendar.c:957) and ti_iso_to_hebrew_date
    (temporal/calendar.c:770), where int y = (int)floor_div64(30*days+10646, 10631)
    overflows int32 and seeds a while (yd > days) y--; / y++ loop that steps one year at
    a time across billions of iterations.
  • Trigger (pure JS):
    let d = new Temporal.PlainDateTime(2147483647,1,1,0,0,0,0,0,0,'islamic-civil');
    d.year;   // hangs forever
    
    Also via PlainDateTime.from({year:2147483647,...,calendar:'hebrew'}).daysInMonth.
  • Verified: construction returns normally; the first calendar getter never returns
    (killed at the timeout). QuickJS cannot interrupt a tight native loop, so the interpreter
    thread wedges permanently. No memory corruption.
  • Fix: apply the ISO date-time range limit for all calendars after
    construct/with/from/add (the PlainDate constructor at plaindate.c:159 already does
    this unconditionally — mirror it), and compute the calendar-year estimate in int64 with a
    bound on the correction loops.
3. High — stack-buffer overflow in canonicalize_locale (Intl)
  • Location: intl/intl.c:985, overflow inside pstrcpy (cutils.c:46).
  • Root cause: canonicalize_locale splits the tag into char buf[512] and keeps
    pointers subtags[i] into it. The heploc → alalc97 variant-alias rewrite is done in
    place with pstrcpy(subtags[i], sizeof(buf), "alalc97") — the bound is the whole 512-byte
    buffer, not the room remaining from the mid-buffer slot. alalc97 is one byte longer than
    heploc, so a maximal (511-char) well-formed tag ending in -heploc writes its
    terminating NUL one byte past buf. The sibling region rewrites (NZ, RU, RS, SA)
    are same-or-shorter and do not overflow.
  • Trigger (pure JS): a 511-char BCP-47 tag ending -heploc, via either
    Intl.getCanonicalLocales(tag) or new Intl.Locale(tag).
  • Verified: ASan — stack-buffer-overflow WRITE of size 1 in pstrcpy … canonicalize_locale intl.c:985, from both entry points.
  • Impact: a single-NUL stack overwrite past a 512-byte frame buffer. The overflowing
    byte is constant (\0) and one past the array, which constrains exploitation, but it can
    corrupt adjacent stack state / a canary.
  • Fix: do not rewrite in place; reassign the pointer subtags[i] = "alalc97"; exactly as
    the function's grandfathered-tag mappings already do, or emit the replacement when building
    the output DynBuf.
4. Medium — OOB heap read in NumberFormat engineering notation (Intl)
  • Location: intl/numberformat.c:2448 (intl_mv_format_scientific, reached from
    js_numberformat_format_internal2): memcpy(int_buf, mv->digits, digits_before).
  • Root cause: for notation:"engineering" the integer-part length digits_before is
    1..3, but mv->digits holds the normalized significand with trailing zeros stripped,
    which can be shorter. For a value like 1e23 the significand is just "1" (1 byte) while
    digits_before is 3, so the memcpy reads up to 2 bytes past the significand's heap
    allocation.
  • Trigger (pure JS): new Intl.NumberFormat("en",{notation:"engineering"}).format(1e23).
    Fires for values near powers of ten whose base-10 exponent ≡ 2 (mod 3); also via
    formatRange/formatToParts and any numbering system.
  • Verified: ASan — heap-buffer-overflow READ of size 3 … intl_mv_format_scientific numberformat.c:2429.
  • Impact: crash/DoS plus UB. The first over-read byte is the digit string's NUL
    terminator, so stray bytes do not reliably reach the returned string — no dependable
    info-leak, hence Medium.
  • Fix: clamp the copy to min(mv->num_digits, digits_before) and zero-pad the remainder.
5. Medium — async-generator next() queued behind return() never settles
  • Location: quickjs.c:22285-22306 (js_async_generator_resolve_function, the
    magic >= 2 AWAITING_RETURN branch) and quickjs.c:22195-22204
    (js_async_generator_resume_next, COMPLETED case).
  • Root cause: when an async generator receives return() while suspended it enters
    AWAITING_RETURN and awaits a promise; requests arriving meanwhile are queued but
    resume_next bails for that state. When the awaited promise settles, the resolve handler
    resolves the return request and sets COMPLETED but — unlike the EXECUTING branch — never
    re-enters resume_next, so the spec's AsyncGeneratorDrainQueue never runs. A secondary
    defect makes the COMPLETED case drain only one request per re-entry.
  • Trigger (pure JS): g.return(v); g.next(); g.next(); on any async generator. The
    next() promises never settle; code awaiting them (or Promise.all/allSettled) hangs
    forever, and each stuck JSAsyncGeneratorRequest is retained for the generator's life.
  • Verified: on both the ASan and production builds, only the return promise prints;
    the two next() promises never settle. No memory corruption.
  • Fix: call js_async_generator_resume_next after the resolve/reject in the magic >= 2
    branch, and let the COMPLETED case continue draining NEXT/THROW requests.
6. Medium — OOB heap read in js_os_poll worker poll loop (libc)
  • Location: quickjs-libc.c:2731 (js_os_poll, non-Windows). Introduced by the fork's
    Atomics.waitAsync work (commit f2eb204).
  • Root cause: the async-atomics waker fd is added to ts->poll_fds at slot nfds-1
    (:2701), but after poll() returns it is examined as
    ts->poll_fds[ts->atomics_async_waker.read_fd].revents — subscripted by the file
    descriptor number
    instead of its poll-array slot. Every other entry correctly uses its
    stored poll_fd_index. When read_fd >= poll_fds_size (the array has a minimum of 16
    entries) this reads a struct pollfd out of bounds on the heap.
  • Trigger (pure JS): the main thread's waker fd is small, but a worker runs
    js_std_init_handlers late, after many fds are open, so its waker read_fd is large. A
    script that opens ~40 os.pipe()s, starts an os.Worker, and drives the worker's waker
    via Atomics.waitAsync + cross-thread Atomics.notify reaches the read with read_fd
    far beyond the array.
  • Verified: ASan (worker thread T1) — heap-buffer-overflow READ of size 2 … js_os_poll quickjs-libc.c:2731 … 590 bytes after 128-byte region.
  • Impact: the out-of-bounds revents only gates a js_waker_clear() call, so the leaked
    bytes are not returned to the script (no info disclosure). Worst case is a crash/DoS.
    Reachable from unprivileged JS in any embedder that enables the os module and workers.
  • Fix: store the waker's poll slot index the same way handlers/ports do and use it at
    :2731; never use .read_fd as an array subscript.
7. Low — slice_memcpy(dst, NULL, 0) in js_typed_array_slice
  • Location: quickjs.c:62534 (slice_memcpy) called from js_typed_array_slice
    (quickjs.c:62587). (Found independently via the test262 UBSan run.)
  • Root cause: after the count>0 check, __speciesCreate runs a user Symbol.species
    constructor that can shrink a length-tracking typed array's resizable buffer to 0. count
    is then recomputed to 0, but slice_memcpy is still called with a now-NULL source pointer
    and len==0. validate_typed_array does not catch it because a length-tracking view on a
    shrunk buffer is not "out of bounds", just zero-length.
  • Verified: UBSan — null pointer passed as argument 2, which is declared to never be null at quickjs.c:62537; reproduced with a minimal PoC and seen naturally in test262.
  • Impact: memcpy nonnull-attribute UB only; len is 0, so no out-of-bounds access and
    no data movement. Not exploitable; worth fixing for UB-cleanliness.
  • Fix: guard the call with (count << shift) > 0.
8. Low — NULL memcpy/memcmp for empty \q{} regexp string alternative
  • Location: libregexp.c:279 (memcpy) / :236 (memcmp) in re_string_find2, reached
    from parse_class_string_disjunction (libregexp.c:1019).
  • Root cause: when the first alternative of a v-flag \q{...} string disjunction is
    empty, the local DynBuf is never allocated, so re_string_add(len=0, buf=NULL) passes
    NULL to memcpy/memcmp.
  • Trigger (pure JS): new RegExp("[\\q{|a}]","v") or new RegExp("[\\q{}]","v").
  • Verified: UBSan — null pointer passed as argument 2 … re_string_find2 libregexp.c:279.
    The normal build compiles and matches correctly; len is 0 so no corruption.
  • Fix: skip the memcmp and only memcpy when len > 0.
9. Low — Math.sumPrecise int64 accumulator overflow (wrong result)
  • Location: quickjs.c:49960 (sum_precise_add); SUM_PRECISE_COUNTER_INIT = 250 at
    :49919; renormalization at :49943.
  • Root cause: each add can place ~2^56 into an int64 accumulator limb, but
    renormalization only runs every 250 adds; 250 * 2^56 ≈ 1.80e19 > INT64_MAX, so many
    same-exponent inputs overflow the limb (signed-overflow UB; wraps) and the sum is wrong. A
    safe counter bound is < 128.
  • Trigger (pure JS): Math.sumPrecise(new Array(300).fill(Math.pow(2,53)-1)) returns
    2684145377912815000; the correct value is 2702159776422297000.
  • Verified: reproduced identically on both builds; no crash (the fixed acc[] is never
    indexed out of range — numeric corruption only).
  • Fix: lower SUM_PRECISE_COUNTER_INIT to ≤ ~64.
10. Low — 16-bit scope-index truncation for > 65535 lexical scopes (compiler)
  • Location: quickjs.c:24757 (push_scope), :24780 (pop_scope), :24790
    (close_scopes); the code already carries the comment
    /* XXX: should check for scope overflow */.
  • Root cause: scope_count only grows (one scope per block/for/catch/class body) and
    is emitted as a 16-bit operand with no upper bound, unlike locals/args/closures which are
    capped at JS_MAX_LOCAL_VARS. Above 65535 scopes the operand wraps, but the truncated value
    stays in [0,65535] < scope_count, so the index is always in-bounds — a miscompilation
    (wrong closure value / clobbered hoisted binding), never an OOB.
  • Trigger (pure JS): one function body with > 65535 block scopes plus a closure.
  • Verified: PoCs run clean under ASan (wrong result / clean TypeError, no crash).
  • Fix: cap scopes like the other compiler limits in push_scope (and propagate the
    error), or widen the operand to 32 bits.
11. Low — integer truncation and OOM-path leaks (Temporal / Intl)
  • PlainYearMonth add/subtract (temporal/plainyearmonth.c:682,695): duration
    years/months cast int64 → int, so subtract({years:4294967295}) wraps to -1 and
    returns a wrong date instead of a RangeError. The final ISO-limit check still prevents an
    out-of-range object from escaping — logic bug only. The analogous
    PlainDateTime/PlainDate with/add paths share the pattern.
  • DateTimeFormat OOM leaks (intl/datetimeformat.c:2737, :3811): error paths return
    JS_EXCEPTION instead of goto fail, leaking the format data / an unwrapped value. OOM-only.
  • listformat.c uninitialized items: on an OOM mid-loop the cleanup would free
    uninitialized slots; unreachable in practice (elements are guaranteed strings). Use
    js_mallocz for safety.
  • duration-string parse (int64_t)num cast (temporal/duration.c:469…490): an
    out-of-range double from "P1e26Y" is cast without a magnitude check (float-cast-overflow
    UB); this UBSan build does not enable that check and the value is rejected afterward —
    speculative/Info.
12. Low — js_dtoa_max_len under-sizes the output buffer (libc, not JS-reachable)
  • Location: dtoa.c:1034 (js_dtoa_max_len) versus the writes in js_dtoa
    (dtoa.c:1305-1314). js_dtoa_max_len is the public buffer-sizing API; callers allocate
    len_max + 1.
  • Root cause: for two flag combinations the bound is smaller than js_dtoa actually
    writes: JS_DTOA_FORMAT_FRAC | JS_DTOA_EXP_ENABLED (the FRAC branch omits room for the
    exponent suffix, e.g. d=0, n_digits=5 → "0.00000e+0" = 10 bytes vs len_max 9) and
    JS_DTOA_FORMAT_FIXED | JS_DTOA_EXP_DISABLED on tiny subnormals (the bound uses the raw
    biased exponent, so the leading-zero run overruns, e.g. d=5e-324 → 326 vs 320).
  • Reachability: js_dtoa is only called from quickjs.c, and the Number.prototype
    methods never emit either combo. A 3M-double fuzz of the exact reachable patterns
    (toString/toFixed/toExponential/toPrecision) with exact len_max+1 allocations
    found no reachable overflow. This is a latent defect in the reusable library routine,
    a hazard only for embedders that call js_dtoa directly with those flags. Confirmed with a
    standalone ASan C harness (dtoa.c:1314 overflow).
  • Fix: add the exponent allowance in the FRAC branch when EXP is enabled, and normalize
    subnormals before computing the EXP_DISABLED digit count.
Info — unvalidated deserialized bytecode (requires untrusted bytecode)
  • Location: JS_ReadFunctionBytecode (quickjs.c:39836) / JS_ReadFunctionTag — the
    reader copies stack_size, cpool_count, byte_code_len and operands verbatim and does
    not re-run the compiler's compute_stack_size verifier or bounds-check opcode operands.
  • Verified: ASan — a 17-byte crafted blob gives heap-buffer-overflow READ in get_u32 / JS_ReadFunctionBytecode via the JS_READ_OBJ_BYTECODE path (e.g. js_std_eval_binary
    loading a tampered qjsc .bin).
  • Status: upstream QuickJS documents bytecode as a trusted input, so this is expected
    behavior, not a default-threat-model vulnerability. It matters only for embedders that feed
    attacker-controlled bytecode/SAB (JS_ReadObject with the bytecode/SAB flags). The bjson
    surface (bjson.read, JS_ReadObject without those flags) does not reach this path and
    held up under 4000 mutations. Flagged so embedders do not treat bytecode as safe.

Areas reviewed and found clean (no memory-safety findings)

  • ArrayBuffer / SharedArrayBuffer / TypedArray / DataView / Atomics, including the fork's
    new resizable buffers, transfer/transferToImmutable, immutable ArrayBuffers and the
    write_count write-guard, Uint8Array base64/hex, Float16, and Atomics.waitAsync/pause.
    Every raw-memory path re-validates bounds after each user callback. 25 PoCs + a 40k-iteration
    base64/hex sizing fuzz, all clean.
  • Fast arrays, Array.prototype, iterators, the Iterator-helper suite, Map/Set including
    the new Set combinators and getOrInsert. No cached-pointer-across-callback bug remains.
  • Parser / bytecode compiler / module system, including compute_stack_size (the verifier
    the interpreter relies on), the 16-bit var-ref fix (#589), template/v-flag/private-field
    changes, and JSON/text/bytes module imports. Deep-nesting PoCs (200k) yield clean
    SyntaxError: stack overflow.
  • Interpreter / calls / promises: bound-function argc, the four alloca sites, OP_ret/
    OP_gosub, error-stack accessor, build_backtrace OOM fix, Promise combinators.
  • Objects / Proxy / Reflect / shapes / BigInt / Date / GC: all newer opaque-holding classes
    have correct gc_mark/finalizers; Proxy invariant and revocation paths; new BigInt limb
    implementation; the custom small-block allocator (static review + Valgrind).
  • Strings / ropes / StringBuffer / JSON / number↔string: the in-place concat optimization's
    refcount==1 guard is sound; JS_STRING_LEN_MAX enforced; JSON depth-guarded.
  • RegExp engine (rewritten iterative executor) + libunicode: shared capture/register array
    sizing, duplicate named groups, v-flag set ops, surrogate boundaries, \p{} lookups, case
    folding. ~300k-iteration fuzz, only the Low \q{} UB above.
  • Intl DateTimeFormat + time zones: tz transition binary-search sentinels, ISO/tz string
    parsers, skeleton→pattern formatting. No memory-safety bug (two Low OOM leaks noted above).
  • libc / CLI / workers: js_printf_internal buffer, std.urlGet command-injection
    surface, std/os read/write bounds, os.exec, SAB refcounting, rqsort, UTF-8 helpers,
    js_atod, and the qjs/qjsc/run-test262 argument and build-command handling.

Caveats / coverage notes

  • The ASan build compiles with JS_MALLOC_LARGE_BLOCKS_ONLY=1 (quickjs.c:253), so the
    custom small-block arena allocator is not exercised under ASan. It was reviewed statically
    (found consistent) and exercised under Valgrind on the normal build (test suite + Intl
    stress) with no errors — but sanitizer coverage of that allocator is weaker than the rest.
  • intl/locale-data.c (33k lines) and libunicode-table.h are generated data tables; the
    accessor/lookup functions were reviewed and table invariants (sorted order, NUL termination,
    index bounds) were assumed correct rather than audited line by line.
  • libFuzzer was unavailable (missing clang ASan runtime), so the in-tree fuzz/ harnesses were
    not run; JS-level fuzzers were used instead.
  • libc / CLI / workers (quickjs-libc.c, cutils.c, dtoa.c, qjs.c, qjsc.c,
    run-test262.c): the printf format buffer, std.urlGet shell quoting (no command
    injection), os.read/os.write bounds, os.exec argv building, SAB atomic refcounting,
    rqsort under an adversarial comparator, and the qjsc build-command construction were all
    traced and found safe. The two confirmed bugs are Findings 6 and 12 above.

test262 result: the full suite ran to completion under ASan+UBSan — 19 conformance
mismatches out of 53021 tests (expected spec-divergences, not crashes) and exactly one
sanitizer diagnostic in the entire run, the benign slice_memcpy NULL memcpy (Finding 7).
Zero hard sanitizer errors.

Dominant language
C
Stars
11.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bellard/quickjs

All issues in bellard/quickjs

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.