Re: [PATCH v2 07/19] x86: introduce __uaccess_begin_nospec and ASM_IFENCE

From: Dan Williams
Date: Fri Jan 12 2018 - 13:21:54 EST


On Fri, Jan 12, 2018 at 9:51 AM, Josh Poimboeuf <jpoimboe@xxxxxxxxxx> wrote:
> On Thu, Jan 11, 2018 at 04:47:02PM -0800, Dan Williams wrote:
>> For 'get_user' paths, do not allow the kernel to speculate on the value
>> of a user controlled pointer. In addition to the 'stac' instruction for
>> Supervisor Mode Access Protection, an 'ifence' causes the 'access_ok'
>> result to resolve in the pipeline before the cpu might take any
>> speculative action on the pointer value.
>
> So I understand the need to "patch first and ask questions later". I
> also understand that usercopy is an obvious attack point for speculative
> bugs. However, I'm still hopelessly confused about what exactly this
> patch (and the next one) are supposed to accomplish.
>
> I can't figure out if:
>
> a) I'm missing something completely obvious;
> b) this is poorly described; or
> c) it doesn't actually fix/protect/harden anything.
>
> The commit log doesn't help me at all. In fact, it confuses me more.
> For example, this paragraph:
>
>> Since this is a major kernel interface that deals with user controlled
>> data, the '__uaccess_begin_nospec' mechanism will prevent speculative
>> execution past an 'access_ok' permission check. While speculative
>> execution past 'access_ok' is not enough to lead to a kernel memory
>> leak, it is a necessary precondition.
>
> That just sounds wrong. What if the speculation starts *after* the
> access_ok() check? Then the barrier has no purpose.
>
> Most access_ok/get_user/copy_from_user calls are like this:
>
> if (copy_from_user(...uptr..)) /* or access_ok() or get_user() */
> return -EFAULT;
>
> So in other words, the usercopy function is called *before* the branch.
>
> But to halt speculation, the lfence needs to come *after* the branch.
> So putting lfences *before* the branch doesn't solve anything.
>
> So what am I missing?

We're trying to prevent a pointer under user control from being
de-referenced inside the kernel, before we know it has been limited to
something safe. In the following sequence the branch we are worried
about speculating is the privilege check:

if (access_ok(uptr)) /* <--- Privelege Check */
if (copy_from_user_(uptr))

The cpu can speculatively skip that access_ok() check and cause a read
of kernel memory.