Re: [PATCH v2] x86: Disable kernel stack offset randomization for !TSC
From: H. Peter Anvin
Date: Wed Jan 11 2023 - 20:54:16 EST
On January 11, 2023 5:34:29 PM PST, "Maciej W. Rozycki" <macro@xxxxxxxxxxx> wrote:
>On Tue, 10 Jan 2023, Jason A. Donenfeld wrote:
>
>> > Index: linux-macro/arch/x86/include/asm/entry-common.h
>> > ===================================================================
>> > --- linux-macro.orig/arch/x86/include/asm/entry-common.h
>> > +++ linux-macro/arch/x86/include/asm/entry-common.h
>> > @@ -5,6 +5,7 @@
>> > #include <linux/randomize_kstack.h>
>> > #include <linux/user-return-notifier.h>
>> >
>> > +#include <asm/cpufeature.h>
>> > #include <asm/nospec-branch.h>
>> > #include <asm/io_bitmap.h>
>> > #include <asm/fpu/api.h>
>> > @@ -85,7 +86,8 @@ static inline void arch_exit_to_user_mod
>> > * Therefore, final stack offset entropy will be 5 (x86_64) or
>> > * 6 (ia32) bits.
>> > */
>> > - choose_random_kstack_offset(rdtsc() & 0xFF);
>> > + if (cpu_feature_enabled(X86_FEATURE_TSC))
>> > + choose_random_kstack_offset(rdtsc() & 0xFF);
>>
>> What would happen if you just called `get_random_u8()` here?
>
> Thank you for your input. I've had a look at the function and it seems a
>bit heavyweight compared to a mere single CPU instruction, but I guess why
>not. Do you have any performance figures (in terms of CPU cycles) for the
>usual cases? Offhand I'm not sure how I could benchmark it myself.
>
> I have made a patch and of course it makes the system boot too, although
>it's not clear to me how I can actually verify randomisation works. I can
>assume it does I suppose.
>
> Maciej
Not to mention that we could use rdrand here if it is available (although it is slower than rdtsc.)
RDTSC isn't a super fast instruction either, but what is *way* more significant is that this use of RDTSC is NOT safe: in certain power states it may very well be that stone number of lower bits of TSC contain no entropy at all.
At the very least one should do a rotating multiply with a large (32-bit) prime number.