KVM: x86: fix emulation of "MOV SS, null selector"

This is CVE-2017-2583.  On Intel this causes a failed vmentry because
SS's type is neither 3 nor 7 (even though the manual says this check is
only done for usable SS, and the dmesg splat says that SS is unusable!).
On AMD it's worse: svm.c is confused and sets CPL to 0 in the vmcb.

The fix fabricates a data segment descriptor when SS is set to a null
selector, so that CPL and SS.DPL are set correctly in the VMCS/vmcb.
Furthermore, only allow setting SS to a NULL selector if SS.RPL < 3;
this in turn ensures CPL < 3 because RPL must be equal to CPL.

Thanks to Andy Lutomirski and Willy Tarreau for help in analyzing
the bug and deciphering the manuals.

Reported-by: Xiaohan Zhang <zhangxiaohan1@huawei.com>
Fixes: 79d5b4c3cd809c770d4bf9812635647016c56011
Cc: stable@nongnu.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
static int fxrstor_fixup(struct x86_emulate_ctxt *ctxt,
		struct fxregs_state *new)
{
	int rc = X86EMUL_CONTINUE;
	struct fxregs_state old;

	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(old));
	if (rc != X86EMUL_CONTINUE)
		return rc;

	/*
	 * 64 bit host will restore XMM 8-15, which is not correct on non-64
	 * bit guests.  Load the current values in order to preserve 64 bit
	 * XMMs after fxrstor.
	 */
#ifdef CONFIG_X86_64
	/* XXX: accessing XMM 8-15 very awkwardly */
	memcpy(&new->xmm_space[8 * 16/4], &old.xmm_space[8 * 16/4], 8 * 16);
#endif

	/*
	 * Hardware doesn't save and restore XMM 0-7 without CR4.OSFXSR, but
	 * does save and restore MXCSR.
	 */
	if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))
		memcpy(new->xmm_space, old.xmm_space, 8 * 16);

	return rc;
}

static int fxrstor_fixup(struct x86_emulate_ctxt *ctxt,
		struct fxregs_state *new)
{
	int rc = X86EMUL_CONTINUE;
	struct fxregs_state old;

	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(old));
	if (rc != X86EMUL_CONTINUE)
		return rc;

	/*
	 * 64 bit host will restore XMM 8-15, which is not correct on non-64
	 * bit guests.  Load the current values in order to preserve 64 bit
	 * XMMs after fxrstor.
	 */
#ifdef CONFIG_X86_64
	/* XXX: accessing XMM 8-15 very awkwardly */
	memcpy(&new->xmm_space[8 * 16/4], &old.xmm_space[8 * 16/4], 8 * 16);
#endif

	/*
	 * Hardware doesn't save and restore XMM 0-7 without CR4.OSFXSR, but
	 * does save and restore MXCSR.
	 */
	if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))
		memcpy(new->xmm_space, old.xmm_space, 8 * 16);

	return rc;
}
