THEME
// Blog · 2026-11-19

Anatomy of a C++ Use-After-Free: Fixing a Reentrancy Lifetime Bug in Microsoft WIL

Visitors

A Quick Intro

While auditing the Windows Implementation Library (WIL)—a C++ header library widely used across Windows, the Windows App SDK, and Microsoft services—I discovered a subtle Use-After-Free (UAF) condition in details::apartment_variable_base<...>::get_or_create().

Although the Microsoft Security Response Center (MSRC) assessed this as a reliability/correctness bug rather than a cross-trust-boundary security vulnerability, the underlying lifetime bug could lead to deterministic heap corruption and crashes in multi-threaded or reentrant environments.

In this write-up, we will examine how the bug manifests, why it occurs even without multiple threads, how MSRC handled the report under Case 179888, and how the fix was implemented and merged via PR #679.

Where to find it: - Issue Report: GitHub Issue #678 - Merged Fix: GitHub PR #679

Tooling I Used

Uncovering low-level concurrency and memory lifetime bugs requires a different toolkit than web applications.

Visual Studio Code & Static Analysis: Used for code navigation across headers, tracking macro expansions, and following template instantiations in modern C++.

Custom C++ Test Harnesses: Writing isolated multi-threaded reproducers using native Windows COM initialization (CoInitializeEx) and mock platforms to reliably trigger race conditions under AddressSanitizer (ASan) and PageHeap.

Together, these tools allowed me to isolate the exact lock-drop window where the state corruption occurs.

The Vulnerable Code Path

The core issue lived in include/wil/com_apartment_variable.h. Specifically, how get_or_create() caches a raw pointer to an apartment storage structure while dropping a global lock (s_lock) to execute arbitrary user-supplied code (creator()).

template <typename T>
std::any& get_or_create(any_maker<T>&& creator)
{
    apartment_variable_storage* variable_storage = nullptr;
    {
        auto lock = winrt::slim_lock_guard(s_lock);
        variable_storage = ensure_current_apartment_variables();
        auto variable = variable_storage->variables.find(this);
        if (variable != variable_storage->variables.end())
            return variable->second;
    } // (1) Lock dropped here

    auto value = creator(); // (2) Arbitrary user code

    auto insert_lock = winrt::slim_lock_guard(s_lock);
    return variable_storage->variables.insert({this, std::move(value)}).first->second;
    // (3) UAF: variable_storage may have been destroyed
}

Meanwhile, the companion function clear() tears down the storage when the last entry in the apartment is removed:

void clear()
{
    auto lock = winrt::slim_lock_guard(s_lock);
    if (auto variable_storage = get_current_apartment_variable_storage())
    {
        variable_storage->variables.erase(this);
        if (variable_storage->variables.size() == 0)
        {
            s_apartmentStorage.get().erase(test_hook::GetApartmentId());
            // (4) Destroys storage
        }
    }
}

Root Cause Analysis: Why It's a Real UAF

If clear() runs on the last apartment_variable in the same apartment between (1) and (3), it destroys the apartment_variable_storage object and its inner std::unordered_map. When get_or_create() resumes at (3), variable_storage is dangling, and variables.insert(...) reads and writes through freed unordered_map internals (_M_buckets, _M_bucket_count).

Crucially, this does not even require two threads. Because GetApartmentId() returns a shared apartment identifier, the same thread can re-enter clear() from inside creator() on another apartment_variable in the same apartment, destroying the storage deterministically.

MSRC Triage (Case 179888)

I reported this behavior to the Microsoft Security Response Center under case number 179888 (Submission VULN-262693). MSRC closed the report with the standard rationale:

“The submission has been thoroughly assessed and found that this is not a security vulnerability because the race requires concurrent use and teardown within the same trusted process, and no lower-trust input path or affected application was demonstrated.”

I completely agreed with their trust-boundary assessment: WIL is a header-only utility library and does not constitute a security boundary on its own. However, the lifetime bug remained a critical correctness and reliability defect.

Rather than letting it drop, I opened Issue #678 on the open-source repository to engage directly with the maintainers.

The Corrected Approach

WIL maintainer Duncan Horn (dunhor) picked up the report, agreed with the diagnostic, and opened PR #679.

The fix avoids relying on the stale, cached pointer after creator() finishes execution. Instead, it re-fetches the current storage state securely under the lock:

auto insert_lock = winrt::slim_lock_guard(s_lock);
auto current_storage = ensure_current_apartment_variables();
auto [it, inserted] = current_storage->variables.try_emplace(this, std::move(value));
return it->second;

This prevents dereferencing freed pointers and correctly handles cases where apartment storage was recreated or raced against during the callback window.

Timeline

DateWhat Happened
November 10, 2026Discovered the UAF condition, built the PoC, and submitted the technical report to MSRC (Case 179888).
November 17, 2026MSRC closed the case as a non-security reliability bug.
November 17–18, 2026Opened public GitHub Issue #678 with full root-cause analysis and suggested fixes/tests.
November 18, 2026Maintainer Duncan Horn authored PR #679, incorporated the fix, and successfully merged into master.

References

ResourceLink
GitHub Issue #678View Issue
GitHub PR #679View Pull Request
Microsoft WIL RepositoryGitHub

Wrapping Up

Auditing low-level C++ libraries and header utilities often uncovers fascinating lifetime and concurrency edge cases. Even when findings fall outside strict security boundaries for bounty payouts, responsible disclosure and direct engagement with open-source maintainers help harden foundational codebases relied upon by developers worldwide.

From isolating a subtle UAF in com_apartment_variable.h to collaborating on clean regression tests, this journey highlights how rigorous debugging benefits software reliability across the board.

// Keep exploring

More articles