Re: [PATCH] binfmt_elf: Introduce KUnit test

From: Steven Rostedt
Date: Thu Feb 24 2022 - 09:16:01 EST


On Wed, 23 Feb 2022 22:13:25 -0800
Kees Cook <keescook@xxxxxxxxxxxx> wrote:

> Steven, I want to do fancy live-patch kind or things to replace functions,
> but it doesn't need to be particularly fancy because KUnit tests (usually)
> run single-threaded, etc. It looks like kprobes could almost do it, but
> I don't see a way to have it _avoid_ making a function call.


// This is called just before the hijacked function is called
static void notrace my_tramp(unsigned long ip, unsigned long parent_ip,
struct ftrace_ops *ops,
struct ftrace_regs *fregs)
{
int bit;

bit = ftrace_test_recursion_trylock(ip, parent_ip);
if (WARN_ON_ONCE(bit < 0))
return;

/*
* This uses the live kernel patching arch code to now return
* to new_function() instead of the one that was called.
* If you want to do a lookup, you can look at the "ip"
* which will give you the function you are about to replace.
* Note, it may not be equal to the function address,
* but for that, you can have this:
* ip = ftrace_location(function_ip);
* which will give the ip that is passed here.
*/
klp_arch_set_pc(fregs, new_function);

ftrace_test_recursion_unlock(bit);
}

static struct ftrace_ops my_ops = {
.func = my_tramp;
.flags = FTRACE_OPS_FL_IPMODIFY |
#ifndef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS
FTRACE_OPS_FL_SAVE_REGS |
#endif
FTRACE_OPS_FL_DYNAMIC;
};

// Assuming you know the function ip you want to hijack
register_my_kutest_ip(unsigned long func_ip)
{
unsigned long ip;
int ret;

ip = ftrace_location(func_ip);
if (!ip) // not a ftrace function?
return;

ret = ftrace_set_filter_ip(&my_ops, ip, 0, 0);
if (ret < 0)
return;

// you can register more than one ip if the last parameter
// is zero (1 means to reset the list)

ret = register_ftrace_function(&my_ops);
if (ret < 0)
return;
}

That's pretty much it. Note, I did not compile nor test the above, so there
may be some mistakes.

For more information about how to use ftrace, see

Documentation/trace/ftrace-uses.rst

Which should probably get a section on how to do kernel patching.

-- Steve