Re: [PATCH] x86: fix possible spectre-v1 in do_get_thread_area()

From: Thomas Gleixner
Date: Sun Jun 23 2019 - 07:49:04 EST


On Fri, 24 May 2019, Dianzhang Chen wrote:

> The idx in do_get_thread_area() is controlled by userspace via syscall: ptrace(defined in kernel/ptrace.c), hence leading to a potential exploitation of the Spectre variant 1 vulnerability.
> The idx can be controlled from: ptrace -> arch_ptrace -> do_get_thread_area.
>
> Fix this by sanitizing idx before using it to index p->thread.tls_array.
>
> Signed-off-by: Dianzhang Chen <dianzhangchen0@xxxxxxxxx>
> ---
> arch/x86/kernel/tls.c | 9 +++++++--
> 1 file changed, 7 insertions(+), 2 deletions(-)
>
> diff --git a/arch/x86/kernel/tls.c b/arch/x86/kernel/tls.c
> index a5b802a..e3dc05b 100644
> --- a/arch/x86/kernel/tls.c
> +++ b/arch/x86/kernel/tls.c
> @@ -5,6 +5,7 @@
> #include <linux/user.h>
> #include <linux/regset.h>
> #include <linux/syscalls.h>
> +#include <linux/nospec.h>
>
> #include <linux/uaccess.h>
> #include <asm/desc.h>
> @@ -220,15 +221,19 @@ int do_get_thread_area(struct task_struct *p, int idx,
> struct user_desc __user *u_info)
> {
> struct user_desc info;
> + int index = idx - GDT_ENTRY_TLS_MIN;
>
> if (idx == -1 && get_user(idx, &u_info->entry_number))
> return -EFAULT;

This is broken in case of idx == -1 because index is not reevaluated after
idx is copied from u_info. You have to calculate index _AFTER_ that.

> - if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
> + if (index < 0 || index > GDT_ENTRY_TLS_MAX - GDT_ENTRY_TLS_MIN)
> return -EINVAL;
>
> + index = array_index_nospec(index,
> + GDT_ENTRY_TLS_MAX - GDT_ENTRY_TLS_MIN + 1);

What about defining the array size and using it here and in the sanity
check above?

> +
> fill_user_desc(&info, idx,
> - &p->thread.tls_array[idx - GDT_ENTRY_TLS_MIN]);
> + &p->thread.tls_array[index]);

Please get rid of the line break. The line now fits into 80 char.

Thanks,

tglx