Re: [PATCH 0/2] x86: UMIP emulation leaking kernel addresses

From: Brian Gerst
Date: Sat Dec 09 2023 - 12:16:38 EST


On Tue, Dec 5, 2023 at 8:22 PM Michal Luczaj <mhal@xxxxxxx> wrote:
>
> User space executing opcode SGDT on a UMIP-enabled CPU results in
> #GP(0). In an effort to support legacy applications, #GP handler calls
> fixup_umip_exception() to patch up the exception and return a dummy
> value:
>
> if (static_cpu_has(X86_FEATURE_UMIP)) {
> if (user_mode(regs) && fixup_umip_exception(regs))
> goto exit;
> }
>
> SGDT is emulated by decoding the instruction and copying dummy data to
> the memory address specified by the operand:
>
> uaddr = insn_get_addr_ref(&insn, regs);
> if ((unsigned long)uaddr == -1L)
> return false;
>
> nr_copied = copy_to_user(uaddr, dummy_data, dummy_data_size);
> if (nr_copied > 0) {
> /*
> * If copy fails, send a signal and tell caller that
> * fault was fixed up.
> */
> force_sig_info_umip_fault(uaddr, regs);
> return true;
> }
>
> Decoder handles segmentation, so for "sgdt %ss:(%rax)" the value of
> `uaddr` will be correctly (in compatibility mode) shifted by the base
> address of the segment. There's a catch though: decoder does not check
> segment's DPL, nor its type.
>
> ptrace() can be used to prepare a RPL=3 selector for a S=0/DPL=0
> segment, potentially one with a kernel space base address. On return to
> user space, CPU will reject such selector load; exception will be
> raised. But because the #GP handler sees no distinction between
> SGDT-induced #GP(0) and IRET-induced #GP(selector), emulator will kick
> in and process the malformed @regs->ss.
>
> If the first 4 GiB of user space are unmapped or non-writable,
> copy_to_user() will fail, and signal to user will reveal `uaddr` -- i.e.
> the (part of) kernel address. On x86_64, addresses of GDT_ENTRY_TSS (for
> each CPU) and GDT_ENTRY_LDT (when in use) can be fully leaked in a few
> steps.

A different way to plug this is to harden ptrace (and sigreturn) to
verify that the segments are code or data type segments instead of
relying on an IRET fault.

Brian Gerst