Skip to content

Commit f91f7ac

Browse files
petrpavlukees
authored andcommitted
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 <[email protected]> Acked-by: Peter Zijlstra (Intel) <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Kees Cook <[email protected]>
1 parent de9c2c6 commit f91f7ac

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

drivers/misc/lkdtm/refcount.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,21 @@ static void lkdtm_REFCOUNT_SUB_AND_TEST_NEGATIVE(void)
182182
check_negative(&neg, 3);
183183
}
184184

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+
185200
static void check_from_zero(refcount_t *ref)
186201
{
187202
switch (refcount_read(ref)) {
@@ -400,6 +415,7 @@ static struct crashtype crashtypes[] = {
400415
CRASHTYPE(REFCOUNT_DEC_NEGATIVE),
401416
CRASHTYPE(REFCOUNT_DEC_AND_TEST_NEGATIVE),
402417
CRASHTYPE(REFCOUNT_SUB_AND_TEST_NEGATIVE),
418+
CRASHTYPE(REFCOUNT_SUB_AND_TEST_ZERO),
403419
CRASHTYPE(REFCOUNT_INC_ZERO),
404420
CRASHTYPE(REFCOUNT_ADD_ZERO),
405421
CRASHTYPE(REFCOUNT_INC_SATURATED),

include/linux/refcount.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,12 @@ bool __refcount_sub_and_test(int i, refcount_t *r, int *oldp)
266266
if (oldp)
267267
*oldp = old;
268268

269-
if (old == i) {
269+
if (old > 0 && old == i) {
270270
smp_acquire__after_ctrl_dep();
271271
return true;
272272
}
273273

274-
if (unlikely(old < 0 || old - i < 0))
274+
if (unlikely(old <= 0 || old - i < 0))
275275
refcount_warn_saturate(r, REFCOUNT_SUB_UAF);
276276

277277
return false;

0 commit comments

Comments
 (0)