Open Bug 2078730 Opened 1 month ago Updated 1 month ago

JIT regexp stub updates legacy RegExp statics for a RegExp from another realm (missing realm check in UpdateRegExpStatics)

Categories

(Core :: JavaScript: Standard Library, defect, P3)

defect

Tracking

()

UNCONFIRMED

People

(Reporter: bugmon, Unassigned)

References

(Blocks 1 open bug)

Details

(Keywords: assertion, testcase)

Attachments

(4 files)

The JIT regexp exec stub in js/src/jit/CodeGenerator.cpp (PrepareAndExecuteRegExp calling UpdateRegExpStatics) decides whether to update the legacy RegExp static properties by testing only RegExpObject::LegacyFeaturesEnabledBit on the RegExp object. It does not compare the RegExp's realm with the current realm, which the C++ path does in ShouldUpdateRegExpStatics (js/src/builtin/RegExp.cpp). When RegExp.prototype.exec is called on a RegExp created in another same-compartment realm, the interpreter invalidates the caller realm's statics (RegExp.$1 throws TypeError), while the stub clears the invalidated flag and writes the match into the caller realm's statics (RegExp.$1 returns the foreign RegExp's capture). The result of the same program therefore depends on which tier executed the match.

A web page can make its own realm's RegExp.$1 and related legacy static properties report the match of a RegExp belonging to another same-compartment realm by calling RegExp.prototype.exec on that RegExp repeatedly until the JIT regexp stub is used. The demonstrated effect is a tier-dependent wrong answer; no memory corruption, crash or assertion was observed. The two realms share a compartment, so no cross-origin disclosure is shown. The behaviour requires javascript.options.experimental.legacy_regexp, whose default is @IS_NIGHTLY_BUILD@.

Build Info

Affected Code

File: js/src/builtin/RegExp.cpp, line 328-343

static bool ShouldUpdateRegExpStatics(JSContext* cx,
                                      Handle<RegExpObject*> regexp) {
  if (!JS::Prefs::experimental_legacy_regexp()) {
    return true;
  }
  // Step 5. Let thisRealm be the current Realm Record.
  JS::Realm* thisRealm = cx->realm();
  // Step 6. Let rRealm be the value of R's [[Realm]] internal slot.
  JS::Realm* rRealm = regexp->realm();

  // Step 7. If SameValue(thisRealm, rRealm) is true, then
  if (thisRealm == rRealm) {
    return regexp->legacyFeaturesEnabled();
  }
  return false;
}

File: js/src/builtin/RegExp.cpp, line 360-366

    if (ShouldUpdateRegExpStatics(cx, regexp)) {
      if (!res->updateFromMatchPairs(cx, input, *matches)) {
        return RegExpRunStatus::Error;
      }
    } else {
      res->invalidate();
    }

File: js/src/jit/CodeGenerator.cpp, line 2276-2290

  if (JS::Prefs::experimental_legacy_regexp()) {
    Address invalidatedAddress(staticsReg,
                               RegExpStatics::offsetOfInvalidated());

    masm.unboxNonDouble(Address(regexp, NativeObject::getFixedSlotOffset(
                                            RegExpObject::flagsSlot())),
                        temp1, JSVAL_TYPE_INT32);
    masm.branchTest32(Assembler::NonZero, temp1,
                      Imm32(RegExpObject::LegacyFeaturesEnabledBit),
                      &legacyFeaturesEnabled);
    masm.store8(Imm32(1), invalidatedAddress);
    masm.jump(&done);
    masm.bind(&legacyFeaturesEnabled);
    masm.store8(Imm32(0), invalidatedAddress);
  }

File: js/src/jit/CodeGenerator.cpp, line 2618-2624

  // Lazily update the RegExpStatics.
  size_t offset = GlobalObjectData::offsetOfRegExpRealm() +
                  RegExpRealm::offsetOfRegExpStatics();
  masm.loadGlobalObjectData(temp1);
  masm.loadPtr(Address(temp1, offset), temp1);
  UpdateRegExpStatics(masm, regexp, input, lastIndex, temp1, temp2, temp3,
                      initialStringHeap, volatileRegs);

File: js/src/jit/CacheIR.cpp, line 7812-7834

  RegExpObject* re = &arg(0).toObject().as<RegExpObject>();
  if (!HasOptimizableLastIndexSlot(re, cx_)) {
    return AttachDecision::NoAction;
  }

  // Initialize the input operand.
  initializeInputOperand();

  // Note: we don't need to call emitNativeCalleeGuard for intrinsics.

  ValOperandId arg0Id = loadArgumentIntrinsic(ArgumentKind::Arg0);
  ObjOperandId regExpId = writer.guardToObject(arg0Id);
  writer.guardShape(regExpId, re->shape());
  EmitGuardLastIndexIsNonNegativeInt32(writer, regExpId);

  ValOperandId arg1Id = loadArgumentIntrinsic(ArgumentKind::Arg1);
  StringOperandId inputId = writer.guardToString(arg1Id);

  if (native == InlinableNative::IntrinsicRegExpBuiltinExecForTest) {
    writer.regExpBuiltinExecTestResult(regExpId, inputId, stub);
  } else {
    writer.regExpBuiltinExecMatchResult(regExpId, inputId, stub);
  }

File: modules/libpref/init/StaticPrefList.yaml, line 9763-9767

- name: javascript.options.experimental.legacy_regexp
  type: bool
  value: @IS_NIGHTLY_BUILD@
  mirror: always
  set_spidermonkey_pref: startup

The C++ path gates the statics update on the RegExp's realm matching the current realm. The JIT stub loads the statics of the current realm (loadGlobalObjectData reads the context's realm, js/src/jit/MacroAssembler.cpp:2773-2777) and gates the update only on the LegacyFeaturesEnabledBit of the RegExp. The CacheIR attach for the intrinsic guards only the RegExp's shape and lastIndex, so the stub is attached for a RegExp from another realm.

Exploit Chain

  1. Script in realm A obtains a RegExp object created in realm B, where A and B share a compartment (shell: newGlobal({sameCompartmentAs: globalThis}); browser: a same-origin iframe's contentWindow).
  2. Realm A runs a match of its own so its RegExp.$1 holds a known value, then calls RegExp.prototype.exec.call(foreignRegExp, "abc") in a loop.
  3. While the match runs through the C++ path, ShouldUpdateRegExpStatics sees cx->realm() != regexp->realm() and invalidates realm A's statics; reading RegExp.$1 throws TypeError.
  4. Once the self-hosted exec IC is attached and the RegExp has native code, the stub's UpdateRegExpStatics tests only LegacyFeaturesEnabledBit, clears the invalidated flag and records the match in realm A's statics.
  5. Realm A reads RegExp.$1 and gets "b", the capture from realm B's RegExp. Under --no-jit-backend, --no-native-regexp or --cache-ir-stubs=off the same read throws TypeError.

Steps to Reproduce

  1. Build the SpiderMonkey debug shell from the unmodified tree with /app/mozconfigs/mozconfig.js.linux.debug (binary: /firefox/obj-js-debug/dist/bin/js). No source patches or prefs.
  2. Run testcase.js through js_shell_differential_evaluator with the same binary on both sides, flags_a = ["--no-threads", "--no-jit-backend"], flags_b = ["--no-threads", "--baseline-eager"]. Result: differs: true; shell_a exits 0, shell_b exits 3 with "Error: RegExp.$1 was updated by a RegExp from another realm".
  3. Repeat with "--differential-testing" prepended to both flag sets. Result: differs: true with the same exit codes and error.
  4. Bisection: flags_a = ["--differential-testing", "--no-threads", "--baseline-eager", "--no-native-regexp"] (exit 0) against flags_b = ["--differential-testing", "--no-threads"] (exit 3) also gives differs: true, so the default configuration is affected and native regexp code is required. A direct run with --baseline-eager --cache-ir-stubs=off also takes the TypeError path.
  5. Optional browser check (existing /firefox/obj-firefox-asan build, not rebuilt for this verification, default prefs): a page that takes /a(b)c/ from a same-origin iframe via contentWindow.eval and calls RegExp.prototype.exec.call(re, "abc") 3000 times logged "before=y after=value:b firstHit=11".

Security Impact

  • Severity: Low
  • Attacker capability: Script can cause its realm's legacy RegExp static properties (RegExp.$1 and related) to be populated from a match performed by a RegExp of another same-compartment realm, where the non-JIT path would leave them invalidated. This is a tier-dependent incorrect result. No memory corruption, crash, assertion failure or cross-origin data access was demonstrated; the script already holds a direct reference to the foreign RegExp and to the input string.
  • Preconditions: javascript.options.experimental.legacy_regexp enabled (default value is @IS_NIGHTLY_BUILD@); a RegExp from a different realm in the same compartment (for example a same-origin iframe); enough exec calls for the IC to attach and the RegExp to get native code (11 iterations in the browser run).

ASAN Report

No sanitizer report; this is a js_differential finding. Verifier's own runs, clean tree, /firefox/obj-js-debug/dist/bin/js:

Run 1 (without --differential-testing): differs: true
shell_a argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--no-threads","--no-jit-backend","/tmp/fx_audit_jsdiff_bl2hjh_s/testcase.js"] exit_code: 0, stderr empty
shell_b argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--no-threads","--baseline-eager","/tmp/fx_audit_jsdiff_bl2hjh_s/testcase.js"] exit_code: 3
shell_b stderr:
/tmp/fx_audit_jsdiff_bl2hjh_s/testcase.js:17:9 Error: RegExp.$1 was updated by a RegExp from another realm
Stack:
  @/tmp/fx_audit_jsdiff_bl2hjh_s/testcase.js:17:9

Run 2 (with --differential-testing): differs: true
shell_a argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--differential-testing","--no-threads","--no-jit-backend","/tmp/fx_audit_jsdiff_gbr8ljr7/testcase.js"] exit_code: 0, stderr empty
shell_b argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--differential-testing","--no-threads","--baseline-eager","/tmp/fx_audit_jsdiff_gbr8ljr7/testcase.js"] exit_code: 3
shell_b stderr:
/tmp/fx_audit_jsdiff_gbr8ljr7/testcase.js:17:9 Error: RegExp.$1 was updated by a RegExp from another realm
Stack:
  @/tmp/fx_audit_jsdiff_gbr8ljr7/testcase.js:17:1

Run 3 (bisection, with --differential-testing): differs: true
shell_a argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--differential-testing","--no-threads","--baseline-eager","--no-native-regexp","/tmp/fx_audit_jsdiff_l23de7rs/testcase.js"] exit_code: 0, stderr empty
shell_b argv: ["/firefox/obj-js-debug/dist/bin/js","--fuzzing-safe","--differential-testing","--no-threads","/tmp/fx_audit_jsdiff_l23de7rs/testcase.js"] exit_code: 3
shell_b stderr:
/tmp/fx_audit_jsdiff_l23de7rs/testcase.js:17:9 Error: RegExp.$1 was updated by a RegExp from another realm
Stack:
  @/tmp/fx_audit_jsdiff_l23de7rs/testcase.js:17:1

Diagnostic (same loop, printing RegExp.$1 in the caller realm after the loop; --fuzzing-safe --differential-testing --no-threads plus):
  --no-jit-backend:                      before: y / after threw: TypeError RegExp static property 'static_paren1_getter' is invalid
  --baseline-eager:                      before: y / after: b
  --baseline-eager --no-native-regexp:   before: y / after threw: TypeError
  (no extra flags):                      before: y / after: b
  --ion-eager:                           before: y / after: b
  --baseline-eager --cache-ir-stubs=off: before: y / after threw: TypeError

Browser variant (same-origin iframe, /firefox/obj-firefox-asan/dist/bin/firefox, default prefs, no crash):
[Child 5849: Main Thread]: I/console log: "VERIF_RESULT before=y after=value:b firstHit=11"

Which side is wrong: the JIT side. It is not an Ion pass; the divergence appears from Baseline onward and disappears with --no-jit-backend, --no-native-regexp or --cache-ir-stubs=off, which places it in the regexp exec stub reached from the CacheIR IC (UpdateRegExpStatics in js/src/jit/CodeGenerator.cpp).
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Attached file testcase.js —
Attached file flags.txt —

This bug was filed automatically by an AI-powered security testing tool. The analysis, testcase, and any suggested patches were generated by an AI model and have NOT been verified by a human.

Please review all details carefully before triaging. The issue was confirmed by an independent verifier, but for non-ASAN issues, the verifier has been made less strict. Additionally, the root cause analysis and suggested fix may contain errors.

Group: core-security → javascript-core-security
Blocks: sm-security
Severity: -- → S3
Priority: -- → P3
Blocks: 2009034
No longer blocks: sm-security
Group: javascript-core-security
Keywords: sec-other
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: