Smack: fix use-after-free in smk_write_relabel_self()
authorEric Biggers <ebiggers@google.com>
Wed, 8 Jul 2020 20:15:20 +0000 (13:15 -0700)
committerCasey Schaufler <casey@schaufler-ca.com>
Tue, 14 Jul 2020 18:19:58 +0000 (11:19 -0700)
smk_write_relabel_self() frees memory from the task's credentials with
no locking, which can easily cause a use-after-free because multiple
tasks can share the same credentials structure.

Fix this by using prepare_creds() and commit_creds() to correctly modify
the task's credentials.

Reproducer for "BUG: KASAN: use-after-free in smk_write_relabel_self":

#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>

static void *thrproc(void *arg)
{
int fd = open("/sys/fs/smackfs/relabel-self", O_WRONLY);
for (;;) write(fd, "foo", 3);
}

int main()
{
pthread_t t;
pthread_create(&t, NULL, thrproc, NULL);
thrproc(NULL);
}

Reported-by: syzbot+e6416dabb497a650da40@syzkaller.appspotmail.com
Fixes: 38416e53936e ("Smack: limited capability for changing process label")
Cc: <stable@vger.kernel.org> # v4.4+
Signed-off-by: Eric Biggers <ebiggers@google.com>
Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
security/smack/smackfs.c

index c21b656b32631e1be2d95e2f72c143da73a746ea..840a192e93370d4fd11e1c11a70efa20c533fc61 100644 (file)
@@ -2720,7 +2720,6 @@ static int smk_open_relabel_self(struct inode *inode, struct file *file)
 static ssize_t smk_write_relabel_self(struct file *file, const char __user *buf,
                                size_t count, loff_t *ppos)
 {
-       struct task_smack *tsp = smack_cred(current_cred());
        char *data;
        int rc;
        LIST_HEAD(list_tmp);
@@ -2745,11 +2744,21 @@ static ssize_t smk_write_relabel_self(struct file *file, const char __user *buf,
        kfree(data);
 
        if (!rc || (rc == -EINVAL && list_empty(&list_tmp))) {
+               struct cred *new;
+               struct task_smack *tsp;
+
+               new = prepare_creds();
+               if (!new) {
+                       rc = -ENOMEM;
+                       goto out;
+               }
+               tsp = smack_cred(new);
                smk_destroy_label_list(&tsp->smk_relabel);
                list_splice(&list_tmp, &tsp->smk_relabel);
+               commit_creds(new);
                return count;
        }
-
+out:
        smk_destroy_label_list(&list_tmp);
        return rc;
 }