Skip to content

Commit 040757f

Browse files
committed
ucount: Remove the atomicity from ucount->count
Always increment/decrement ucount->count under the ucounts_lock. The increments are there already and moving the decrements there means the locking logic of the code is simpler. This simplification in the locking logic fixes a race between put_ucounts and get_ucounts that could result in a use-after-free because the count could go zero then be found by get_ucounts and then be freed by put_ucounts. A bug presumably this one was found by a combination of syzkaller and KASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov spotted the race in the code. Cc: stable@vger.kernel.org Fixes: f6b2db1 ("userns: Make the count of user namespaces per user") Reported-by: JongHwan Kim <zzoru007@gmail.com> Reported-by: Dmitry Vyukov <dvyukov@google.com> Reviewed-by: Andrei Vagin <avagin@gmail.com> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
1 parent c1ae3cf commit 040757f

2 files changed

Lines changed: 12 additions & 8 deletions

File tree

include/linux/user_namespace.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ struct ucounts {
7272
struct hlist_node node;
7373
struct user_namespace *ns;
7474
kuid_t uid;
75-
atomic_t count;
75+
int count;
7676
atomic_t ucount[UCOUNT_COUNTS];
7777
};
7878

kernel/ucount.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
144144

145145
new->ns = ns;
146146
new->uid = uid;
147-
atomic_set(&new->count, 0);
147+
new->count = 0;
148148

149149
spin_lock_irq(&ucounts_lock);
150150
ucounts = find_ucounts(ns, uid, hashent);
@@ -155,8 +155,10 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
155155
ucounts = new;
156156
}
157157
}
158-
if (!atomic_add_unless(&ucounts->count, 1, INT_MAX))
158+
if (ucounts->count == INT_MAX)
159159
ucounts = NULL;
160+
else
161+
ucounts->count += 1;
160162
spin_unlock_irq(&ucounts_lock);
161163
return ucounts;
162164
}
@@ -165,13 +167,15 @@ static void put_ucounts(struct ucounts *ucounts)
165167
{
166168
unsigned long flags;
167169

168-
if (atomic_dec_and_test(&ucounts->count)) {
169-
spin_lock_irqsave(&ucounts_lock, flags);
170+
spin_lock_irqsave(&ucounts_lock, flags);
171+
ucounts->count -= 1;
172+
if (!ucounts->count)
170173
hlist_del_init(&ucounts->node);
171-
spin_unlock_irqrestore(&ucounts_lock, flags);
174+
else
175+
ucounts = NULL;
176+
spin_unlock_irqrestore(&ucounts_lock, flags);
172177

173-
kfree(ucounts);
174-
}
178+
kfree(ucounts);
175179
}
176180

177181
static inline bool atomic_inc_below(atomic_t *v, int u)

0 commit comments

Comments
 (0)