[PATCH] taskstats: fix data-race

From: Christian Brauner
Date: Sat Oct 05 2019 - 07:28:15 EST


When assiging and testing taskstats in taskstats
taskstats_exit() there's a race around writing and reading sig->stats.

cpu0:
task calls exit()
do_exit()
-> taskstats_exit()
-> taskstats_tgid_alloc()
The task takes sighand lock and assigns new stats to sig->stats.

cpu1:
task catches signal
do_exit()
-> taskstats_tgid_alloc()
-> taskstats_exit()
The tasks reads sig->stats __without__ holding sighand lock seeing
garbage.

Fix this by taking sighand lock when reading sig->stats.

Reported-by: syzbot+c5d03165a1bd1dead0c1@xxxxxxxxxxxxxxxxxxxxxxxxx
Signed-off-by: Christian Brauner <christian.brauner@xxxxxxxxxx>
---
kernel/taskstats.c | 28 +++++++++++++++++-----------
1 file changed, 17 insertions(+), 11 deletions(-)

diff --git a/kernel/taskstats.c b/kernel/taskstats.c
index 13a0f2e6ebc2..58b145234c4a 100644
--- a/kernel/taskstats.c
+++ b/kernel/taskstats.c
@@ -553,26 +553,32 @@ static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info)

static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk)
{
+ int empty;
+ struct taskstats *stats_new, *stats = NULL;
struct signal_struct *sig = tsk->signal;
- struct taskstats *stats;
-
- if (sig->stats || thread_group_empty(tsk))
- goto ret;

/* No problem if kmem_cache_zalloc() fails */
- stats = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
+ stats_new = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
+
+ empty = thread_group_empty(tsk);

spin_lock_irq(&tsk->sighand->siglock);
+ if (sig->stats || empty) {
+ stats = sig->stats;
+ spin_unlock_irq(&tsk->sighand->siglock);
+ goto free_cache;
+ }
+
if (!sig->stats) {
- sig->stats = stats;
- stats = NULL;
+ sig->stats = stats_new;
+ spin_unlock_irq(&tsk->sighand->siglock);
+ return stats_new;
}
spin_unlock_irq(&tsk->sighand->siglock);

- if (stats)
- kmem_cache_free(taskstats_cache, stats);
-ret:
- return sig->stats;
+free_cache:
+ kmem_cache_free(taskstats_cache, stats_new);
+ return stats;
}

/* Send pid data out on exit */
--
2.23.0