Re: [PATCH v2 2/6] x86/entry/64: Convert SYSRET validation tests to C

From: Brian Gerst
Date: Sun Jul 23 2023 - 07:18:14 EST


On Sun, Jul 23, 2023 at 5:53 AM Li, Xin3 <xin3.li@xxxxxxxxx> wrote:
>
>
> > @@ -84,6 +85,43 @@ __visible noinstr void do_syscall_64(struct pt_regs *regs, int
> > nr)
> >
> > instrumentation_end();
> > syscall_exit_to_user_mode(regs);
>
> Would it be better to make the following code a new function?
>
> And then the similar changes in patch 6 could be merged into the new
> function with #ifdef CONFIG_X86_64.
>
> > +
> > + /*
> > + * Check that the register state is valid for using SYSRET to exit
> > + * to userspace. Otherwise use the slower but fully capable IRET
> > + * exit path.
> > + */
> > +
> > + /* XEN PV guests always use IRET path */
> > + if (cpu_feature_enabled(X86_FEATURE_XENPV))
> > + return false;
> > +
> > + /* SYSRET requires RCX == RIP and R11 == EFLAGS */
> > + if (unlikely(regs->cx != regs->ip || regs->r11 != regs->flags))
> > + return false;
> > +
> > + /* CS and SS must match the values set in MSR_STAR */
> > + if (unlikely(regs->cs != __USER_CS || regs->ss != __USER_DS))
> > + return false;
> > +
> > + /*
> > + * On Intel CPUs, SYSRET with non-canonical RCX/RIP will #GP
> > + * in kernel space. This essentially lets the user take over
> > + * the kernel, since userspace controls RSP.
> > + */
> > + if (unlikely(!__is_canonical_address(regs->ip, __VIRTUAL_MASK_SHIFT +
> > 1)))
> > + return false;
> > +
> > + /*
> > + * SYSRET cannot restore RF. It can restore TF, but unlike IRET,
> > + * restoring TF results in a trap from userspace immediately after
> > + * SYSRET.
> > + */
> > + if (unlikely(regs->flags & (X86_EFLAGS_RF | X86_EFLAGS_TF)))
> > + return false;
> > +
> > + /* Use SYSRET to exit to userspace */
> > + return true;
> > }
> > #endif
> >

The tests are similar but not enough to combine them. If
IA32_EMULATION is enabled, both versions are needed so one copy of the
function with #ifdefs won't work..

Brian Gerst