| 0/0 |
2026/11/17 14:02 |
flow |
assessment-kcsan |
52m
Results: map[Benign:false Explanation:### Race Summary
`wg_queue_enqueue_per_peer_rx` (in `wg_packet_decrypt_worker`) vs
`wg_index_hashtable_lookup` on `keypair->entry.peer` (`struct
index_hashtable_entry::peer`).
### Synchronization Context
- **CPU 0** (`wg_index_hashtable_lookup`) runs under RCU read lock
(`rcu_read_lock_bh()`) with no locks held that grant write privileges. Lookup
functions in hashtables are expected to be pure readers. However,
`wg_index_hashtable_lookup()` mutates the shared hashtable entry in-place
(`entry->peer = wg_peer_get_maybe_zero(entry->peer)`).
- **CPU 1** (`wg_queue_enqueue_per_peer_rx`) reads `PACKET_PEER(skb)` (which
accesses `keypair->entry.peer`) concurrently without holding any locks.
### Final Classification
**HARMFUL**
### Failure Reasoning
`entry->peer` is supposed to be immutable for the entire lifetime of the keypair
/ handshake entry after initialization. The function
`wg_index_hashtable_lookup()` takes an out-parameter `struct wg_peer **peer`
intended to return a strong peer reference to the caller (`/* Returns a strong
reference to a entry->peer */`).
Due to a coding error, `wg_index_hashtable_lookup()` assigns the return value of
`wg_peer_get_maybe_zero(entry->peer)` to `entry->peer` rather than `*peer`:
```c
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
```
When a peer is being torn down and its refcount drops to 0, if an incoming
packet or cookie message causes a lookup on that entry,
`wg_peer_get_maybe_zero(entry->peer)` returns `NULL`.
As a result:
1. `entry->peer` is mutated in-place to `NULL`.
2. Concurrent or subsequent workers in `wg_queue_enqueue_per_peer_rx()` read
`PACKET_PEER(skb)` as `NULL`, passing it to `wg_peer_get()`. This returns
`NULL`, and `napi_schedule(&peer->napi)` dereferences `NULL`, causing an
immediate kernel crash.
3. When the keypair is subsequently released via `keypair_free_kref()`, it
dereferences `keypair->entry.peer->device`, causing a kernel crash (NULL pointer
dereference).
### Failure Sequencing
```text
CPU 0 (Softirq / Lookup) CPU 1 (Decrypt Worker)
wg_packet_decrypt_worker()
// Decrypting packet
with keypair
decrypt_packet(skb,
PACKET_CB(skb)->keypair)
// Peer deletion initiated; peer->refcount == 0
wg_packet_consume_data()
wg_index_hashtable_lookup()
rcu_read_lock_bh()
entry = ... // finds keypair entry
// wg_peer_get_maybe_zero() returns NULL
entry->peer = NULL; // OVERWRITES entry->peer with NULL!
rcu_read_unlock_bh()
wg_queue_enqueue_per_peer_rx(skb,
state)
// Reads
PACKET_PEER(skb) ==
entry->peer (NULL)
peer =
wg_peer_get(NULL); //
returns NULL
napi_schedule(&peer->napi);
// -> NULL pointer
dereference! (CRASH)
```
### FailureDetectableBy
`any`
### Recommended Fix
In `drivers/net/wireguard/peerlookup.c`, assign the result of
`wg_peer_get_maybe_zero(entry->peer)` directly to `*peer` rather than mutating
`entry->peer`:
```diff
--- a/drivers/net/wireguard/peerlookup.c
+++ b/drivers/net/wireguard/peerlookup.c
@@ -215,9 +215,8 @@ wg_index_hashtable_lookup(struct index_hashtable *table,
}
}
if (likely(entry)) {
- entry->peer = wg_peer_get_maybe_zero(entry->peer);
- if (likely(entry->peer))
- *peer = entry->peer;
+ *peer = wg_peer_get_maybe_zero(entry->peer);
+ if (likely(*peer))
+ ;
else
entry = NULL;
}
``` FailureDetectableBy:any]
|
| 1/1 |
2026/11/17 14:02 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/6d0c4d912ac4c28457116fbfe153047fb3052961/data]
|
| 2/1 |
2026/11/17 14:02 |
action |
kernel-builder |
0m
Results: map[KernelObj:/app/workdir/cache/build/4fc9cb093f0faa8b5951a9949e7cc5ff4ce76564/data]
|
| 3/1 |
2026/11/17 14:02 |
action |
codesearch-prepare |
0m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/11/17 14:03 |
agent |
expert |
51m
Model:
Results: map[Benign:false FailureDetectableBy:any]
Instruction: # KCSAN Data Race Severity Analysis Protocol
You are an expert Linux kernel concurrency engineer analyzing a Kernel
Concurrency Sanitizer (KCSAN) data race report to determine if it is
**BENIGN** or **HARMFUL**.
## 1. CLASSIFICATIONS
### **BENIGN (Truly Benign)**
The logic is sound and structurally tolerant to compiler optimizations or
stale reads (or benign tearing on diagnostics/stats).
- **Diagnostics/Stats:** Reads or non-critical updates used only for `/proc`,
`/sys`, counters, timestamps, or `pr_info`.
- **Heuristic Hints:** A "hint" flag or threshold where an old value only
causes a slightly delayed update or a sub-optimal but safe fast-path.
- **Single-Writer Flag Updates:** A single writer updating flags where the
concurrent read is a simple bitwise check (e.g., `flags & MASK`). These are
historically tolerated, assuming neither "Fused Accesses" nor "Ordering
Violations" are relevant in this context.
- **Marked Reloads & Lock Re-checks:** A load feeding into a `cmpxchg()` loop,
checked against a later `READ_ONCE()` reload, or re-verified under a lock
(assuming no "Ordering Violations" on the lockless fast-path).
- **Safe Overwrites & Plain Scalar Accesses:** Writing the same value already
present, or aligned word-sized scalar accesses (e.g., `read (marked)` vs
plain `write`) where observing either the old or new value is safe.
### **HARMFUL (Logic Bug or Marking Required)**
The race causes incorrect behavior due to a synchronization failure or
because missing annotations allow the compiler or CPU to break the algorithm.
**Marking Required for Correctness:**
Do **not** classify a race as HARMFUL merely because an access lacks
`READ_ONCE()`/`WRITE_ONCE()`; you must prove one of these concrete hazards:
- **Fused Accesses:** The compiler hoists a plain load out of a tight
barrier-free spin loop causing a livelock (note: non-inlined calls,
`schedule()`, and locks act as compiler barriers), or reloads a pointer/index
between check and use (TOCTOU).
- **Torn Accesses:** An access larger than word size (e.g., 64-bit on 32-bit
arch, or multi-word structs; aligned `<= sizeof(long)` scalars and pointers
do not tear) is split into multiple non-atomic accesses. Note that
`READ_ONCE()` does **not** guarantee atomicity for 64-bit variables on 32-bit
architectures.
- **Ordering Violations:** The race breaks a required "happens-before"
relationship between dependent memory accesses (requires primitives with
implied or explicit memory barriers).
**Logic Bugs:**
A fundamental synchronization failure. Marking accesses will **not** fix it;
the logic itself must change.
- **Pointers/Lifecycle:** The racing variable is a pointer being dereferenced
or a refcount governing object lifecycle (Use-After-Free risk).
- **Control Flow:** The variable guards a critical section, memory allocation,
or hardware command.
- **Bitfields:** Concurrent writes to different bits in the same word.
Compilers often use non-atomic read-modify-write sequences, meaning a
write to `bit_A` can "clobber" a concurrent write to `bit_B`. However,
do not blindly assume all bitfield accesses are harmful; you must prove
that a concurrent write actually clobbers another in a way that breaks
logic.
- **Complex Structures:** Races on shared lists, trees, or hashmaps.
- **Lossy Updates:** Concurrent plain RMW operations (e.g., `var++`) on
non-diagnostic variables where every increment must be preserved.
- **State Machines:** Races allowing a state machine to bypass transitions
or enter an invalid state.
- **Adjacent Unsynchronized Operations:** Consider races happening at the
same time. For example, if both threads execute `struct->has_elements = true;
list_add(node, &struct->list);`, the race on `has_elements` implies an
adjacent race on `list_head`, which is HARMFUL.
## 2. RESEARCH & ANALYSIS WORKFLOW
1. **Locate the Race:** Find the exact variables and functions in the stack
traces. Do not speculate about hypothetical compiler
behaviors or theoretical dangers (e.g., dismissing something as
"fundamentally unsafe") without tracing the actual data flow to a crash.
2. **Contextualize:** Identify held locks, RCU sections, or interrupt
contexts. Explain why the race is possible (e.g., "Thread A holds `lock`,
but Thread B is a lockless reader").
3. **Data Flow:** Follow the racing variable into its subsequent uses. If
the reader sees a stale or torn value, what branch is taken? Does it lead
to a pointer dereference or `BUG_ON()`? **You must prove harm via this
data flow.**
4. **Failure Sequencing (if HARMFUL):** Construct a two-column execution trace
demonstrating the failure.
*Example format:*
```text
CPU0 CPU1
function_a()
// lockless read
ptr = global_ptr
<PREEMPT>
function_b()
lock(&my_lock)
global_ptr = NULL
unlock(&my_lock)
kfree(ptr)
if (ptr)
*ptr = 1; // -> Use-After-Free!
```
## 3. OUTPUT FORMAT
- **Race Summary:** `[Function A]` vs `[Function B]` on `[Variable/Field]`.
- **Synchronization context:** List held locks and explain the lack of mutual
exclusion.
- **Final Classification:** **BENIGN** or **HARMFUL**.
**If BENIGN:**
- **Reasoning:** Briefly explain why the race is structurally tolerant to stale
reads (or benign tearing on diagnostics/stats).
- **Recommended Annotations:** Suggest appropriate annotations (e.g.,
`READ_ONCE()`, `WRITE_ONCE()`, `data_race()`).
**If HARMFUL:**
- **Failure Reasoning:** Explain and provide a two-column interleaving showing
exactly how the race leads to a failure such as corruption or kernel crash.
- **FailureDetectableBy:** One of:
- `"kasan"`: memory safety bug (use-after-free, out-of-bounds, double-free).
- `"kmsan"`: uninitialized memory read/exposure (e.g. missing publish/subscribe ordering).
- `"any"`: kernel crash/hang (`BUG_ON`, `WARN_ON`, NULL deref, GPF, deadlock).
- `"user"`: user-visible ABI/semantic corruption detectable by userspace without a kernel crash.
- `"none"`: purely internal kernel state/accounting bug without crash or user-visible invariant violation.
- **Recommended Fix (ONLY if fix is trivial):** Suggest a structural fix (e.g.,
"Hold `mapping->i_pages` lock", "Convert to `atomic_t`") or required memory
ordering annotations (e.g., "Wrap in `READ_ONCE()`", "Use
`smp_load_acquire()`").
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The data race report is:
==================================================================
BUG: KCSAN: data-race in wg_index_hashtable_lookup / wg_packet_decrypt_worker
read to 0xffff88811b7fb000 of 8 bytes by task 3374 on cpu 1:
wg_queue_enqueue_per_peer_rx drivers/net/wireguard/queueing.h:195 [inline]
wg_packet_decrypt_worker+0x45c/0x670 drivers/net/wireguard/receive.c:503
process_one_work kernel/workqueue.c:3495 [inline]
process_scheduled_works+0x582/0xab0 kernel/workqueue.c:3578
worker_thread+0x56c/0x770 kernel/workqueue.c:3659
kthread+0x248/0x2a0 kernel/kthread.c:436
ret_from_fork+0x146/0x330 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
write to 0xffff88811b7fb000 of 8 bytes by interrupt on cpu 0:
wg_index_hashtable_lookup+0xcf/0x120 drivers/net/wireguard/peerlookup.c:218
wg_packet_consume_data drivers/net/wireguard/receive.c:517 [inline]
wg_packet_receive+0xa90/0x1260 drivers/net/wireguard/receive.c:576
wg_receive+0x4e/0x80 drivers/net/wireguard/socket.c:325
udp_queue_rcv_one_skb+0x85f/0x8b0 net/ipv4/udp.c:2433
udp_queue_rcv_skb+0x355/0x430 net/ipv4/udp.c:2473
udp_unicast_rcv_skb+0x196/0x1c0 net/ipv4/udp.c:2621
udp_rcv+0xa3c/0xf20 net/ipv4/udp.c:2698
ip_protocol_deliver_rcu+0x400/0x7b0 net/ipv4/ip_input.c:207
ip_local_deliver_finish+0x1f0/0x2e0 net/ipv4/ip_input.c:241
NF_HOOK include/linux/netfilter.h:325 [inline]
ip_local_deliver+0xe8/0x1e0 net/ipv4/ip_input.c:262
dst_input include/net/dst.h:482 [inline]
ip_rcv_finish+0x188/0x1a0 net/ipv4/ip_input.c:492
NF_HOOK include/linux/netfilter.h:325 [inline]
ip_rcv+0x62/0x160 net/ipv4/ip_input.c:612
__netif_receive_skb_one_core net/core/dev.c:6447 [inline]
__netif_receive_skb net/core/dev.c:6560 [inline]
process_backlog+0x349/0x690 net/core/dev.c:6911
__napi_poll+0x73/0x350 net/core/dev.c:7997
napi_poll net/core/dev.c:8060 [inline]
net_rx_action+0x33f/0x850 net/core/dev.c:8217
handle_softirqs+0x109/0x310 kernel/softirq.c:669
do_softirq+0x46/0x60 kernel/softirq.c:569
__local_bh_enable_ip+0x79/0x80 kernel/softirq.c:473
__raw_read_unlock_bh include/linux/rwlock_api_smp.h:283 [inline]
_raw_read_unlock_bh+0x2f/0x40 kernel/locking/spinlock.c:319
wg_socket_send_skb_to_peer+0x10c/0x130 drivers/net/wireguard/socket.c:183
wg_packet_create_data_done drivers/net/wireguard/send.c:251 [inline]
wg_packet_tx_worker+0x173/0x340 drivers/net/wireguard/send.c:276
process_one_work kernel/workqueue.c:3495 [inline]
process_scheduled_works+0x582/0xab0 kernel/workqueue.c:3578
worker_thread+0x56c/0x770 kernel/workqueue.c:3659
kthread+0x248/0x2a0 kernel/kthread.c:436
ret_from_fork+0x146/0x330 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:245
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 3626 Comm: kworker/0:5 Not tainted syzkaller #0 PREEMPT(lazy)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 11/06/2026
Workqueue: wg-crypt-wg2 wg_packet_tx_worker
==================================================================
Reply: ### Race Summary
`wg_queue_enqueue_per_peer_rx` (in `wg_packet_decrypt_worker`) vs `wg_index_hashtable_lookup` on `keypair->entry.peer` (`struct index_hashtable_entry::peer`).
### Synchronization Context
- **CPU 0** (`wg_index_hashtable_lookup`) runs under RCU read lock (`rcu_read_lock_bh()`) with no locks held that grant write privileges. Lookup functions in hashtables are expected to be pure readers. However, `wg_index_hashtable_lookup()` mutates the shared hashtable entry in-place (`entry->peer = wg_peer_get_maybe_zero(entry->peer)`).
- **CPU 1** (`wg_queue_enqueue_per_peer_rx`) reads `PACKET_PEER(skb)` (which accesses `keypair->entry.peer`) concurrently without holding any locks.
### Final Classification
**HARMFUL**
### Failure Reasoning
`entry->peer` is supposed to be immutable for the entire lifetime of the keypair / handshake entry after initialization. The function `wg_index_hashtable_lookup()` takes an out-parameter `struct wg_peer **peer` intended to return a strong peer reference to the caller (`/* Returns a strong reference to a entry->peer */`).
Due to a coding error, `wg_index_hashtable_lookup()` assigns the return value of `wg_peer_get_maybe_zero(entry->peer)` to `entry->peer` rather than `*peer`:
```c
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
```
When a peer is being torn down and its refcount drops to 0, if an incoming packet or cookie message causes a lookup on that entry, `wg_peer_get_maybe_zero(entry->peer)` returns `NULL`.
As a result:
1. `entry->peer` is mutated in-place to `NULL`.
2. Concurrent or subsequent workers in `wg_queue_enqueue_per_peer_rx()` read `PACKET_PEER(skb)` as `NULL`, passing it to `wg_peer_get()`. This returns `NULL`, and `napi_schedule(&peer->napi)` dereferences `NULL`, causing an immediate kernel crash.
3. When the keypair is subsequently released via `keypair_free_kref()`, it dereferences `keypair->entry.peer->device`, causing a kernel crash (NULL pointer dereference).
### Failure Sequencing
```text
CPU 0 (Softirq / Lookup) CPU 1 (Decrypt Worker)
wg_packet_decrypt_worker()
// Decrypting packet with keypair
decrypt_packet(skb, PACKET_CB(skb)->keypair)
// Peer deletion initiated; peer->refcount == 0
wg_packet_consume_data()
wg_index_hashtable_lookup()
rcu_read_lock_bh()
entry = ... // finds keypair entry
// wg_peer_get_maybe_zero() returns NULL
entry->peer = NULL; // OVERWRITES entry->peer with NULL!
rcu_read_unlock_bh()
wg_queue_enqueue_per_peer_rx(skb, state)
// Reads PACKET_PEER(skb) == entry->peer (NULL)
peer = wg_peer_get(NULL); // returns NULL
napi_schedule(&peer->napi);
// -> NULL pointer dereference! (CRASH)
```
### FailureDetectableBy
`any`
### Recommended Fix
In `drivers/net/wireguard/peerlookup.c`, assign the result of `wg_peer_get_maybe_zero(entry->peer)` directly to `*peer` rather than mutating `entry->peer`:
```diff
--- a/drivers/net/wireguard/peerlookup.c
+++ b/drivers/net/wireguard/peerlookup.c
@@ -215,9 +215,8 @@ wg_index_hashtable_lookup(struct index_hashtable *table,
}
}
if (likely(entry)) {
- entry->peer = wg_peer_get_maybe_zero(entry->peer);
- if (likely(entry->peer))
- *peer = entry->peer;
+ *peer = wg_peer_get_maybe_zero(entry->peer);
+ if (likely(*peer))
+ ;
else
entry = NULL;
}
```
|
| 5/2 |
2026/11/17 14:03 |
llm |
expert |
0m
Model:
Tokens:
input: 7375
output: 116
thoughts: 276
Thoughts: **KCSAN Data Race Investigation**
Okay, so the KCSAN report just flagged a data race. The report pinpoints the race happening in `wg_index_hashtable_lookup` and `wg_packet_decrypt_worker`, specifically in the WireGuard code. I see a read occurring in `wg_packet_decrypt_worker` at `drivers/net/wireguard/receive.c:503` (through the `wg_queue_enqueue_per_peer_rx` path), and a write happening from interrupt context in `wg_index_hashtable_lookup` at `drivers/net/wireguard/peerlookup.c:218`. The write also seems to be happening via `wg_packet_receive` at `drivers/net/wireguard/receive.c:576`, likely from the `wg_packet_consume_data` path, which is called from within the `wg_packet_receive` function. That's not ideal, as interrupt contexts should be short and not interact in this way.
The conflicting access is to the same 8-byte region at `0xffff88811b7fb000`. I need to dig into the WireGuard codebase to figure out *what* data is being accessed and, crucially, *why* these two functions are accessing the same memory location concurrently. I'll start by using my standard tools - probably `read-file` or `grepper` - to quickly examine those specific lines and the surrounding code in `drivers/net/wireguard/`. I need to understand the logic flow here.
|
| 6/2 |
2026/11/17 14:03 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/queueing.h FirstLine:180 LineCount:40]
Results: map[Contents: 180: * peer can be freed from below us.
181: */
182: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
183:
184: atomic_set_release(&PACKET_CB(skb)->state, state);
185: queue_work_on(wg_cpumask_choose_online(&peer->serial_work_cpu, peer->internal_id),
186: peer->device->packet_crypt_wq, &peer->transmit_packet_work);
187: wg_peer_put(peer);
188: }
189:
190: static inline void wg_queue_enqueue_per_peer_rx(struct sk_buff *skb, enum packet_state state)
191: {
192: /* We take a reference, because as soon as we call atomic_set, the
193: * peer can be freed from below us.
194: */
195: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
196:
197: atomic_set_release(&PACKET_CB(skb)->state, state);
198: napi_schedule(&peer->napi);
199: wg_peer_put(peer);
200: }
201:
202: #ifdef DEBUG
203: bool wg_packet_counter_selftest(void);
204: #endif
205:
206: #endif /* _WG_QUEUEING_H */
]
|
| 7/2 |
2026/11/17 14:03 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peerlookup.c FirstLine:200 LineCount:40]
Results: map[Contents: 200: /* Returns a strong reference to a entry->peer */
201: struct index_hashtable_entry *
202: wg_index_hashtable_lookup(struct index_hashtable *table,
203: const enum index_hashtable_type type_mask,
204: const __le32 index, struct wg_peer **peer)
205: {
206: struct index_hashtable_entry *iter_entry, *entry = NULL;
207:
208: rcu_read_lock_bh();
209: hlist_for_each_entry_rcu_bh(iter_entry, index_bucket(table, index),
210: index_hash) {
211: if (iter_entry->index == index) {
212: if (likely(iter_entry->type & type_mask))
213: entry = iter_entry;
214: break;
215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
224: rcu_read_unlock_bh();
225: return entry;
226: }
]
|
| 8/2 |
2026/11/17 14:03 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/receive.c FirstLine:490 LineCount:40]
Results: map[Contents: 490: return work_done;
491: }
492:
493: void wg_packet_decrypt_worker(struct work_struct *work)
494: {
495: struct crypt_queue *queue = container_of(work, struct multicore_worker,
496: work)->ptr;
497: struct sk_buff *skb;
498:
499: while ((skb = ptr_ring_consume_bh(&queue->ring)) != NULL) {
500: enum packet_state state =
501: likely(decrypt_packet(skb, PACKET_CB(skb)->keypair)) ?
502: PACKET_STATE_CRYPTED : PACKET_STATE_DEAD;
503: wg_queue_enqueue_per_peer_rx(skb, state);
504: if (need_resched())
505: cond_resched();
506: }
507: }
508:
509: static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb)
510: {
511: __le32 idx = ((struct message_data *)skb->data)->key_idx;
512: struct wg_peer *peer = NULL;
513: int ret;
514:
515: rcu_read_lock_bh();
516: PACKET_CB(skb)->keypair =
517: (struct noise_keypair *)wg_index_hashtable_lookup(
518: wg->index_hashtable, INDEX_HASHTABLE_KEYPAIR, idx,
519: &peer);
520: if (unlikely(!wg_noise_keypair_get(PACKET_CB(skb)->keypair)))
521: goto err_keypair;
522:
523: if (unlikely(READ_ONCE(peer->is_dead)))
524: goto err;
525:
526: ret = wg_queue_enqueue_per_device_and_peer(&wg->decrypt_queue, &peer->rx_queue, skb,
527: wg->packet_crypt_wq);
528: if (unlikely(ret == -EPIPE))
529: wg_queue_enqueue_per_peer_rx(skb, PACKET_STATE_DEAD);
]
|
| 9/2 |
2026/11/17 14:03 |
llm |
expert |
0m
Model:
Tokens:
input: 9660
output: 33
thoughts: 318
Thoughts: **Analyzing WireGuard Data Structures**
Okay, let's break this down. I'm looking at these memory access patterns associated with WireGuard's packet processing, specifically around the receive path and the peer lookup. I'm seeing a read operation and a write operation hitting the same memory address, which immediately flags a potential synchronization issue or data race that needs closer inspection.
On the read side, task 3374 on CPU 1 is reading 8 bytes from `0xffff88811b7fb000`. The function in the call stack is `wg_packet_decrypt_worker`, originating from `drivers/net/wireguard/receive.c:503`. This is getting down to `wg_queue_enqueue_per_peer_rx` which in turn calls `wg_peer_get` at `drivers/net/wireguard/queueing.h:195`. The key line here is `struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));`. So, `PACKET_PEER(skb)` is being passed to `wg_peer_get`, which is, in turn, returning a `wg_peer` pointer, and that pointer is being read.
On the write side, an interrupt on CPU 0 is writing 8 bytes to that *same* memory address. The call stack points to `wg_index_hashtable_lookup` at `drivers/net/wireguard/peerlookup.c:218`. Line 218 is where the write occurs: `entry->peer = wg_peer_get_maybe_zero(entry->peer);`. Here, `wg_peer_get_maybe_zero` is updating `entry->peer`. The critical thing here is: What exactly is `entry->peer` and how does it relate to the read operation? This raises a few questions:
* What is the underlying data structure of the `struct index_hashtable_entry`?
* How is `entry->peer` being initialized and updated?
Since these accesses are happening concurrently - a read during packet handling and a write during a lookup - the potential for contention is obvious. I need to understand what this `entry->peer` represents in relation to the received packet's peer, which is referenced in the read operation using `PACKET_PEER(skb)`. This requires more detailed analysis of the underlying data structures, and how `PACKET_PEER(skb)` is populated and then how `entry->peer` is used later on. I'll need to dig into the WireGuard code to get that context.
|
| 10/2 |
2026/11/17 14:03 |
tool |
grepper |
0m
Args: map[Expression:PACKET_PEER PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/queueing.h=59=struct packet_cb {
--
drivers/net/wireguard/queueing.h-67-#define PACKET_CB(skb) ((struct packet_cb *)((skb)->cb))
drivers/net/wireguard/queueing.h:68:#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
drivers/net/wireguard/queueing.h-69-
--
drivers/net/wireguard/queueing.h=177=static inline void wg_queue_enqueue_per_peer_tx(struct sk_buff *skb, enum packet_state state)
--
drivers/net/wireguard/queueing.h-181- */
drivers/net/wireguard/queueing.h:182: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
drivers/net/wireguard/queueing.h-183-
--
drivers/net/wireguard/queueing.h=190=static inline void wg_queue_enqueue_per_peer_rx(struct sk_buff *skb, enum packet_state state)
--
drivers/net/wireguard/queueing.h-194- */
drivers/net/wireguard/queueing.h:195: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
drivers/net/wireguard/queueing.h-196-
]
|
| 11/2 |
2026/11/17 14:03 |
llm |
expert |
0m
Model:
Tokens:
input: 10960
output: 39
thoughts: 377
Thoughts: **Debugging a WireGuard Data Structure**
Okay, so I'm diving into this WireGuard code, and I'm looking at how peers are accessed within packets. I see that `PACKET_PEER(skb)` is essentially a shortcut for getting the peer from the packet control block's keypair entry β that makes sense, fairly standard. Now, I'm digging into `wg_index_hashtable_lookup`, trying to follow the data flow. It's a fairly standard hash table lookup with RCU protection, iterating through buckets, and checking the index and type mask... all good so far.
But wait a minute... line 218 is giving me pause. I'm seeing `entry->peer = wg_peer_get_maybe_zero(entry->peer);` being assigned to. *Why* are we assigning back to `entry->peer`? This is weird, I'm expecting `wg_peer_get_maybe_zero` to just return a pointer, maybe increment the reference count, but not _assign_ back to the `entry`. That's not the usual pattern. This feels like a potential race condition or a subtle logic error.
Time to consult the git history! I need to see the context of this change, what was the intent? Or maybe I'll dig into the `wg_peer_get_maybe_zero` function itself. I need to understand what side effects are happening here and whether this assignment is intended or a bug. Gotta get to the bottom of this!
|
| 12/2 |
2026/11/17 14:04 |
tool |
git-blame |
0m
Args: map[End:225 File:drivers/net/wireguard/peerlookup.c Start:215]
Results: map[Output:e7096c131e516 215) }
e7096c131e516 216) }
e7096c131e516 217) if (likely(entry)) {
e7096c131e516 218) entry->peer = wg_peer_get_maybe_zero(entry->peer);
e7096c131e516 219) if (likely(entry->peer))
e7096c131e516 220) *peer = entry->peer;
e7096c131e516 221) else
e7096c131e516 222) entry = NULL;
e7096c131e516 223) }
e7096c131e516 224) rcu_read_unlock_bh();
e7096c131e516 225) return entry;
]
|
| 13/2 |
2026/11/17 14:04 |
llm |
expert |
0m
Model:
Tokens:
input: 12005
output: 31
thoughts: 100
Thoughts: Okay, let's see. My first thought is: **Decoding the `wg_index_hashtable_lookup` Write to `entry->peer`**.
Hang on a second⦠why is `wg_index_hashtable_lookup` assigning a value to `entry->peer` with `wg_peer_get_maybe_zero`? That strikes me as odd. Isn't that value supposed to be looked up, not overwritten? I'm thrown off by this. I need to clarify the intent.
Wait, let me back up a step. Could it be a read operation, not a write? I'm not entirely convinced it's necessarily writing to the field. I need to be sure.
Right! Okay, I need to go straight to the source. Time to dig into the commit history. I need to check commit e7096c131e516, or any related commits in the `git log` related to `peerlookup.c` or, specifically, `index_hashtable_lookup`. That should clarify the context and the rationale behind that particular line. Let's see what the change history tells us.
|
| 14/2 |
2026/11/17 14:04 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/net/wireguard/peerlookup.c]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
6147f7b1e90f wireguard: peerlookup: take lock before checking hash in replace operation
e7096c131e51 net: WireGuard secure network tunnel
]
|
| 15/2 |
2026/11/17 14:04 |
llm |
expert |
0m
Model:
Tokens:
input: 12499
output: 44
thoughts: 32
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `wg_peer_get_maybe_zero`**
Okay, hold on a second. I need to clarify something here. `wg_peer_get_maybe_zero`... what exactly is the intent of that function? The name suggests something potentially nuanced involving zero-initialization, but I need to be precise. Before I go further down this rabbit hole, let me quickly review the code for `wg_peer_get_maybe_zero` itself. A quick scan of its implementation will likely resolve the ambiguity in the naming, which could be anything from a pointer check to a memory allocation strategy. I'm assuming that zero-initialization is the focus here. I'll get the details before I continue.
|
| 16/2 |
2026/11/17 14:05 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.c Name:wg_peer_get_maybe_zero]
Results: map[SourceCode: 71: struct wg_peer *wg_peer_get_maybe_zero(struct wg_peer *peer)
72: {
73: RCU_LOCKDEP_WARN(!rcu_read_lock_bh_held(),
74: "Taking peer reference without holding the RCU read lock");
75: if (unlikely(!peer || !kref_get_unless_zero(&peer->refcount)))
76: return NULL;
77: return peer;
78: }
SourceFile:drivers/net/wireguard/peer.c]
|
| 17/2 |
2026/11/17 14:05 |
llm |
expert |
0m
Model:
Tokens:
input: 12910
output: 35
thoughts: 560
Thoughts: **Analyzing Potential RCU Read Lock Violation in WireGuard's Peer Lookup**
Okay, let's break this down. I'm looking at `wg_peer_get_maybe_zero` and immediately see a potential issue with the RCU read lock. The function's structure itself, with the `kref_get_unless_zero` check, makes perfect sense in terms of reference counting. It's designed to either return a valid peer pointer (after incrementing its reference count) or NULL if the reference count is zero. So far, so good.
But then, I get to `wg_index_hashtable_lookup`, and my spidey-sense starts tingling. The line `entry->peer = wg_peer_get_maybe_zero(entry->peer);` is the key point. If `wg_peer_get_maybe_zero` either *fails* (returns `NULL`) *or* succeeds (returns the valid `peer` pointer, after the increment), why is it *writing* back to `entry->peer`? This is a problem! If it *succeeds*, the `peer` will be unchanged and nothing is actually altered, which seems ok. But if it returns *NULL*, `entry->peer` will be changed to NULL!
The core concern here is the potential for *modification* of shared memory under the RCU read lock. I mean, even if it returns a *valid* pointer it is still doing a write under the lock, which seems... wrong. I'm trying to figure out the reasoning behind this `entry->peer = ...` assignment. The code is either updating an existing entry, and changing a pointer, or clearing the pointer to NULL.
Is this intentional, or is it a typo? I suspect that the code *should* be creating a *local* variable: `struct wg_peer *p = wg_peer_get_maybe_zero(entry->peer);` and then using *that* local variable to do the conditional check and assignment to the caller:
struct wg_peer *p = wg_peer_get_maybe_zero(entry->peer);
if (likely(p))
*peer = p;
else
entry = NULL;
This would avoid any modification to `entry->peer` *at all*, which seems much safer within the context of an RCU read lock. I need to dig deeper! I need to check the definition of `struct index_hashtable_entry` and how it is used to see if there is any plausible reason that this write is necessary or correct. There might be a reason, but it's not immediately obvious, and the behavior appears to be risky as it stands.
|
| 18/2 |
2026/11/17 14:05 |
tool |
grepper |
0m
Args: map[Expression:struct index_hashtable_entry PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/noise.h=30=struct noise_keypair {
drivers/net/wireguard/noise.h:31: struct index_hashtable_entry entry;
drivers/net/wireguard/noise.h-32- struct noise_symmetric_key sending;
--
drivers/net/wireguard/noise.h=65=struct noise_handshake {
drivers/net/wireguard/noise.h:66: struct index_hashtable_entry entry;
drivers/net/wireguard/noise.h-67-
--
drivers/net/wireguard/peerlookup.c=119=__le32 wg_index_hashtable_insert(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.c:120: struct index_hashtable_entry *entry)
drivers/net/wireguard/peerlookup.c-121-{
drivers/net/wireguard/peerlookup.c:122: struct index_hashtable_entry *existing_entry;
drivers/net/wireguard/peerlookup.c-123-
--
drivers/net/wireguard/peerlookup.c=166=bool wg_index_hashtable_replace(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.c:167: struct index_hashtable_entry *old,
drivers/net/wireguard/peerlookup.c:168: struct index_hashtable_entry *new)
drivers/net/wireguard/peerlookup.c-169-{
--
drivers/net/wireguard/peerlookup.c=192=void wg_index_hashtable_remove(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.c:193: struct index_hashtable_entry *entry)
drivers/net/wireguard/peerlookup.c-194-{
--
drivers/net/wireguard/peerlookup.c-200-/* Returns a strong reference to a entry->peer */
drivers/net/wireguard/peerlookup.c:201:struct index_hashtable_entry *
drivers/net/wireguard/peerlookup.c-202-wg_index_hashtable_lookup(struct index_hashtable *table,
--
drivers/net/wireguard/peerlookup.c-205-{
drivers/net/wireguard/peerlookup.c:206: struct index_hashtable_entry *iter_entry, *entry = NULL;
drivers/net/wireguard/peerlookup.c-207-
--
drivers/net/wireguard/peerlookup.h=39=enum index_hashtable_type {
--
drivers/net/wireguard/peerlookup.h-43-
drivers/net/wireguard/peerlookup.h:44:struct index_hashtable_entry {
drivers/net/wireguard/peerlookup.h-45- struct wg_peer *peer;
--
drivers/net/wireguard/peerlookup.h=52=__le32 wg_index_hashtable_insert(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.h:53: struct index_hashtable_entry *entry);
drivers/net/wireguard/peerlookup.h-54-bool wg_index_hashtable_replace(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.h:55: struct index_hashtable_entry *old,
drivers/net/wireguard/peerlookup.h:56: struct index_hashtable_entry *new);
drivers/net/wireguard/peerlookup.h-57-void wg_index_hashtable_remove(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.h:58: struct index_hashtable_entry *entry);
drivers/net/wireguard/peerlookup.h:59:struct index_hashtable_entry *
drivers/net/wireguard/peerlookup.h-60-wg_index_hashtable_lookup(struct index_hashtable *table,
]
|
| 19/2 |
2026/11/17 14:05 |
llm |
expert |
0m
Model:
Tokens:
input: 15081
output: 38
thoughts: 36
Thoughts: Okay, let's dive into this. I need to get a handle on the internals of WireGuard's peer lookup mechanism, specifically how it's structured in the kernel. My initial thought is to examine the `drivers/net/wireguard/peerlookup.h` header file. I want to understand the composition of `struct index_hashtable_entry`. I'm going to look at the member variables and data types to get a feel for how the data is stored. Furthermore, I'll pay close attention to the initialization process of these entries. Understanding the entry structure and its initialization is key to grasping how WireGuard performs its lookups, handles collisions, and manages its internal data structures efficiently. I expect this will give me a better understanding of potential performance characteristics and possible areas for optimization down the line.
|
| 20/2 |
2026/11/17 14:05 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peerlookup.h FirstLine:35 LineCount:40]
Results: map[Contents: 35: DECLARE_HASHTABLE(hashtable, 13);
36: spinlock_t lock;
37: };
38:
39: enum index_hashtable_type {
40: INDEX_HASHTABLE_HANDSHAKE = 1U << 0,
41: INDEX_HASHTABLE_KEYPAIR = 1U << 1
42: };
43:
44: struct index_hashtable_entry {
45: struct wg_peer *peer;
46: struct hlist_node index_hash;
47: enum index_hashtable_type type;
48: __le32 index;
49: };
50:
51: struct index_hashtable *wg_index_hashtable_alloc(void);
52: __le32 wg_index_hashtable_insert(struct index_hashtable *table,
53: struct index_hashtable_entry *entry);
54: bool wg_index_hashtable_replace(struct index_hashtable *table,
55: struct index_hashtable_entry *old,
56: struct index_hashtable_entry *new);
57: void wg_index_hashtable_remove(struct index_hashtable *table,
58: struct index_hashtable_entry *entry);
59: struct index_hashtable_entry *
60: wg_index_hashtable_lookup(struct index_hashtable *table,
61: const enum index_hashtable_type type_mask,
62: const __le32 index, struct wg_peer **peer);
63:
64: #endif /* _WG_PEERLOOKUP_H */
]
|
| 21/2 |
2026/11/17 14:05 |
llm |
expert |
0m
Model:
Tokens:
input: 15798
output: 34
thoughts: 18
Thoughts: Okay, here's my attempt at summarizing my thought process regarding `entry->peer`, as if I'm thinking it, and addressing it to an expert in the field:
**Digging into `entry->peer` in WireGuard**
Alright, let's get down to brass tacks. I need to trace the initialization and subsequent usage of `entry->peer` throughout the WireGuard codebase. This field is *critical*, and understanding its lifecycle is fundamental. I'm thinking, this should quickly reveal how peer information is being handled within a tunnel's context.
First, I'll need to locate where `entry->peer` is *originally* set. Where's the allocation or assignment? Is it part of the interface creation, peer handshake, or perhaps a configuration loading routine? I'm anticipating there could be several points where its value is set depending on the specific operation being performed. I need to identify *all* of those points.
Next, I'll need to identify how the value is used and if it is accessed. I'm going to look for reads and writes, and how `entry->peer` is employed in sending, receiving, and managing traffic. Are there any critical sections or locking mechanisms involved when accessing or modifying it? Thinking about it now, the way `entry->peer` is handled likely informs all the peer interactions, packet forwarding, and security aspects, so I expect to see it everywhere.
I'm focusing on those crucial interactions β the synchronization, the security checks, the potential for race conditions. I'm keen to ensure the code is thread-safe and robust, especially considering the real-time nature of network traffic. Given the potential for concurrent access, I'm expecting some clever pointer manipulation and atomic operations.
Once I have a firm grasp of initialization and usage, I can identify how the structure evolves over time, and look for any interesting optimizations that are happening with this field. If there are any performance or security implications associated with it, I'll be in a good position to understand them. Let's start with the source code.
|
| 22/2 |
2026/11/17 14:06 |
tool |
grepper |
0m
Args: map[Expression:entry\.peer|\->peer PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:
Full output is too long, showing 200 out of 316 lines.
Use more precise expression or PathPrefixes if possible.
Number of matching lines per file (10 files in total):
drivers/net/wireguard/allowedips.c:16
drivers/net/wireguard/device.c:12
drivers/net/wireguard/netlink.c:15
drivers/net/wireguard/noise.c:14
drivers/net/wireguard/peer.c:8
drivers/net/wireguard/peerlookup.c:4
drivers/net/wireguard/queueing.h:1
drivers/net/wireguard/receive.c:1
drivers/net/wireguard/selftest/allowedips.c:2
drivers/net/wireguard/send.c:1
drivers/net/wireguard/allowedips.c=64=static void root_remove_peer_lists(struct allowedips_node *root)
--
drivers/net/wireguard/allowedips.c-71- push_rcu(stack, node->bit[1], &len);
drivers/net/wireguard/allowedips.c:72: if (rcu_access_pointer(node->peer))
drivers/net/wireguard/allowedips.c:73: list_del(&node->peer_list);
drivers/net/wireguard/allowedips.c-74- }
--
drivers/net/wireguard/allowedips.c=106=static struct allowedips_node *find_node(struct allowedips_node *trie, u8 bits,
--
drivers/net/wireguard/allowedips.c-111- while (node && prefix_matches(node, key, bits)) {
drivers/net/wireguard/allowedips.c:112: if (rcu_access_pointer(node->peer))
drivers/net/wireguard/allowedips.c-113- found = node;
--
drivers/net/wireguard/allowedips.c=122=static struct wg_peer *lookup(struct allowedips_node __rcu *root, u8 bits,
--
drivers/net/wireguard/allowedips.c-135- if (node) {
drivers/net/wireguard/allowedips.c:136: peer = wg_peer_get_maybe_zero(rcu_dereference_bh(node->peer));
drivers/net/wireguard/allowedips.c-137- if (!peer)
--
drivers/net/wireguard/allowedips.c=176=static int add(struct allowedips_node __rcu **trie, u8 bits, const u8 *key,
--
drivers/net/wireguard/allowedips.c-187- return -ENOMEM;
drivers/net/wireguard/allowedips.c:188: RCU_INIT_POINTER(node->peer, peer);
drivers/net/wireguard/allowedips.c:189: list_add_tail(&node->peer_list, &peer->allowedips_list);
drivers/net/wireguard/allowedips.c-190- copy_and_assign_cidr(node, key, cidr, bits);
--
drivers/net/wireguard/allowedips.c-194- if (node_placement(*trie, key, cidr, bits, &node, lock)) {
drivers/net/wireguard/allowedips.c:195: rcu_assign_pointer(node->peer, peer);
drivers/net/wireguard/allowedips.c:196: list_move_tail(&node->peer_list, &peer->allowedips_list);
drivers/net/wireguard/allowedips.c-197- return 0;
--
drivers/net/wireguard/allowedips.c-202- return -ENOMEM;
drivers/net/wireguard/allowedips.c:203: RCU_INIT_POINTER(newnode->peer, peer);
drivers/net/wireguard/allowedips.c:204: list_add_tail(&newnode->peer_list, &peer->allowedips_list);
drivers/net/wireguard/allowedips.c-205- copy_and_assign_cidr(newnode, key, cidr, bits);
--
drivers/net/wireguard/allowedips.c-230- if (unlikely(!node)) {
drivers/net/wireguard/allowedips.c:231: list_del(&newnode->peer_list);
drivers/net/wireguard/allowedips.c-232- kmem_cache_free(node_cache, newnode);
--
drivers/net/wireguard/allowedips.c-234- }
drivers/net/wireguard/allowedips.c:235: INIT_LIST_HEAD(&node->peer_list);
drivers/net/wireguard/allowedips.c-236- copy_and_assign_cidr(node, newnode->bits, cidr, bits);
--
drivers/net/wireguard/allowedips.c=247=static void remove_node(struct allowedips_node *node, struct mutex *lock)
--
drivers/net/wireguard/allowedips.c-251-
drivers/net/wireguard/allowedips.c:252: list_del_init(&node->peer_list);
drivers/net/wireguard/allowedips.c:253: RCU_INIT_POINTER(node->peer, NULL);
drivers/net/wireguard/allowedips.c-254- if (node->bit[0] && node->bit[1])
--
drivers/net/wireguard/allowedips.c-264- free_parent = !rcu_access_pointer(node->bit[0]) && !rcu_access_pointer(node->bit[1]) &&
drivers/net/wireguard/allowedips.c:265: (node->parent_bit_packed & 3) <= 1 && !rcu_access_pointer(parent->peer);
drivers/net/wireguard/allowedips.c-266- if (free_parent)
--
drivers/net/wireguard/allowedips.c=278=static int remove(struct allowedips_node __rcu **trie, u8 bits, const u8 *key,
--
drivers/net/wireguard/allowedips.c-285- if (!rcu_access_pointer(*trie) || !node_placement(*trie, key, cidr, bits, &node, lock) ||
drivers/net/wireguard/allowedips.c:286: peer != rcu_access_pointer(node->peer))
drivers/net/wireguard/allowedips.c-287- return 0;
--
drivers/net/wireguard/device.c=31=static int wg_open(struct net_device *dev)
--
drivers/net/wireguard/device.c-53- goto out;
drivers/net/wireguard/device.c:54: list_for_each_entry(peer, &wg->peer_list, peer_list) {
drivers/net/wireguard/device.c-55- wg_packet_send_staged_packets(peer);
--
drivers/net/wireguard/device.c=64=static int wg_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
--
drivers/net/wireguard/device.c-82- mutex_lock(&wg->device_update_lock);
drivers/net/wireguard/device.c:83: list_for_each_entry(peer, &wg->peer_list, peer_list) {
drivers/net/wireguard/device.c-84- timer_delete(&peer->timer_zero_key_material);
--
drivers/net/wireguard/device.c=97=static int wg_vm_notification(struct notifier_block *nb, unsigned long action, void *data)
--
drivers/net/wireguard/device.c-104- mutex_lock(&wg->device_update_lock);
drivers/net/wireguard/device.c:105: list_for_each_entry(peer, &wg->peer_list, peer_list)
drivers/net/wireguard/device.c-106- wg_noise_expire_current_peer_keypairs(peer);
--
drivers/net/wireguard/device.c=115=static int wg_stop(struct net_device *dev)
--
drivers/net/wireguard/device.c-121- mutex_lock(&wg->device_update_lock);
drivers/net/wireguard/device.c:122: list_for_each_entry(peer, &wg->peer_list, peer_list) {
drivers/net/wireguard/device.c-123- wg_packet_purge_staged_packets(peer);
--
drivers/net/wireguard/device.c=137=static netdev_tx_t wg_xmit(struct sk_buff *skb, struct net_device *dev)
--
drivers/net/wireguard/device.c-152-
drivers/net/wireguard/device.c:153: peer = wg_allowedips_lookup_dst(&wg->peer_allowedips, skb);
drivers/net/wireguard/device.c-154- if (unlikely(!peer)) {
--
drivers/net/wireguard/device.c=242=static void wg_destruct(struct net_device *dev)
--
drivers/net/wireguard/device.c-264- kvfree(wg->index_hashtable);
drivers/net/wireguard/device.c:265: kvfree(wg->peer_hashtable);
drivers/net/wireguard/device.c-266- mutex_unlock(&wg->device_update_lock);
--
drivers/net/wireguard/device.c=310=static int wg_newlink(struct net_device *dev,
--
drivers/net/wireguard/device.c-321- mutex_init(&wg->device_update_lock);
drivers/net/wireguard/device.c:322: wg_allowedips_init(&wg->peer_allowedips);
drivers/net/wireguard/device.c-323- wg_cookie_checker_init(&wg->cookie_checker, wg);
drivers/net/wireguard/device.c:324: INIT_LIST_HEAD(&wg->peer_list);
drivers/net/wireguard/device.c-325- wg->device_update_gen = 1;
drivers/net/wireguard/device.c-326-
drivers/net/wireguard/device.c:327: wg->peer_hashtable = wg_pubkey_hashtable_alloc();
drivers/net/wireguard/device.c:328: if (!wg->peer_hashtable)
drivers/net/wireguard/device.c-329- return ret;
--
drivers/net/wireguard/device.c-402-err_free_peer_hashtable:
drivers/net/wireguard/device.c:403: kvfree(wg->peer_hashtable);
drivers/net/wireguard/device.c-404- return ret;
--
drivers/net/wireguard/device.c=414=static void __net_exit wg_netns_exit_rtnl(struct net *net, struct list_head *dev_kill_list)
--
drivers/net/wireguard/device.c-425- wg_socket_reinit(wg, NULL, NULL);
drivers/net/wireguard/device.c:426: list_for_each_entry(peer, &wg->peer_list, peer_list)
drivers/net/wireguard/device.c-427- wg_socket_clear_peer_endpoint_src(peer);
--
drivers/net/wireguard/netlink.c=77=get_peer(struct wg_peer *peer, struct sk_buff *skb, struct dump_ctx *ctx)
--
drivers/net/wireguard/netlink.c-137- if (!ctx->allowedips_seq)
drivers/net/wireguard/netlink.c:138: ctx->allowedips_seq = ctx->wg->peer_allowedips.seq;
drivers/net/wireguard/netlink.c:139: else if (ctx->allowedips_seq != ctx->wg->peer_allowedips.seq)
drivers/net/wireguard/netlink.c-140- goto no_allowedips;
--
drivers/net/wireguard/netlink.c=181=int wg_get_device_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
--
drivers/net/wireguard/netlink.c-234- */
drivers/net/wireguard/netlink.c:235: if (list_empty(&wg->peer_list) ||
drivers/net/wireguard/netlink.c-236- (ctx->next_peer && ctx->next_peer->is_dead)) {
--
drivers/net/wireguard/netlink.c-239- }
drivers/net/wireguard/netlink.c:240: peer = list_prepare_entry(ctx->next_peer, &wg->peer_list, peer_list);
drivers/net/wireguard/netlink.c:241: list_for_each_entry_continue(peer, &wg->peer_list, peer_list) {
drivers/net/wireguard/netlink.c-242- if (get_peer(peer, skb, ctx)) {
--
drivers/net/wireguard/netlink.c=285=static int set_port(struct wg_device *wg, u16 port)
--
drivers/net/wireguard/netlink.c-290- return 0;
drivers/net/wireguard/netlink.c:291: list_for_each_entry(peer, &wg->peer_list, peer_list)
drivers/net/wireguard/netlink.c-292- wg_socket_clear_peer_endpoint_src(peer);
--
drivers/net/wireguard/netlink.c=300=static int set_allowedip(struct wg_peer *peer, struct nlattr **attrs)
--
drivers/net/wireguard/netlink.c-317- if (flags & WGALLOWEDIP_F_REMOVE_ME)
drivers/net/wireguard/netlink.c:318: ret = wg_allowedips_remove_v4(&peer->device->peer_allowedips,
drivers/net/wireguard/netlink.c-319- nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr,
--
drivers/net/wireguard/netlink.c-321- else
drivers/net/wireguard/netlink.c:322: ret = wg_allowedips_insert_v4(&peer->device->peer_allowedips,
drivers/net/wireguard/netlink.c-323- nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr,
--
drivers/net/wireguard/netlink.c-327- if (flags & WGALLOWEDIP_F_REMOVE_ME)
drivers/net/wireguard/netlink.c:328: ret = wg_allowedips_remove_v6(&peer->device->peer_allowedips,
drivers/net/wireguard/netlink.c-329- nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr,
--
drivers/net/wireguard/netlink.c-331- else
drivers/net/wireguard/netlink.c:332: ret = wg_allowedips_insert_v6(&peer->device->peer_allowedips,
drivers/net/wireguard/netlink.c-333- nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr,
--
drivers/net/wireguard/netlink.c=340=static int set_peer(struct wg_device *wg, struct nlattr **attrs)
--
drivers/net/wireguard/netlink.c-365-
drivers/net/wireguard/netlink.c:366: peer = wg_pubkey_hashtable_lookup(wg->peer_hashtable,
drivers/net/wireguard/netlink.c-367- nla_data(attrs[WGPEER_A_PUBLIC_KEY]));
--
drivers/net/wireguard/netlink.c-430- if (flags & WGPEER_F_REPLACE_ALLOWEDIPS)
drivers/net/wireguard/netlink.c:431: wg_allowedips_remove_by_peer(&wg->peer_allowedips, peer,
drivers/net/wireguard/netlink.c-432- &wg->device_update_lock);
--
drivers/net/wireguard/netlink.c=473=int wg_set_device_doit(struct sk_buff *skb, struct genl_info *info)
--
drivers/net/wireguard/netlink.c-505- wg->fwmark = nla_get_u32(info->attrs[WGDEVICE_A_FWMARK]);
drivers/net/wireguard/netlink.c:506: list_for_each_entry(peer, &wg->peer_list, peer_list)
drivers/net/wireguard/netlink.c-507- wg_socket_clear_peer_endpoint_src(peer);
--
drivers/net/wireguard/netlink.c-535- if (curve25519_generate_public(public_key, private_key)) {
drivers/net/wireguard/netlink.c:536: peer = wg_pubkey_hashtable_lookup(wg->peer_hashtable,
drivers/net/wireguard/netlink.c-537- public_key);
--
drivers/net/wireguard/netlink.c-549- wg_cookie_checker_precompute_device_keys(&wg->cookie_checker);
drivers/net/wireguard/netlink.c:550: list_for_each_entry_safe(peer, temp, &wg->peer_list, peer_list) {
drivers/net/wireguard/netlink.c-551- wg_noise_precompute_static_static(peer);
--
drivers/net/wireguard/noise.c=59=void wg_noise_handshake_init(struct noise_handshake *handshake,
--
drivers/net/wireguard/noise.c-67- handshake->entry.type = INDEX_HASHTABLE_HANDSHAKE;
drivers/net/wireguard/noise.c:68: handshake->entry.peer = peer;
drivers/net/wireguard/noise.c-69- memcpy(handshake->remote_static, peer_public_key, NOISE_PUBLIC_KEY_LEN);
--
drivers/net/wireguard/noise.c=88=void wg_noise_handshake_clear(struct noise_handshake *handshake)
--
drivers/net/wireguard/noise.c-91- wg_index_hashtable_remove(
drivers/net/wireguard/noise.c:92: handshake->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-93- &handshake->entry);
--
drivers/net/wireguard/noise.c=98=static struct noise_keypair *keypair_create(struct wg_peer *peer)
--
drivers/net/wireguard/noise.c-106- keypair->entry.type = INDEX_HASHTABLE_KEYPAIR;
]
|
| 23/2 |
2026/11/17 14:06 |
llm |
expert |
0m
Model:
Tokens:
input: 21185
output: 37
thoughts: 45
Thoughts: Here's my analysis of the provided snippet, as if it were my thought process:
**Diving into the WireGuard Noise Protocol Implementation**
Alright, let's get down to it. I'm focusing on the noise.c implementation within the WireGuard driver. The key line that immediately jumps out at me is `keypair->entry.peer = peer;`. This suggests that the code is linking a `peer` structure to a specific `keypair` entry. This is fundamental to WireGuard's operation, associating cryptographic keys with the remote endpoint. I'll need to confirm exactly what this `peer` object represents in the broader context.
To understand the full implication of this assignment, I'll need to examine the surrounding code. Specifically, lines 95 to 130 of `drivers/net/wireguard/noise.c` are what I need to parse. I'll be looking for how `keypair` and `peer` are defined and initialized within that block, any encryption or authentication setup within the key exchange, the intended association here, and any checks and balances involved in this `peer` association. I'm going to look for any obvious race conditions that might exist.
Let's begin.
|
| 24/2 |
2026/11/17 14:06 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/noise.c FirstLine:95 LineCount:40]
Results: map[Contents: 95: up_write(&handshake->lock);
96: }
97:
98: static struct noise_keypair *keypair_create(struct wg_peer *peer)
99: {
100: struct noise_keypair *keypair = kzalloc_obj(*keypair);
101:
102: if (unlikely(!keypair))
103: return NULL;
104: spin_lock_init(&keypair->receiving_counter.lock);
105: keypair->internal_id = atomic64_inc_return(&keypair_counter);
106: keypair->entry.type = INDEX_HASHTABLE_KEYPAIR;
107: keypair->entry.peer = peer;
108: kref_init(&keypair->refcount);
109: return keypair;
110: }
111:
112: static void keypair_free_rcu(struct rcu_head *rcu)
113: {
114: kfree_sensitive(container_of(rcu, struct noise_keypair, rcu));
115: }
116:
117: static void keypair_free_kref(struct kref *kref)
118: {
119: struct noise_keypair *keypair =
120: container_of(kref, struct noise_keypair, refcount);
121:
122: net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
123: keypair->entry.peer->device->dev->name,
124: keypair->internal_id,
125: keypair->entry.peer->internal_id);
126: wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
127: &keypair->entry);
128: call_rcu(&keypair->rcu, keypair_free_rcu);
129: }
130:
131: void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now)
132: {
133: if (unlikely(!keypair))
134: return;
]
|
| 25/2 |
2026/11/17 14:06 |
llm |
expert |
0m
Model:
Tokens:
input: 22178
output: 30
thoughts: 1448
Thoughts: **A Deep Dive into a Potential Race Condition in the WireGuard Code**
Okay, so I'm looking at this WireGuard code, specifically how `keypair` and `handshake` entries are handled within the index hashtable. I see that when a `keypair` is created, it's linked to a `peer`. Similarly, `handshake` entries are also associated with a `peer`. Now, I'm focusing on the `wg_index_hashtable_lookup` function. This function's role is pretty clear: find an entry in the hashtable based on a type mask and index, and importantly, it attempts to return a *strong reference* to the `peer`.
The confusing bit starts in the `wg_index_hashtable_lookup` function, specifically with this pattern: `entry->peer = wg_peer_get_maybe_zero(entry->peer);` My initial thought was, why are we re-assigning `entry->peer`? The function *already* takes a `struct wg_peer **peer` as an out parameter to *return* the peer. The comment explicitly states that the function returns a strong reference.
Then I realized, it's calling `wg_peer_get_maybe_zero` which is a critical function! It attempts to increment the reference count of the `peer` using `kref_get_unless_zero`. If the reference count is already zero, indicating the peer is dying, this function returns NULL. The code then does: `entry->peer = NULL`.
The problem is, `wg_index_hashtable_lookup` then calls `wg_peer_get_maybe_zero` and reassigns `entry->peer`! The author probably intended to increment the peer's refcount by passing the `peer` parameter as the out parameter, but instead, they did `entry->peer = wg_peer_get_maybe_zero`.
This is where the alarm bells go off. If `kref_get_unless_zero` fails (peer is dying), `wg_peer_get_maybe_zero` returns NULL, and `entry->peer` is *set* to NULL. But later on, `keypair_free_kref` is going to dereference `keypair->entry.peer`: and if `entry->peer` is NULL due to this potential race condition, it's going to lead to a *massive* crash, a null pointer dereference! I mean, look at this: `keypair->entry.peer->device->dev->name`... `keypair->entry.peer->internal_id`... `keypair->entry.peer->device->index_hashtable` - all of these dereferences will cause a crash, if the peer has been deallocated before the keypair is freed. This potentially happens in a multi-threaded system.
So, I need to investigate now: when and how is `wg_index_hashtable_lookup` called? What's the exact flow of execution when a peer's reference count hits zero? Is this an active bug? I need to check the git history to see if there's been any fix for `entry->peer = wg_peer_get_maybe_zero` or some workarounds. This looks like a potentially serious issue.
|
| 26/2 |
2026/11/17 14:07 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:entry->peer = wg_peer_get_maybe_zero]
Results:
|
| 27/2 |
2026/11/17 14:17 |
llm |
expert |
0m
Model:
Tokens:
input: 24402
output: 43
thoughts: 15
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Adding a Path Prefix for WireGuard Drivers**
Alright, I'm thinking about how we're structuring this. We're dealing with the WireGuard driver, specifically, and its location within our overall directory structure. My initial instinct is to introduce a `PathPrefix` directive. It's a clean way to ensure that we're properly scoping the drivers, to ensure there are no collisions with drivers for other features.
My thinking is that the drivers should go under a dedicated directory, like "drivers," then a further subdirectory for "net," and then finally a specific subdirectory for "wireguard." Therefore, I want to add `PathPrefix="drivers/net/wireguard/"`. This immediately tells us where we can find these components, and provides a clear separation. I like this approach; it makes maintenance easier down the line and keeps things nice and organized.
|
| 28/2 |
2026/11/17 14:17 |
tool |
git-log |
0m
Args: map[CodeRegexp:entry->peer = wg_peer_get_maybe_zero PathPrefix:drivers/net/wireguard/]
Results: map[Output:e7096c131e51 net: WireGuard secure network tunnel
]
|
| 29/2 |
2026/11/17 14:17 |
llm |
expert |
0m
Model:
Tokens:
input: 24699
output: 32
thoughts: 21
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Investigating WireGuard's Data Structures**
Alright, let's dive into some specifics within the WireGuard codebase. My immediate thought is to zero in on how they're handling peer lookups and indexing. I want to see how efficiently they're managing the connection table. Specifically, I'm going to start by searching the commit messages for instances of `index_hashtable` and `peerlookup`. Those terms likely point to the core data structures and access methods involved in rapidly finding and managing peer information. That's where the critical performance bottlenecks would likely show up, if any exist. This should give me a solid starting point for understanding their design choices and any potential optimizations.
|
| 30/2 |
2026/11/17 14:18 |
tool |
git-log |
0m
Args: map[Count:20 PathPrefix:drivers/net/wireguard/peerlookup.c]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
6147f7b1e90f wireguard: peerlookup: take lock before checking hash in replace operation
e7096c131e51 net: WireGuard secure network tunnel
]
|
| 31/2 |
2026/11/17 14:18 |
llm |
expert |
0m
Model:
Tokens:
input: 25036
output: 38
thoughts: 46
Thoughts: Here's my summary, as though I'm thinking through this process:
**WireGuard Peer Lookup - Digging into the History**
Okay, so `drivers/net/wireguard/peerlookup.c`...that's a pretty specific file, and four commits? That feels awfully light for something potentially critical in a network driver. I'm immediately suspicious. Let's dig deeper. The fact that the code is so sparse is a clear indication that it does a single, very specific thing, and it does it well.
I need to understand *how* it's doing what it does and, more importantly, *why* any changes might have been made to it. Let's see if I can understand how this part of the code works.
I'm going to run a `git log -S "entry->peer" drivers/net/wireguard/`. The "entry->peer" string is likely a key variable name or structure member related to peer lookup within the WireGuard driver. By searching for changes that introduce or modify this string, I can get a clearer picture of how it's used and what the development history around it actually *is*. This will tell me what's gone on here. I expect it's very specific, considering the small amount of work, but I'm curious to see.
|
| 32/2 |
2026/11/17 14:19 |
tool |
git-log |
0m
Args: map[CodeRegexp:entry->peer Count:10 PathPrefix:drivers/net/wireguard/]
Results: map[Output:e7096c131e51 net: WireGuard secure network tunnel
]
|
| 33/2 |
2026/11/17 14:19 |
llm |
expert |
0m
Model:
Tokens:
input: 25434
output: 39
thoughts: 1671
Thoughts: **Analyzing the WireGuard KCSAN Report: A Deep Dive**
Okay, let's break this down. This KCSAN report has flagged a data race, and we need to understand *why*. The key here is the address `0xffff88811b7fb000`. Both Thread 1 and Thread 2 are interacting with it. Thread 1 is reading from it, and Thread 2 is writing to it.
First, the address itself. I recognize this; it's `entry->peer`. Specifically, it's the `wg_peer` pointer within a `noise_keypair` entry. This becomes clear by tracing through the `struct` definitions: `noise_keypair` contains an `index_hashtable_entry`, and that entry holds the `wg_peer` pointer. Importantly, `peer` is at offset 0 within `index_hashtable_entry`, which itself is at offset 0 of `noise_keypair`, so the address makes sense. It's an 8-byte aligned slab allocation, ending in `000`.
Now, let's dissect the threads and their interactions with this address. Thread 1 is the "reader." It's inside `wg_packet_decrypt_worker`, consuming data from a ring buffer. Inside, `wg_queue_enqueue_per_peer_rx` is called. Critically, it calls `PACKET_PEER(skb)` which expands to `PACKET_CB(skb)->keypair->entry.peer`, effectively reading the `peer` pointer. This pointer is then passed to `wg_peer_get` which increments its reference count, and then the function returns the value.
Thread 2 is the "writer" which is an interrupt. It's handling a received packet and ends up in `wg_packet_consume_data`. It retrieves a `keypair` by calling `wg_index_hashtable_lookup` via an index. The code then executes `entry->peer = wg_peer_get_maybe_zero(entry->peer);`
Okay, this is where it gets interesting. Both threads are touching `keypair->entry.peer`, and the key here is that `wg_index_hashtable_lookup` seems to be *writing* to `entry->peer`. This immediately jumps out at me as a potential problem. A lookup function is supposed to *look up* not *modify*. In my experience, hash table lookup functions should never mutate the entries they find. The caller expects the entry to be as it was when inserted.
Why would the `lookup` function need to write to the entry? Does `entry->peer` ever need to change *after* the `noise_keypair` is initialized? I would need to analyze the rest of the codebase to see if this is intended, or a bug. Let's grep for `entry->peer` and `->entry.peer` to see where else it's modified and determine if this write operation is justified or if this is, indeed, the root cause of the data race.
|
| 34/2 |
2026/11/17 14:20 |
tool |
grepper |
0m
Args: map[Expression:(entry\->peer|\->entry\.peer) PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/noise.c=59=void wg_noise_handshake_init(struct noise_handshake *handshake,
--
drivers/net/wireguard/noise.c-67- handshake->entry.type = INDEX_HASHTABLE_HANDSHAKE;
drivers/net/wireguard/noise.c:68: handshake->entry.peer = peer;
drivers/net/wireguard/noise.c-69- memcpy(handshake->remote_static, peer_public_key, NOISE_PUBLIC_KEY_LEN);
--
drivers/net/wireguard/noise.c=88=void wg_noise_handshake_clear(struct noise_handshake *handshake)
--
drivers/net/wireguard/noise.c-91- wg_index_hashtable_remove(
drivers/net/wireguard/noise.c:92: handshake->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-93- &handshake->entry);
--
drivers/net/wireguard/noise.c=98=static struct noise_keypair *keypair_create(struct wg_peer *peer)
--
drivers/net/wireguard/noise.c-106- keypair->entry.type = INDEX_HASHTABLE_KEYPAIR;
drivers/net/wireguard/noise.c:107: keypair->entry.peer = peer;
drivers/net/wireguard/noise.c-108- kref_init(&keypair->refcount);
--
drivers/net/wireguard/noise.c=117=static void keypair_free_kref(struct kref *kref)
--
drivers/net/wireguard/noise.c-122- net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
drivers/net/wireguard/noise.c:123: keypair->entry.peer->device->dev->name,
drivers/net/wireguard/noise.c-124- keypair->internal_id,
drivers/net/wireguard/noise.c:125: keypair->entry.peer->internal_id);
drivers/net/wireguard/noise.c:126: wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-127- &keypair->entry);
--
drivers/net/wireguard/noise.c=131=void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now)
--
drivers/net/wireguard/noise.c-136- wg_index_hashtable_remove(
drivers/net/wireguard/noise.c:137: keypair->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-138- &keypair->entry);
--
drivers/net/wireguard/noise.c=517=wg_noise_handshake_create_initiation(struct message_handshake_initiation *dst,
--
drivers/net/wireguard/noise.c-569- dst->sender_index = wg_index_hashtable_insert(
drivers/net/wireguard/noise.c:570: handshake->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-571- &handshake->entry);
--
drivers/net/wireguard/noise.c=667=bool wg_noise_handshake_create_response(struct message_handshake_response *dst,
--
drivers/net/wireguard/noise.c-713- dst->sender_index = wg_index_hashtable_insert(
drivers/net/wireguard/noise.c:714: handshake->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-715- &handshake->entry);
--
drivers/net/wireguard/noise.c=815=bool wg_noise_handshake_begin_session(struct noise_handshake *handshake,
--
drivers/net/wireguard/noise.c-825-
drivers/net/wireguard/noise.c:826: new_keypair = keypair_create(handshake->entry.peer);
drivers/net/wireguard/noise.c-827- if (!new_keypair)
--
drivers/net/wireguard/noise.c-845- net_dbg_ratelimited("%s: Keypair %llu created for peer %llu\n",
drivers/net/wireguard/noise.c:846: handshake->entry.peer->device->dev->name,
drivers/net/wireguard/noise.c-847- new_keypair->internal_id,
drivers/net/wireguard/noise.c:848: handshake->entry.peer->internal_id);
drivers/net/wireguard/noise.c-849- ret = wg_index_hashtable_replace(
drivers/net/wireguard/noise.c:850: handshake->entry.peer->device->index_hashtable,
drivers/net/wireguard/noise.c-851- &handshake->entry, &new_keypair->entry);
--
drivers/net/wireguard/peerlookup.c=192=void wg_index_hashtable_remove(struct index_hashtable *table,
--
drivers/net/wireguard/peerlookup.c-199-
drivers/net/wireguard/peerlookup.c:200:/* Returns a strong reference to a entry->peer */
drivers/net/wireguard/peerlookup.c-201-struct index_hashtable_entry *
drivers/net/wireguard/peerlookup.c=202=wg_index_hashtable_lookup(struct index_hashtable *table,
--
drivers/net/wireguard/peerlookup.c-217- if (likely(entry)) {
drivers/net/wireguard/peerlookup.c:218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
drivers/net/wireguard/peerlookup.c:219: if (likely(entry->peer))
drivers/net/wireguard/peerlookup.c:220: *peer = entry->peer;
drivers/net/wireguard/peerlookup.c-221- else
--
drivers/net/wireguard/queueing.h=59=struct packet_cb {
--
drivers/net/wireguard/queueing.h-67-#define PACKET_CB(skb) ((struct packet_cb *)((skb)->cb))
drivers/net/wireguard/queueing.h:68:#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
drivers/net/wireguard/queueing.h-69-
--
drivers/net/wireguard/send.c=342=void wg_packet_send_staged_packets(struct wg_peer *peer)
--
drivers/net/wireguard/send.c-385- packets.prev->next = NULL;
drivers/net/wireguard/send.c:386: wg_peer_get(keypair->entry.peer);
drivers/net/wireguard/send.c-387- PACKET_CB(packets.next)->keypair = keypair;
]
|
| 35/2 |
2026/11/17 14:20 |
llm |
expert |
1m
Model:
Tokens:
input: 29660
output: 38
thoughts: 767
Thoughts: **Analyzing Potential Race Conditions in WireGuard's Peer Management**
Okay, so I've been digging into this `noise.c` code, and something's really bugging me about the way `entry->peer` is being handled. I see it's assumed to be immutable and directly pointing to the `wg_peer` struct all over the place β lines 68, 92, 107, 123, 125, 126, 137, 570, 714, 826, 846, 848, and 850, to be precise.
Then I stumbled upon this function `wg_index_hashtable_lookup`. The comment claims it returns a strong reference to `entry->peer`, which makes sense in the context of reference counting. But then I looked at the code itself: `entry->peer = wg_peer_get_maybe_zero(entry->peer);` Wait a minute! The *code* actually overwrites `entry->peer`! This is a classic typo situation. I'm pretty sure what the author meant to write was something like:
if (likely(entry)) {
*peer = wg_peer_get_maybe_zero(entry->peer);
if (!*peer)
entry = NULL;
}
Instead of:
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
This overwriting is a serious issue. If `wg_peer_get_maybe_zero` returns non-NULL (same pointer), no immediate problem; however, if it returns NULL, the value of `entry->peer` is overwritten, possibly leading to use-after-free bugs.
But hold on, let's explore this further. Can `wg_peer_get_maybe_zero` actually *return* NULL? Yes, it can, when `kref_get_unless_zero(&peer->refcount)` fails. And when does `peer->refcount` hit zero? That's when a peer is being removed or destroyed! So, this potential for overwriting `entry->peer` with NULL looks like it could introduce a race condition during peer removal or destruction. I need to investigate `drivers/net/wireguard/peer.c` now to understand the precise lifecycle of the peer's refcount and exactly how it is decremented to zero.
|
| 36/2 |
2026/11/17 14:21 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.c FirstLine:180 LineCount:50]
Results: map[Contents: 180: }
181: synchronize_net();
182: list_for_each_entry_safe(peer, temp, &dead_peers, peer_list)
183: peer_remove_after_dead(peer);
184: }
185:
186: static void rcu_release(struct rcu_head *rcu)
187: {
188: struct wg_peer *peer = container_of(rcu, struct wg_peer, rcu);
189:
190: dst_cache_destroy(&peer->endpoint_cache);
191: WARN_ON(wg_prev_queue_peek(&peer->tx_queue) || wg_prev_queue_peek(&peer->rx_queue));
192:
193: /* The final zeroing takes care of clearing any remaining handshake key
194: * material and other potentially sensitive information.
195: */
196: memzero_explicit(peer, sizeof(*peer));
197: kmem_cache_free(peer_cache, peer);
198: }
199:
200: static void kref_release(struct kref *refcount)
201: {
202: struct wg_peer *peer = container_of(refcount, struct wg_peer, refcount);
203:
204: pr_debug("%s: Peer %llu (%pISpfsc) destroyed\n",
205: peer->device->dev->name, peer->internal_id,
206: &peer->endpoint.addr);
207:
208: /* Remove ourself from dynamic runtime lookup structures, now that the
209: * last reference is gone.
210: */
211: wg_index_hashtable_remove(peer->device->index_hashtable,
212: &peer->handshake.entry);
213:
214: /* Remove any lingering packets that didn't have a chance to be
215: * transmitted.
216: */
217: wg_packet_purge_staged_packets(peer);
218:
219: /* Free the memory used. */
220: call_rcu(&peer->rcu, rcu_release);
221: }
222:
223: void wg_peer_put(struct wg_peer *peer)
224: {
225: if (unlikely(!peer))
226: return;
227: kref_put(&peer->refcount, kref_release);
228: }
229:
]
|
| 37/2 |
2026/11/17 14:21 |
llm |
expert |
1m
Model:
Tokens:
input: 31782
output: 44
thoughts: 85
Thoughts: Okay, let's break this down.
**Investigating Potential Keypair Leakage in WireGuard Code**
Right, so I'm looking at `peer.c`, specifically the function `kref_release`. My immediate thought is about the handshake entry. I know `kref_release` takes care of removing `peer->handshake.entry` from `peer->device->index_hashtable`. But that raises a question, a pretty critical one: what happens to the keypairs *associated* with that peer when the handshake entry goes away? Are they also being properly cleaned up?
I need to make sure keypairs are being handled correctly when a peer is released. Therefore, I need to trace the code to understand where the keypairs are managed.
My next step is clear. I need to track down the calls to `keypair_free_kref`, `wg_noise_keypair_put`, or any other function that's responsible for the keypair removal. I need to be sure that these functions are actually invoked when they should be. That's the key: verify that they're all released without any leaks.
|
| 38/2 |
2026/11/17 14:23 |
tool |
grepper |
0m
Args: map[Expression:keypair_free_kref|wg_noise_keypair_put PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/noise.c=112=static void keypair_free_rcu(struct rcu_head *rcu)
--
drivers/net/wireguard/noise.c-116-
drivers/net/wireguard/noise.c:117:static void keypair_free_kref(struct kref *kref)
drivers/net/wireguard/noise.c-118-{
--
drivers/net/wireguard/noise.c-130-
drivers/net/wireguard/noise.c:131:void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now)
drivers/net/wireguard/noise.c-132-{
--
drivers/net/wireguard/noise.c-138- &keypair->entry);
drivers/net/wireguard/noise.c:139: kref_put(&keypair->refcount, keypair_free_kref);
drivers/net/wireguard/noise.c-140-}
--
drivers/net/wireguard/noise.c=151=void wg_noise_keypairs_clear(struct noise_keypairs *keypairs)
--
drivers/net/wireguard/noise.c-163- RCU_INIT_POINTER(keypairs->next_keypair, NULL);
drivers/net/wireguard/noise.c:164: wg_noise_keypair_put(old, true);
drivers/net/wireguard/noise.c-165-
--
drivers/net/wireguard/noise.c-168- RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
drivers/net/wireguard/noise.c:169: wg_noise_keypair_put(old, true);
drivers/net/wireguard/noise.c-170-
--
drivers/net/wireguard/noise.c-173- RCU_INIT_POINTER(keypairs->current_keypair, NULL);
drivers/net/wireguard/noise.c:174: wg_noise_keypair_put(old, true);
drivers/net/wireguard/noise.c-175-
--
drivers/net/wireguard/noise.c=198=static void add_new_keypair(struct noise_keypairs *keypairs,
--
drivers/net/wireguard/noise.c-227- next_keypair);
drivers/net/wireguard/noise.c:228: wg_noise_keypair_put(current_keypair, true);
drivers/net/wireguard/noise.c-229- } else /* If there wasn't an existing next keypair, we replace
--
drivers/net/wireguard/noise.c-236- */
drivers/net/wireguard/noise.c:237: wg_noise_keypair_put(previous_keypair, true);
drivers/net/wireguard/noise.c-238- rcu_assign_pointer(keypairs->current_keypair, new_keypair);
--
drivers/net/wireguard/noise.c-245- rcu_assign_pointer(keypairs->next_keypair, new_keypair);
drivers/net/wireguard/noise.c:246: wg_noise_keypair_put(next_keypair, true);
drivers/net/wireguard/noise.c-247- RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
drivers/net/wireguard/noise.c:248: wg_noise_keypair_put(previous_keypair, true);
drivers/net/wireguard/noise.c-249- }
--
drivers/net/wireguard/noise.c=253=bool wg_noise_received_with_keypair(struct noise_keypairs *keypairs,
--
drivers/net/wireguard/noise.c-284- lockdep_is_held(&keypairs->keypair_update_lock)));
drivers/net/wireguard/noise.c:285: wg_noise_keypair_put(old_keypair, true);
drivers/net/wireguard/noise.c-286- rcu_assign_pointer(keypairs->current_keypair, received_keypair);
--
drivers/net/wireguard/noise.h=101=static inline void wg_noise_reset_last_sent_handshake(atomic64_t *handshake_ns)
--
drivers/net/wireguard/noise.h-106-
drivers/net/wireguard/noise.h:107:void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now);
drivers/net/wireguard/noise.h-108-struct noise_keypair *wg_noise_keypair_get(struct noise_keypair *keypair);
--
drivers/net/wireguard/receive.c=438=int wg_packet_rx_poll(struct napi_struct *napi, int budget)
--
drivers/net/wireguard/receive.c-477-next:
drivers/net/wireguard/receive.c:478: wg_noise_keypair_put(keypair, false);
drivers/net/wireguard/receive.c-479- wg_peer_put(peer);
--
drivers/net/wireguard/receive.c=509=static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb)
--
drivers/net/wireguard/receive.c-534-err:
drivers/net/wireguard/receive.c:535: wg_noise_keypair_put(PACKET_CB(skb)->keypair, false);
drivers/net/wireguard/receive.c-536-err_keypair:
--
drivers/net/wireguard/send.c=262=void wg_packet_tx_worker(struct work_struct *work)
--
drivers/net/wireguard/send.c-279-
drivers/net/wireguard/send.c:280: wg_noise_keypair_put(keypair, false);
drivers/net/wireguard/send.c-281- wg_peer_put(peer);
--
drivers/net/wireguard/send.c=311=static void wg_packet_create_data(struct wg_peer *peer, struct sk_buff *first)
--
drivers/net/wireguard/send.c-327- return;
drivers/net/wireguard/send.c:328: wg_noise_keypair_put(PACKET_CB(first)->keypair, false);
drivers/net/wireguard/send.c-329- wg_peer_put(peer);
--
drivers/net/wireguard/send.c=342=void wg_packet_send_staged_packets(struct wg_peer *peer)
--
drivers/net/wireguard/send.c-393-out_nokey:
drivers/net/wireguard/send.c:394: wg_noise_keypair_put(keypair, false);
drivers/net/wireguard/send.c-395-
]
|
| 39/2 |
2026/11/17 14:23 |
llm |
expert |
1m
Model:
Tokens:
input: 33946
output: 38
thoughts: 55
Thoughts: Okay, let's dive into this `peer_remove_after_dead` situation. I need to understand the implications of a peer being freed or removed within this WireGuard context. My first step is to check the code that handles this specific scenario β `drivers/net/wireguard/peer.c`, specifically lines 140 through 185. I'll read through that section carefully to grasp what happens under the hood when a peer is declared dead and subsequently removed. I'm looking for the nitty-gritty details; how resources are cleaned up, what data structures are modified, and what potential side effects I need to be aware of. I'm assuming there's some sort of critical section or locking to consider, and the interaction with other parts of the WireGuard kernel module is paramount. My goal here is to build a mental map of this removal process and identify any potential pitfalls.
|
| 40/2 |
2026/11/17 14:24 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.c FirstLine:140 LineCount:45]
Results: map[Contents: 140: * all existing keypairs and no more can be created; we won't have new
141: * references in (3) eventually, because we're removed from the pubkey
142: * hash table, which allows for a maximum of one handshake response,
143: * via the still-uncleared index hashtable entry, but not more than one,
144: * and in wg_cookie_message_consume, the lookup eventually gets a peer
145: * with a refcount of zero, so no new reference is taken.
146: */
147:
148: --peer->device->num_peers;
149: wg_peer_put(peer);
150: }
151:
152: /* We have a separate "remove" function make sure that all active places where
153: * a peer is currently operating will eventually come to an end and not pass
154: * their reference onto another context.
155: */
156: void wg_peer_remove(struct wg_peer *peer)
157: {
158: if (unlikely(!peer))
159: return;
160: lockdep_assert_held(&peer->device->device_update_lock);
161:
162: peer_make_dead(peer);
163: synchronize_net();
164: peer_remove_after_dead(peer);
165: }
166:
167: void wg_peer_remove_all(struct wg_device *wg)
168: {
169: struct wg_peer *peer, *temp;
170: LIST_HEAD(dead_peers);
171:
172: lockdep_assert_held(&wg->device_update_lock);
173:
174: /* Avoid having to traverse individually for each one. */
175: wg_allowedips_free(&wg->peer_allowedips, &wg->device_update_lock);
176:
177: list_for_each_entry_safe(peer, temp, &wg->peer_list, peer_list) {
178: peer_make_dead(peer);
179: list_add_tail(&peer->peer_list, &dead_peers);
180: }
181: synchronize_net();
182: list_for_each_entry_safe(peer, temp, &dead_peers, peer_list)
183: peer_remove_after_dead(peer);
184: }
]
|
| 41/2 |
2026/11/17 14:24 |
llm |
expert |
0m
Model:
Tokens:
input: 34954
output: 37
thoughts: 26
Thoughts: Okay, let's dive into this. I need to get a handle on the interaction between peers in WireGuard, so reading a chunk of `drivers/net/wireguard/peer.c` is the logical next step. Specifically, I'm thinking lines 90-140 should give me a good initial view of how the peer management works at a low level. I'm expecting to see data structure definitions, likely function prototypes related to peer creation, destruction, or perhaps how the kernel module interacts with the peer context. I'll be looking for any hints on how the cryptographic keys are managed and how the handshake process is initiated or monitored from the kernel side. I'm also very interested in any mutexes or locking mechanisms employed to ensure thread-safety when multiple threads or processes try to access or modify peer data. From there, I'll be looking for how the data structures are initialized, and if there is a constructor and destructor in place.
|
| 42/2 |
2026/11/17 14:25 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.c FirstLine:90 LineCount:50]
Results: map[Contents: 90:
91: /* The caller must now synchronize_net() for this to take effect. */
92: }
93:
94: static void peer_remove_after_dead(struct wg_peer *peer)
95: {
96: WARN_ON(!peer->is_dead);
97:
98: /* No more keypairs can be created for this peer, since is_dead protects
99: * add_new_keypair, so we can now destroy existing ones.
100: */
101: wg_noise_keypairs_clear(&peer->keypairs);
102:
103: /* Destroy all ongoing timers that were in-flight at the beginning of
104: * this function.
105: */
106: wg_timers_stop(peer);
107:
108: /* The transition between packet encryption/decryption queues isn't
109: * guarded by is_dead, but each reference's life is strictly bounded by
110: * two generations: once for parallel crypto and once for serial
111: * ingestion, so we can simply flush twice, and be sure that we no
112: * longer have references inside these queues.
113: */
114:
115: /* a) For encrypt/decrypt. */
116: flush_workqueue(peer->device->packet_crypt_wq);
117: /* b.1) For send (but not receive, since that's napi). */
118: flush_workqueue(peer->device->packet_crypt_wq);
119: /* b.2.1) For receive (but not send, since that's wq). */
120: napi_disable(&peer->napi);
121: /* b.2.1) It's now safe to remove the napi struct, which must be done
122: * here from process context.
123: */
124: netif_napi_del(&peer->napi);
125:
126: /* Ensure any workstructs we own (like transmit_handshake_work or
127: * clear_peer_work) no longer are in use.
128: */
129: flush_workqueue(peer->device->handshake_send_wq);
130:
131: /* After the above flushes, a peer might still be active in a few
132: * different contexts: 1) from xmit(), before hitting is_dead and
133: * returning, 2) from wg_packet_consume_data(), before hitting is_dead
134: * and returning, 3) from wg_receive_handshake_packet() after a point
135: * where it has processed an incoming handshake packet, but where
136: * all calls to pass it off to timers fails because of is_dead. We won't
137: * have new references in (1) eventually, because we're removed from
138: * allowedips; we won't have new references in (2) eventually, because
139: * wg_index_hashtable_lookup will always return NULL, since we removed
]
|
| 43/2 |
2026/11/17 14:25 |
llm |
expert |
0m
Model:
Tokens:
input: 36092
output: 49
thoughts: 148
Thoughts: **Analyzing Potential Reference Leak in `peer.c`**
Okay, let's dive in. I'm focusing on lines 138-146 in `peer.c`, specifically the part about how we *won't* have new references in scenario (2) eventually. The key seems to be the fact that `wg_index_hashtable_lookup` will always return NULL. That's because we've removed all existing keypairs, and no new ones can be created. This leads to a situation where, within `wg_cookie_message_consume`, the lookup eventually results in a peer with a refcount of zero, so no new reference is taken. Got it. But hold on, the critical function here is `wg_cookie_message_consume`, right? It *calls* `wg_index_hashtable_lookup`. So, the relationship is `wg_cookie_message_consume` -> `wg_index_hashtable_lookup`. Now, to get a better handle on this, I need to understand all the points in the code where `wg_index_hashtable_lookup` is actually invoked. That will give me a comprehensive picture of how this lookup function is used, and more importantly, how the potential leak could be triggered. Let's find all the callers of `wg_index_hashtable_lookup` and trace the code paths.
|
| 44/2 |
2026/11/17 14:26 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.c IncludeSnippetLines:5 Name:wg_index_hashtable_lookup]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_cookie_message_consume SourceFile:drivers/net/wireguard/cookie.c SourceLine:205 SourceSnippet: 200: {
201: struct wg_peer *peer = NULL;
202: u8 cookie[COOKIE_LEN];
203: bool ret;
204:
205: if (unlikely(!wg_index_hashtable_lookup(wg->index_hashtable,
206: INDEX_HASHTABLE_HANDSHAKE |
207: INDEX_HASHTABLE_KEYPAIR,
208: src->receiver_index, &peer)))
209: return;
210:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_consume_response SourceFile:drivers/net/wireguard/noise.c SourceLine:746 SourceSnippet: 741: down_read(&wg->static_identity.lock);
742:
743: if (unlikely(!wg->static_identity.has_identity))
744: goto out;
745:
746: handshake = (struct noise_handshake *)wg_index_hashtable_lookup(
747: wg->index_hashtable, INDEX_HASHTABLE_HANDSHAKE,
748: src->receiver_index, &peer);
749: if (unlikely(!handshake))
750: goto out;
751:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_consume_data SourceFile:drivers/net/wireguard/receive.c SourceLine:517 SourceSnippet: 512: struct wg_peer *peer = NULL;
513: int ret;
514:
515: rcu_read_lock_bh();
516: PACKET_CB(skb)->keypair =
517: (struct noise_keypair *)wg_index_hashtable_lookup(
518: wg->index_hashtable, INDEX_HASHTABLE_KEYPAIR, idx,
519: &peer);
520: if (unlikely(!wg_noise_keypair_get(PACKET_CB(skb)->keypair)))
521: goto err_keypair;
522:
]] TruncatedOutput:false]
|
| 45/2 |
2026/11/17 14:26 |
llm |
expert |
1m
Model:
Tokens:
input: 37274
output: 175
thoughts: 6467
Thoughts: **A Deep Dive into a Potential Race Condition and Null Pointer Dereference in WireGuard's Peer Lookup**
Okay, so I've been tracing through the `wg_index_hashtable_lookup` function in WireGuard, and I've found something that's making me a bit uneasy. It seems there's a potential race condition and a possible null pointer dereference lurking in the code, and I've got to break this down thoroughly.
It all starts with how `wg_index_hashtable_lookup` is used. There are three primary callers: `wg_cookie_message_consume`, `wg_noise_handshake_consume_response`, and `wg_packet_consume_data`. All three use this function to look up peer entries in a hashtable. The comment says this function returns a "strong reference to a entry->peer".
Now, the worrisome part is within `wg_index_hashtable_lookup` itself. Specifically, this line: `entry->peer = wg_peer_get_maybe_zero(entry->peer);`. The logic, as I understand it, goes like this:
1. We find a matching entry in the hashtable.
2. `wg_peer_get_maybe_zero` is called on the existing `entry->peer`. `wg_peer_get_maybe_zero` checks the refcount and either increments it or returns NULL if the refcount is zero.
3. The result of `wg_peer_get_maybe_zero` is then *written back* to `entry->peer`.
This seems problematic. Why are we writing back to `entry->peer`? The code should return the strong reference via `*peer`, the function's parameter, and *not* touch `entry->peer`. The author most likely meant to write `*peer = wg_peer_get_maybe_zero(entry->peer);` instead. This would be consistent with the intent to get the reference back to the caller.
Here's the problem:
1. **Race Condition:** Multiple threads might call `wg_index_hashtable_lookup` concurrently for the same index. This means concurrent reads and *writes* to `entry->peer`. There is no locking.
2. **Potential Null Pointer Dereference:** If a peer's refcount drops to zero *between* the initial lookup and the write-back, `wg_peer_get_maybe_zero` will return NULL. The line `entry->peer = NULL;` corrupts the entry, permanently setting `entry->peer` to NULL.
Now, here's where it gets critical. If `entry->peer` becomes NULL and that entry is later used in various places (e.g. `keypair_free_kref`, `wg_noise_handshake_clear`, or within the packet processing context by `wg_queue_enqueue_per_peer_rx`), we're looking at a **kernel panic** due to a null pointer dereference. The code accesses `keypair->entry.peer->device` (or similar structures), and that pointer could be NULL if the entry got corrupted.
Specifically, in the `wg_queue_enqueue_per_peer_rx` function, the `PACKET_CB(skb)->keypair->entry.peer` might have become null, which is then used as a parameter to the `wg_peer_get` function, which, if it's NULL, results in the `napi_schedule` function dereferencing NULL. **KERNEL PANIC.**
The WireGuard comment in `peer.c` states: "and in wg_cookie_message_consume, the lookup eventually gets a peer with a refcount of zero, so no new reference is taken". The developers have anticipated the refcount zero, so why do they not check for this case in lookup?!
I think it's clear that this write-back to `entry->peer` is a bug. It's unintended and can lead to a serious crash, especially under concurrent access and with the possibility of the peer being removed while being looked up. It needs to be corrected to prevent potential memory corruption and kernel crashes.
|
| 46/2 |
2026/11/17 14:27 |
tool |
codeexpert |
25m
Args: map[Question:In drivers/net/wireguard/peerlookup.c, wg_index_hashtable_lookup() has:
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
Why does it assign to entry->peer? Is entry->peer supposed to be immutable for the lifetime of entry? If entry->peer is set to NULL when wg_peer_get_maybe_zero() returns NULL, what happens in keypair_free_kref() or wg_noise_handshake_clear() or PACKET_PEER(skb)?]
Results: map[Answer:Based on analysis of the WireGuard codebase in `drivers/net/wireguard/`:
### 1. Why does it assign to `entry->peer`?
This assignment appears to be an unintended coding mistake (a typo in variable assignment).
- The function comment explicitly notes:
`/* Returns a strong reference to a entry->peer */`
- The function receives an out-parameter `struct wg_peer **peer` where that strong reference is supposed to be returned to the caller.
- The intended logic was:
```c
if (likely(entry)) {
*peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(*peer))
; // keep entry
else
entry = NULL;
}
```
Instead, `entry->peer` was used as the target of the assignment:
```c
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
```
- **Why this was hidden during testing / normal operation:**
When the peer is alive, `wg_peer_get_maybe_zero(entry->peer)` increments `peer->refcount` via `kref_get_unless_zero()` and returns the exact same pointer `entry->peer`. Assigning `entry->peer = entry->peer` is an idempotent no-op write on the happy path.
- **Issues caused by this write:**
`wg_index_hashtable_lookup()` runs strictly within an RCU read-side critical section (`rcu_read_lock_bh()`). Mutating `entry->peer` during a lookup violates RCU invariants and creates an unsynchronized data race between concurrent lookups on multiple CPUs.
---
### 2. Is `entry->peer` supposed to be immutable for the lifetime of `entry`?
**Yes, `entry->peer` is strictly immutable for the lifetime of the entry.**
- `struct index_hashtable_entry` is only embedded in two structs:
1. `struct noise_handshake` (embedded in `struct wg_peer`)
2. `struct noise_keypair` (dynamically allocated for a `struct wg_peer`)
- In `keypair_create()` (`noise.c:107`), `keypair->entry.peer = peer;` is initialized when the keypair is allocated.
- In `wg_noise_handshake_init()` (`noise.c:68`), `handshake->entry.peer = peer;` is initialized when the peer's handshake is set up.
- A handshake and its keypairs are permanently associated with one peer throughout their entire lifecycle. Nowhere else in WireGuard is `entry.peer` ever reassigned or modified.
---
### 3. What happens if `entry->peer` is set to NULL?
If `wg_peer_get_maybe_zero(entry->peer)` fails (which occurs when the peer's refcount has dropped to 0 during peer removal/destruction), it returns `NULL`. As a result, `entry->peer = NULL;` mutates the entry object in-place before returning `NULL`.
If this occurs, any subsequent access assuming `entry->peer` is valid will trigger a **kernel NULL pointer dereference crash (kernel oops/panic)**:
1. **In `keypair_free_kref()` (`drivers/net/wireguard/noise.c`):**
```c
static void keypair_free_kref(struct kref *kref)
{
struct noise_keypair *keypair =
container_of(kref, struct noise_keypair, refcount);
net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
keypair->entry.peer->device->dev->name,
keypair->internal_id,
keypair->entry.peer->internal_id);
wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
&keypair->entry);
call_rcu(&keypair->rcu, keypair_free_rcu);
}
```
When the last reference to a keypair is put (e.g., after in-flight packets or workers finish), `keypair_free_kref()` dereferences `keypair->entry.peer->device` and `keypair->entry.peer->internal_id`. If `keypair->entry.peer` was overwritten with `NULL`, this immediately dereferences `NULL`.
2. **In `wg_noise_handshake_clear()` (`drivers/net/wireguard/noise.c`):**
```c
void wg_noise_handshake_clear(struct noise_handshake *handshake)
{
down_write(&handshake->lock);
wg_index_hashtable_remove(
handshake->entry.peer->device->index_hashtable,
&handshake->entry);
handshake_zero(handshake);
up_write(&handshake->lock);
}
```
If called on a handshake whose `handshake->entry.peer` was zeroed out (e.g. from `wg_stop()`, timer expiry, or power management notification), dereferencing `handshake->entry.peer->device` crashes with a NULL pointer dereference.
3. **In `PACKET_PEER(skb)` (`drivers/net/wireguard/queueing.h`):**
`PACKET_PEER(skb)` is defined as:
```c
#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
```
In `wg_queue_enqueue_per_peer_rx()` and `wg_queue_enqueue_per_peer_tx()`:
```c
struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
```
`wg_peer_get(peer)` calls `kref_get(&peer->refcount)`. Passing `NULL` causes an immediate NULL pointer dereference crash inside `kref_get()` / `refcount_inc()`, as well as on any subsequent dereference of `peer`.
---
### Unverified / Incomplete Parts
- Git history in this repository shows that this code originated in the initial merge commit `e7096c131e51` ("net: WireGuard secure network tunnel"). Without access to external mailing lists or unmerged upstream patch trackers, it was not verified whether an upstream fix has been proposed or discussed on the WireGuard or netdev mailing lists.]
|
| 47/3 |
2026/11/17 14:27 |
agent |
codeexpert |
25m
Model:
Results: map[Answer:Based on analysis of the WireGuard codebase in `drivers/net/wireguard/`:
### 1. Why does it assign to `entry->peer`?
This assignment appears to be an unintended coding mistake (a typo in variable assignment).
- The function comment explicitly notes:
`/* Returns a strong reference to a entry->peer */`
- The function receives an out-parameter `struct wg_peer **peer` where that strong reference is supposed to be returned to the caller.
- The intended logic was:
```c
if (likely(entry)) {
*peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(*peer))
; // keep entry
else
entry = NULL;
}
```
Instead, `entry->peer` was used as the target of the assignment:
```c
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
```
- **Why this was hidden during testing / normal operation:**
When the peer is alive, `wg_peer_get_maybe_zero(entry->peer)` increments `peer->refcount` via `kref_get_unless_zero()` and returns the exact same pointer `entry->peer`. Assigning `entry->peer = entry->peer` is an idempotent no-op write on the happy path.
- **Issues caused by this write:**
`wg_index_hashtable_lookup()` runs strictly within an RCU read-side critical section (`rcu_read_lock_bh()`). Mutating `entry->peer` during a lookup violates RCU invariants and creates an unsynchronized data race between concurrent lookups on multiple CPUs.
---
### 2. Is `entry->peer` supposed to be immutable for the lifetime of `entry`?
**Yes, `entry->peer` is strictly immutable for the lifetime of the entry.**
- `struct index_hashtable_entry` is only embedded in two structs:
1. `struct noise_handshake` (embedded in `struct wg_peer`)
2. `struct noise_keypair` (dynamically allocated for a `struct wg_peer`)
- In `keypair_create()` (`noise.c:107`), `keypair->entry.peer = peer;` is initialized when the keypair is allocated.
- In `wg_noise_handshake_init()` (`noise.c:68`), `handshake->entry.peer = peer;` is initialized when the peer's handshake is set up.
- A handshake and its keypairs are permanently associated with one peer throughout their entire lifecycle. Nowhere else in WireGuard is `entry.peer` ever reassigned or modified.
---
### 3. What happens if `entry->peer` is set to NULL?
If `wg_peer_get_maybe_zero(entry->peer)` fails (which occurs when the peer's refcount has dropped to 0 during peer removal/destruction), it returns `NULL`. As a result, `entry->peer = NULL;` mutates the entry object in-place before returning `NULL`.
If this occurs, any subsequent access assuming `entry->peer` is valid will trigger a **kernel NULL pointer dereference crash (kernel oops/panic)**:
1. **In `keypair_free_kref()` (`drivers/net/wireguard/noise.c`):**
```c
static void keypair_free_kref(struct kref *kref)
{
struct noise_keypair *keypair =
container_of(kref, struct noise_keypair, refcount);
net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
keypair->entry.peer->device->dev->name,
keypair->internal_id,
keypair->entry.peer->internal_id);
wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
&keypair->entry);
call_rcu(&keypair->rcu, keypair_free_rcu);
}
```
When the last reference to a keypair is put (e.g., after in-flight packets or workers finish), `keypair_free_kref()` dereferences `keypair->entry.peer->device` and `keypair->entry.peer->internal_id`. If `keypair->entry.peer` was overwritten with `NULL`, this immediately dereferences `NULL`.
2. **In `wg_noise_handshake_clear()` (`drivers/net/wireguard/noise.c`):**
```c
void wg_noise_handshake_clear(struct noise_handshake *handshake)
{
down_write(&handshake->lock);
wg_index_hashtable_remove(
handshake->entry.peer->device->index_hashtable,
&handshake->entry);
handshake_zero(handshake);
up_write(&handshake->lock);
}
```
If called on a handshake whose `handshake->entry.peer` was zeroed out (e.g. from `wg_stop()`, timer expiry, or power management notification), dereferencing `handshake->entry.peer->device` crashes with a NULL pointer dereference.
3. **In `PACKET_PEER(skb)` (`drivers/net/wireguard/queueing.h`):**
`PACKET_PEER(skb)` is defined as:
```c
#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
```
In `wg_queue_enqueue_per_peer_rx()` and `wg_queue_enqueue_per_peer_tx()`:
```c
struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
```
`wg_peer_get(peer)` calls `kref_get(&peer->refcount)`. Passing `NULL` causes an immediate NULL pointer dereference crash inside `kref_get()` / `refcount_inc()`, as well as on any subsequent dereference of `peer`.
---
### Unverified / Incomplete Parts
- Git history in this repository shows that this code originated in the initial merge commit `e7096c131e51` ("net: WireGuard secure network tunnel"). Without access to external mailing lists or unmerged upstream patch trackers, it was not verified whether an upstream fix has been proposed or discussed on the WireGuard or netdev mailing lists.]
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: In drivers/net/wireguard/peerlookup.c, wg_index_hashtable_lookup() has:
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
Why does it assign to entry->peer? Is entry->peer supposed to be immutable for the lifetime of entry? If entry->peer is set to NULL when wg_peer_get_maybe_zero() returns NULL, what happens in keypair_free_kref() or wg_noise_handshake_clear() or PACKET_PEER(skb)?
|
| 48/4 |
2026/11/17 14:27 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 4446
output: 79
thoughts: 220
Thoughts: **Analyzing WireGuard Peer Lookup**
Okay, so I'm looking at this `wg_index_hashtable_lookup()` function in `drivers/net/wireguard/peerlookup.c` and I'm a bit puzzled by this sequence:
My immediate question is: Why the assignment to `entry->peer`? Is the intent that `entry->peer` is immutable *for the entire duration* the `entry` exists? And if `wg_peer_get_maybe_zero()` returns `NULL`, which it *does* allow, setting `entry->peer` to `NULL`, what happens down the line in places like `keypair_free_kref()`, `wg_noise_handshake_clear()`, or `PACKET_PEER(skb)`? Are we setting ourselves up for potential null pointer dereferences or other subtle memory management issues?
Time to dig into the code! I need to examine `drivers/net/wireguard/peerlookup.c` and search the code for `wg_index_hashtable_lookup`, of course, but I also need to pay close attention to instances of `entry->peer`. I'll also check the Git history and commit messages around this area for any clues or justifications for this pattern. Let's get the tools running!
|
| 49/4 |
2026/11/17 14:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.c Name:wg_index_hashtable_lookup]
Results: map[SourceCode: 200: /* Returns a strong reference to a entry->peer */
201: struct index_hashtable_entry *
202: wg_index_hashtable_lookup(struct index_hashtable *table,
203: const enum index_hashtable_type type_mask,
204: const __le32 index, struct wg_peer **peer)
205: {
206: struct index_hashtable_entry *iter_entry, *entry = NULL;
207:
208: rcu_read_lock_bh();
209: hlist_for_each_entry_rcu_bh(iter_entry, index_bucket(table, index),
210: index_hash) {
211: if (iter_entry->index == index) {
212: if (likely(iter_entry->type & type_mask))
213: entry = iter_entry;
214: break;
215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
224: rcu_read_unlock_bh();
225: return entry;
226: }
SourceFile:drivers/net/wireguard/peerlookup.c]
|
| 50/4 |
2026/11/17 14:28 |
tool |
grepper |
0m
Args: map[Expression:wg_index_hashtable_lookup PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/cookie.c=198=void wg_cookie_message_consume(struct message_handshake_cookie *src,
--
drivers/net/wireguard/cookie.c-204-
drivers/net/wireguard/cookie.c:205: if (unlikely(!wg_index_hashtable_lookup(wg->index_hashtable,
drivers/net/wireguard/cookie.c-206- INDEX_HASHTABLE_HANDSHAKE |
--
drivers/net/wireguard/noise.c=728=wg_noise_handshake_consume_response(struct message_handshake_response *src,
--
drivers/net/wireguard/noise.c-745-
drivers/net/wireguard/noise.c:746: handshake = (struct noise_handshake *)wg_index_hashtable_lookup(
drivers/net/wireguard/noise.c-747- wg->index_hashtable, INDEX_HASHTABLE_HANDSHAKE,
--
drivers/net/wireguard/peer.c=94=static void peer_remove_after_dead(struct wg_peer *peer)
--
drivers/net/wireguard/peer.c-138- * allowedips; we won't have new references in (2) eventually, because
drivers/net/wireguard/peer.c:139: * wg_index_hashtable_lookup will always return NULL, since we removed
drivers/net/wireguard/peer.c-140- * all existing keypairs and no more can be created; we won't have new
--
drivers/net/wireguard/peerlookup.c=201=struct index_hashtable_entry *
drivers/net/wireguard/peerlookup.c:202:wg_index_hashtable_lookup(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.c-203- const enum index_hashtable_type type_mask,
--
drivers/net/wireguard/peerlookup.h=59=struct index_hashtable_entry *
drivers/net/wireguard/peerlookup.h:60:wg_index_hashtable_lookup(struct index_hashtable *table,
drivers/net/wireguard/peerlookup.h-61- const enum index_hashtable_type type_mask,
--
drivers/net/wireguard/receive.c=509=static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb)
--
drivers/net/wireguard/receive.c-516- PACKET_CB(skb)->keypair =
drivers/net/wireguard/receive.c:517: (struct noise_keypair *)wg_index_hashtable_lookup(
drivers/net/wireguard/receive.c-518- wg->index_hashtable, INDEX_HASHTABLE_KEYPAIR, idx,
]
|
| 51/4 |
2026/11/17 14:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6178
output: 39
thoughts: 29
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating a Suspect Line of Code**
Alright, I'm thinking I need to understand the history of line 218 in `drivers/net/wireguard/peerlookup.c`. My first instinct is to immediately reach for either `git blame` or `git log`. Depending on the situation and what I'm trying to figure out, I'll choose one over the other. If I want to know the last commit that touched that *specific* line and who's responsible, I'll go with `git blame`. It'll quickly show me the author, the commit, and when the change was made. If I'm looking for a more holistic understanding of *all* changes to that line over time, and perhaps the surrounding lines too, then `git log -L 218,218:drivers/net/wireguard/peerlookup.c` would be more appropriate. I'm probably looking at a bug or a specific behavior and I need to establish the provenance of this line, see what context might have driven its current state. I expect that the information returned will guide my next steps: whether to dig deeper into the code, investigate related commits or even reach out to the author or other contributors for further clarification.
|
| 52/4 |
2026/11/17 14:29 |
tool |
git-blame |
0m
Args: map[End:225 File:drivers/net/wireguard/peerlookup.c Start:215]
Results: map[Output:e7096c131e516 215) }
e7096c131e516 216) }
e7096c131e516 217) if (likely(entry)) {
e7096c131e516 218) entry->peer = wg_peer_get_maybe_zero(entry->peer);
e7096c131e516 219) if (likely(entry->peer))
e7096c131e516 220) *peer = entry->peer;
e7096c131e516 221) else
e7096c131e516 222) entry = NULL;
e7096c131e516 223) }
e7096c131e516 224) rcu_read_unlock_bh();
e7096c131e516 225) return entry;
]
|
| 53/4 |
2026/11/17 14:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6844
output: 32
thoughts: 105
Thoughts: **WireGuard Peer Lookup Code Review**
Okay, so `e7096c131e516` is the commit that brought WireGuard into the kernel β the core introduction. Now I need to quickly establish if the `drivers/net/wireguard/peerlookup.c` file has seen any subsequent modifications or if we're essentially looking at the original implementation. My immediate thought is to check the Git log for that specific file. I want to see if there have been any follow-up commits touching that area, indicating bug fixes, optimizations, or even refactoring that's relevant to this module. I need to understand if this is *the* code, or if it's been iterated on, patched, or if there's been discussion around any particular issues in that part of the code. This will help me contextualize the current state and understand its history. Let's see what the `git log` reveals.
|
| 54/4 |
2026/11/17 14:29 |
tool |
git-log |
0m
Args: map[Count:10 PathPrefix:drivers/net/wireguard/peerlookup.c]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
6147f7b1e90f wireguard: peerlookup: take lock before checking hash in replace operation
e7096c131e51 net: WireGuard secure network tunnel
]
|
| 55/4 |
2026/11/17 14:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7296
output: 41
thoughts: 38
Thoughts: Okay, let's dive into this. Here's how I'd approach this, as an expert in the field:
**Analyzing the `index_hashtable_entry` Structure**
Right, my focus is on the `index_hashtable_entry`. I need to understand its definition and how it's being used. The first logical step is to pinpoint exactly where this structure is defined. Time to go hunting! Let's get cracking with a codesearch to nail down its declaration. That's the foundation β once I know the structure, I can really start to understand its function.
|
| 56/4 |
2026/11/17 14:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.h Name:index_hashtable_entry]
Results: map[SourceCode: 44: struct index_hashtable_entry {
45: struct wg_peer *peer;
46: struct hlist_node index_hash;
47: enum index_hashtable_type type;
48: __le32 index;
49: };
SourceFile:drivers/net/wireguard/peerlookup.h]
|
| 57/4 |
2026/11/17 14:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7611
output: 49
thoughts: 22
Thoughts: Here's a summary of my thought process, as requested:
**Investigating `struct index_hashtable_entry` and the `peer` Field**
Okay, so I need to track down all instances of `struct index_hashtable_entry` and, more specifically, how the `peer` field within that structure is being used. This immediately flags a couple of things in my mind. Firstly, this is likely part of the indexing infrastructure, meaning I need to understand how entries are stored and retrieved. Secondly, the presence of a "peer" field suggests some sort of relationship or connection is being modeled within this hashtable. Is it a peer-to-peer relationship, or something more abstract? Are we talking about a distributed index or some internal linked structure?
My first step is to perform a code search. I need a comprehensive search strategy; I need to cover all relevant codebases. I'll start with a straightforward textual search for `struct index_hashtable_entry`. That should give me the declarations and initializations. I'll need to pay close attention to any typedefs, macros, or other ways the structure might be referenced indirectly. Once I have the declarations, Iβll need to extend my search to identify uses of the structure itself, and *specifically* uses of the `peer` field. A simple grep, or a more sophisticated code-aware search tool, will be vital here. I will look for any assignments or accesses of the field, especially those involving pointers. I'll need to trace the data flow through the code. I'm also going to watch out for conditional logic associated with the `peer` field. That could reveal important use cases that are not immediately obvious.
From there, I'll analyze the code that interacts with the `peer` field. I want to see how it's initialized, modified, and used. Is it a pointer to another structure? What kind? Are there any locking mechanisms involved? Is there a memory management scheme associated with `peer`? Is this a standard linked-list style pointer, or something more complex? I want to build a complete picture of the relationships that the `peer` field represents and understand the impact of the field's manipulations on the overall system. I'll look for any patterns, common idioms, or potential areas for concurrency issues related to how that `peer` pointer is accessed and modified. It could well be that this single field reveals critical information about the underlying design.
|
| 58/4 |
2026/11/17 14:30 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.h IncludeSnippetLines:5 Name:index_hashtable_entry::peer]
Results: map[References:[map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:keypair_create SourceFile:drivers/net/wireguard/noise.c SourceLine:107 SourceSnippet: 102: if (unlikely(!keypair))
103: return NULL;
104: spin_lock_init(&keypair->receiving_counter.lock);
105: keypair->internal_id = atomic64_inc_return(&keypair_counter);
106: keypair->entry.type = INDEX_HASHTABLE_KEYPAIR;
107: keypair->entry.peer = peer;
108: kref_init(&keypair->refcount);
109: return keypair;
110: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:keypair_free_kref SourceFile:drivers/net/wireguard/noise.c SourceLine:122 SourceSnippet: 117: static void keypair_free_kref(struct kref *kref)
118: {
119: struct noise_keypair *keypair =
120: container_of(kref, struct noise_keypair, refcount);
121:
122: net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
123: keypair->entry.peer->device->dev->name,
124: keypair->internal_id,
125: keypair->entry.peer->internal_id);
126: wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
127: &keypair->entry);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:keypair_free_kref SourceFile:drivers/net/wireguard/noise.c SourceLine:122 SourceSnippet: 117: static void keypair_free_kref(struct kref *kref)
118: {
119: struct noise_keypair *keypair =
120: container_of(kref, struct noise_keypair, refcount);
121:
122: net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
123: keypair->entry.peer->device->dev->name,
124: keypair->internal_id,
125: keypair->entry.peer->internal_id);
126: wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
127: &keypair->entry);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:keypair_free_kref SourceFile:drivers/net/wireguard/noise.c SourceLine:126 SourceSnippet: 121:
122: net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
123: keypair->entry.peer->device->dev->name,
124: keypair->internal_id,
125: keypair->entry.peer->internal_id);
126: wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
127: &keypair->entry);
128: call_rcu(&keypair->rcu, keypair_free_rcu);
129: }
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:wg_index_hashtable_lookup SourceFile:drivers/net/wireguard/peerlookup.c SourceLine:218 SourceSnippet: 213: entry = iter_entry;
214: break;
215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_index_hashtable_lookup SourceFile:drivers/net/wireguard/peerlookup.c SourceLine:218 SourceSnippet: 213: entry = iter_entry;
214: break;
215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_index_hashtable_lookup SourceFile:drivers/net/wireguard/peerlookup.c SourceLine:219 SourceSnippet: 214: break;
215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
224: rcu_read_unlock_bh();
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_index_hashtable_lookup SourceFile:drivers/net/wireguard/peerlookup.c SourceLine:220 SourceSnippet: 215: }
216: }
217: if (likely(entry)) {
218: entry->peer = wg_peer_get_maybe_zero(entry->peer);
219: if (likely(entry->peer))
220: *peer = entry->peer;
221: else
222: entry = NULL;
223: }
224: rcu_read_unlock_bh();
225: return entry;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_begin_session SourceFile:drivers/net/wireguard/noise.c SourceLine:826 SourceSnippet: 821: down_write(&handshake->lock);
822: if (handshake->state != HANDSHAKE_CREATED_RESPONSE &&
823: handshake->state != HANDSHAKE_CONSUMED_RESPONSE)
824: goto out;
825:
826: new_keypair = keypair_create(handshake->entry.peer);
827: if (!new_keypair)
828: goto out;
829: new_keypair->i_am_the_initiator = handshake->state ==
830: HANDSHAKE_CONSUMED_RESPONSE;
831: new_keypair->remote_index = handshake->remote_index;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_begin_session SourceFile:drivers/net/wireguard/noise.c SourceLine:845 SourceSnippet: 840: handshake_zero(handshake);
841: rcu_read_lock_bh();
842: if (likely(!READ_ONCE(container_of(handshake, struct wg_peer,
843: handshake)->is_dead))) {
844: add_new_keypair(keypairs, new_keypair);
845: net_dbg_ratelimited("%s: Keypair %llu created for peer %llu\n",
846: handshake->entry.peer->device->dev->name,
847: new_keypair->internal_id,
848: handshake->entry.peer->internal_id);
849: ret = wg_index_hashtable_replace(
850: handshake->entry.peer->device->index_hashtable,
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_begin_session SourceFile:drivers/net/wireguard/noise.c SourceLine:845 SourceSnippet: 840: handshake_zero(handshake);
841: rcu_read_lock_bh();
842: if (likely(!READ_ONCE(container_of(handshake, struct wg_peer,
843: handshake)->is_dead))) {
844: add_new_keypair(keypairs, new_keypair);
845: net_dbg_ratelimited("%s: Keypair %llu created for peer %llu\n",
846: handshake->entry.peer->device->dev->name,
847: new_keypair->internal_id,
848: handshake->entry.peer->internal_id);
849: ret = wg_index_hashtable_replace(
850: handshake->entry.peer->device->index_hashtable,
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_begin_session SourceFile:drivers/net/wireguard/noise.c SourceLine:850 SourceSnippet: 845: net_dbg_ratelimited("%s: Keypair %llu created for peer %llu\n",
846: handshake->entry.peer->device->dev->name,
847: new_keypair->internal_id,
848: handshake->entry.peer->internal_id);
849: ret = wg_index_hashtable_replace(
850: handshake->entry.peer->device->index_hashtable,
851: &handshake->entry, &new_keypair->entry);
852: } else {
853: kfree_sensitive(new_keypair);
854: }
855: rcu_read_unlock_bh();
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_clear SourceFile:drivers/net/wireguard/noise.c SourceLine:92 SourceSnippet: 88: void wg_noise_handshake_clear(struct noise_handshake *handshake)
89: {
90: down_write(&handshake->lock);
91: wg_index_hashtable_remove(
92: handshake->entry.peer->device->index_hashtable,
93: &handshake->entry);
94: handshake_zero(handshake);
95: up_write(&handshake->lock);
96: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_create_initiation SourceFile:drivers/net/wireguard/noise.c SourceLine:570 SourceSnippet: 565: tai64n_now(timestamp);
566: message_encrypt(dst->encrypted_timestamp, timestamp,
567: NOISE_TIMESTAMP_LEN, key, handshake->hash);
568:
569: dst->sender_index = wg_index_hashtable_insert(
570: handshake->entry.peer->device->index_hashtable,
571: &handshake->entry);
572:
573: handshake->state = HANDSHAKE_CREATED_INITIATION;
574: ret = true;
575:
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_create_response SourceFile:drivers/net/wireguard/noise.c SourceLine:714 SourceSnippet: 709:
710: /* {} */
711: message_encrypt(dst->encrypted_nothing, NULL, 0, key, handshake->hash);
712:
713: dst->sender_index = wg_index_hashtable_insert(
714: handshake->entry.peer->device->index_hashtable,
715: &handshake->entry);
716:
717: handshake->state = HANDSHAKE_CREATED_RESPONSE;
718: ret = true;
719:
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:wg_noise_handshake_init SourceFile:drivers/net/wireguard/noise.c SourceLine:68 SourceSnippet: 63: struct wg_peer *peer)
64: {
65: memset(handshake, 0, sizeof(*handshake));
66: init_rwsem(&handshake->lock);
67: handshake->entry.type = INDEX_HASHTABLE_HANDSHAKE;
68: handshake->entry.peer = peer;
69: memcpy(handshake->remote_static, peer_public_key, NOISE_PUBLIC_KEY_LEN);
70: if (peer_preshared_key)
71: memcpy(handshake->preshared_key, peer_preshared_key,
72: NOISE_SYMMETRIC_KEY_LEN);
73: handshake->static_identity = static_identity;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_noise_keypair_put SourceFile:drivers/net/wireguard/noise.c SourceLine:137 SourceSnippet: 132: {
133: if (unlikely(!keypair))
134: return;
135: if (unlikely(unreference_now))
136: wg_index_hashtable_remove(
137: keypair->entry.peer->device->index_hashtable,
138: &keypair->entry);
139: kref_put(&keypair->refcount, keypair_free_kref);
140: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_packet_send_staged_packets SourceFile:drivers/net/wireguard/send.c SourceLine:386 SourceSnippet: 381: if (unlikely(PACKET_CB(skb)->nonce >= REJECT_AFTER_MESSAGES))
382: goto out_invalid;
383: }
384:
385: packets.prev->next = NULL;
386: wg_peer_get(keypair->entry.peer);
387: PACKET_CB(packets.next)->keypair = keypair;
388: wg_packet_create_data(peer, packets.next);
389: return;
390:
391: out_invalid:
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_queue_enqueue_per_peer_rx SourceFile:drivers/net/wireguard/queueing.h SourceLine:195 SourceSnippet: 190: static inline void wg_queue_enqueue_per_peer_rx(struct sk_buff *skb, enum packet_state state)
191: {
192: /* We take a reference, because as soon as we call atomic_set, the
193: * peer can be freed from below us.
194: */
195: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
196:
197: atomic_set_release(&PACKET_CB(skb)->state, state);
198: napi_schedule(&peer->napi);
199: wg_peer_put(peer);
200: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:wg_queue_enqueue_per_peer_tx SourceFile:drivers/net/wireguard/queueing.h SourceLine:182 SourceSnippet: 177: static inline void wg_queue_enqueue_per_peer_tx(struct sk_buff *skb, enum packet_state state)
178: {
179: /* We take a reference, because as soon as we call atomic_set, the
180: * peer can be freed from below us.
181: */
182: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
183:
184: atomic_set_release(&PACKET_CB(skb)->state, state);
185: queue_work_on(wg_cpumask_choose_online(&peer->serial_work_cpu, peer->internal_id),
186: peer->device->packet_crypt_wq, &peer->transmit_packet_work);
187: wg_peer_put(peer);
]] TruncatedOutput:false]
|
| 59/4 |
2026/11/17 14:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12934
output: 33
thoughts: 35
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Initial Observation and Deep Dive Trigger**
Ah, interesting. Let's see... *that* certainly caught my eye. The definition of `PACKET_PEER(skb)`... It seems like there might be something subtle lurking there. Given the context, I suspect it's likely crucial for understanding the data flow within the packet processing framework. Right then, let's fire up the search tools. Time to track down every instance of `PACKET_PEER` in the code base and understand its implications. I need to understand this fully, from its initial declaration to its ultimate usage. This could be the key to understanding a particularly thorny networking issue I've been wrestling with recently. Let's dig in.
|
| 60/4 |
2026/11/17 14:30 |
tool |
grepper |
0m
Args: map[Expression:PACKET_PEER PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/queueing.h=59=struct packet_cb {
--
drivers/net/wireguard/queueing.h-67-#define PACKET_CB(skb) ((struct packet_cb *)((skb)->cb))
drivers/net/wireguard/queueing.h:68:#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
drivers/net/wireguard/queueing.h-69-
--
drivers/net/wireguard/queueing.h=177=static inline void wg_queue_enqueue_per_peer_tx(struct sk_buff *skb, enum packet_state state)
--
drivers/net/wireguard/queueing.h-181- */
drivers/net/wireguard/queueing.h:182: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
drivers/net/wireguard/queueing.h-183-
--
drivers/net/wireguard/queueing.h=190=static inline void wg_queue_enqueue_per_peer_rx(struct sk_buff *skb, enum packet_state state)
--
drivers/net/wireguard/queueing.h-194- */
drivers/net/wireguard/queueing.h:195: struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
drivers/net/wireguard/queueing.h-196-
]
|
| 61/4 |
2026/11/17 14:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13561
output: 38
thoughts: 719
Thoughts: **Analyzing Potential Mutability Issues in WireGuard's Peer Lookup**
Okay, so I'm looking at this `wg_index_hashtable_lookup` function in WireGuard, and my first thought is, "why is it doing this assignment to `entry->peer`?". I mean, I see that the code is doing `entry->peer = wg_peer_get_maybe_zero(entry->peer);` and I immediately start to wonder, is `entry->peer` supposed to be immutable for the life of `entry`? The implications of setting it to `NULL` if `wg_peer_get_maybe_zero()` returns `NULL` are pretty serious, right? My brain is now racing to follow the breadcrumbs. Where else is `entry->peer` being used? I see it used in `keypair_free_kref()`, `wg_noise_handshake_clear()` and via the macro `PACKET_PEER(skb)`. If `entry->peer` becomes `NULL` due to the `wg_peer_get_maybe_zero` call failing, this could lead to a really nasty NULL pointer dereference. I think I see a possible bug! I need to investigate this further. I'm wondering if this change could potentially be an issue.
Now, I'm going to leverage my expert knowledge and start digging into the WireGuard code history. I'm going to check the git history. I will search for commits touching the `wg_index_hashtable_lookup` function and maybe even more broadly for `wg_peer_get_maybe_zero`. I also want to look for discussion on the mailing lists. I am going to try and track down any relevant discussions on LKML. I will use `git log` on the `drivers/net/wireguard/` directory to see if I can find a relevant commit message or maybe I can use `CodeRegexp` or something similar for more targeted results. It's time to start looking into the evolution of this code.
|
| 62/4 |
2026/11/17 14:30 |
tool |
git-log |
0m
Args: map[CodeRegexp:wg_peer_get_maybe_zero PathPrefix:drivers/net/wireguard]
Results: map[Output:e7096c131e51 net: WireGuard secure network tunnel
]
|
| 63/4 |
2026/11/17 14:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14781
output: 32
thoughts: 22
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Digging into the WireGuard Kernel Module's Peer Handling**
Right, let's get down to brass tacks. I need to understand how the `entry->peer` structure is used within the WireGuard kernel module, specifically within the `drivers/net/wireguard` directory. My initial approach is going to be a targeted code archaeology expedition using `git log`. I'm specifically looking for instances where `entry->peer` is referenced, which probably deals with a peer's details. This will help me quickly zero in on the relevant code areas, maybe find some interesting commits that relate to its management. It's a pragmatic, focused approach to understand the relevant codebase, so I don't have to wade through irrelevant log messages.
|
| 64/4 |
2026/11/17 14:31 |
tool |
git-log |
0m
Args: map[CodeRegexp:entry->peer PathPrefix:drivers/net/wireguard]
Results: map[Output:e7096c131e51 net: WireGuard secure network tunnel
]
|
| 65/4 |
2026/11/17 14:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15050
output: 31
thoughts: 29
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Investigating a Specific Git Commit**
Right, let's take a look at what went down in commit `e7096c131e51`. I need to understand the context, the rationale behind the changes. The best way to do that, as always, is to dive straight into the commit itself. I'll use `git show` to examine the commit message and diff. I'm hoping the commit message is clear and concise, maybe provides a link to a JIRA ticket, or at the very least, articulates the "why" behind the code changes. I'll be looking for clues about the bug it fixes, the feature it implements, or any refactoring rationale. If the message is lacking, or the changes are complex, I'll need to use the diff data to reconstruct the context myself, probably start by noting what files were modified, and checking the relevant code blocks. I'm expecting this commit is probably one of the intermediate steps in a bigger change, so I'll also check if there are any related commits or branches in the `git log` or the commit graph, for a deeper understanding of the overall picture.
|
| 66/4 |
2026/11/17 14:31 |
tool |
git-show |
0m
Args: map[Commit:e7096c131e51 Stat:true]
Results: map[Output:commit e7096c131e5161fa3b8e52a650d7719d2857adfd
Author: Jason A. Donenfeld <Jason@zx2c4.com>
Date: Mon Dec 9 00:27:34 2019 +0100
net: WireGuard secure network tunnel
WireGuard is a layer 3 secure networking tunnel made specifically for
the kernel, that aims to be much simpler and easier to audit than IPsec.
Extensive documentation and description of the protocol and
considerations, along with formal proofs of the cryptography, are
available at:
* https://www.wireguard.com/
* https://www.wireguard.com/papers/wireguard.pdf
This commit implements WireGuard as a simple network device driver,
accessible in the usual RTNL way used by virtual network drivers. It
makes use of the udp_tunnel APIs, GRO, GSO, NAPI, and the usual set of
networking subsystem APIs. It has a somewhat novel multicore queueing
system designed for maximum throughput and minimal latency of encryption
operations, but it is implemented modestly using workqueues and NAPI.
Configuration is done via generic Netlink, and following a review from
the Netlink maintainer a year ago, several high profile userspace tools
have already implemented the API.
This commit also comes with several different tests, both in-kernel
tests and out-of-kernel tests based on network namespaces, taking profit
of the fact that sockets used by WireGuard intentionally stay in the
namespace the WireGuard interface was originally created, exactly like
the semantics of userspace tun devices. See wireguard.com/netns/ for
pictures and examples.
The source code is fairly short, but rather than combining everything
into a single file, WireGuard is developed as cleanly separable files,
making auditing and comprehension easier. Things are laid out as
follows:
* noise.[ch], cookie.[ch], messages.h: These implement the bulk of the
cryptographic aspects of the protocol, and are mostly data-only in
nature, taking in buffers of bytes and spitting out buffers of
bytes. They also handle reference counting for their various shared
pieces of data, like keys and key lists.
* ratelimiter.[ch]: Used as an integral part of cookie.[ch] for
ratelimiting certain types of cryptographic operations in accordance
with particular WireGuard semantics.
* allowedips.[ch], peerlookup.[ch]: The main lookup structures of
WireGuard, the former being trie-like with particular semantics, an
integral part of the design of the protocol, and the latter just
being nice helper functions around the various hashtables we use.
* device.[ch]: Implementation of functions for the netdevice and for
rtnl, responsible for maintaining the life of a given interface and
wiring it up to the rest of WireGuard.
* peer.[ch]: Each interface has a list of peers, with helper functions
available here for creation, destruction, and reference counting.
* socket.[ch]: Implementation of functions related to udp_socket and
the general set of kernel socket APIs, for sending and receiving
ciphertext UDP packets, and taking care of WireGuard-specific sticky
socket routing semantics for the automatic roaming.
* netlink.[ch]: Userspace API entry point for configuring WireGuard
peers and devices. The API has been implemented by several userspace
tools and network management utility, and the WireGuard project
distributes the basic wg(8) tool.
* queueing.[ch]: Shared function on the rx and tx path for handling
the various queues used in the multicore algorithms.
* send.c: Handles encrypting outgoing packets in parallel on
multiple cores, before sending them in order on a single core, via
workqueues and ring buffers. Also handles sending handshake and cookie
messages as part of the protocol, in parallel.
* receive.c: Handles decrypting incoming packets in parallel on
multiple cores, before passing them off in order to be ingested via
the rest of the networking subsystem with GRO via the typical NAPI
poll function. Also handles receiving handshake and cookie messages
as part of the protocol, in parallel.
* timers.[ch]: Uses the timer wheel to implement protocol particular
event timeouts, and gives a set of very simple event-driven entry
point functions for callers.
* main.c, version.h: Initialization and deinitialization of the module.
* selftest/*.h: Runtime unit tests for some of the most security
sensitive functions.
* tools/testing/selftests/wireguard/netns.sh: Aforementioned testing
script using network namespaces.
This commit aims to be as self-contained as possible, implementing
WireGuard as a standalone module not needing much special handling or
coordination from the network subsystem. I expect for future
optimizations to the network stack to positively improve WireGuard, and
vice-versa, but for the time being, this exists as intentionally
standalone.
We introduce a menu option for CONFIG_WIREGUARD, as well as providing a
verbose debug log and self-tests via CONFIG_WIREGUARD_DEBUG.
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Cc: David Miller <davem@davemloft.net>
Cc: Greg KH <gregkh@linuxfoundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Cc: linux-crypto@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: netdev@vger.kernel.org
Signed-off-by: David S. Miller <davem@davemloft.net>
MAINTAINERS | 8 +
drivers/net/Kconfig | 41 ++
drivers/net/Makefile | 1 +
drivers/net/wireguard/Makefile | 18 +
drivers/net/wireguard/allowedips.c | 381 ++++++++++++
drivers/net/wireguard/allowedips.h | 59 ++
drivers/net/wireguard/cookie.c | 236 ++++++++
drivers/net/wireguard/cookie.h | 59 ++
drivers/net/wireguard/device.c | 458 +++++++++++++++
drivers/net/wireguard/device.h | 73 +++
drivers/net/wireguard/main.c | 64 +++
drivers/net/wireguard/messages.h | 128 +++++
drivers/net/wireguard/netlink.c | 642 +++++++++++++++++++++
drivers/net/wireguard/netlink.h | 12 +
drivers/net/wireguard/noise.c | 828 +++++++++++++++++++++++++++
drivers/net/wireguard/noise.h | 137 +++++
drivers/net/wireguard/peer.c | 240 ++++++++
drivers/net/wireguard/peer.h | 83 +++
drivers/net/wireguard/peerlookup.c | 221 +++++++
drivers/net/wireguard/peerlookup.h | 64 +++
drivers/net/wireguard/queueing.c | 53 ++
drivers/net/wireguard/queueing.h | 197 +++++++
drivers/net/wireguard/ratelimiter.c | 223 ++++++++
drivers/net/wireguard/ratelimiter.h | 19 +
drivers/net/wireguard/receive.c | 595 +++++++++++++++++++
drivers/net/wireguard/selftest/allowedips.c | 683 ++++++++++++++++++++++
drivers/net/wireguard/selftest/counter.c | 104 ++++
drivers/net/wireguard/selftest/ratelimiter.c | 226 ++++++++
drivers/net/wireguard/send.c | 413 +++++++++++++
drivers/net/wireguard/socket.c | 437 ++++++++++++++
drivers/net/wireguard/socket.h | 44 ++
drivers/net/wireguard/timers.c | 243 ++++++++
drivers/net/wireguard/timers.h | 31 +
drivers/net/wireguard/version.h | 1 +
include/uapi/linux/wireguard.h | 196 +++++++
tools/testing/selftests/wireguard/netns.sh | 537 +++++++++++++++++
36 files changed, 7755 insertions(+)
]
|
| 67/4 |
2026/11/17 14:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17507
output: 43
thoughts: 255
Thoughts: **Analyzing the WireGuard Peer Assignment Question**
Okay, let's break this down. The user is asking some crucial questions, let's make sure we address each one meticulously. Specifically:
1. *Why* are we assigning to `entry->peer`? I need to understand the intent behind this assignment in the WireGuard data structures.
2. Is `entry->peer` *supposed* to be immutable once set? This suggests a potential lifetime management issue or assumptions about pointer stability. This impacts memory safety.
3. If `wg_peer_get_maybe_zero()` returns NULL and we set `entry->peer` to NULL, then what happens in the contexts of `keypair_free_kref()`, `wg_noise_handshake_clear()`, or `PACKET_PEER(skb)`? This is key, since these are likely the places where a dangling pointer could cause the system to crash or leak memory, and that's an issue for security.
Now, I need to dive into the code. I'm going to look specifically at the relevant functions and data structures. I need to understand the relationship between these parts of the system:
* The `wg_index_hashtable_lookup` function. How is the index hashtable used?
* `wg_peer_get_maybe_zero` - this is obviously a critical function, and a good place to start. I need to understand its behavior. I should also check out `wg_peer_get`.
* `keypair_free_kref` and the keypair lifecycle in general.
* `wg_noise_handshake_clear` - this also involves security context, so a high-priority.
* `PACKET_PEER(skb)` - I need to understand how the `skb` (socket buffer) interacts with the peer context.
* The overall usage of the `index_hashtable` - insertion, deletion, lookup semantics, that's crucial.
* The `keypair` and `handshake` lifecycles are also important to understand.
I need to read the code in `drivers/net/wireguard/peer.h` or `peer.c`, focusing specifically on those functions and data structures. By getting a good understanding of the code, I will be able to answer the user's questions clearly, accurately, and with specific references to the code.
|
| 68/4 |
2026/11/17 14:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peer.h Name:wg_peer_get_maybe_zero]
Results: map[SourceCode: 71: struct wg_peer *wg_peer_get_maybe_zero(struct wg_peer *peer)
72: {
73: RCU_LOCKDEP_WARN(!rcu_read_lock_bh_held(),
74: "Taking peer reference without holding the RCU read lock");
75: if (unlikely(!peer || !kref_get_unless_zero(&peer->refcount)))
76: return NULL;
77: return peer;
78: }
SourceFile:drivers/net/wireguard/peer.c]
|
| 69/4 |
2026/11/17 14:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18493
output: 37
thoughts: 973
Thoughts: **Analyzing Potential Concurrency Issues in `wg_index_hashtable_lookup`**
Okay, let's break this down. I'm looking at `wg_peer_get_maybe_zero` and I see that it returns `NULL` if a peer's refcount is zero, meaning the peer is being destroyed. Now, let's look at `wg_index_hashtable_lookup`. Here, it's returning a strong reference to an `entry->peer`.
The core of my concern focuses on this line: `entry->peer = wg_peer_get_maybe_zero(entry->peer);`. Why this assignment? Why not directly assign to the output `*peer` or use a local variable? This feels potentially problematic. I need to understand why they're writing back to `entry->peer` here. Is it a bug? A typo? Or a fundamentally flawed understanding of the mechanics?
Let's trace this execution flow more carefully. If `wg_peer_get_maybe_zero` *doesn't* return `NULL`, it increments the peer's refcount, and then the line `entry->peer = entry->peer` does nothing, and then the caller gets the strong reference through `*peer`, which is the intended behavior. That seems right.
But, if `wg_peer_get_maybe_zero` *does* return `NULL` (because the peer is being freed), `entry->peer` becomes `NULL`. That's the problem. And I see a bigger problem: We're inside an RCU read lock (`rcu_read_lock_bh()`) and *writing* to `entry->peer`! This is a concurrent write! Multiple lookups could concurrently modify `entry->peer`. That's a nasty race condition waiting to happen.
Now, the crucial question is: Is `entry->peer` supposed to be immutable for the lifetime of `entry`? I need to understand how these entries are created, initialized, and destroyed. I need to figure out where `index_hashtable_entry` is used and how `entry->peer` is set and cleared.
I know `index_hashtable_entry` is embedded within other structures, so let's start with a search. I'll check all the struct definitions in the WireGuard code that contain `struct index_hashtable_entry`. Here's one: `struct noise_handshake` in `drivers/net/wireguard/noise.h`. I'll have to read through lines 30-100 of that file to get a good handle on its usage.
|
| 70/4 |
2026/11/17 14:32 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/noise.h FirstLine:35 LineCount:55]
Results: map[Contents: 35: struct noise_replay_counter receiving_counter;
36: __le32 remote_index;
37: bool i_am_the_initiator;
38: struct kref refcount;
39: struct rcu_head rcu;
40: u64 internal_id;
41: };
42:
43: struct noise_keypairs {
44: struct noise_keypair __rcu *current_keypair;
45: struct noise_keypair __rcu *previous_keypair;
46: struct noise_keypair __rcu *next_keypair;
47: spinlock_t keypair_update_lock;
48: };
49:
50: struct noise_static_identity {
51: u8 static_public[NOISE_PUBLIC_KEY_LEN];
52: u8 static_private[NOISE_PUBLIC_KEY_LEN];
53: struct rw_semaphore lock;
54: bool has_identity;
55: };
56:
57: enum noise_handshake_state {
58: HANDSHAKE_ZEROED,
59: HANDSHAKE_CREATED_INITIATION,
60: HANDSHAKE_CONSUMED_INITIATION,
61: HANDSHAKE_CREATED_RESPONSE,
62: HANDSHAKE_CONSUMED_RESPONSE
63: };
64:
65: struct noise_handshake {
66: struct index_hashtable_entry entry;
67:
68: enum noise_handshake_state state;
69: u64 last_initiation_consumption;
70:
71: struct noise_static_identity *static_identity;
72:
73: u8 ephemeral_private[NOISE_PUBLIC_KEY_LEN];
74: u8 remote_static[NOISE_PUBLIC_KEY_LEN];
75: u8 remote_ephemeral[NOISE_PUBLIC_KEY_LEN];
76: u8 precomputed_static_static[NOISE_PUBLIC_KEY_LEN];
77:
78: u8 preshared_key[NOISE_SYMMETRIC_KEY_LEN];
79:
80: u8 hash[NOISE_HASH_LEN];
81: u8 chaining_key[NOISE_HASH_LEN];
82:
83: u8 latest_timestamp[NOISE_TIMESTAMP_LEN];
84: __le32 remote_index;
85:
86: /* Protects all members except the immutable (after noise_handshake_
87: * init): remote_static, precomputed_static_static, static_identity.
88: */
89: struct rw_semaphore lock;
]
|
| 71/4 |
2026/11/17 14:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 20831
output: 37
thoughts: 33
Thoughts: Here's my analysis of the provided snippet, framed as a thought process:
**Diving into the WireGuard Noise Implementation**
Okay, let's get down to brass tacks. I'm going to focus my attention on the `struct noise_keypair`. I want to drill down into the low-level details of the Noise protocol implementation within WireGuard, specifically the structure used for key management. To get the lay of the land, I'm going to examine lines 20-35 of `drivers/net/wireguard/noise.h`. This section likely defines the core structure used to hold cryptographic keys related to the Noise protocol. I suspect it'll tell me how WireGuard stores and organizes its ephemeral keys, static keys, and any associated data for this key exchange. I'm anticipating elements like public and private key representations, possibly some sort of sequence counters or flags. I'm keen to understand the exact data structures and any potential optimizations or security considerations built into them. This will provide a crucial foundation for understanding the rest of the implementation.
|
| 72/4 |
2026/11/17 14:33 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/noise.h FirstLine:20 LineCount:20]
Results: map[Contents: 20: spinlock_t lock;
21: unsigned long backtrack[COUNTER_BITS_TOTAL / BITS_PER_LONG];
22: };
23:
24: struct noise_symmetric_key {
25: u8 key[NOISE_SYMMETRIC_KEY_LEN];
26: u64 birthdate;
27: bool is_valid;
28: };
29:
30: struct noise_keypair {
31: struct index_hashtable_entry entry;
32: struct noise_symmetric_key sending;
33: atomic64_t sending_counter;
34: struct noise_symmetric_key receiving;
35: struct noise_replay_counter receiving_counter;
36: __le32 remote_index;
37: bool i_am_the_initiator;
38: struct kref refcount;
39: struct rcu_head rcu;
]
|
| 73/4 |
2026/11/17 14:33 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21397
output: 37
thoughts: 37
Thoughts: **Investigating the Wireguard Peer Structure**
Okay, let's dive in. My immediate thought is to understand the relationship between the `noise_handshake` component and the broader `struct wg_peer` definition. I need to get a clear picture of how they're connected, how `noise_handshake` is integrated. Time to look directly at the code. I'm going to start by pulling up the `drivers/net/wireguard/peer.h` file. That's the logical place to begin, as it should contain the definition for `wg_peer` and, hopefully, reveal how `noise_handshake` is embedded within it. From there, I can begin to unpack the data structures.
|
| 74/4 |
2026/11/17 14:33 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.h FirstLine:30 LineCount:60]
Results: map[Contents: 30: /* Essentially the same as addr6->scope_id */
31: int src_if4;
32: };
33: struct in6_addr src6;
34: };
35: };
36:
37: struct wg_peer {
38: struct wg_device *device;
39: struct prev_queue tx_queue, rx_queue;
40: struct sk_buff_head staged_packet_queue;
41: int serial_work_cpu;
42: bool is_dead;
43: struct noise_keypairs keypairs;
44: struct endpoint endpoint;
45: struct dst_cache endpoint_cache;
46: rwlock_t endpoint_lock;
47: struct noise_handshake handshake;
48: atomic64_t last_sent_handshake;
49: struct work_struct transmit_handshake_work, clear_peer_work, transmit_packet_work;
50: struct cookie latest_cookie;
51: struct hlist_node pubkey_hash;
52: u64 rx_bytes, tx_bytes;
53: struct timer_list timer_retransmit_handshake, timer_send_keepalive;
54: struct timer_list timer_new_handshake, timer_zero_key_material;
55: struct timer_list timer_persistent_keepalive;
56: unsigned int timer_handshake_attempts;
57: u16 persistent_keepalive_interval;
58: bool timer_need_another_keepalive;
59: bool sent_lastminute_handshake;
60: struct timespec64 walltime_last_handshake;
61: struct kref refcount;
62: struct rcu_head rcu;
63: struct list_head peer_list;
64: struct list_head allowedips_list;
65: struct napi_struct napi;
66: u64 internal_id;
67: };
68:
69: struct wg_peer *wg_peer_create(struct wg_device *wg,
70: const u8 public_key[NOISE_PUBLIC_KEY_LEN],
71: const u8 preshared_key[NOISE_SYMMETRIC_KEY_LEN]);
72:
73: struct wg_peer *__must_check wg_peer_get_maybe_zero(struct wg_peer *peer);
74: static inline struct wg_peer *wg_peer_get(struct wg_peer *peer)
75: {
76: kref_get(&peer->refcount);
77: return peer;
78: }
79: void wg_peer_put(struct wg_peer *peer);
80: void wg_peer_remove(struct wg_peer *peer);
81: void wg_peer_remove_all(struct wg_device *wg);
82:
83: int wg_peer_init(void);
84: void wg_peer_uninit(void);
85:
86: #endif /* _WG_PEER_H */
]
|
| 75/4 |
2026/11/17 14:33 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 22490
output: 25
thoughts: 1543
Thoughts: **Analyzing the WireGuard Peer Lookup**
Okay, let's break this down. I'm looking at `struct wg_peer` and its nested structures: `noise_handshake` and `noise_keypair`. It's clear that both `noise_handshake` and `noise_keypair` contain `struct index_hashtable_entry entry`, and importantly, the `entry` has a `peer` field. The initialization of `entry.peer` is crucial here. I see it's set in both `keypair_create` and `wg_noise_handshake_init`, and always points back to the owning `struct wg_peer`. This `peer` association is immutable during the lifetime of the keypair and the handshake β a key point.
Now, I'm focusing on `wg_index_hashtable_lookup`. The comment claims it returns a "strong reference to a entry->peer," but the code itself does something unexpected. Why is `entry->peer` being reassigned *within* this function? There's definitely something suspicious here. The function takes a `struct wg_peer **peer` as an out-parameter, so it seems the intended behavior is to return a reference to the `wg_peer` through this out parameter, not to modify `entry->peer` itself.
The comment and the out-parameter *suggest* the author *meant* to do this: assign the *result* of `wg_peer_get_maybe_zero()` to the out-parameter `*peer`, not the `entry->peer`. The subsequent `if (likely(*peer))` strongly implies a null check on the _returned_ pointer, and if NULL, then `entry` would be NULLed.
Essentially, there's a potential bug here. The line `entry->peer = wg_peer_get_maybe_zero(entry->peer);` is likely a mistaken assignment that should have been assigning the return value to `*peer` instead. This is likely a typo. The code *should* be:
*peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(*peer))
...
else
entry = NULL;
This ensures that `entry->peer` *remains* the original peer pointer, while the caller receives a strong reference, or `NULL`. This would ensure that the original data stored in `entry->peer` isn't overwritten.
The next step is to search for confirmation. Let's dig into the git log and history of WireGuard's code to see if there's any record of this, or some other explanation.
|
| 76/4 |
2026/11/17 14:34 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:wg_index_hashtable_lookup]
Results:
|
| 77/4 |
2026/11/17 14:44 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24654
output: 30
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Considering Best Practices for PathPrefix and Git Log Analysis**
Alright, let's establish a solid, consistent approach here. I'm thinking we should absolutely *always* define a `PathPrefix`. It just makes things cleaner, more predictable, and helps avoid potential conflicts down the line. To be specific, for this driver, let's set it to `"drivers/net/wireguard"`. That gives us a clearly defined and logical location.
Now, with that `PathPrefix` in place, it opens up some useful possibilities. I'm imagining a quick `git log` scan could reveal some immediate insights. We could filter the history, specifically targeting modifications within that prefixed path to ensure the driver follows the best coding practices. This is useful for quickly confirming that the right practices are in place. This will provide a straightforward way to confirm that the project is working as intended.
|
| 78/4 |
2026/11/17 14:44 |
tool |
git-log |
0m
Args: map[MessageRegexps:[lookup] PathPrefix:drivers/net/wireguard]
Results: map[Output:ba3d7b93dbe3 wireguard: allowedips: add WGALLOWEDIP_F_REMOVE_ME flag
c1822fb64f67 wireguard: allowedips: remove redundant selftest call
6147f7b1e90f wireguard: peerlookup: take lock before checking hash in replace operation
9179ba31367b wireguard: noise: take lock when removing handshake entry from table
ec31c2676a10 wireguard: noise: reject peers with low order public keys
e7096c131e51 net: WireGuard secure network tunnel
]
|
| 79/4 |
2026/11/17 14:44 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 25072
output: 26
thoughts: 18
Thoughts: Okay, here's my interpretation of what's going through my mind, delivered as requested:
**Deconstructing Commit 9179ba31367b**
Alright, let's dive in. First things first, I need to understand what's changed within commit `9179ba31367b`. I want to immediately get a grasp of its impact, so I'll start by rapidly reviewing the diff, focusing on any significant additions, deletions, or modifications. Given my expertise, I'll be looking for specific patterns, potential regressions, or novel approaches β anything that jumps out as particularly interesting or problematic. Iβm thinking about the wider system architecture and how this likely fits in, which areas of the codebase it touches, and what other modules might be impacted. My goal is a quick, high-level understanding before I get bogged down in the minutiae. I'll mentally categorize the changes, perhaps noting any potential refactoring opportunities or edge cases that need closer scrutiny. This initial scan is about forming a hypothesis β what's the main point, what's likely the intention, and what are the possible implications?
|
| 80/4 |
2026/11/17 14:44 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 9179ba31367bcf481c3c79b5f028c94faad9f30a
Author: Jason A. Donenfeld <Jason@zx2c4.com>
Date: Wed Sep 9 13:58:14 2020 +0200
wireguard: noise: take lock when removing handshake entry from table
Eric reported that syzkaller found a race of this variety:
CPU 1 CPU 2
-------------------------------------------|---------------------------------------
wg_index_hashtable_replace(old, ...) |
if (hlist_unhashed(&old->index_hash)) |
| wg_index_hashtable_remove(old)
| hlist_del_init_rcu(&old->index_hash)
| old->index_hash.pprev = NULL
hlist_replace_rcu(&old->index_hash, ...) |
*old->index_hash.pprev |
Syzbot wasn't actually able to reproduce this more than once or create a
reproducer, because the race window between checking "hlist_unhashed" and
calling "hlist_replace_rcu" is just so small. Adding an mdelay(5) or
similar there helps make this demonstrable using this simple script:
#!/bin/bash
set -ex
trap 'kill $pid1; kill $pid2; ip link del wg0; ip link del wg1' EXIT
ip link add wg0 type wireguard
ip link add wg1 type wireguard
wg set wg0 private-key <(wg genkey) listen-port 9999
wg set wg1 private-key <(wg genkey) peer $(wg show wg0 public-key) endpoint 127.0.0.1:9999 persistent-keepalive 1
wg set wg0 peer $(wg show wg1 public-key)
ip link set wg0 up
yes link set wg1 up | ip -force -batch - &
pid1=$!
yes link set wg1 down | ip -force -batch - &
pid2=$!
wait
The fundumental underlying problem is that we permit calls to wg_index_
hashtable_remove(handshake.entry) without requiring the caller to take
the handshake mutex that is intended to protect members of handshake
during mutations. This is consistently the case with calls to wg_index_
hashtable_insert(handshake.entry) and wg_index_hashtable_replace(
handshake.entry), but it's missing from a pertinent callsite of wg_
index_hashtable_remove(handshake.entry). So, this patch makes sure that
mutex is taken.
The original code was a little bit funky though, in the form of:
remove(handshake.entry)
lock(), memzero(handshake.some_members), unlock()
remove(handshake.entry)
The original intention of that double removal pattern outside the lock
appears to be some attempt to prevent insertions that might happen while
locks are dropped during expensive crypto operations, but actually, all
callers of wg_index_hashtable_insert(handshake.entry) take the write
lock and then explicitly check handshake.state, as they should, which
the aforementioned memzero clears, which means an insertion should
already be impossible. And regardless, the original intention was
necessarily racy, since it wasn't guaranteed that something else would
run after the unlock() instead of after the remove(). So, from a
soundness perspective, it seems positive to remove what looks like a
hack at best.
The crash from both syzbot and from the script above is as follows:
general protection fault, probably for non-canonical address 0xdffffc0000000000: 0000 [#1] PREEMPT SMP KASAN
KASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007]
CPU: 0 PID: 7395 Comm: kworker/0:3 Not tainted 5.9.0-rc4-syzkaller #0
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011
Workqueue: wg-kex-wg1 wg_packet_handshake_receive_worker
RIP: 0010:hlist_replace_rcu include/linux/rculist.h:505 [inline]
RIP: 0010:wg_index_hashtable_replace+0x176/0x330 drivers/net/wireguard/peerlookup.c:174
Code: 00 fc ff df 48 89 f9 48 c1 e9 03 80 3c 01 00 0f 85 44 01 00 00 48 b9 00 00 00 00 00 fc ff df 48 8b 45 10 48 89 c6 48 c1 ee 03 <80> 3c 0e 00 0f 85 06 01 00 00 48 85 d2 4c 89 28 74 47 e8 a3 4f b5
RSP: 0018:ffffc90006a97bf8 EFLAGS: 00010246
RAX: 0000000000000000 RBX: ffff888050ffc4f8 RCX: dffffc0000000000
RDX: 0000000000000000 RSI: 0000000000000000 RDI: ffff88808e04e010
RBP: ffff88808e04e000 R08: 0000000000000001 R09: ffff8880543d0000
R10: ffffed100a87a000 R11: 000000000000016e R12: ffff8880543d0000
R13: ffff88808e04e008 R14: ffff888050ffc508 R15: ffff888050ffc500
FS: 0000000000000000(0000) GS:ffff8880ae600000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000f5505db0 CR3: 0000000097cf7000 CR4: 00000000001526f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
Call Trace:
wg_noise_handshake_begin_session+0x752/0xc9a drivers/net/wireguard/noise.c:820
wg_receive_handshake_packet drivers/net/wireguard/receive.c:183 [inline]
wg_packet_handshake_receive_worker+0x33b/0x730 drivers/net/wireguard/receive.c:220
process_one_work+0x94c/0x1670 kernel/workqueue.c:2269
worker_thread+0x64c/0x1120 kernel/workqueue.c:2415
kthread+0x3b5/0x4a0 kernel/kthread.c:292
ret_from_fork+0x1f/0x30 arch/x86/entry/entry_64.S:294
Reported-by: syzbot <syzkaller@googlegroups.com>
Reported-by: Eric Dumazet <edumazet@google.com>
Link: https://lore.kernel.org/wireguard/20200908145911.4090480-1-edumazet@google.com/
Fixes: e7096c131e51 ("net: WireGuard secure network tunnel")
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
diff --git a/drivers/net/wireguard/noise.c b/drivers/net/wireguard/noise.c
index 3dd3b76790d0..c0cfd9b36c0b 100644
--- a/drivers/net/wireguard/noise.c
+++ b/drivers/net/wireguard/noise.c
@@ -87,15 +87,12 @@ static void handshake_zero(struct noise_handshake *handshake)
void wg_noise_handshake_clear(struct noise_handshake *handshake)
{
+ down_write(&handshake->lock);
wg_index_hashtable_remove(
handshake->entry.peer->device->index_hashtable,
&handshake->entry);
- down_write(&handshake->lock);
handshake_zero(handshake);
up_write(&handshake->lock);
- wg_index_hashtable_remove(
- handshake->entry.peer->device->index_hashtable,
- &handshake->entry);
}
static struct noise_keypair *keypair_create(struct wg_peer *peer)
]
|
| 81/4 |
2026/11/17 14:44 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 28006
output: 35
thoughts: 1164
Thoughts: **Vulnerability Assessment: NULL Pointer Dereference in WireGuard Kernel Module**
Okay, I'm digging into this WireGuard code, and I see some serious potential issues here. First, I'm looking at `wg_noise_handshake_clear`. The code removes an entry from an index hashtable using `wg_index_hashtable_remove`, specifically using `handshake->entry.peer->device->index_hashtable`. My concern is that if `handshake->entry.peer` is NULL, this immediately leads to a NULL pointer dereference, crashing the kernel when trying to dereference `handshake->entry.peer->device`. A handshake could potentially be cleared from the index before the peer itself is valid.
Then, moving on to `keypair_free_kref`, it's the same scenario, but worse. I see multiple dereferences of `keypair->entry.peer` without any null checks: `keypair->entry.peer->device->dev->name`, `keypair->entry.peer->internal_id`, and `keypair->entry.peer->device->index_hashtable`. If `keypair->entry.peer` is NULL, each of these results in a crash due to NULL pointer dereference. This implies a keypair is freed and its associated peer entry becomes invalid. However, the code still tries to access the peer data, resulting in a crash.
Now, I'm focusing on the `wg_queue_enqueue_per_peer_tx` and `wg_queue_enqueue_per_peer_rx` functions, and `PACKET_PEER(skb)`. This is where it gets really interesting. `PACKET_PEER(skb)` is defined as `PACKET_CB(skb)->keypair->entry.peer`. The functions call `wg_peer_get(PACKET_PEER(skb))` which then calls `kref_get(&peer->refcount)`. The problem here is that `kref_get` increments `peer->refcount` without first checking if `peer` is NULL. Dereferencing a NULL pointer leads to an immediate kernel crash. Even further, `peer->napi`, `peer->serial_work_cpu`, and `peer->device` are used right after without null checks, so a null peer is completely fatal to the device. The references taken here seem to be taken with the intent to protect the peer, however, if we are getting a null peer, this is going to crash right away!
The root cause in this situation appears to come from a failure to validate the peer pointer, specifically within the `keypair->entry.peer` data. There appears to be a window where the peer may be invalid. When this invalidated peer data is dereferenced, the kernel is crashed due to a NULL pointer dereference.
|
| 82/4 |
2026/11/17 14:45 |
tool |
grepper |
0m
Args: map[Expression:wg_packet_consume_data PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/peer.c=94=static void peer_remove_after_dead(struct wg_peer *peer)
--
drivers/net/wireguard/peer.c-132- * different contexts: 1) from xmit(), before hitting is_dead and
drivers/net/wireguard/peer.c:133: * returning, 2) from wg_packet_consume_data(), before hitting is_dead
drivers/net/wireguard/peer.c-134- * and returning, 3) from wg_receive_handshake_packet() after a point
--
drivers/net/wireguard/receive.c=295=static bool counter_validate(struct noise_replay_counter *counter, u64 their_counter)
--
drivers/net/wireguard/receive.c-334-
drivers/net/wireguard/receive.c:335:static void wg_packet_consume_data_done(struct wg_peer *peer,
drivers/net/wireguard/receive.c-336- struct sk_buff *skb,
--
drivers/net/wireguard/receive.c=438=int wg_packet_rx_poll(struct napi_struct *napi, int budget)
--
drivers/net/wireguard/receive.c-473- wg_reset_packet(skb, false);
drivers/net/wireguard/receive.c:474: wg_packet_consume_data_done(peer, skb, &endpoint);
drivers/net/wireguard/receive.c-475- free = false;
--
drivers/net/wireguard/receive.c=493=void wg_packet_decrypt_worker(struct work_struct *work)
--
drivers/net/wireguard/receive.c-508-
drivers/net/wireguard/receive.c:509:static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb)
drivers/net/wireguard/receive.c-510-{
--
drivers/net/wireguard/receive.c=542=void wg_packet_receive(struct wg_device *wg, struct sk_buff *skb)
--
drivers/net/wireguard/receive.c-575- PACKET_CB(skb)->ds = ip_tunnel_get_dsfield(ip_hdr(skb), skb);
drivers/net/wireguard/receive.c:576: wg_packet_consume_data(wg, skb);
drivers/net/wireguard/receive.c-577- break;
]
|
| 83/4 |
2026/11/17 14:45 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 30452
output: 38
thoughts: 23
Thoughts: Okay, let's dive into this. Here's my thought process on the matter:
**Analyzing the WireGuard Receive Path**
Alright, I need to understand what's happening in the `drivers/net/wireguard/receive.c` file, specifically around line 509. My experience tells me that area likely handles a critical function within the receive path of WireGuard. Itβs probably where packet processing, decryption, or some form of integrity check occurs after the initial reception on the network interface. I expect to see logic related to verifying the senderβs identity (perhaps comparing a public key or checking a key ID), ensuring the packet hasnβt been tampered with (e.g., verifying a MAC or signature), and then potentially passing the decrypted data further up the networking stack. Line 509 itself is probably either the start of a new function or a critical conditional branch within that area. Iβm guessing itβs either the integrity check or the start of the decryption routine. Let's see whatβs there.
|
| 84/4 |
2026/11/17 14:45 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/receive.c FirstLine:505 LineCount:40]
Results: map[Contents: 505: cond_resched();
506: }
507: }
508:
509: static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb)
510: {
511: __le32 idx = ((struct message_data *)skb->data)->key_idx;
512: struct wg_peer *peer = NULL;
513: int ret;
514:
515: rcu_read_lock_bh();
516: PACKET_CB(skb)->keypair =
517: (struct noise_keypair *)wg_index_hashtable_lookup(
518: wg->index_hashtable, INDEX_HASHTABLE_KEYPAIR, idx,
519: &peer);
520: if (unlikely(!wg_noise_keypair_get(PACKET_CB(skb)->keypair)))
521: goto err_keypair;
522:
523: if (unlikely(READ_ONCE(peer->is_dead)))
524: goto err;
525:
526: ret = wg_queue_enqueue_per_device_and_peer(&wg->decrypt_queue, &peer->rx_queue, skb,
527: wg->packet_crypt_wq);
528: if (unlikely(ret == -EPIPE))
529: wg_queue_enqueue_per_peer_rx(skb, PACKET_STATE_DEAD);
530: if (likely(!ret || ret == -EPIPE)) {
531: rcu_read_unlock_bh();
532: return;
533: }
534: err:
535: wg_noise_keypair_put(PACKET_CB(skb)->keypair, false);
536: err_keypair:
537: rcu_read_unlock_bh();
538: wg_peer_put(peer);
539: dev_kfree_skb(skb);
540: }
541:
542: void wg_packet_receive(struct wg_device *wg, struct sk_buff *skb)
543: {
544: if (unlikely(prepare_skb_header(skb, wg) < 0))
]
|
| 85/4 |
2026/11/17 14:45 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 31400
output: 41
thoughts: 1025
Thoughts: **Vulnerability Analysis in `wg_packet_consume_data`**
Okay, let's break this down. I'm looking at `wg_packet_consume_data` and immediately see a potential issue with the handling of `wg_index_hashtable_lookup`. We have an RCU read lock, a keypair lookup, and a quick check for a valid keypair using `wg_noise_keypair_get`. The critical point, as I see it, is what happens when `wg_index_hashtable_lookup` returns NULL, or rather, when it _should_ return something, but ultimately doesn't.
If `wg_index_hashtable_lookup` returns NULL, `wg_noise_keypair_get(NULL)` returns NULL and we jump to error handling, releasing resources and freeing the SKB. That's the expected path. But what if the lookup *finds* an entry, but the `entry->peer` pointer *within* that entry somehow ends up being NULL? That's where things get interesting.
I need to dig into the `wg_index_hashtable_lookup` function and look at how it actually handles the `entry` and the `peer`. I see that it calls `wg_peer_get_maybe_zero(entry->peer)`. If that function returns NULL, *crucially*, it sets `entry->peer = NULL` *before* returning NULL. *That* `entry` then gets returned to `wg_packet_consume_data`. So, the caller gets a NULL `entry`, but the underlying `entry->peer` (which probably lives inside a keypair or handshake struct!) has already been mutated to NULL. This is a critical point.
Now, what happens to that `entry` whose `entry->peer` was just overwritten with NULL? I need to trace the use of that entry later. It's either in the hashtable, or it *was* in the hashtable. The question is whether it can be re-accessed later, or if the keypair/handshake are freed before the mutated value is dealt with.
I see a red flag; I need to look at what happens to this entry later. Specifically, when `keypair_free_kref()` is called! Let's examine it:
If `keypair->entry.peer` is now NULL, this is a recipe for disaster! `keypair->entry.peer->device->dev->name` and `keypair->entry.peer->device->index_hashtable` will both dereference a NULL pointer! Kernel BUG/NULL pointer dereference crash! This is a clear vulnerability. It's a double whammy, because if this code crashes, the hashtable entry isn't even removed!
And another thought: why would `wg_peer_get_maybe_zero(entry->peer)` return NULL in the first place? It's when the peer's reference count is *already* zero! This happens when a peer is being removed or freed! I need to investigate the peer lifetime and specifically what happens with peer removal to verify this hypothesis. I must inspect `peer.c` around `peer_remove_after_dead()` and follow the freeing of peers and keypairs to fully understand the race conditions.
|
| 86/4 |
2026/11/17 14:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peer.c Name:peer_remove_after_dead]
Results: map[SourceCode: 94: static void peer_remove_after_dead(struct wg_peer *peer)
95: {
96: WARN_ON(!peer->is_dead);
97:
98: /* No more keypairs can be created for this peer, since is_dead protects
99: * add_new_keypair, so we can now destroy existing ones.
100: */
101: wg_noise_keypairs_clear(&peer->keypairs);
102:
103: /* Destroy all ongoing timers that were in-flight at the beginning of
104: * this function.
105: */
106: wg_timers_stop(peer);
107:
108: /* The transition between packet encryption/decryption queues isn't
109: * guarded by is_dead, but each reference's life is strictly bounded by
110: * two generations: once for parallel crypto and once for serial
111: * ingestion, so we can simply flush twice, and be sure that we no
112: * longer have references inside these queues.
113: */
114:
115: /* a) For encrypt/decrypt. */
116: flush_workqueue(peer->device->packet_crypt_wq);
117: /* b.1) For send (but not receive, since that's napi). */
118: flush_workqueue(peer->device->packet_crypt_wq);
119: /* b.2.1) For receive (but not send, since that's wq). */
120: napi_disable(&peer->napi);
121: /* b.2.1) It's now safe to remove the napi struct, which must be done
122: * here from process context.
123: */
124: netif_napi_del(&peer->napi);
125:
126: /* Ensure any workstructs we own (like transmit_handshake_work or
127: * clear_peer_work) no longer are in use.
128: */
129: flush_workqueue(peer->device->handshake_send_wq);
130:
131: /* After the above flushes, a peer might still be active in a few
132: * different contexts: 1) from xmit(), before hitting is_dead and
133: * returning, 2) from wg_packet_consume_data(), before hitting is_dead
134: * and returning, 3) from wg_receive_handshake_packet() after a point
135: * where it has processed an incoming handshake packet, but where
136: * all calls to pass it off to timers fails because of is_dead. We won't
137: * have new references in (1) eventually, because we're removed from
138: * allowedips; we won't have new references in (2) eventually, because
139: * wg_index_hashtable_lookup will always return NULL, since we removed
140: * all existing keypairs and no more can be created; we won't have new
141: * references in (3) eventually, because we're removed from the pubkey
142: * hash table, which allows for a maximum of one handshake response,
143: * via the still-uncleared index hashtable entry, but not more than one,
144: * and in wg_cookie_message_consume, the lookup eventually gets a peer
145: * with a refcount of zero, so no new reference is taken.
146: */
147:
148: --peer->device->num_peers;
149: wg_peer_put(peer);
150: }
SourceFile:drivers/net/wireguard/peer.c]
|
| 87/4 |
2026/11/17 14:46 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 34213
output: 42
thoughts: 111
Thoughts: **Analyzing Peer Removal in WireGuard**
Okay, I need to understand this WireGuard code more deeply, specifically how peer removal is handled. Let's start by focusing on lines 140-146; that's where the critical stuff likely happens. The text mentions that in `wg_cookie_message_consume`, there's a point where the peer lookup results in a peer with a zero refcount, and no new reference is taken. Hmm, interesting. Now, when a peer *is* being removed, what's the sequence?
I'm digging into how the `peer->keypairs` data is handled during this process. Line 101 reveals that `wg_noise_keypairs_clear(&peer->keypairs)` is called. Naturally, my next step is to examine what `wg_noise_keypairs_clear` actually *does*. That's where the real insights will be.
|
| 88/4 |
2026/11/17 14:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/noise.c Name:wg_noise_keypairs_clear]
Results: map[SourceCode: 151: void wg_noise_keypairs_clear(struct noise_keypairs *keypairs)
152: {
153: struct noise_keypair *old;
154:
155: spin_lock_bh(&keypairs->keypair_update_lock);
156:
157: /* We zero the next_keypair before zeroing the others, so that
158: * wg_noise_received_with_keypair returns early before subsequent ones
159: * are zeroed.
160: */
161: old = rcu_dereference_protected(keypairs->next_keypair,
162: lockdep_is_held(&keypairs->keypair_update_lock));
163: RCU_INIT_POINTER(keypairs->next_keypair, NULL);
164: wg_noise_keypair_put(old, true);
165:
166: old = rcu_dereference_protected(keypairs->previous_keypair,
167: lockdep_is_held(&keypairs->keypair_update_lock));
168: RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
169: wg_noise_keypair_put(old, true);
170:
171: old = rcu_dereference_protected(keypairs->current_keypair,
172: lockdep_is_held(&keypairs->keypair_update_lock));
173: RCU_INIT_POINTER(keypairs->current_keypair, NULL);
174: wg_noise_keypair_put(old, true);
175:
176: spin_unlock_bh(&keypairs->keypair_update_lock);
177: }
SourceFile:drivers/net/wireguard/noise.c]
|
| 89/4 |
2026/11/17 14:46 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 35082
output: 39
thoughts: 272
Thoughts: **Analyzing the Noise Keypair Removal**
Okay, so I'm diving into this `wg_noise_keypair_put(old, true)` call. Let's break down the logic. My immediate thought is, what's happening under the hood with that `wg_noise_keypair_put` function? Right, it's defined as `void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now)`. Got it. Now, it does a quick check for a null keypair, which is standard defensive programming. If `unreference_now` is true, it removes the entry from the index hashtable. Finally, it calls `kref_put` on the keypair's reference count.
Now, I'm already thinking about potential race conditions and memory management. We see `peer_remove_after_dead()` calls `wg_peer_put(peer)` at line 149. The critical question here is what happens if a keypair is still referenced when that `peer`'s reference count drops to zero, or worse, during the peer's destruction? If a packet arrived at this exact moment, and that peer had been destroyed, would `wg_index_hashtable_lookup()` fail, or worse?
I need to see exactly when the `peer` is freed, so let's check `wg_peer_put` and `peer_make_dead` for the details. This looks like a potential point of failure if not handled precisely.
|
| 90/4 |
2026/11/17 14:47 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peer.c Name:wg_peer_put]
Results: map[SourceCode: 223: void wg_peer_put(struct wg_peer *peer)
224: {
225: if (unlikely(!peer))
226: return;
227: kref_put(&peer->refcount, kref_release);
228: }
SourceFile:drivers/net/wireguard/peer.c]
|
| 91/4 |
2026/11/17 14:47 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 35836
output: 39
thoughts: 16
Thoughts: Here's my summary, as if I were thinking these thoughts:
**Peering into Peer.c**
Alright, time to dig into this. I need to understand what's going on with the memory management, and `kref_release` feels like a likely suspect. Let me check the `peer.c` file. Specifically, I'm going to focus in on the `kref_release` calls within that module. It's often where you find the core logic for object lifecycle management and resource cleanup in this type of codebase. I'll need to trace the references and understand how the reference counting is used in relation to the peer objects. Hopefully, the implementation is straightforward. I'm looking for any potential leaks, double frees, or incorrect reference handling patterns. Let's see what we can find.
|
| 92/4 |
2026/11/17 14:47 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peer.c Name:peer_make_dead]
Results: map[SourceCode: 80: static void peer_make_dead(struct wg_peer *peer)
81: {
82: /* Remove from configuration-time lookup structures. */
83: list_del_init(&peer->peer_list);
84: wg_allowedips_remove_by_peer(&peer->device->peer_allowedips, peer,
85: &peer->device->device_update_lock);
86: wg_pubkey_hashtable_remove(peer->device->peer_hashtable, peer);
87:
88: /* Mark as dead, so that we don't allow jumping contexts after. */
89: WRITE_ONCE(peer->is_dead, true);
90:
91: /* The caller must now synchronize_net() for this to take effect. */
92: }
SourceFile:drivers/net/wireguard/peer.c]
|
| 93/4 |
2026/11/17 14:47 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 36315
output: 38
thoughts: 38
Thoughts: Okay, let's dive into this. I'm focusing on `kref_release`, specifically within the context of wireguard's peer management, so that would be lines 150-225 of `drivers/net/wireguard/peer.c`. Let's see what's happening in there.
|
| 94/4 |
2026/11/17 14:47 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.c FirstLine:150 LineCount:50]
Results: map[Contents: 150: }
151:
152: /* We have a separate "remove" function make sure that all active places where
153: * a peer is currently operating will eventually come to an end and not pass
154: * their reference onto another context.
155: */
156: void wg_peer_remove(struct wg_peer *peer)
157: {
158: if (unlikely(!peer))
159: return;
160: lockdep_assert_held(&peer->device->device_update_lock);
161:
162: peer_make_dead(peer);
163: synchronize_net();
164: peer_remove_after_dead(peer);
165: }
166:
167: void wg_peer_remove_all(struct wg_device *wg)
168: {
169: struct wg_peer *peer, *temp;
170: LIST_HEAD(dead_peers);
171:
172: lockdep_assert_held(&wg->device_update_lock);
173:
174: /* Avoid having to traverse individually for each one. */
175: wg_allowedips_free(&wg->peer_allowedips, &wg->device_update_lock);
176:
177: list_for_each_entry_safe(peer, temp, &wg->peer_list, peer_list) {
178: peer_make_dead(peer);
179: list_add_tail(&peer->peer_list, &dead_peers);
180: }
181: synchronize_net();
182: list_for_each_entry_safe(peer, temp, &dead_peers, peer_list)
183: peer_remove_after_dead(peer);
184: }
185:
186: static void rcu_release(struct rcu_head *rcu)
187: {
188: struct wg_peer *peer = container_of(rcu, struct wg_peer, rcu);
189:
190: dst_cache_destroy(&peer->endpoint_cache);
191: WARN_ON(wg_prev_queue_peek(&peer->tx_queue) || wg_prev_queue_peek(&peer->rx_queue));
192:
193: /* The final zeroing takes care of clearing any remaining handshake key
194: * material and other potentially sensitive information.
195: */
196: memzero_explicit(peer, sizeof(*peer));
197: kmem_cache_free(peer_cache, peer);
198: }
199:
]
|
| 95/4 |
2026/11/17 14:47 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 37235
output: 38
thoughts: 22
Thoughts: Okay, let's dive into this. I'm focusing my attention on `peer.c`, specifically lines 200 through 225. I need to understand what's happening within this segment of code, its purpose, and how it fits into the broader architecture of this system. I'm expecting to find some crucial logic related to peer-to-peer communication or handling of peer connections. It's time to dig in and unravel the details. I anticipate it deals with either incoming or outgoing connections, possibly connection initialization, authentication or data exchange routines specific to the peer layer. I'm prepared to critically assess the coding style, identify potential areas of concern for performance, security, or maintainability and identify whether there are any deviations from established best practices in this area. My focus is on understanding the granular detail and how that impacts the bigger picture.
|
| 96/4 |
2026/11/17 14:48 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/peer.c FirstLine:200 LineCount:25]
Results: map[Contents: 200: static void kref_release(struct kref *refcount)
201: {
202: struct wg_peer *peer = container_of(refcount, struct wg_peer, refcount);
203:
204: pr_debug("%s: Peer %llu (%pISpfsc) destroyed\n",
205: peer->device->dev->name, peer->internal_id,
206: &peer->endpoint.addr);
207:
208: /* Remove ourself from dynamic runtime lookup structures, now that the
209: * last reference is gone.
210: */
211: wg_index_hashtable_remove(peer->device->index_hashtable,
212: &peer->handshake.entry);
213:
214: /* Remove any lingering packets that didn't have a chance to be
215: * transmitted.
216: */
217: wg_packet_purge_staged_packets(peer);
218:
219: /* Free the memory used. */
220: call_rcu(&peer->rcu, rcu_release);
221: }
222:
223: void wg_peer_put(struct wg_peer *peer)
224: {
]
|
| 97/4 |
2026/11/17 14:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 37856
output: 36
thoughts: 519
Thoughts: **Analyzing a Potential Race Condition in WireGuard Peer Removal**
Okay, let's break this down. I'm looking at the `kref_release()` function, specifically how it interacts with the `index_hashtable`. The key observation is that `peer->handshake.entry` remains in the `index_hashtable` *until* the very last reference to the `peer` is released in `kref_release()`. Got it.
Now, let's consider what happens *before* `kref_release()` gets called. I know that `peer_remove_after_dead()` calls `wg_peer_put(peer)` when `peer->refcount` hits zero. *That* `wg_peer_put` call might be the critical point where the refcount drops to zero.
Here's where the potential problem lies. Consider this window of vulnerability: when `peer->refcount` *is* zero (or actively undergoing final release). If a new packet arrives β say, a handshake response or a cookie message β that corresponds to the `index` of the `peer->handshake.entry` still in the `index_hashtable`, the `wg_index_hashtable_lookup()` function will look up the `index` and find the entry.
It gets to the crux of the problem: if `entry` is found, the code does this: `entry->peer = wg_peer_get_maybe_zero(entry->peer);`. Now, because `peer->refcount` is zero, or nearly zero, `wg_peer_get_maybe_zero` calls `kref_get_unless_zero(&peer->refcount)`. Because the refcount is zero, or getting there, that function returns 0. So, `wg_peer_get_maybe_zero` returns NULL!
And what does *that* mean? The code does this: `entry->peer = NULL;` It's setting `peer->handshake.entry.peer = NULL;`!
Wait, but what happens next? What can call `wg_noise_handshake_clear` and when? I need to understand when and how `wg_noise_handshake_clear` is called in relation to this sequence. I'll need to run a `grep` to trace where that function is used to understand the flow better. This feels like a classic race condition waiting to happen. I need to fully understand the execution path when a packet comes in for a peer *just* as it's being freed.
|
| 98/4 |
2026/11/17 14:48 |
tool |
grepper |
0m
Args: map[Expression:wg_noise_handshake_clear PathPrefixes:[drivers/net/wireguard/]]
Results: map[Output:drivers/net/wireguard/device.c=64=static int wg_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
--
drivers/net/wireguard/device.c-84- timer_delete(&peer->timer_zero_key_material);
drivers/net/wireguard/device.c:85: wg_noise_handshake_clear(&peer->handshake);
drivers/net/wireguard/device.c-86- wg_noise_keypairs_clear(&peer->keypairs);
--
drivers/net/wireguard/device.c=115=static int wg_stop(struct net_device *dev)
--
drivers/net/wireguard/device.c-124- wg_timers_stop(peer);
drivers/net/wireguard/device.c:125: wg_noise_handshake_clear(&peer->handshake);
drivers/net/wireguard/device.c-126- wg_noise_keypairs_clear(&peer->keypairs);
--
drivers/net/wireguard/noise.c=78=static void handshake_zero(struct noise_handshake *handshake)
--
drivers/net/wireguard/noise.c-87-
drivers/net/wireguard/noise.c:88:void wg_noise_handshake_clear(struct noise_handshake *handshake)
drivers/net/wireguard/noise.c-89-{
--
drivers/net/wireguard/noise.c=179=void wg_noise_expire_current_peer_keypairs(struct wg_peer *peer)
--
drivers/net/wireguard/noise.c-182-
drivers/net/wireguard/noise.c:183: wg_noise_handshake_clear(&peer->handshake);
drivers/net/wireguard/noise.c-184- wg_noise_reset_last_sent_handshake(&peer->last_sent_handshake);
--
drivers/net/wireguard/noise.h=95=void wg_noise_handshake_init(struct noise_handshake *handshake,
--
drivers/net/wireguard/noise.h-99- struct wg_peer *peer);
drivers/net/wireguard/noise.h:100:void wg_noise_handshake_clear(struct noise_handshake *handshake);
drivers/net/wireguard/noise.h-101-static inline void wg_noise_reset_last_sent_handshake(atomic64_t *handshake_ns)
--
drivers/net/wireguard/timers.c=125=static void wg_queued_expired_zero_key_material(struct work_struct *work)
--
drivers/net/wireguard/timers.c-132- &peer->endpoint.addr, (int)REJECT_AFTER_TIME * 3);
drivers/net/wireguard/timers.c:133: wg_noise_handshake_clear(&peer->handshake);
drivers/net/wireguard/timers.c-134- wg_noise_keypairs_clear(&peer->keypairs);
]
|
| 99/4 |
2026/11/17 14:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39719
output: 43
thoughts: 376
Thoughts: **Keypair Destruction and Index Hashtable Management**
Okay, so I'm digging into how keypairs are handled here. A crucial question keeps popping up β could `wg_peer_get_maybe_zero(entry->peer)` potentially return NULL for a KEYPAIR? I need to clarify that. Let's see how they're destroyed and where that might occur.
It seems that `keypairs_clear()` is the culprit; it calls `wg_noise_keypair_put(old, true);`. Hold on a second, within `wg_noise_keypairs_clear(keypairs)`, the code dereferences `keypairs->current_keypair` with RCU protection and then sets it to NULL. Then, it calls `wg_noise_keypair_put(old, true)`. Now, I need to understand what `wg_noise_keypair_put(old, true)` is *actually* doing.
Looking at the `wg_noise_keypair_put` function, it first checks for a NULL keypair, which is expected. The interesting part is that if `unreference_now` is true, it removes `keypair->entry` from the index hashtable using `wg_index_hashtable_remove`. BUT, I see that the function `wg_index_hashtable_remove` uses `hlist_del_init_rcu`. Time to head to `peerlookup.c` and dig into `wg_index_hashtable_remove` to see what is happening there!
|
| 100/4 |
2026/11/17 14:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/net/wireguard/peerlookup.c Name:wg_index_hashtable_remove]
Results: map[SourceCode: 192: void wg_index_hashtable_remove(struct index_hashtable *table,
193: struct index_hashtable_entry *entry)
194: {
195: spin_lock_bh(&table->lock);
196: hlist_del_init_rcu(&entry->index_hash);
197: spin_unlock_bh(&table->lock);
198: }
SourceFile:drivers/net/wireguard/peerlookup.c]
|
| 101/4 |
2026/11/17 14:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40615
output: 48
thoughts: 117
Thoughts: **Analyzing the Concurrency in wg_index_hashtable_remove**
Okay, so `wg_index_hashtable_remove` is using `hlist_del_init_rcu`! That immediately sets off some alarms, especially when you're dealing with concurrent access. The crux of the issue is that an RCU reader that initiates its lookup *before* or during the `hlist_del_init_rcu` operation *could still* potentially find the entry in the hashtable if it is still protected by `rcu_read_lock_bh()`. We need to be very precise about the read-side critical section.
And here's where it gets interesting: what happens if the `unreference_now` flag is false? That's a critical detail that needs very careful examination. Where exactly is `wg_noise_keypair_put(..., false)` called? I need to track down every single instance of that function call to fully understand its impact on the lifecycle of these keypairs.
Alright, let's pull up the call graph for `wg_noise_keypair_put`. Time to methodically check every single caller, and deeply analyze its call stack, and the conditions of its invocation, to figure out the exact implications of this.
|
| 102/4 |
2026/11/17 14:49 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/net/wireguard/noise.h IncludeSnippetLines:5 Name:wg_noise_keypair_put]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:add_new_keypair SourceFile:drivers/net/wireguard/noise.c SourceLine:228 SourceSnippet: 223: * for the future.
224: */
225: RCU_INIT_POINTER(keypairs->next_keypair, NULL);
226: rcu_assign_pointer(keypairs->previous_keypair,
227: next_keypair);
228: wg_noise_keypair_put(current_keypair, true);
229: } else /* If there wasn't an existing next keypair, we replace
230: * the previous with the current one.
231: */
232: rcu_assign_pointer(keypairs->previous_keypair,
233: current_keypair);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:add_new_keypair SourceFile:drivers/net/wireguard/noise.c SourceLine:237 SourceSnippet: 232: rcu_assign_pointer(keypairs->previous_keypair,
233: current_keypair);
234: /* At this point we can get rid of the old previous keypair, and
235: * set up the new keypair.
236: */
237: wg_noise_keypair_put(previous_keypair, true);
238: rcu_assign_pointer(keypairs->current_keypair, new_keypair);
239: } else {
240: /* If we're the responder, it means we can't use the new keypair
241: * until we receive confirmation via the first data packet, so
242: * we get rid of the existing previous one, the possibly
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:add_new_keypair SourceFile:drivers/net/wireguard/noise.c SourceLine:246 SourceSnippet: 241: * until we receive confirmation via the first data packet, so
242: * we get rid of the existing previous one, the possibly
243: * existing next one, and slide in the new next one.
244: */
245: rcu_assign_pointer(keypairs->next_keypair, new_keypair);
246: wg_noise_keypair_put(next_keypair, true);
247: RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
248: wg_noise_keypair_put(previous_keypair, true);
249: }
250: spin_unlock_bh(&keypairs->keypair_update_lock);
251: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:add_new_keypair SourceFile:drivers/net/wireguard/noise.c SourceLine:248 SourceSnippet: 243: * existing next one, and slide in the new next one.
244: */
245: rcu_assign_pointer(keypairs->next_keypair, new_keypair);
246: wg_noise_keypair_put(next_keypair, true);
247: RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
248: wg_noise_keypair_put(previous_keypair, true);
249: }
250: spin_unlock_bh(&keypairs->keypair_update_lock);
251: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_noise_keypairs_clear SourceFile:drivers/net/wireguard/noise.c SourceLine:164 SourceSnippet: 159: * are zeroed.
160: */
161: old = rcu_dereference_protected(keypairs->next_keypair,
162: lockdep_is_held(&keypairs->keypair_update_lock));
163: RCU_INIT_POINTER(keypairs->next_keypair, NULL);
164: wg_noise_keypair_put(old, true);
165:
166: old = rcu_dereference_protected(keypairs->previous_keypair,
167: lockdep_is_held(&keypairs->keypair_update_lock));
168: RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
169: wg_noise_keypair_put(old, true);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_noise_keypairs_clear SourceFile:drivers/net/wireguard/noise.c SourceLine:169 SourceSnippet: 164: wg_noise_keypair_put(old, true);
165:
166: old = rcu_dereference_protected(keypairs->previous_keypair,
167: lockdep_is_held(&keypairs->keypair_update_lock));
168: RCU_INIT_POINTER(keypairs->previous_keypair, NULL);
169: wg_noise_keypair_put(old, true);
170:
171: old = rcu_dereference_protected(keypairs->current_keypair,
172: lockdep_is_held(&keypairs->keypair_update_lock));
173: RCU_INIT_POINTER(keypairs->current_keypair, NULL);
174: wg_noise_keypair_put(old, true);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_noise_keypairs_clear SourceFile:drivers/net/wireguard/noise.c SourceLine:174 SourceSnippet: 169: wg_noise_keypair_put(old, true);
170:
171: old = rcu_dereference_protected(keypairs->current_keypair,
172: lockdep_is_held(&keypairs->keypair_update_lock));
173: RCU_INIT_POINTER(keypairs->current_keypair, NULL);
174: wg_noise_keypair_put(old, true);
175:
176: spin_unlock_bh(&keypairs->keypair_update_lock);
177: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_noise_received_with_keypair SourceFile:drivers/net/wireguard/noise.c SourceLine:285 SourceSnippet: 280: old_keypair = rcu_dereference_protected(keypairs->previous_keypair,
281: lockdep_is_held(&keypairs->keypair_update_lock));
282: rcu_assign_pointer(keypairs->previous_keypair,
283: rcu_dereference_protected(keypairs->current_keypair,
284: lockdep_is_held(&keypairs->keypair_update_lock)));
285: wg_noise_keypair_put(old_keypair, true);
286: rcu_assign_pointer(keypairs->current_keypair, received_keypair);
287: RCU_INIT_POINTER(keypairs->next_keypair, NULL);
288:
289: spin_unlock_bh(&keypairs->keypair_update_lock);
290: return true;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_consume_data SourceFile:drivers/net/wireguard/receive.c SourceLine:535 SourceSnippet: 530: if (likely(!ret || ret == -EPIPE)) {
531: rcu_read_unlock_bh();
532: return;
533: }
534: err:
535: wg_noise_keypair_put(PACKET_CB(skb)->keypair, false);
536: err_keypair:
537: rcu_read_unlock_bh();
538: wg_peer_put(peer);
539: dev_kfree_skb(skb);
540: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_create_data SourceFile:drivers/net/wireguard/send.c SourceLine:328 SourceSnippet: 323: wg_queue_enqueue_per_peer_tx(first, PACKET_STATE_DEAD);
324: err:
325: rcu_read_unlock_bh();
326: if (likely(!ret || ret == -EPIPE))
327: return;
328: wg_noise_keypair_put(PACKET_CB(first)->keypair, false);
329: wg_peer_put(peer);
330: kfree_skb_list(first);
331: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_rx_poll SourceFile:drivers/net/wireguard/receive.c SourceLine:478 SourceSnippet: 473: wg_reset_packet(skb, false);
474: wg_packet_consume_data_done(peer, skb, &endpoint);
475: free = false;
476:
477: next:
478: wg_noise_keypair_put(keypair, false);
479: wg_peer_put(peer);
480: if (unlikely(free))
481: dev_kfree_skb(skb);
482:
483: if (++work_done >= budget)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_send_staged_packets SourceFile:drivers/net/wireguard/send.c SourceLine:394 SourceSnippet: 389: return;
390:
391: out_invalid:
392: WRITE_ONCE(keypair->sending.is_valid, false);
393: out_nokey:
394: wg_noise_keypair_put(keypair, false);
395:
396: /* We orphan the packets if we're waiting on a handshake, so that they
397: * don't block a socket's pool.
398: */
399: skb_queue_walk(&packets, skb)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:wg_packet_tx_worker SourceFile:drivers/net/wireguard/send.c SourceLine:280 SourceSnippet: 275: if (likely(state == PACKET_STATE_CRYPTED))
276: wg_packet_create_data_done(peer, first);
277: else
278: kfree_skb_list(first);
279:
280: wg_noise_keypair_put(keypair, false);
281: wg_peer_put(peer);
282: if (need_resched())
283: cond_resched();
284: }
285: }
]] TruncatedOutput:false]
|
| 103/4 |
2026/11/17 14:49 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 44224
output: 38
thoughts: 9355
Thoughts: **A Deep Dive into a Potential WireGuard Kernel Vulnerability**
Alright, let's break this down. I've been staring at this WireGuard code, and I think I've found a critical flaw. It boils down to a potential race condition and NULL pointer dereference in the keypair and handshake management, specifically, within `wg_index_hashtable_lookup` and the lifetime management of the `index_hashtable_entry` structure.
Here's the gist: When a `keypair` is created, its reference count is initialized to one. When packets are flying around, they grab references to this keypair. Now, if the `peer` associated with this keypair gets removed, there's a specific function, `peer_remove_after_dead`, that's called. This function essentially clears the keypairs associated with the dying peer. The problem lies in how this is handled, specifically within `wg_noise_keypair_put`. In this function we call `wg_index_hashtable_remove` and decrement refcount with `kref_put`. If packets are in-flight when a peer dies, `keypair->refcount` is still > 0.
So, the `peer` is put and might be freed.
Now here's where it gets interesting and where the code goes wrong.
The issue arises if an incoming packet arrives *after* the peer removal, but *before* the RCU grace period expires, or even concurrently with peer refcount being 0. `wg_index_hashtable_lookup` gets called and finds an entry in the hashtable with a `keypair`. When it looks up the keypair via RCU, `wg_peer_get_maybe_zero` returns NULL because the peer's refcount has dropped to 0, which means the peer is being freed. BUT, this function, `wg_index_hashtable_lookup`, is writing `entry->peer = NULL` *within* the lookup function!
The main problem is that `entry->peer` in `index_hashtable_entry` is not a temporary variable or per-lookup variable. It's supposed to be an immutable pointer to the `wg_peer` for the *lifetime* of the keypair or handshake. It's set once at creation. The code *should* be checking the peer refcount *without* overwriting the entry in the hashtable. This is the crux of the bug!
This overwrite of `entry->peer` to NULL creates cascading failures:
* Later, in the keypair cleanup (`keypair_free_kref`), the code dereferences `keypair->entry.peer` (which is now NULL), leading to a kernel crash (NULL pointer dereference).
* In `PACKET_PEER(skb)` (which expands to `PACKET_CB(skb)->keypair->entry.peer`), the code also dereferences `NULL` causing a crash when an in-flight packet attempts to obtain a peer reference via `wg_peer_get()`. This applies to both received and transmitted packets, crashing the system in multiple places.
* Similarly, `wg_noise_handshake_clear` also dereferences a NULL `handshake->entry.peer` in multiple critical code paths: the interface going down, suspend/resume, expired key cleanup, etc.
I've examined the code very closely and it strongly suggests that the code *intended* to use a local variable, not to directly overwrite the hashtable entry. The author likely intended to do the "get maybe zero" and then make a test of the return value, similar to how every single other code path does. This is a very subtle but very dangerous bug that can lead to frequent and reproducible kernel crashes. The problem lies specifically in `wg_index_hashtable_lookup` and how it mishandles the potential for a peer's refcount to hit zero *during* a lookup. The function *should* be checking without modifying the shared entry in the hashtable, but it's not. It writes `entry->peer = NULL`, which can then cause crashes *later* in multiple places that expect the peer pointer to be valid.
Worse, this is a *data race*. Multiple cores can call `wg_index_hashtable_lookup` at the same time and overwrite the entry, even with the RCU locks, due to a likely mistaken assignment.
|
| 104/4 |
2026/11/17 14:51 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/cookie.c FirstLine:195 LineCount:35]
Results: map[Contents: 195: checker->cookie_encryption_key);
196: }
197:
198: void wg_cookie_message_consume(struct message_handshake_cookie *src,
199: struct wg_device *wg)
200: {
201: struct wg_peer *peer = NULL;
202: u8 cookie[COOKIE_LEN];
203: bool ret;
204:
205: if (unlikely(!wg_index_hashtable_lookup(wg->index_hashtable,
206: INDEX_HASHTABLE_HANDSHAKE |
207: INDEX_HASHTABLE_KEYPAIR,
208: src->receiver_index, &peer)))
209: return;
210:
211: down_read(&peer->latest_cookie.lock);
212: if (unlikely(!peer->latest_cookie.have_sent_mac1)) {
213: up_read(&peer->latest_cookie.lock);
214: goto out;
215: }
216: ret = xchacha20poly1305_decrypt(
217: cookie, src->encrypted_cookie, sizeof(src->encrypted_cookie),
218: peer->latest_cookie.last_mac1_sent, COOKIE_LEN, src->nonce,
219: peer->latest_cookie.cookie_decryption_key);
220: up_read(&peer->latest_cookie.lock);
221:
222: if (ret) {
223: down_write(&peer->latest_cookie.lock);
224: memcpy(peer->latest_cookie.cookie, cookie, COOKIE_LEN);
225: peer->latest_cookie.birthdate = ktime_get_coarse_boottime_ns();
226: peer->latest_cookie.is_valid = true;
227: peer->latest_cookie.have_sent_mac1 = false;
228: up_write(&peer->latest_cookie.lock);
229: } else {
]
|
| 105/4 |
2026/11/17 14:51 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 55149
output: 38
thoughts: 27
Thoughts: Okay, here's my take on those lines of code, presented as a first-person expert analysis:
**Deep Dive into `drivers/net/wireguard/noise.c`**
Alright, let's take a look at lines 740-770 in `drivers/net/wireguard/noise.c`. I'm immediately interested in the context of this section. It's almost certainly within the key exchange or handshake logic, given the file and general location. I need to quickly ascertain what specific functionality these lines are responsible for, but I can already make a pretty educated guess that itβs related to some sort of cryptographic operation within the Noise protocol implementation. It's likely involved in either key derivation, validation, or perhaps the handling of incoming or outgoing handshake messages.
I'd expect to see some interaction with the Noise protocol's state machine here. Is it a transition point? Are we deriving secrets? Are we checking signatures or MACs? I hope they've handled potential timing attacks carefully, which is always a concern in crypto code.
My mind immediately starts to run through different scenarios. Is this the initiator or the responder code? Is this related to the DH exchange, the AEAD encryption, or both? I should look for variable names like `remote_pubkey`, `local_privkey`, `handshake_hash`, or `cipher_key`. These will instantly give me a clue of what section it is. I'll need to pay close attention to the error handling within this block. WireGuard's security rests on the robustness of these low-level routines.
|
| 106/4 |
2026/11/17 14:52 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/noise.c FirstLine:740 LineCount:35]
Results: map[Contents: 740:
741: down_read(&wg->static_identity.lock);
742:
743: if (unlikely(!wg->static_identity.has_identity))
744: goto out;
745:
746: handshake = (struct noise_handshake *)wg_index_hashtable_lookup(
747: wg->index_hashtable, INDEX_HASHTABLE_HANDSHAKE,
748: src->receiver_index, &peer);
749: if (unlikely(!handshake))
750: goto out;
751:
752: down_read(&handshake->lock);
753: state = handshake->state;
754: memcpy(hash, handshake->hash, NOISE_HASH_LEN);
755: memcpy(chaining_key, handshake->chaining_key, NOISE_HASH_LEN);
756: memcpy(ephemeral_private, handshake->ephemeral_private,
757: NOISE_PUBLIC_KEY_LEN);
758: memcpy(preshared_key, handshake->preshared_key,
759: NOISE_SYMMETRIC_KEY_LEN);
760: up_read(&handshake->lock);
761:
762: if (state != HANDSHAKE_CREATED_INITIATION)
763: goto fail;
764:
765: /* e */
766: message_ephemeral(e, src->unencrypted_ephemeral, chaining_key, hash);
767:
768: /* ee */
769: if (!mix_dh(chaining_key, NULL, ephemeral_private, e))
770: goto fail;
771:
772: /* se */
773: if (!mix_dh(chaining_key, NULL, wg->static_identity.static_private, e))
774: goto fail;
]
|
| 107/4 |
2026/11/17 14:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 56106
output: 38
thoughts: 53
Thoughts: Okay, let's dive into this. Here's how I'd approach this task, weaving in my expertise:
**Examining wg_noise_handshake_consume_response in wireguard/noise.c**
Alright, I need to get a clear picture of how peer and handshake data are managed within the `wg_noise_handshake_consume_response` function, specifically focusing on lines 795-815 of `drivers/net/wireguard/noise.c`. This is key for understanding the critical handshake response processing logic in WireGuard's noise protocol implementation. I'm already anticipating some of the nuances based on my familiarity with the Noise protocol family and WireGuard's architecture. I expect these lines to be pivotal for things like key derivation, sequence number validation, and potentially handling the ephemeral keys received from the peer. I'll be looking to see precisely how the `peer` structure is updated based on the handshake data, including any state transitions or security checks involved. Furthermore, I'll pay close attention to the error handling within this segment β which is essential to understand potential vulnerabilities. I am also very curious to see how quickly invalid data is discarded and how much information is retained. This process is crucial to the security of the connection, so I will analyze these details with care.
|
| 108/4 |
2026/11/17 14:52 |
tool |
read-file |
0m
Args: map[File:drivers/net/wireguard/noise.c FirstLine:795 LineCount:25]
Results: map[Contents: 795: memcpy(handshake->hash, hash, NOISE_HASH_LEN);
796: memcpy(handshake->chaining_key, chaining_key, NOISE_HASH_LEN);
797: handshake->remote_index = src->sender_index;
798: handshake->state = HANDSHAKE_CONSUMED_RESPONSE;
799: up_write(&handshake->lock);
800: ret_peer = peer;
801: goto out;
802:
803: fail:
804: wg_peer_put(peer);
805: out:
806: memzero_explicit(key, NOISE_SYMMETRIC_KEY_LEN);
807: memzero_explicit(hash, NOISE_HASH_LEN);
808: memzero_explicit(chaining_key, NOISE_HASH_LEN);
809: memzero_explicit(ephemeral_private, NOISE_PUBLIC_KEY_LEN);
810: memzero_explicit(preshared_key, NOISE_SYMMETRIC_KEY_LEN);
811: up_read(&wg->static_identity.lock);
812: return ret_peer;
813: }
814:
815: bool wg_noise_handshake_begin_session(struct noise_handshake *handshake,
816: struct noise_keypairs *keypairs)
817: {
818: struct noise_keypair *new_keypair;
819: bool ret = false;
]
|
| 109/4 |
2026/11/17 14:52 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 57025
output: 1538
thoughts: 1255
Thoughts: **Analyzing the Code and the Implications of the `entry->peer` Assignment**
Okay, let's break this down. My initial assessment is that the `entry->peer = wg_peer_get_maybe_zero(entry->peer);` line is likely a bug, a typo more than anything. The intent seems to be to *obtain* a strong reference to the peer and *return* it via the `*peer` out-parameter. The comment above `wg_index_hashtable_lookup()` explicitly states that it returns a strong reference to `entry->peer`. The normal operation of `wg_peer_get_maybe_zero(entry->peer)` would increment the peer's reference count, effectively creating the strong reference. So, the original intent would be that the code should be: `*peer = wg_peer_get_maybe_zero(entry->peer);`. I can see how in the happy path this might have slipped by, as the assignment `entry->peer = entry->peer;` (an idempotent write) would be effectively masked if the function returned a valid pointer.
Now, this assignment becomes problematic when we consider it's happening under `rcu_read_lock_bh()`. Modifying `entry->peer` in this context is logically incorrect and introduces a dangerous concurrent data race. That's a serious issue.
Thinking about the `entry->peer`'s immutability, I'm pretty confident it's supposed to be constant for the lifetime of the `entry`. The `struct index_hashtable_entry` is embedded within both `struct noise_handshake` and `struct noise_keypair`. Looking at `keypair_create()` and `wg_noise_handshake_init()`, the `entry.peer` is initialized with the peer when either the keypair or handshake is allocated. I don't see any other points in the WireGuard codebase where `entry.peer` is reassigned or modified. That's a good indicator.
Now, let's explore the consequence of `wg_peer_get_maybe_zero()` returning NULL and setting `entry->peer` to NULL. This happens when the peer is dying and its reference count hits zero. The fact that the code then attempts to dereference `entry.peer` in places like `keypair_free_kref()`, `wg_noise_handshake_clear()`, and `PACKET_PEER(skb)` is going to lead to crashes, and very quickly.
In `keypair_free_kref()`, accessing `keypair->entry.peer->device` or `keypair->entry.peer->internal_id` when `keypair->entry.peer` is NULL will trigger an immediate NULL pointer dereference. The same holds true in `wg_noise_handshake_clear()`, where dereferencing `handshake->entry.peer->device->index_hashtable` is the culprit.
And finally, with `PACKET_PEER(skb)`, which translates to `keypair->entry.peer`, if that value is NULL, then `wg_peer_get(peer)` turns into `wg_peer_get(NULL)`, and will attempt to take the address of a NULL pointer. Which crashes, and subsequent dereferences of `peer` also lead to an oops.
The severity of this is pretty high. This bug could lead to kernel panics, and it's essential to determine if it's been addressed in any upstream patches. I'll need to check for existing reports or patches related to this particular issue. I need to know if this is a known, fixed issue, or if it's something that needs to be brought to the developers' attention.
|
| 110/4 |
2026/11/17 14:53 |
tool |
set-results |
0m
Args: map[Answer:Based on analysis of the WireGuard codebase in `drivers/net/wireguard/`:
### 1. Why does it assign to `entry->peer`?
This assignment appears to be an unintended coding mistake (a typo in variable assignment).
- The function comment explicitly notes:
`/* Returns a strong reference to a entry->peer */`
- The function receives an out-parameter `struct wg_peer **peer` where that strong reference is supposed to be returned to the caller.
- The intended logic was:
```c
if (likely(entry)) {
*peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(*peer))
; // keep entry
else
entry = NULL;
}
```
Instead, `entry->peer` was used as the target of the assignment:
```c
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
```
- **Why this was hidden during testing / normal operation:**
When the peer is alive, `wg_peer_get_maybe_zero(entry->peer)` increments `peer->refcount` via `kref_get_unless_zero()` and returns the exact same pointer `entry->peer`. Assigning `entry->peer = entry->peer` is an idempotent no-op write on the happy path.
- **Issues caused by this write:**
`wg_index_hashtable_lookup()` runs strictly within an RCU read-side critical section (`rcu_read_lock_bh()`). Mutating `entry->peer` during a lookup violates RCU invariants and creates an unsynchronized data race between concurrent lookups on multiple CPUs.
---
### 2. Is `entry->peer` supposed to be immutable for the lifetime of `entry`?
**Yes, `entry->peer` is strictly immutable for the lifetime of the entry.**
- `struct index_hashtable_entry` is only embedded in two structs:
1. `struct noise_handshake` (embedded in `struct wg_peer`)
2. `struct noise_keypair` (dynamically allocated for a `struct wg_peer`)
- In `keypair_create()` (`noise.c:107`), `keypair->entry.peer = peer;` is initialized when the keypair is allocated.
- In `wg_noise_handshake_init()` (`noise.c:68`), `handshake->entry.peer = peer;` is initialized when the peer's handshake is set up.
- A handshake and its keypairs are permanently associated with one peer throughout their entire lifecycle. Nowhere else in WireGuard is `entry.peer` ever reassigned or modified.
---
### 3. What happens if `entry->peer` is set to NULL?
If `wg_peer_get_maybe_zero(entry->peer)` fails (which occurs when the peer's refcount has dropped to 0 during peer removal/destruction), it returns `NULL`. As a result, `entry->peer = NULL;` mutates the entry object in-place before returning `NULL`.
If this occurs, any subsequent access assuming `entry->peer` is valid will trigger a **kernel NULL pointer dereference crash (kernel oops/panic)**:
1. **In `keypair_free_kref()` (`drivers/net/wireguard/noise.c`):**
```c
static void keypair_free_kref(struct kref *kref)
{
struct noise_keypair *keypair =
container_of(kref, struct noise_keypair, refcount);
net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
keypair->entry.peer->device->dev->name,
keypair->internal_id,
keypair->entry.peer->internal_id);
wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
&keypair->entry);
call_rcu(&keypair->rcu, keypair_free_rcu);
}
```
When the last reference to a keypair is put (e.g., after in-flight packets or workers finish), `keypair_free_kref()` dereferences `keypair->entry.peer->device` and `keypair->entry.peer->internal_id`. If `keypair->entry.peer` was overwritten with `NULL`, this immediately dereferences `NULL`.
2. **In `wg_noise_handshake_clear()` (`drivers/net/wireguard/noise.c`):**
```c
void wg_noise_handshake_clear(struct noise_handshake *handshake)
{
down_write(&handshake->lock);
wg_index_hashtable_remove(
handshake->entry.peer->device->index_hashtable,
&handshake->entry);
handshake_zero(handshake);
up_write(&handshake->lock);
}
```
If called on a handshake whose `handshake->entry.peer` was zeroed out (e.g. from `wg_stop()`, timer expiry, or power management notification), dereferencing `handshake->entry.peer->device` crashes with a NULL pointer dereference.
3. **In `PACKET_PEER(skb)` (`drivers/net/wireguard/queueing.h`):**
`PACKET_PEER(skb)` is defined as:
```c
#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
```
In `wg_queue_enqueue_per_peer_rx()` and `wg_queue_enqueue_per_peer_tx()`:
```c
struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
```
`wg_peer_get(peer)` calls `kref_get(&peer->refcount)`. Passing `NULL` causes an immediate NULL pointer dereference crash inside `kref_get()` / `refcount_inc()`, as well as on any subsequent dereference of `peer`.
---
### Unverified / Incomplete Parts
- Git history in this repository shows that this code originated in the initial merge commit `e7096c131e51` ("net: WireGuard secure network tunnel"). Without access to external mailing lists or unmerged upstream patch trackers, it was not verified whether an upstream fix has been proposed or discussed on the WireGuard or netdev mailing lists.]
Results: map[Answer:Based on analysis of the WireGuard codebase in `drivers/net/wireguard/`:
### 1. Why does it assign to `entry->peer`?
This assignment appears to be an unintended coding mistake (a typo in variable assignment).
- The function comment explicitly notes:
`/* Returns a strong reference to a entry->peer */`
- The function receives an out-parameter `struct wg_peer **peer` where that strong reference is supposed to be returned to the caller.
- The intended logic was:
```c
if (likely(entry)) {
*peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(*peer))
; // keep entry
else
entry = NULL;
}
```
Instead, `entry->peer` was used as the target of the assignment:
```c
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
```
- **Why this was hidden during testing / normal operation:**
When the peer is alive, `wg_peer_get_maybe_zero(entry->peer)` increments `peer->refcount` via `kref_get_unless_zero()` and returns the exact same pointer `entry->peer`. Assigning `entry->peer = entry->peer` is an idempotent no-op write on the happy path.
- **Issues caused by this write:**
`wg_index_hashtable_lookup()` runs strictly within an RCU read-side critical section (`rcu_read_lock_bh()`). Mutating `entry->peer` during a lookup violates RCU invariants and creates an unsynchronized data race between concurrent lookups on multiple CPUs.
---
### 2. Is `entry->peer` supposed to be immutable for the lifetime of `entry`?
**Yes, `entry->peer` is strictly immutable for the lifetime of the entry.**
- `struct index_hashtable_entry` is only embedded in two structs:
1. `struct noise_handshake` (embedded in `struct wg_peer`)
2. `struct noise_keypair` (dynamically allocated for a `struct wg_peer`)
- In `keypair_create()` (`noise.c:107`), `keypair->entry.peer = peer;` is initialized when the keypair is allocated.
- In `wg_noise_handshake_init()` (`noise.c:68`), `handshake->entry.peer = peer;` is initialized when the peer's handshake is set up.
- A handshake and its keypairs are permanently associated with one peer throughout their entire lifecycle. Nowhere else in WireGuard is `entry.peer` ever reassigned or modified.
---
### 3. What happens if `entry->peer` is set to NULL?
If `wg_peer_get_maybe_zero(entry->peer)` fails (which occurs when the peer's refcount has dropped to 0 during peer removal/destruction), it returns `NULL`. As a result, `entry->peer = NULL;` mutates the entry object in-place before returning `NULL`.
If this occurs, any subsequent access assuming `entry->peer` is valid will trigger a **kernel NULL pointer dereference crash (kernel oops/panic)**:
1. **In `keypair_free_kref()` (`drivers/net/wireguard/noise.c`):**
```c
static void keypair_free_kref(struct kref *kref)
{
struct noise_keypair *keypair =
container_of(kref, struct noise_keypair, refcount);
net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n",
keypair->entry.peer->device->dev->name,
keypair->internal_id,
keypair->entry.peer->internal_id);
wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable,
&keypair->entry);
call_rcu(&keypair->rcu, keypair_free_rcu);
}
```
When the last reference to a keypair is put (e.g., after in-flight packets or workers finish), `keypair_free_kref()` dereferences `keypair->entry.peer->device` and `keypair->entry.peer->internal_id`. If `keypair->entry.peer` was overwritten with `NULL`, this immediately dereferences `NULL`.
2. **In `wg_noise_handshake_clear()` (`drivers/net/wireguard/noise.c`):**
```c
void wg_noise_handshake_clear(struct noise_handshake *handshake)
{
down_write(&handshake->lock);
wg_index_hashtable_remove(
handshake->entry.peer->device->index_hashtable,
&handshake->entry);
handshake_zero(handshake);
up_write(&handshake->lock);
}
```
If called on a handshake whose `handshake->entry.peer` was zeroed out (e.g. from `wg_stop()`, timer expiry, or power management notification), dereferencing `handshake->entry.peer->device` crashes with a NULL pointer dereference.
3. **In `PACKET_PEER(skb)` (`drivers/net/wireguard/queueing.h`):**
`PACKET_PEER(skb)` is defined as:
```c
#define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer)
```
In `wg_queue_enqueue_per_peer_rx()` and `wg_queue_enqueue_per_peer_tx()`:
```c
struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb));
```
`wg_peer_get(peer)` calls `kref_get(&peer->refcount)`. Passing `NULL` causes an immediate NULL pointer dereference crash inside `kref_get()` / `refcount_inc()`, as well as on any subsequent dereference of `peer`.
---
### Unverified / Incomplete Parts
- Git history in this repository shows that this code originated in the initial merge commit `e7096c131e51` ("net: WireGuard secure network tunnel"). Without access to external mailing lists or unmerged upstream patch trackers, it was not verified whether an upstream fix has been proposed or discussed on the WireGuard or netdev mailing lists.]
|
| 111/2 |
2026/11/17 14:53 |
llm |
expert |
0m
Model:
Tokens:
input: 46344
output: 23
thoughts: 1726
Thoughts: **Bug Analysis: WireGuard NULL Pointer Dereference**
Okay, this confirms itβwe have a synchronization failure leading to a kernel crash. Let's break it down methodically.
First, the core of the issue is a race condition between `wg_index_hashtable_lookup` (the writer) and `wg_packet_decrypt_worker` (the reader) operating on the `keypair->entry.peer` field. `wg_index_hashtable_lookup`'s write is not protected by any lock, unlike the read that happens in the worker.
Specifically, `wg_index_hashtable_lookup` erroneously *writes* to `entry->peer` when it should be assigning to the out-parameter `*peer`. The crucial flaw is that when a peer is being torn down, its refcount drops to zero, and `wg_peer_get_maybe_zero()` returns NULL. The code then *overwrites* `entry->peer` with this NULL value.
Now, concurrently, a worker thread, likely in `wg_packet_decrypt_worker` via `wg_queue_enqueue_per_peer_rx`, reads `PACKET_PEER(skb)` (which accesses `keypair->entry.peer`) without any synchronization. This read occurs while the write is happening. Because `entry->peer` has become NULL due to the race, `peer` becomes NULL when calling `wg_peer_get(NULL)`, and dereferencing that NULL pointer via `napi_schedule(&peer->napi)` causes an immediate kernel crash.
The crash doesn't stop there. Later, when the keypair is freed in `keypair_free_kref()`, the code dereferences `keypair->entry.peer->device`, causing a secondary kernel crash as well. This reinforces the severity.
The root cause is a logic bug coupled with a synchronization failure. `entry->peer` is supposed to be immutable after initialization, yet the code modifies it. We are crashing due to a NULL pointer dereference, which is categorized as a "any" failure.
Let's verify. Based on the provided stack traces:
* **Reader (CPU 1):** `wg_queue_enqueue_per_peer_rx` calls `wg_peer_get` on a NULL `peer` and `napi_schedule` on that pointer.
* **Writer (CPU 0):** `wg_index_hashtable_lookup` corrupts `entry->peer` because it should have been assigning the value to `*peer` instead.
The critical sequence of events is clear:
1. **Peer Destruction/Tear-down (happens in softirq):** The peer refcount goes to 0, `wg_peer_get_maybe_zero` returns NULL.
2. **Corruption:** `wg_index_hashtable_lookup` erroneously writes `NULL` to `entry->peer` in the keypair entry.
3. **Race:** A concurrent worker attempts to access `PACKET_PEER(skb)` (which points to `keypair->entry.peer`) and now tries to schedule on the NULL `peer`.
The recommended fix, as per the code, is to assign directly to `*peer` (the out-parameter) inside `wg_index_hashtable_lookup` using the `wg_peer_get_maybe_zero` result.
This is a clear-cut case. Let's log it.
|
| 112/2 |
2026/11/17 14:54 |
tool |
set-results |
0m
Args: map[Benign:false FailureDetectableBy:any]
Results: map[Benign:false FailureDetectableBy:any]
|
| 113/2 |
2026/11/17 14:54 |
llm |
expert |
0m
Model:
Tokens:
input: 48863
output: 1087
thoughts: 20
Thoughts: Okay, here's the summary, expressed in the first person, assuming the user is an expert:
**Finalizing the Response**
Alright, everything's locked in. Protocols checked, data validated, all systems go. I'm at the point where I can confidently craft the final, comprehensive response. It's time to pull all the disparate threads together into a cohesive, rigorously argued piece. No more preliminary drafts or exploratory hypotheses. This is the definitive answer, delivered with the precision and thoroughness this situation demands. Time to get to work.
|
| 114/1 |
2026/11/17 14:55 |
action |
format-explanation |
0m
Results: map[Explanation:### Race Summary
`wg_queue_enqueue_per_peer_rx` (in `wg_packet_decrypt_worker`) vs
`wg_index_hashtable_lookup` on `keypair->entry.peer` (`struct
index_hashtable_entry::peer`).
### Synchronization Context
- **CPU 0** (`wg_index_hashtable_lookup`) runs under RCU read lock
(`rcu_read_lock_bh()`) with no locks held that grant write privileges. Lookup
functions in hashtables are expected to be pure readers. However,
`wg_index_hashtable_lookup()` mutates the shared hashtable entry in-place
(`entry->peer = wg_peer_get_maybe_zero(entry->peer)`).
- **CPU 1** (`wg_queue_enqueue_per_peer_rx`) reads `PACKET_PEER(skb)` (which
accesses `keypair->entry.peer`) concurrently without holding any locks.
### Final Classification
**HARMFUL**
### Failure Reasoning
`entry->peer` is supposed to be immutable for the entire lifetime of the keypair
/ handshake entry after initialization. The function
`wg_index_hashtable_lookup()` takes an out-parameter `struct wg_peer **peer`
intended to return a strong peer reference to the caller (`/* Returns a strong
reference to a entry->peer */`).
Due to a coding error, `wg_index_hashtable_lookup()` assigns the return value of
`wg_peer_get_maybe_zero(entry->peer)` to `entry->peer` rather than `*peer`:
```c
if (likely(entry)) {
entry->peer = wg_peer_get_maybe_zero(entry->peer);
if (likely(entry->peer))
*peer = entry->peer;
else
entry = NULL;
}
```
When a peer is being torn down and its refcount drops to 0, if an incoming
packet or cookie message causes a lookup on that entry,
`wg_peer_get_maybe_zero(entry->peer)` returns `NULL`.
As a result:
1. `entry->peer` is mutated in-place to `NULL`.
2. Concurrent or subsequent workers in `wg_queue_enqueue_per_peer_rx()` read
`PACKET_PEER(skb)` as `NULL`, passing it to `wg_peer_get()`. This returns
`NULL`, and `napi_schedule(&peer->napi)` dereferences `NULL`, causing an
immediate kernel crash.
3. When the keypair is subsequently released via `keypair_free_kref()`, it
dereferences `keypair->entry.peer->device`, causing a kernel crash (NULL pointer
dereference).
### Failure Sequencing
```text
CPU 0 (Softirq / Lookup) CPU 1 (Decrypt Worker)
wg_packet_decrypt_worker()
// Decrypting packet
with keypair
decrypt_packet(skb,
PACKET_CB(skb)->keypair)
// Peer deletion initiated; peer->refcount == 0
wg_packet_consume_data()
wg_index_hashtable_lookup()
rcu_read_lock_bh()
entry = ... // finds keypair entry
// wg_peer_get_maybe_zero() returns NULL
entry->peer = NULL; // OVERWRITES entry->peer with NULL!
rcu_read_unlock_bh()
wg_queue_enqueue_per_peer_rx(skb,
state)
// Reads
PACKET_PEER(skb) ==
entry->peer (NULL)
peer =
wg_peer_get(NULL); //
returns NULL
napi_schedule(&peer->napi);
// -> NULL pointer
dereference! (CRASH)
```
### FailureDetectableBy
`any`
### Recommended Fix
In `drivers/net/wireguard/peerlookup.c`, assign the result of
`wg_peer_get_maybe_zero(entry->peer)` directly to `*peer` rather than mutating
`entry->peer`:
```diff
--- a/drivers/net/wireguard/peerlookup.c
+++ b/drivers/net/wireguard/peerlookup.c
@@ -215,9 +215,8 @@ wg_index_hashtable_lookup(struct index_hashtable *table,
}
}
if (likely(entry)) {
- entry->peer = wg_peer_get_maybe_zero(entry->peer);
- if (likely(entry->peer))
- *peer = entry->peer;
+ *peer = wg_peer_get_maybe_zero(entry->peer);
+ if (likely(*peer))
+ ;
else
entry = NULL;
}
```]
|