Re: [tip: x86/bugs] x86/retpoline: Ensure default return thunk isn't used at runtime

From: Borislav Petkov
Date: Wed Oct 18 2023 - 16:38:03 EST


On Wed, Oct 18, 2023 at 07:55:31PM +0200, Borislav Petkov wrote:
> And that happens because for whatever reason apply_returns() can't find
> that last jmp __x86_return_thunk for %r15 and it barfs.

Some more info on why it happens:

something with gcc-13 or this config of whatever ends up generating
this:

ffffffff81d71200 <__x86_indirect_thunk_r14>:
ffffffff81d71200: e8 01 00 00 00 call ffffffff81d71206 <__x86_indirect_thunk_r14+0x6>
ffffffff81d71205: cc int3
ffffffff81d71206: 4c 89 34 24 mov %r14,(%rsp)
ffffffff81d7120a: e9 91 00 00 00 jmp ffffffff81d712a0 <__x86_return_thunk>
^^^^^^^^^

ffffffff81d7120f: 66 66 2e 0f 1f 84 00 data16 cs nopw 0x0(%rax,%rax,1)
ffffffff81d71216: 00 00 00 00
ffffffff81d7121a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)

ffffffff81d71220 <__x86_indirect_thunk_r15>:
ffffffff81d71220: e8 01 00 00 00 call ffffffff81d71226 <__x86_indirect_thunk_r15+0x6>
ffffffff81d71225: cc int3
ffffffff81d71226: 4c 89 3c 24 mov %r15,(%rsp)
ffffffff81d7122a: eb 74 jmp ffffffff81d712a0 <__x86_return_thunk>
^^^^^^^^^^

notice the two JMP opcodes there.

Now look at the code in apply_returns:

if (op == JMP32_INSN_OPCODE)
dest = addr + insn.length + insn.immediate.value;

with

#define JMP32_INSN_OPCODE 0xE9

And here's the fix:

diff --git a/arch/x86/kernel/alternative.c b/arch/x86/kernel/alternative.c
index 73be3931e4f0..50d64f5226f4 100644
--- a/arch/x86/kernel/alternative.c
+++ b/arch/x86/kernel/alternative.c
@@ -748,14 +748,20 @@ void __init_or_module noinline apply_returns(s32 *start, s32 *end)
continue;

op = insn.opcode.bytes[0];
- if (op == JMP32_INSN_OPCODE)
+ if (op == JMP32_INSN_OPCODE || op == JMP8_INSN_OPCODE)
dest = addr + insn.length + insn.immediate.value;


I'd still prefer the revert, though, that close to the MW. We can work
at those things later, at leisure.

Thx.

--
Regards/Gruss,
Boris.

https://people.kernel.org/tglx/notes-about-netiquette