Skip to content
Memory corruption Advisory Advanced CVE-2024-6776

Use after free in Audio (CVE-2024-6776)

A use-after-free vulnerability exists in Chromium's SCKAudioInputStream::Start where a block function captures a raw pointer to the object and can be invoked after the object is destroyed. An attacker could potentially exploit this to cause memory corruption or execute arbitrary code.

lime Follow

Originally disclosed on Chrome VRP

Bounty$4,000 High View original
  • Fix shipped in 35 days

Steps to reproduce the problem

  1. host poc.html http://localhost:8000/poc.html
  2. npm install puppeteer-core and node run.js (remember replace the launchCommand to your chromium path)

Problem Description

  1. There is an object-c block function in SCKAudioInputStream:: Start, and the block function uses the member shared_helper_ of SCKAudioInputStream. Therefore, if you run this block function before

This is destroyed, which means that the SCKAudioInputStream class is destroyed. When calling shared_helper_ ->OnStreamError (error), `shared_helper_ will implicitly capture this dereference, causing UAF. because The block function will be dispatched to a separate thread in Macos.

C++
void SCKAudioInputStream::Start(AudioInputCallback* callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(callback);

  // Don't do anything if the stream isn't open and ignore any consecutive
  // Start() calls.
  if (!stream_ || sink_) {
    return;
  }

  sink_ = callback;

  // Sample and error callbacks are set and reset by SCKAudioInputStream when
  // starting and stopping the stream, respectively. Thus, |this| will always be
  // valid if the callback is not null.
  shared_helper_->SetStreamCallbacks(
      base::BindRepeating(&SCKAudioInputStream::OnStreamSample,
                          base::Unretained(this)),
      base::BindRepeating(&SCKAudioInputStream::OnStreamError,
                          base::Unretained(this)));

  [stream_ startCaptureWithCompletionHandler:^(NSError* error) {
    if (!error) {
      return;
    }

    shared_helper_->OnStreamError(error); //<--- uaf here
  }];
}
  1. SCKAudioInputStream is created in AudioManagerBase:: MakeAudioInputStream, then insert into input_streams_, and MakeAudioInputStrea returns this stream.
C++
AudioInputStream* AudioManagerBase::MakeAudioInputStream(
    const AudioParameters& input_params,
    const std::string& device_id,
    const LogCallback& log_callback) {
...

  AudioInputStream* stream;
  switch (params.format()) {
    case AudioParameters::AUDIO_PCM_LINEAR:
      stream = MakeLinearInputStream(params, device_id, log_callback);
      break;
    case AudioParameters::AUDIO_PCM_LOW_LATENCY:
      stream = MakeLowLatencyInputStream(params, device_id, log_callback); // <---- create
      break;
    case AudioParameters::AUDIO_FAKE:
      stream = FakeAudioInputStream::MakeFakeStream(this, params);
      break;
    default:
      stream = nullptr;
      break;
  }

  if (stream) {
    input_streams_.insert(stream); // insert
    if (!log_callback.is_null()) {
      SendLogMessage(log_callback, "%s => (number of streams=%d)", __func__,
                     input_stream_count());
    }

...
}
  1. Closed in InputStream::~InputStream
C++
InputStream::~InputStream()
    InputController::Close()
        SCKAudioInputStream::Close()
  1. Call close_callback in SCKAudioInputStream:: Close(), and the close_callback is passed in when SCKAudioInputStream is created
C++
AudioInputStream* AudioManagerMac::MakeLowLatencyInputStream(
    const AudioParameters& params,
    const std::string& device_id,
    const LogCallback& log_callback) {
  DCHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());

  if (AudioDeviceDescription::IsLoopbackDevice(device_id)) {
    screen_capture_kit_swizzler_ = SwizzleScreenCaptureKit();

    return CreateSCKAudioInputStream(
        params, device_id, log_callback,
        base::BindRepeating(&AudioManagerBase::ReleaseInputStream,
                            base::Unretained(this))); 
  }
  1. AudioManagerBase::ReleaseInputStream Erase this and then delete this(stream)
C++
void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) {
  CHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK(stream);
  // TODO(xians) : Have a clearer destruction path for the AudioInputStream.
  CHECK_EQ(1u, input_streams_.erase(stream));
  delete stream;
}
  1. InputStream is created and held by StreamFactory.
C++
void StreamFactory::CreateInputStream(
...

  input_streams_.insert(std::make_unique<InputStream>(
      std::move(created_callback), std::move(deleter_callback),
      std::move(stream_receiver), std::move(client), std::move(observer),
      std::move(pending_log), audio_manager_, aecdump_recording_manager_,
      UserInputMonitor::Create(std::move(key_press_count_buffer)),
#if BUILDFLAG(CHROME_WIDE_ECHO_CANCELLATION)
      output_device_mixer_manager_.get(), std::move(processing_config),
#else
      nullptr, nullptr,
#endif
      device_id, params, shared_memory_count, enable_agc));
}
  1. So when StreamFactory is destroyed, the destruction of StreamFactory ultimately leads to the destruction of SCKAudioInputStream. And the StreamFactory lifecycle is bound to one endpoint of the browser. So when the browser disconnects one end of Mojo, the Service is destroyed.

bitset: https://source.chromium.org/chromium/chromium/src/+/eed1c5f6d99764cf0eb93b0108a14af9e287ccda

Note: The reason for the patch is that I don't know how to sign and how to attach TCC permissions to the programme

Summary

AddressSanitizer: heap-use-after-free on media::SCKAudioInputStream::Start

Custom Questions

Type of crash:

browser

Crash state:

see asan.txt

Reporter credit:

lime(limeSe) and fmyy(@binary_fmyy) From TIANGONG Team of Legendsec at QI-ANXIN Group

Additional Data

Category: Security
Chrome Channel: Not sure
Regression: N/A

The original report as published on the Chromium issue tracker, by lime(@limeSec_) and fmyy(@binary_fmyy) From TIANGONG Team of Legendsec at QI-ANXIN Group. Images and videos are our own copies; raw HTML is shown as text. View it on Chromium issue tracker.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

This is a Chrome VRP advisory for CVE-2024-6776, a use-after-free rated high severity in Chrome's audio code, specifically in SCKAudioInputStream, the ScreenCaptureKit-backed audio input stream used on macOS. The bug was reported by lime (@limeSec_) and fmyy (@binary_fmyy) of the TIANGONG Team of Legendsec at QI-ANXIN Group, and the bounty was 4000.00 USD. It was disclosed on 2024-07-16.

An audio input stream is the object Chrome creates when a page or an internal service asks to capture audio from an input device. On macOS, when the requested device is a loopback device, Chrome routes the request through ScreenCaptureKit and creates an SCKAudioInputStream. That class wraps a native stream_ object and a shared_helper_ member, and it registers callbacks that the native layer invokes when samples arrive or when the stream fails.

The report's own summary of the crash is:

Text
AddressSanitizer: heap-use-after-free on media::SCKAudioInputStream::Start

Setup

The reproduction needs a local web server, Node with puppeteer-core, and a Chromium build, with the launch command pointed at its path. The report notes that the researcher did not know how to sign the build or attach TCC permissions to the program, and gives that as the reason for the patch.

  1. Host poc.html at http://localhost:8000/poc.html.
  2. Install puppeteer-core and run node run.js, replacing the launch command with the path to the local Chromium build.
Bash
npm install puppeteer-core
node run.js

The report does not include the contents of poc.html or run.js, so the exact page and driver script are not shown here.

Finding it

The researcher looked at SCKAudioInputStream::Start and noticed that it installs an Objective-C block as the completion handler for startCaptureWithCompletionHandler:. That block captures this implicitly through the member access shared_helper_, and on macOS the block is dispatched to a separate thread. If the SCKAudioInputStream object is destroyed before the block runs, the call shared_helper_->OnStreamError(error) dereferences freed memory.

The vulnerable function, as quoted in the report:

C++
void SCKAudioInputStream::Start(AudioInputCallback* callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(callback);

  // Don't do anything if the stream isn't open and ignore any consecutive
  // Start() calls.
  if (!stream_ || sink_) {
    return;
  }

  sink_ = callback;

  // Sample and error callbacks are set and reset by SCKAudioInputStream when
  // starting and stopping the stream, respectively. Thus, |this| will always be
  // valid if the callback is not null.
  shared_helper_->SetStreamCallbacks(
      base::BindRepeating(&SCKAudioInputStream::OnStreamSample,
                          base::Unretained(this)),
      base::BindRepeating(&SCKAudioInputStream::OnStreamError,
                          base::Unretained(this)));

  [stream_ startCaptureWithCompletionHandler:^(NSError* error) {
    if (!error) {
      return;
    }

    shared_helper_->OnStreamError(error); //<--- uaf here
  }];
}

The comment in the code claims that this will always be valid while the callback is set, because the callbacks are reset when the stream is stopped. The completion handler is a different path: it is not one of the registered callbacks, it is a block handed to ScreenCaptureKit, and nothing in the code ties its lifetime to the lifetime of the SCKAudioInputStream.

Exploitation

Step 1: the stream is created and tracked

SCKAudioInputStream is created inside AudioManagerBase::MakeAudioInputStream, which then inserts the stream into input_streams_ and returns it.

C++
AudioInputStream* AudioManagerBase::MakeAudioInputStream(
    const AudioParameters& input_params,
    const std::string& device_id,
    const LogCallback& log_callback) {
...

  AudioInputStream* stream;
  switch (params.format()) {
    case AudioParameters::AUDIO_PCM_LINEAR:
      stream = MakeLinearInputStream(params, device_id, log_callback);
      break;
    case AudioParameters::AUDIO_PCM_LOW_LATENCY:
      stream = MakeLowLatencyInputStream(params, device_id, log_callback); // <---- create
      break;
    case AudioParameters::AUDIO_FAKE:
      stream = FakeAudioInputStream::MakeFakeStream(this, params);
      break;
    default:
      stream = nullptr;
      break;
  }

  if (stream) {
    input_streams_.insert(stream); // insert
    if (!log_callback.is_null()) {
      SendLogMessage(log_callback, "%s => (number of streams=%d)", __func__,
                     input_stream_count());
    }

...
}

The low-latency path is the one that matters here, because that is where the macOS implementation creates the ScreenCaptureKit stream.

Step 2: the stream is closed through the destructor chain

The report traces the teardown as follows:

C++
InputStream::~InputStream()
    InputController::Close()
        SCKAudioInputStream::Close()

So destroying the InputStream wrapper eventually calls SCKAudioInputStream::Close().

Step 3: Close invokes the close callback

SCKAudioInputStream::Close() calls close_callback, and that callback was supplied when the stream was created. The creation site in AudioManagerMac::MakeLowLatencyInputStream binds AudioManagerBase::ReleaseInputStream:

C++
AudioInputStream* AudioManagerMac::MakeLowLatencyInputStream(
    const AudioParameters& params,
    const std::string& device_id,
    const LogCallback& log_callback) {
  DCHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());

  if (AudioDeviceDescription::IsLoopbackDevice(device_id)) {
    screen_capture_kit_swizzler_ = SwizzleScreenCaptureKit();

    return CreateSCKAudioInputStream(
        params, device_id, log_callback,
        base::BindRepeating(&AudioManagerBase::ReleaseInputStream,
                            base::Unretained(this)));
  }

Note the loopback check: this path is only taken when the device is a loopback device.

Step 4: ReleaseInputStream erases and deletes the stream

C++
void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) {
  CHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK(stream);
  // TODO(xians) : Have a clearer destruction path for the AudioInputStream.
  CHECK_EQ(1u, input_streams_.erase(stream));
  delete stream;
}

This removes the stream from input_streams_ and deletes it. At this point the SCKAudioInputStream is gone, but the completion handler block handed to ScreenCaptureKit in Start may still be pending on another thread.

Step 5: the stream is held by StreamFactory

StreamFactory::CreateInputStream stores the InputStream in input_streams_:

C++
void StreamFactory::CreateInputStream(
...

  input_streams_.insert(std::make_unique<InputStream>(
      std::move(created_callback), std::move(deleter_callback),
      std::move(stream_receiver), std::move(client), std::move(observer),
      std::move(pending_log), audio_manager_, aecdump_recording_manager_,
      UserInputMonitor::Create(std::move(key_press_count_buffer)),
#if BUILDFLAG(CHROME_WIDE_ECHO_CANCELLATION)
      output_device_mixer_manager_.get(), std::move(processing_config),
#else
      nullptr, nullptr,
#endif
      device_id, params, shared_memory_count, enable_agc));
}

Step 6: destroying StreamFactory destroys the stream

The StreamFactory lifetime is bound to one endpoint of the browser. When the browser disconnects one end of Mojo, the service is destroyed, which destroys the StreamFactory, which destroys the InputStream, which reaches SCKAudioInputStream::Close() and ReleaseInputStream, deleting the SCKAudioInputStream. If the ScreenCaptureKit completion handler fires with an error after that point, it calls shared_helper_->OnStreamError(error) on freed memory.

The report gives the commit it was tested against:

Text
https://source.chromium.org/chromium/chromium/src/+/[redacted]

Root cause

The completion handler block in SCKAudioInputStream::Start captures this implicitly by referring to the member shared_helper_. The block is dispatched to a separate thread on macOS, so it can run after the object has been destroyed. The registered sample and error callbacks use base::Unretained(this) as well, but the code comment argues those are safe because they are reset when the stream stops. The completion handler is not covered by that reasoning: nothing cancels it or keeps the object alive until it runs.

The destruction path is ordinary and reachable: closing the stream calls close_callback, which is AudioManagerBase::ReleaseInputStream, which erases the stream from input_streams_ and deletes it. Because StreamFactory owns the InputStream and its lifetime is tied to a Mojo endpoint, tearing down that endpoint is enough to destroy the SCKAudioInputStream while the native completion handler is still outstanding.

Impact

The crash is a heap-use-after-free in the browser process, confirmed by AddressSanitizer on media::SCKAudioInputStream::Start. The report classifies the crash type as browser. The trigger requires the loopback device path, since that is the only branch that creates an SCKAudioInputStream, and it requires the stream to be destroyed while the ScreenCaptureKit completion handler is still pending. The report does not describe a specific attacker-controlled sequence beyond the reproduction steps, so the practical reach from a web page is not spelled out.

Fix

The report does not describe the patch. The note about the patch refers only to the researcher's local build: it was added because the researcher did not know how to sign the build or attach TCC permissions to the program, not as a fix for the bug.

Variants to test

  1. Other Objective-C blocks in Chrome's macOS media code that capture this implicitly. A positive result is a block that runs on a separate thread and dereferences a member after the owning object can be destroyed.
  2. Other base::Unretained(this) callbacks whose lifetime is not actually tied to the object, especially where the code comment claims the callback is reset on stop. A positive result is a path where the reset does not happen before destruction.
  3. Other stream types created through AudioManagerBase::MakeAudioInputStream and released through ReleaseInputStream. A positive result is a stream whose native completion handler can outlive the delete stream.
  4. Other Mojo-endpoint-bound factories that own objects with native asynchronous callbacks. A positive result is a disconnect that destroys the owner while a native callback is still queued on another thread.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

Chrome can record sound from your microphone, or from your computer's own speakers, when a website or a built-in Chrome feature asks it to. On macOS, Chrome sometimes uses an Apple framework called ScreenCaptureKit to do that recording. The piece of Chrome code that talks to ScreenCaptureKit is a class called SCKAudioInputStream.

This report describes a bug in that class. Chrome started a recording and handed ScreenCaptureKit a small piece of code to run later, when the start finished. That small piece of code remembered a pointer to the SCKAudioInputStream object. If the object was deleted before the small piece of code ran, the code would reach into memory that no longer belonged to it. That kind of bug is called a use-after-free: the program uses memory after it has been freed. It is rated high severity, and the reporter received a 4000.00 USD bounty. The report was disclosed on 2024-07-16.

A few words before we start:

  • Class: a blueprint in code. An object is one thing built from that blueprint, with its own data inside.
  • Object: a live thing in memory, created from a class. When it is no longer needed, the program deletes it and the memory can be reused.
  • Pointer: a memory address. It tells the program where an object lives. If the object is deleted, the pointer still holds the old address, but nothing valid is there any more.
  • Callback: a function you give to someone else, so they can call it later. Think of leaving your phone number with a shop so they can ring you when your order arrives.
  • Thread: one line of work inside a program. A program can have several threads running at the same time, like several shop assistants serving different customers.
  • API: an agreed way for one piece of software to ask another piece of software to do something. ScreenCaptureKit is an Apple API for capturing screen and audio.
  • Mojo: Chrome's internal messaging system. Different parts of Chrome talk to each other through it, like departments in a company sending each other memos.
  • AddressSanitizer (ASan): a debugging tool that watches memory and shouts when a program reads or writes memory it should not touch.

Context

This is a Chrome VRP advisory. VRP stands for Vulnerability Reward Program: Google pays people who find and report security bugs in Chrome. The bug has an identifier, CVE-2024-6776. CVE means Common Vulnerabilities and Exposures, a public catalogue number given to a security flaw so everyone can refer to the same thing.

The flaw is a use-after-free in Chrome's audio code, specifically in SCKAudioInputStream. That class is the audio input stream Chrome uses on macOS when it records through ScreenCaptureKit.

An audio input stream is the object Chrome creates when a page or an internal Chrome service asks to capture audio from an input device. On macOS, when the requested device is a loopback device, Chrome routes the request through ScreenCaptureKit and creates an SCKAudioInputStream. A loopback device is a virtual device that captures the sound your computer is playing, rather than sound from a microphone.

That class wraps two things: a native stream_ object (the ScreenCaptureKit side) and a shared_helper_ member (a helper object shared with the native layer). It also registers callbacks that the native layer invokes when audio samples arrive or when the stream fails.

The report's own one-line summary of the crash is:

Text
AddressSanitizer: heap-use-after-free on media::SCKAudioInputStream::Start

In plain words: the memory checker caught the program using freed memory inside the Start function of SCKAudioInputStream. The word heap refers to the area of memory where programs create objects while they run.

Setup

The reproduction needs three things: a small web server on your own machine, Node.js with a package called puppeteer-core, and a Chromium build, with the launch command pointed at its path. Node.js is a program that runs JavaScript outside a browser. Puppeteer is a library that drives a browser automatically, like a robot clicking and typing for you. A patch is a small change to source code made before building the program.

The report notes that the researcher could not sign the build or attach TCC permissions to it. Signing means marking a macOS program as coming from a known developer. TCC is macOS's privacy permission system, the one that asks whether an app may use the microphone or the screen. The report says the researcher did not know how to sign the build or attach TCC permissions to the program, and gives that as the reason for the patch.

  1. Host poc.html at http://localhost:8000/poc.html. poc stands for proof of concept: a small page that demonstrates the bug. localhost means your own computer, and 8000 is the port number the local web server listens on.
  2. Install puppeteer-core and run node run.js, replacing the launch command with the path to the local Chromium build.
Bash
npm install puppeteer-core
node run.js

Line by line:

  • npm install puppeteer-core uses npm, Node's package manager, to download and install the Puppeteer library into the current folder.
  • node run.js runs the JavaScript file run.js with Node. That script is what launches the browser and loads the page.

The report does not include the contents of poc.html or run.js, so the exact page and driver script are not shown here.

Finding it

The researcher looked at SCKAudioInputStream::Start and noticed that it installs an Objective-C block as the completion handler for startCaptureWithCompletionHandler:. An Objective-C block is Apple's version of a callback: a chunk of code you hand to a function so it can run it later. A completion handler is a block that runs when an operation finishes.

That block captures this implicitly through the member access shared_helper_. this is the object the function is running on. Capturing it implicitly means the block quietly keeps a reference to the object because it mentions one of the object's members, without anyone writing that down explicitly. On macOS the block is dispatched to a separate thread, so it can run at a different time from the code that created it.

If the SCKAudioInputStream object is destroyed before the block runs, the call shared_helper_->OnStreamError(error) dereferences freed memory. Dereferencing means following a pointer to read or use what is at that address. If the object is gone, the address points at memory that may already belong to something else.

The vulnerable function, as quoted in the report:

C++
void SCKAudioInputStream::Start(AudioInputCallback* callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  CHECK(callback);

  // Don't do anything if the stream isn't open and ignore any consecutive
  // Start() calls.
  if (!stream_ || sink_) {
    return;
  }

  sink_ = callback;

  // Sample and error callbacks are set and reset by SCKAudioInputStream when
  // starting and stopping the stream, respectively. Thus, |this| will always be
  // valid if the callback is not null.
  shared_helper_->SetStreamCallbacks(
      base::BindRepeating(&SCKAudioInputStream::OnStreamSample,
                          base::Unretained(this)),
      base::BindRepeating(&SCKAudioInputStream::OnStreamError,
                          base::Unretained(this)));

  [stream_ startCaptureWithCompletionHandler:^(NSError* error) {
    if (!error) {
      return;
    }

    shared_helper_->OnStreamError(error); //<--- uaf here
  }];
}

Line by line:

  • void SCKAudioInputStream::Start(AudioInputCallback* callback) { declares the Start function, which belongs to the SCKAudioInputStream class and takes a callback to notify about audio input.
  • DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is a debug-only check that this function is called on the thread it is supposed to run on. DCHECK checks are compiled out of release builds.
  • CHECK(callback); stops the program if the callback is missing. CHECK stays in release builds.
  • The if (!stream_ || sink_) { return; } block does nothing if the native stream is not open, or if a sink (the destination for audio) is already set. This avoids starting twice.
  • sink_ = callback; remembers the callback as the destination for the audio.
  • The comment explains the author's belief: the sample and error callbacks are set when the stream starts and reset when it stops, so this should always be valid while a callback is set.
  • shared_helper_->SetStreamCallbacks(...) registers two callbacks with the shared helper: one for incoming audio samples and one for errors. base::BindRepeating wraps a member function into a callback that can be called many times. base::Unretained(this) means "do not keep this object alive for me; just use the raw pointer". That is a promise that the object will outlive the callback.
  • [stream_ startCaptureWithCompletionHandler:^(NSError* error) { ... }]; asks the native stream to start capturing and hands it a block to run when that finishes. The block receives an error object if something went wrong.
  • if (!error) { return; } means: if there was no error, do nothing.
  • shared_helper_->OnStreamError(error); //<--- uaf here is the dangerous line. The block reaches for shared_helper_ through the object it captured. If the object has been deleted by now, this touches freed memory.

The comment in the code claims that this will always be valid while the callback is set, because the callbacks are reset when the stream is stopped. The completion handler is a different path: it is not one of the registered callbacks, it is a block handed to ScreenCaptureKit, and nothing in the code ties its lifetime to the lifetime of the SCKAudioInputStream.

Exploitation

Exploitation here means walking through the exact sequence of events that leads to the bug. The report breaks it into six steps.

Step 1: the stream is created and tracked

SCKAudioInputStream is created inside AudioManagerBase::MakeAudioInputStream, which then inserts the stream into input_streams_ and returns it. input_streams_ is a list the audio manager keeps so it knows which streams are alive.

C++
AudioInputStream* AudioManagerBase::MakeAudioInputStream(
    const AudioParameters& input_params,
    const std::string& device_id,
    const LogCallback& log_callback) {
...

  AudioInputStream* stream;
  switch (params.format()) {
    case AudioParameters::AUDIO_PCM_LINEAR:
      stream = MakeLinearInputStream(params, device_id, log_callback);
      break;
    case AudioParameters::AUDIO_PCM_LOW_LATENCY:
      stream = MakeLowLatencyInputStream(params, device_id, log_callback); // <---- create
      break;
    case AudioParameters::AUDIO_FAKE:
      stream = FakeAudioInputStream::MakeFakeStream(this, params);
      break;
    default:
      stream = nullptr;
      break;
  }

  if (stream) {
    input_streams_.insert(stream); // insert
    if (!log_callback.is_null()) {
      SendLogMessage(log_callback, "%s => (number of streams=%d)", __func__,
                     input_stream_count());
    }

...
}

Line by line:

  • The function signature takes the audio parameters (sample rate, format and so on), a device identifier, and an optional logging callback.
  • AudioInputStream* stream; declares a pointer that will hold the new stream.
  • The switch picks a creation function based on the audio format. AUDIO_PCM_LINEAR uses MakeLinearInputStream, AUDIO_PCM_LOW_LATENCY uses MakeLowLatencyInputStream, and AUDIO_FAKE uses a fake stream for testing. Anything else leaves the pointer empty.
  • The comment // <---- create marks the low-latency branch. That is the one that matters here, because that is where the macOS implementation creates the ScreenCaptureKit stream.
  • input_streams_.insert(stream); adds the new stream to the manager's list, so the manager can find it later.
  • The if (!log_callback.is_null()) block sends a log message with the current number of streams, if a logging callback was supplied.

Step 2: the stream is closed through the destructor chain

The report traces the teardown as follows:

C++
InputStream::~InputStream()
    InputController::Close()
        SCKAudioInputStream::Close()

This is shorthand for a chain of calls. A destructor is the special function that runs when an object is deleted; the ~ in ~InputStream marks it. So destroying the InputStream wrapper eventually calls InputController::Close(), which calls SCKAudioInputStream::Close(). Each arrow is one call inside the previous one.

Step 3: Close invokes the close callback

SCKAudioInputStream::Close() calls close_callback, and that callback was supplied when the stream was created. The creation site in AudioManagerMac::MakeLowLatencyInputStream binds AudioManagerBase::ReleaseInputStream:

C++
AudioInputStream* AudioManagerMac::MakeLowLatencyInputStream(
    const AudioParameters& params,
    const std::string& device_id,
    const LogCallback& log_callback) {
  DCHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format());

  if (AudioDeviceDescription::IsLoopbackDevice(device_id)) {
    screen_capture_kit_swizzler_ = SwizzleScreenCaptureKit();

    return CreateSCKAudioInputStream(
        params, device_id, log_callback,
        base::BindRepeating(&AudioManagerBase::ReleaseInputStream,
                            base::Unretained(this)));
  }

Line by line:

  • The function takes the same three arguments as before: parameters, device identifier and logging callback.
  • DCHECK(GetTaskRunner()->BelongsToCurrentThread()); is a debug check that we are on the right thread.
  • DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); is a debug check that the format really is low latency.
  • if (AudioDeviceDescription::IsLoopbackDevice(device_id)) { is the loopback check: this path is only taken when the device is a loopback device.
  • screen_capture_kit_swizzler_ = SwizzleScreenCaptureKit(); sets up a swizzler. Swizzling is a technique that swaps one function for another at runtime; here it is used to hook ScreenCaptureKit.
  • return CreateSCKAudioInputStream(...) creates the stream. The last argument is the close callback: base::BindRepeating(&AudioManagerBase::ReleaseInputStream, base::Unretained(this)). In plain words: when this stream is closed, call ReleaseInputStream on the audio manager. base::Unretained(this) again means the callback holds a raw pointer to the manager without keeping it alive.

Step 4: ReleaseInputStream erases and deletes the stream

C++
void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) {
  CHECK(GetTaskRunner()->BelongsToCurrentThread());
  DCHECK(stream);
  // TODO(xians) : Have a clearer destruction path for the AudioInputStream.
  CHECK_EQ(1u, input_streams_.erase(stream));
  delete stream;
}

Line by line:

  • CHECK(GetTaskRunner()->BelongsToCurrentThread()); stops the program if this runs on the wrong thread.
  • DCHECK(stream); is a debug check that the pointer is not empty.
  • The comment is a note from the developers that the destruction path should be clearer.
  • CHECK_EQ(1u, input_streams_.erase(stream)); removes the stream from the list and stops the program if the number of removed entries is not exactly one. In other words, it insists the stream was in the list.
  • delete stream; frees the object's memory.

This removes the stream from input_streams_ and deletes it. At this point the SCKAudioInputStream is gone, but the completion handler block handed to ScreenCaptureKit in Start may still be pending on another thread. That is the gap where the bug lives.

Step 5: the stream is held by StreamFactory

StreamFactory::CreateInputStream stores the InputStream in input_streams_:

C++
void StreamFactory::CreateInputStream(
...

  input_streams_.insert(std::make_unique<InputStream>(
      std::move(created_callback), std::move(deleter_callback),
      std::move(stream_receiver), std::move(client), std::move(observer),
      std::move(pending_log), audio_manager_, aecdump_recording_manager_,
      UserInputMonitor::Create(std::move(key_press_count_buffer)),
#if BUILDFLAG(CHROME_WIDE_ECHO_CANCELLATION)
      output_device_mixer_manager_.get(), std::move(processing_config),
#else
      nullptr, nullptr,
#endif
      device_id, params, shared_memory_count, enable_agc));
}

Line by line:

  • input_streams_.insert(...) adds a new InputStream to the factory's own list.
  • std::make_unique<InputStream>(...) creates the object and wraps it in a smart pointer that deletes it automatically when the last owner goes away. A smart pointer is a pointer that manages the object's lifetime for you.
  • std::move(...) hands each argument over to the new object. Moving means transferring ownership rather than copying.
  • The #if BUILDFLAG(CHROME_WIDE_ECHO_CANCELLATION) block is a compile-time switch: if that build flag is on, two extra arguments are passed; otherwise two null pointers are passed.
  • The final arguments are the device identifier, the parameters, a shared memory count and an automatic gain control flag.

Step 6: destroying StreamFactory destroys the stream

The StreamFactory lifetime is bound to one endpoint of the browser. When the browser disconnects one end of Mojo, the service is destroyed, which destroys the StreamFactory, which destroys the InputStream, which reaches SCKAudioInputStream::Close() and ReleaseInputStream, deleting the SCKAudioInputStream. If the ScreenCaptureKit completion handler fires with an error after that point, it calls shared_helper_->OnStreamError(error) on freed memory.

An endpoint here means one end of a Mojo communication channel. When one side goes away, the other side is torn down too, like one person hanging up a phone call.

The report gives the commit it was tested against:

Text
https://source.chromium.org/chromium/chromium/src/+/[redacted]

A commit is a saved snapshot of the source code. This link points to the exact snapshot the researcher used.

Root cause

The completion handler block in SCKAudioInputStream::Start captures this implicitly by referring to the member shared_helper_. The block is dispatched to a separate thread on macOS, so it can run after the object has been destroyed.

The registered sample and error callbacks use base::Unretained(this) as well, but the code comment argues those are safe because they are reset when the stream stops. The completion handler is not covered by that reasoning: nothing cancels it or keeps the object alive until it runs.

The destruction path is ordinary and reachable: closing the stream calls close_callback, which is AudioManagerBase::ReleaseInputStream, which erases the stream from input_streams_ and deletes it. Because StreamFactory owns the InputStream and its lifetime is tied to a Mojo endpoint, tearing down that endpoint is enough to destroy the SCKAudioInputStream while the native completion handler is still outstanding.

Impact

The crash is a heap-use-after-free in the browser process, confirmed by AddressSanitizer on media::SCKAudioInputStream::Start. The browser process is the main Chrome process that runs the user interface and much of the privileged code. The report classifies the crash type as browser.

The trigger requires the loopback device path, since that is the only branch that creates an SCKAudioInputStream, and it requires the stream to be destroyed while the ScreenCaptureKit completion handler is still pending. The report does not describe a specific attacker-controlled sequence beyond the reproduction steps, so the practical reach from a web page is not spelled out.

Fix

The report does not describe the patch. The note about the patch refers only to the researcher's local build: it was added because the researcher did not know how to sign the build or attach TCC permissions to the program, not as a fix for the bug.

Variants to test

These are ideas for other places where the same kind of mistake might exist. A variant is a different spot in the code with the same underlying pattern.

  1. Other Objective-C blocks in Chrome's macOS media code that capture this implicitly. A positive result is a block that runs on a separate thread and dereferences a member after the owning object can be destroyed.
  2. Other base::Unretained(this) callbacks whose lifetime is not actually tied to the object, especially where the code comment claims the callback is reset on stop. A positive result is a path where the reset does not happen before destruction.
  3. Other stream types created through AudioManagerBase::MakeAudioInputStream and released through ReleaseInputStream. A positive result is a stream whose native completion handler can outlive the delete stream.
  4. Other Mojo-endpoint-bound factories that own objects with native asynchronous callbacks. A positive result is a disconnect that destroys the owner while a native callback is still queued on another thread.

Glossary

  • AddressSanitizer (ASan): a debugging tool that detects invalid memory access, such as reading memory after it has been freed.
  • API: an agreed interface that lets one piece of software ask another to do something.
  • Audio input stream: the object Chrome creates to capture audio from an input device.
  • Block (Objective-C): Apple's version of a callback, a chunk of code passed to a function to run later.
  • Browser process: the main Chrome process that runs the user interface and much of the privileged code.
  • Callback: a function handed to another piece of code so it can be called later.
  • Class: a blueprint in code from which objects are created.
  • Commit: a saved snapshot of source code in a version control system.
  • Completion handler: a block or callback that runs when an operation finishes.
  • CVE: Common Vulnerabilities and Exposures, a public catalogue number for a security flaw.
  • DCHECK: a debug-only check that is compiled out of release builds.
  • Dereference: follow a pointer to read or use the thing it points at.
  • Destructor: the special function that runs when an object is deleted.
  • Heap: the area of memory where programs create objects while they run.
  • Loopback device: a virtual audio device that captures the sound the computer is playing rather than a microphone.
  • Mojo: Chrome's internal messaging system between parts of the browser.
  • Node.js: a program that runs JavaScript outside a browser.
  • npm: Node's package manager, used to install libraries.
  • Patch: a small change to source code made before building a program.
  • Pointer: a memory address that tells the program where an object lives.
  • Proof of concept (poc): a small demonstration that shows a bug is real.
  • Puppeteer: a library that drives a browser automatically.
  • Smart pointer: a pointer that manages an object's lifetime and deletes it when the last owner goes away.
  • Swizzling: swapping one function for another at runtime.
  • TCC: macOS's privacy permission system for things like microphone and screen access.
  • Thread: one line of work inside a program; a program can have several running at once.
  • Use-after-free: a bug where a program uses memory after it has been freed.
  • VRP: Vulnerability Reward Program, Google's scheme for paying people who report security bugs in Chrome.

More by lime

View all

4 more disclosed reports, best first.

More from Google Chrome

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.