xfrm: check state validity under lock in xfrm_state_find()
The output-cache insertion path in xfrm_state_find() checks
x->km.state == XFRM_STATE_VALID before acquiring xfrm_state_lock,
then inserts the state into pol->state_cache_list under the lock.
While this insertion block is currently unreachable -- cached is set
unconditionally at the cached: label, making the !cached guard
always false -- the correct pattern is to perform the validity
check under the lock, matching the fix in commit ddd3d01329203
("xfrm: Fix xfrm state cache insertion race") which addressed the
same TOCTOU for the input cache path.
Move the XFRM_STATE_VALID check inside the critical section so the
pattern is correct when the cache insertion becomes reachable.
Signed-off-by: Tristan Madani <tristan@talencesecurity.com>
Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com>
diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c
index 0555e5d..581e6d0 100644
--- a/net/xfrm/xfrm_state.c
+++ b/net/xfrm/xfrm_state.c
@@ -1651,10 +1651,11 @@ xfrm_state_find(const xfrm_address_t *daddr, const xfrm_address_t *saddr,
*err = acquire_in_progress ? -EAGAIN : error;
}
- if (x && x->km.state == XFRM_STATE_VALID && !cached &&
+ if (x && !cached &&
(!(pol->flags & XFRM_POLICY_CPU_ACQUIRE) || x->pcpu_num == pcpu_id)) {
spin_lock_bh(&net->xfrm.xfrm_state_lock);
- if (hlist_unhashed(&x->state_cache))
+ if (x->km.state == XFRM_STATE_VALID &&
+ hlist_unhashed(&x->state_cache))
hlist_add_head_rcu(&x->state_cache, &pol->state_cache_list);
spin_unlock_bh(&net->xfrm.xfrm_state_lock);
}