Root Cause Analysis
Involved Functions, Structs, and Files
Bug Mechanism
When initializing a new handshake or keypair in WireGuard (via wg_noise_handshake_init() or keypair_create()), the entry.peer field of struct index_hashtable_entry is set to point to the owning struct wg_peer:
keypair->entry.type = INDEX_HASHTABLE_KEYPAIR;
keypair->entry.peer = peer;
This pointer is intended to be invariant and immutable throughout the lifetime of the index_hashtable_entry.
wg_index_hashtable_lookup() is declared as:
struct index_hashtable_entry *
wg_index_hashtable_lookup(struct index_hashtable *table,
const enum index_hashtable_type type_mask,
const __le32 index, struct wg_peer **peer);
Its intended purpose is to locate the entry matching the given index, take a reference to entry->peer if its refcount is non-zero, and return that reference to the caller via the output parameter *peer.
However, in drivers/net/wireguard/peerlookup.c:217-223:
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
Instead of assigning the result of wg_peer_get_maybe_zero(entry->peer) to *peer (or a local variable), the code mistakenly writes it directly back into entry->peer.
How the Data Race is Triggered
- CPU 0 (Packet receive path):
Incoming ciphertext packets are processed by
wg_packet_consume_data(), which calls wg_index_hashtable_lookup(). This executes line 218:
entry->peer = wg_peer_get_maybe_zero(entry->peer);
This performs an unsynchronized 8-byte write to the shared entry->peer in the hashtable.
- CPU 1 (Decryption worker path):
Concurrently, a worker thread running
wg_packet_decrypt_worker() decrypts a previously received packet belonging to the same keypair and calls wg_queue_enqueue_per_peer_rx():
struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
PACKET_PEER(skb) expands to PACKET_CB(skb)->keypair->entry.peer, performing an unsynchronized 8-byte read of entry->peer.
- KCSAN detects this concurrent unsynchronized read and write on
entry->peer.
Invariant Violation and Consequences
- Unsynchronized Mutation of Immutable Field:
entry->peer is shared across cores and is assumed to be read-only after creation. Every invocation of wg_index_hashtable_lookup() writes to it.
- Permanent NULL Overwrite on Teardown:
If
wg_index_hashtable_lookup() is called when peer->refcount has already dropped to 0 (for example, looking up peer->handshake.entry, which remains in the index hashtable until kref_release()), wg_peer_get_maybe_zero(entry->peer) returns NULL.
Because of entry->peer = wg_peer_get_maybe_zero(entry->peer);, entry->peer is permanently overwritten with NULL. Subsequent code paths that rely on entry->peer being valid (such as wg_noise_handshake_clear() dereferencing handshake->entry.peer->device) will dereference NULL, triggering a kernel crash (denial of service).