Re: [PATCH v3 2/2] lkdtm: Add Shadow Call Stack tests

Kees Cook
2022-03-03T19:09:36Z

On Thu, Mar 03, 2022 at 10:42:45AM -0800, Kees Cook wrote:
> Though, having the IS_ENABLED in there makes me wonder if this test
> should instead be made _survivable_ on failure. Something like this,
> completely untested:
>
>
> #ifdef CONFIG_ARM64
> static noinline void lkdtm_scs_set_lr(unsigned long *addr)
> {
> unsigned long **lr = (unsigned long **)__builtin_frame_address(0) + 1;
> *lr = addr;
> }
>
> /* Function with __noscs attribute clears its return address. */
> static noinline void __noscs lkdtm_noscs_set_lr(unsigned long *addr)
> {
> unsigned long **lr = (unsigned long **)__builtin_frame_address(0) + 1;
> *lr = addr;
> }
> #endif
>
>
> void lkdtm_CFI_BACKWARD_SHADOW(void)
> {
> #ifdef CONFIG_ARM64
>
> /* Verify the "normal" condition of LR corruption working. */
> do {
> /* Keep label in scope to avoid compiler warning. */
> if ((volatile int)0)
> goto unexpected;
>
> pr_info("Trying to corrupt lr in a function without scs protection ...\n");
> lkdtm_noscs_set_lr(&&expected);
>
> unexpected:
> pr_err("XPASS: Unexpectedly survived lr corruption without scs?!\n");
> break;
>
> expected:
> pr_err("ok: lr corruption redirected without scs.\n");
> } while (0);
>
>
> do {
> /* Keep labe in scope to avoid compiler warning. */
> if ((volatile int)0)
> goto good_scs;
>
> pr_info("Trying to corrupt lr in a function with scs protection ...\n");
> lkdtm_scs_set_lr(&&bad_scs);
>
> good_scs:
> pr_info("ok: scs takes effect.\n");
> break;
>
> bad_scs:
> pr_err("FAIL: return address rewritten!\n");
> pr_expected_config(CONFIG_SHADOW_CALL_STACK);
> } while (0);
> #else
> pr_err("XFAIL: this test is arm64-only\n");
> #endif
> }
>
> And we should, actually, be able to make the "set_lr" functions be
> arch-specific, leaving the test itself arch-agnostic....

Yeah, as a tested example, this works for x86_64, and based on what you
had, I'd expect it to work on arm64 too:

#include <stdio.h>

static __attribute__((noinline))
void set_return_addr(unsigned long *expected, unsigned long *addr)
{
/* Use of volatile is to make sure final write isn't seen as a dead store. */
unsigned long * volatile *ret_addr = (unsigned long **)__builtin_frame_address(0) + 1;

/* Make sure we've found the right place on the stack before writing it. */
if (*ret_addr == expected)
*ret_addr = addr;
}

volatile int force_label;
int main(void)
{
do {
/* Keep labels in scope. */
if (force_label)
goto normal;
if (force_label)
goto redirected;

set_return_addr(&&normal, &&redirected);
normal:
printf("I should be skipped\n");
break;
redirected:
printf("Redirected\n");
} while (0);

return 0;
}

It does _not_ work under Clang, though, which I'm still looking at.

--
Kees Cook