Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

refcount: Report UAF for refcount_sub_and_test(0) when counter==0

When a reference counter is at zero and refcount_sub_and_test() is invoked
to subtract zero, the function accepts this request without any warning and
returns true. This behavior does not seem ideal because the counter being
already at zero indicates a use-after-free. Furthermore, returning true by
refcount_sub_and_test() in this case potentially results in a double-free
done by its caller.

Modify the underlying function __refcount_sub_and_test() to warn about this
case as a use-after-free and have it return false to avoid the potential
double-free.

Signed-off-by: Petr Pavlu <petr.pavlu@suse.com>
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://lore.kernel.org/r/20240717130023.5675-1-petr.pavlu@suse.com
Signed-off-by: Kees Cook <kees@kernel.org>

authored by

Petr Pavlu and committed by
Kees Cook
f91f7ac9 de9c2c66

+18 -2
+16
drivers/misc/lkdtm/refcount.c
··· 182 182 check_negative(&neg, 3); 183 183 } 184 184 185 + /* 186 + * A refcount_sub_and_test() by zero when the counter is at zero should act like 187 + * refcount_sub_and_test() above when going negative. 188 + */ 189 + static void lkdtm_REFCOUNT_SUB_AND_TEST_ZERO(void) 190 + { 191 + refcount_t neg = REFCOUNT_INIT(0); 192 + 193 + pr_info("attempting bad refcount_sub_and_test() at zero\n"); 194 + if (refcount_sub_and_test(0, &neg)) 195 + pr_warn("Weird: refcount_sub_and_test() reported zero\n"); 196 + 197 + check_negative(&neg, 0); 198 + } 199 + 185 200 static void check_from_zero(refcount_t *ref) 186 201 { 187 202 switch (refcount_read(ref)) { ··· 415 400 CRASHTYPE(REFCOUNT_DEC_NEGATIVE), 416 401 CRASHTYPE(REFCOUNT_DEC_AND_TEST_NEGATIVE), 417 402 CRASHTYPE(REFCOUNT_SUB_AND_TEST_NEGATIVE), 403 + CRASHTYPE(REFCOUNT_SUB_AND_TEST_ZERO), 418 404 CRASHTYPE(REFCOUNT_INC_ZERO), 419 405 CRASHTYPE(REFCOUNT_ADD_ZERO), 420 406 CRASHTYPE(REFCOUNT_INC_SATURATED),
+2 -2
include/linux/refcount.h
··· 266 266 if (oldp) 267 267 *oldp = old; 268 268 269 - if (old == i) { 269 + if (old > 0 && old == i) { 270 270 smp_acquire__after_ctrl_dep(); 271 271 return true; 272 272 } 273 273 274 - if (unlikely(old < 0 || old - i < 0)) 274 + if (unlikely(old <= 0 || old - i < 0)) 275 275 refcount_warn_saturate(r, REFCOUNT_SUB_UAF); 276 276 277 277 return false;