mbox series

[0/5] Improve arm64 pkeys handling in signal delivery

Message ID 20241017133909.3837547-1-kevin.brodsky@arm.com
Headers show
Series Improve arm64 pkeys handling in signal delivery | expand

Message

Kevin Brodsky Oct. 17, 2024, 1:39 p.m. UTC
This series is a follow-up to Joey's Permission Overlay Extension (POE)
series [1] that recently landed on mainline. The goal is to improve the
way we handle the register that governs which pkeys/POIndex are
accessible (POR_EL0) during signal delivery. As things stand, we may
unexpectedly fail to write the signal frame on the stack because POR_EL0
is not reset before the uaccess operations. See patch 3 for more details
and the main changes this series brings.

A similar series landed recently for x86/MPK [2]; the present series
aims at aligning arm64 with x86. Worth noting: once the signal frame is
written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
only. This means that a program that sets up an alternate signal stack
with a non-zero pkey will need some assembly trampoline to set POR_EL0
before invoking the real signal handler, as discussed here [3].

The x86 series also added kselftests to ensure that no spurious SIGSEGV
occurs during signal delivery regardless of which pkey is accessible at
the point where the signal is delivered. This series adapts those
kselftests to allow running them on arm64 (patch 4-5).

Finally patch 2 is a clean-up following feedback on Joey's series [4].

I have tested this series on arm64 and x86_64 (booting and running the
protection_keys and pkey_sighandler_tests mm kselftests).

- Kevin

[1] https://lore.kernel.org/linux-arm-kernel/20240822151113.1479789-1-joey.gouly@arm.com/
[2] https://lore.kernel.org/lkml/20240802061318.2140081-1-aruna.ramakrishna@oracle.com/
[3] https://lore.kernel.org/lkml/CABi2SkWxNkP2O7ipkP67WKz0-LV33e5brReevTTtba6oKUfHRw@mail.gmail.com/
[4] https://lore.kernel.org/linux-arm-kernel/20241015114116.GA19334@willie-the-truck/

Cc: akpm@linux-foundation.org
Cc: anshuman.khandual@arm.com
Cc: aruna.ramakrishna@oracle.com
Cc: broonie@kernel.org
Cc: catalin.marinas@arm.com
Cc: dave.hansen@linux.intel.com
Cc: dave.martin@arm.com
Cc: jeffxu@chromium.org
Cc: joey.gouly@arm.com
Cc: shuah@kernel.org
Cc: will@kernel.org
Cc: linux-kselftest@vger.kernel.org
Cc: x86@kernel.org

Kevin Brodsky (5):
  arm64: signal: Remove unused macro
  arm64: signal: Remove unnecessary check when saving POE state
  arm64: signal: Improve POR_EL0 handling to avoid uaccess failures
  selftests/mm: Use generic pkey register manipulation
  selftests/mm: Enable pkey_sighandler_tests on arm64

 arch/arm64/kernel/signal.c                    |  92 +++++++++++++---
 tools/testing/selftests/mm/Makefile           |   8 +-
 tools/testing/selftests/mm/pkey-arm64.h       |   1 +
 tools/testing/selftests/mm/pkey-x86.h         |   2 +
 .../selftests/mm/pkey_sighandler_tests.c      | 101 +++++++++++++-----
 5 files changed, 159 insertions(+), 45 deletions(-)

Comments

Dave Martin Oct. 17, 2024, 3:49 p.m. UTC | #1
On Thu, Oct 17, 2024 at 02:39:05PM +0100, Kevin Brodsky wrote:
> Commit 33f082614c34 ("arm64: signal: Allow expansion of the signal
> frame") introduced the BASE_SIGFRAME_SIZE macro but it has
> apparently never been used.

Nit: Should there be a statement of what the patch does?

Same throughout the series.

(Yes, I know it's in the subject line, but Mutt doesn't think that's
part of the message body, so I can't see it now that I'm replying...
and submitting-patches.rst and e.g., maintainer-tip.rst seem to take
the same policy, albeit without quite stating it explicitly.)

> Signed-off-by: Kevin Brodsky <kevin.brodsky@arm.com>

Weird.  Maybe there are places where this could have been used, but I
guess we have managed fine without it.

Or possibly some unmerged version of the SVE patches used this but it
disappeared in refactoring.

Either way:

Reviewed-by: Dave Martin <Dave.Martin@arm.com>

> ---
>  arch/arm64/kernel/signal.c | 1 -
>  1 file changed, 1 deletion(-)
> 
> diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c
> index 561986947530..dc998326e24d 100644
> --- a/arch/arm64/kernel/signal.c
> +++ b/arch/arm64/kernel/signal.c
> @@ -66,7 +66,6 @@ struct rt_sigframe_user_layout {
>  	unsigned long end_offset;
>  };
>  
> -#define BASE_SIGFRAME_SIZE round_up(sizeof(struct rt_sigframe), 16)
>  #define TERMINATOR_SIZE round_up(sizeof(struct _aarch64_ctx), 16)
>  #define EXTRA_CONTEXT_SIZE round_up(sizeof(struct extra_context), 16)
>  
> -- 
> 2.43.0
> 
>
Dave Martin Oct. 17, 2024, 3:53 p.m. UTC | #2
On Thu, Oct 17, 2024 at 02:39:07PM +0100, Kevin Brodsky wrote:
> TL;DR: reset POR_EL0 to "allow all" before writing the signal frame,
> preventing spurious uaccess failures.
> 
> When POE is supported, the POR_EL0 register constrains memory
> accesses based on the target page's POIndex (pkey). This raises the
> question: what constraints should apply to a signal handler? The
> current answer is that POR_EL0 is reset to POR_EL0_INIT when
> invoking the handler, giving it full access to POIndex 0. This is in
> line with x86's MPK support and remains unchanged.
> 
> This is only part of the story, though. POR_EL0 constrains all
> unprivileged memory accesses, meaning that uaccess routines such as
> put_user() are also impacted. As a result POR_EL0 may prevent the
> signal frame from being written to the signal stack (ultimately
> causing a SIGSEGV). This is especially concerning when an alternate
> signal stack is used, because userspace may want to prevent access
> to it outside of signal handlers. There is currently no provision
> for that: POR_EL0 is reset after writing to the stack, and
> POR_EL0_INIT only enables access to POIndex 0.

This all seems a bit convoluted.

The issues seem to boil down to: the signal frame is read and written
on behalf of the signal handler, and so should be done with consistent
permissions to those the signal handler gets (instead of whatever
random prevailing permissions were specified in POR_EL0 before signal
delivery... and were possibly responsible for triggering the signal in
the first place.)

The need to save/restore POR_EL0 via staging storage seems to follow on
naturally from that, since if POR_EL0 was independent of uaccess then
this patch would be redundant...

> 
> This patch ensures that POR_EL0 is reset to its most permissive

Is this right?  See my comment on save_reset_unpriv_access_state()
below.

> state before the signal stack is accessed. Once the signal frame has
> been fully written, POR_EL0 is still set to POR_EL0_INIT - it is up
> to the signal handler to enable access to additional pkeys if
> needed. As to sigreturn(), it expects having access to the stack
> like any other syscall; we only need to ensure that POR_EL0 is
> restored from the signal frame after all uaccess calls. This
> approach is in line with the recent x86/pkeys series [1].
> 
> Resetting POR_EL0 early introduces some complications, in that we
> can no longer read the register directly in preserve_poe_context().
> This is addressed by introducing a struct (unpriv_access_state)
> and helpers to manage any such register impacting uaccess. Things
> look like this on signal delivery:
> 1. Save original POR_EL0 into struct [save_reset_unpriv_access_state()]
> 2. Set POR_EL0 to "allow all"  [save_reset_unpriv_access_state()]
> 3. Create signal frame
> 4. Write saved POR_EL0 value to the signal frame [preserve_poe_context()]
> 5. Finalise signal frame
> 6. Set POR_EL0 to POR_EL0_INIT [set_handler_unpriv_access_state()]
> 
> The return path (sys_rt_sigreturn) doesn't strictly require any change
> since restore_poe_context() is already called last. However, to
> avoid uaccess calls being accidentally added after that point, we
> use the same approach as in the delivery path, i.e. separating
> uaccess from writing to the register:
> 1. Read saved POR_EL0 value from the signal frame [restore_poe_context()]
> 2. Set POR_EL0 to the saved value [restore_unpriv_access_state()]
> 
> [1] https://lore.kernel.org/lkml/20240802061318.2140081-1-aruna.ramakrishna@oracle.com/
> 
> Signed-off-by: Kevin Brodsky <kevin.brodsky@arm.com>
> ---
>  arch/arm64/kernel/signal.c | 89 ++++++++++++++++++++++++++++++++------
>  1 file changed, 75 insertions(+), 14 deletions(-)
> 
> diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c
> index f5fb48dabebe..3548146084b3 100644
> --- a/arch/arm64/kernel/signal.c
> +++ b/arch/arm64/kernel/signal.c
> @@ -66,9 +66,64 @@ struct rt_sigframe_user_layout {
>  	unsigned long end_offset;
>  };
>  
> +/*
> + * Holds any EL0-controlled state that influences unprivileged memory accesses.
> + * This includes both accesses done in userspace and uaccess done in the kernel.
> + *
> + * This state needs to be carefully managed to ensure that it doesn't cause
> + * uaccess to fail when setting up the signal frame, and the signal handler
> + * itself also expects a well-defined state when entered.
> + */
> +struct unpriv_access_state {
> +	u64 por_el0;
> +};
> +
>  #define TERMINATOR_SIZE round_up(sizeof(struct _aarch64_ctx), 16)
>  #define EXTRA_CONTEXT_SIZE round_up(sizeof(struct extra_context), 16)
>  
> +/*
> + * Save the unpriv access state into ua_state and reset it to disable any
> + * restrictions.
> + */
> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)

Would _user_ be more consistent naming than _unpriv_ ?

Same elsewhere.

> +{
> +	if (system_supports_poe()) {
> +		/*
> +		 * Enable all permissions in all 8 keys
> +		 * (inspired by REPEAT_BYTE())
> +		 */
> +		u64 por_enable_all = (~0u / POE_MASK) * POE_RXW;

Yikes!

Seriously though, why are we granting permissions that the signal
handler isn't itself going to have over its own stack?

I think the logical thing to do is to think of the write/read of the
signal frame as being done on behalf of the signal handler, so the
permissions should be those we're going to give the signal handler:
not less, and (so far as we can approximate) not more.

> +
> +		ua_state->por_el0 = read_sysreg_s(SYS_POR_EL0);
> +		write_sysreg_s(por_enable_all, SYS_POR_EL0);
> +		/* Ensure that any subsequent uaccess observes the updated value */
> +		isb();
> +	}
> +}
> +
> +/*
> + * Set the unpriv access state for invoking the signal handler.
> + *
> + * No uaccess should be done after that function is called.
> + */
> +static void set_handler_unpriv_access_state(void)
> +{
> +	if (system_supports_poe())
> +		write_sysreg_s(POR_EL0_INIT, SYS_POR_EL0);
> +

Spurious blank line?

> +}

[...]

> @@ -1252,9 +1310,11 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
>  {
>  	struct rt_sigframe_user_layout user;
>  	struct rt_sigframe __user *frame;
> +	struct unpriv_access_state ua_state;
>  	int err = 0;
>  
>  	fpsimd_signal_preserve_current_state();
> +	save_reset_unpriv_access_state(&ua_state);

(Trivial nit: maybe put the blank line before this rather than after?
This has nothing to do with "settling" the kernel's internal context
switch state, and a lot to do with generaing the signal frame...)

>  
>  	if (get_sigframe(&user, ksig, regs))
>  		return 1;

[...]

> @@ -1273,6 +1333,7 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
>  			regs->regs[1] = (unsigned long)&frame->info;
>  			regs->regs[2] = (unsigned long)&frame->uc;
>  		}
> +		set_handler_unpriv_access_state();

This bit feels prematurely factored?  We don't have separate functions
for the other low-level preparation done here...

It works either way though, and I don't have a strong view.

Overall, this all looks reasonable.

Cheers
---Dave
Kevin Brodsky Oct. 21, 2024, 10:05 a.m. UTC | #3
On 17/10/2024 17:49, Dave Martin wrote:
> On Thu, Oct 17, 2024 at 02:39:05PM +0100, Kevin Brodsky wrote:
>> Commit 33f082614c34 ("arm64: signal: Allow expansion of the signal
>> frame") introduced the BASE_SIGFRAME_SIZE macro but it has
>> apparently never been used.
> Nit: Should there be a statement of what the patch does?
>
> Same throughout the series.
>
> (Yes, I know it's in the subject line, but Mutt doesn't think that's
> part of the message body, so I can't see it now that I'm replying...
> and submitting-patches.rst and e.g., maintainer-tip.rst seem to take
> the same policy, albeit without quite stating it explicitly.)

Ah good point, I didn't consider that. Will make it explicit in patch 1
and 2.

Kevin
Kevin Brodsky Oct. 21, 2024, 10:06 a.m. UTC | #4
On 17/10/2024 17:53, Dave Martin wrote:
> [...]
>> +/*
>> + * Save the unpriv access state into ua_state and reset it to disable any
>> + * restrictions.
>> + */
>> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)
> Would _user_ be more consistent naming than _unpriv_ ?

I did ponder on the naming. I considered user_access/uaccess instead of
unpriv_access, but my concern is that it might imply that only uaccess
is concerned, while in reality loads/stores that userspace itself
executes are impacted too. I thought using the "unpriv" terminology from
the Arm ARM (used for stage 1 permissions) might avoid such
misunderstanding. I'm interested to hear opinions on this, maybe
accuracy sacrifices readability.

> Same elsewhere.
>
>> +{
>> +	if (system_supports_poe()) {
>> +		/*
>> +		 * Enable all permissions in all 8 keys
>> +		 * (inspired by REPEAT_BYTE())
>> +		 */
>> +		u64 por_enable_all = (~0u / POE_MASK) * POE_RXW;
> Yikes!
>
> Seriously though, why are we granting permissions that the signal
> handler isn't itself going to have over its own stack?
>
> I think the logical thing to do is to think of the write/read of the
> signal frame as being done on behalf of the signal handler, so the
> permissions should be those we're going to give the signal handler:
> not less, and (so far as we can approximate) not more.

Will continue that discussion on the cover letter.

>
>> +
>> +		ua_state->por_el0 = read_sysreg_s(SYS_POR_EL0);
>> +		write_sysreg_s(por_enable_all, SYS_POR_EL0);
>> +		/* Ensure that any subsequent uaccess observes the updated value */
>> +		isb();
>> +	}
>> +}
>> +
>> +/*
>> + * Set the unpriv access state for invoking the signal handler.
>> + *
>> + * No uaccess should be done after that function is called.
>> + */
>> +static void set_handler_unpriv_access_state(void)
>> +{
>> +	if (system_supports_poe())
>> +		write_sysreg_s(POR_EL0_INIT, SYS_POR_EL0);
>> +
> Spurious blank line?

Thanks!

>> +}
> [...]
>
>> @@ -1252,9 +1310,11 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
>>  {
>>  	struct rt_sigframe_user_layout user;
>>  	struct rt_sigframe __user *frame;
>> +	struct unpriv_access_state ua_state;
>>  	int err = 0;
>>  
>>  	fpsimd_signal_preserve_current_state();
>> +	save_reset_unpriv_access_state(&ua_state);
> (Trivial nit: maybe put the blank line before this rather than after?
> This has nothing to do with "settling" the kernel's internal context
> switch state, and a lot to do with generaing the signal frame...)

In fact considering the concern Catalin brought up with POR_EL0 being
reset even when we fail to deliver the signal [1], I'm realising this
call should be moved after get_sigframe(), since the latter doesn't use
uaccess and can fail.

[1] https://lore.kernel.org/linux-arm-kernel/Zw6D2waVyIwYE7wd@arm.com/

>>  
>>  	if (get_sigframe(&user, ksig, regs))
>>  		return 1;
> [...]
>
>> @@ -1273,6 +1333,7 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
>>  			regs->regs[1] = (unsigned long)&frame->info;
>>  			regs->regs[2] = (unsigned long)&frame->uc;
>>  		}
>> +		set_handler_unpriv_access_state();
> This bit feels prematurely factored?  We don't have separate functions
> for the other low-level preparation done here...

I preferred to have a consistent API for all manipulations of POR_EL0,
the idea being that if more registers are added to struct
unpriv_access_state, only the *unpriv_access* helpers need to be amended.

> It works either way though, and I don't have a strong view.
>
> Overall, this all looks reasonable.

Thanks for the review!

Kevin
Kevin Brodsky Oct. 21, 2024, 10:06 a.m. UTC | #5
On 17/10/2024 17:48, Dave Martin wrote:
> On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
>> This series is a follow-up to Joey's Permission Overlay Extension (POE)
>> series [1] that recently landed on mainline. The goal is to improve the
>> way we handle the register that governs which pkeys/POIndex are
>> accessible (POR_EL0) during signal delivery. As things stand, we may
>> unexpectedly fail to write the signal frame on the stack because POR_EL0
>> is not reset before the uaccess operations. See patch 3 for more details
>> and the main changes this series brings.
>>
>> A similar series landed recently for x86/MPK [2]; the present series
>> aims at aligning arm64 with x86. Worth noting: once the signal frame is
>> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
>> only. This means that a program that sets up an alternate signal stack
>> with a non-zero pkey will need some assembly trampoline to set POR_EL0
>> before invoking the real signal handler, as discussed here [3].
> This feels a bit bogus (though it's anyway orthogonal to this series).

I'm not very fond of this either. However I believe this is the correct
first step: bring arm64 in line with x86. Removing all restrictions
before uaccess and then setting POR_EL0 to POR_EL0_INIT enables
userspace to use any pkey for the alternate signal stack without an ABI
change, albeit not in a very comfortable way (if the pkey is not 0).

> Really, we want some way for userspace to tell the kernel what
> permissions to use for the alternate signal stack and signal handlers
> using it, and then honour that request consistently (just as we try to
> do for the main stack today).
>
> ss_flags is mostly unused... I wonder whether we could add something in
> there?  Or add a sigaltstack2()?

Yes, this would be sensible as a second step (backwards-compatible
extension). Exactly how that API would look like is not trivial though:
is the pkey implicitly derived from the pointer provided to
sigaltstack()? Is there a need to specify another pkey for code, or do
we just assume that the signal handler is only using code with pkey 0?
(Not a concern on x86 as MPK doesn't restrict execution.) Would be very
interested to hear opinions on this.

Kevin
Dave Martin Oct. 21, 2024, 1:31 p.m. UTC | #6
On Mon, Oct 21, 2024 at 12:06:25PM +0200, Kevin Brodsky wrote:
> On 17/10/2024 17:48, Dave Martin wrote:
> > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
> >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
> >> series [1] that recently landed on mainline. The goal is to improve the
> >> way we handle the register that governs which pkeys/POIndex are
> >> accessible (POR_EL0) during signal delivery. As things stand, we may
> >> unexpectedly fail to write the signal frame on the stack because POR_EL0
> >> is not reset before the uaccess operations. See patch 3 for more details
> >> and the main changes this series brings.
> >>
> >> A similar series landed recently for x86/MPK [2]; the present series
> >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
> >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
> >> only. This means that a program that sets up an alternate signal stack
> >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
> >> before invoking the real signal handler, as discussed here [3].
> > This feels a bit bogus (though it's anyway orthogonal to this series).
> 
> I'm not very fond of this either. However I believe this is the correct
> first step: bring arm64 in line with x86. Removing all restrictions
> before uaccess and then setting POR_EL0 to POR_EL0_INIT enables
> userspace to use any pkey for the alternate signal stack without an ABI
> change, albeit not in a very comfortable way (if the pkey is not 0).

I see: we try not to prevent userspace from using whatever pkey it
likes for the alternate signal stack, but we are only permissive for
the bare minimum operations that userspace can't possibly control for
itself (i.e., writing the signal frame).

This whole thing feels a bit of a botch, though.

Do we know of anyone actually using a sigaltstack with a pkey other
than 0?  Why the urgency?  Code relying on an asm shim on x86 is
already nonportable, unless I've misunderstood something, so simply
turning on arm64 pkeys support in the kernel and libc shouldn't break
anything today?  (At least, nothing that wasn't asking to be broken.)

> 
> > Really, we want some way for userspace to tell the kernel what
> > permissions to use for the alternate signal stack and signal handler
> > using it, and then honour that request consistently (just as we try to
> > do for the main stack today).
> >
> > ss_flags is mostly unused... I wonder whether we could add something in
> > there?  Or add a sigaltstack2()?
> 
> Yes, this would be sensible as a second step (backwards-compatible
> extension). Exactly how that API would look like is not trivial though:
> is the pkey implicitly derived from the pointer provided to
> sigaltstack()? Is there a need to specify another pkey for code, or do
> we just assume that the signal handler is only using code with pkey 0?
> (Not a concern on x86 as MPK doesn't restrict execution.) Would be very
> interested to hear opinions on this.
> 
> Kevin

I would vote for specifying the pkey (or, if feasible, PKRU or
modifications to it) in some bits of ss_flags, or in an additional
flags argument to sigaltstack2().

Memory with a non-zero pkey cannot be used 100% portably, period, and
having non-RW(X) permissions on pkey 0 at any time is also not
portable, period.  So I'm not sure that having libc magically guess
what userspace's pkeys policy is supposed to be based on racily digging
metadata out of /proc/self/maps or a cache of it etc. would be such a
good idea.

There are other ways to approach (or not approach) this though --
I would be interested to hear what other people think too...

Cheers
---Dave
Dave Martin Oct. 21, 2024, 1:43 p.m. UTC | #7
On Mon, Oct 21, 2024 at 12:06:07PM +0200, Kevin Brodsky wrote:
> On 17/10/2024 17:53, Dave Martin wrote:
> > [...]
> >> +/*
> >> + * Save the unpriv access state into ua_state and reset it to disable any
> >> + * restrictions.
> >> + */
> >> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)
> > Would _user_ be more consistent naming than _unpriv_ ?
> 
> I did ponder on the naming. I considered user_access/uaccess instead of
> unpriv_access, but my concern is that it might imply that only uaccess
> is concerned, while in reality loads/stores that userspace itself
> executes are impacted too. I thought using the "unpriv" terminology from
> the Arm ARM (used for stage 1 permissions) might avoid such
> misunderstanding. I'm interested to hear opinions on this, maybe
> accuracy sacrifices readability.

"user_access" seemed natural to me: it parses equally as "[user
access]" (i.e., uaccess) and "[user] access" (i.e., access by, to, or
on behalf of user(space)).

Introducing an architectural term when there is already a generic OS
and Linux kernel term that means the right thing seemed not to improve
readability, but I guess it's a matter of opinion.

Anyway, it doesn't really matter.

> 
> > Same elsewhere.
> >
> >> +{
> >> +	if (system_supports_poe()) {
> >> +		/*
> >> +		 * Enable all permissions in all 8 keys
> >> +		 * (inspired by REPEAT_BYTE())
> >> +		 */
> >> +		u64 por_enable_all = (~0u / POE_MASK) * POE_RXW;
> > Yikes!
> >
> > Seriously though, why are we granting permissions that the signal
> > handler isn't itself going to have over its own stack?
> >
> > I think the logical thing to do is to think of the write/read of the
> > signal frame as being done on behalf of the signal handler, so the
> > permissions should be those we're going to give the signal handler:
> > not less, and (so far as we can approximate) not more.
> 
> Will continue that discussion on the cover letter.
> 
> >
> >> +
> >> +		ua_state->por_el0 = read_sysreg_s(SYS_POR_EL0);
> >> +		write_sysreg_s(por_enable_all, SYS_POR_EL0);
> >> +		/* Ensure that any subsequent uaccess observes the updated value */
> >> +		isb();
> >> +	}
> >> +}
> >> +
> >> +/*
> >> + * Set the unpriv access state for invoking the signal handler.
> >> + *
> >> + * No uaccess should be done after that function is called.
> >> + */
> >> +static void set_handler_unpriv_access_state(void)
> >> +{
> >> +	if (system_supports_poe())
> >> +		write_sysreg_s(POR_EL0_INIT, SYS_POR_EL0);
> >> +
> > Spurious blank line?
> 
> Thanks!
> 
> >> +}
> > [...]
> >
> >> @@ -1252,9 +1310,11 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
> >>  {
> >>  	struct rt_sigframe_user_layout user;
> >>  	struct rt_sigframe __user *frame;
> >> +	struct unpriv_access_state ua_state;
> >>  	int err = 0;
> >>  
> >>  	fpsimd_signal_preserve_current_state();
> >> +	save_reset_unpriv_access_state(&ua_state);
> > (Trivial nit: maybe put the blank line before this rather than after?
> > This has nothing to do with "settling" the kernel's internal context
> > switch state, and a lot to do with generaing the signal frame...)
> 
> In fact considering the concern Catalin brought up with POR_EL0 being
> reset even when we fail to deliver the signal [1], I'm realising this
> call should be moved after get_sigframe(), since the latter doesn't use
> uaccess and can fail.
> 
> [1] https://lore.kernel.org/linux-arm-kernel/Zw6D2waVyIwYE7wd@arm.com/
> 
> >>  
> >>  	if (get_sigframe(&user, ksig, regs))
> >>  		return 1;
> > [...]

^

Ah, good point.  The save_reset_unpriv_access_state(&ua_state) call
probably belong just before the first __put_user() then.

> >
> >> @@ -1273,6 +1333,7 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
> >>  			regs->regs[1] = (unsigned long)&frame->info;
> >>  			regs->regs[2] = (unsigned long)&frame->uc;
> >>  		}
> >> +		set_handler_unpriv_access_state();
> > This bit feels prematurely factored?  We don't have separate functions
> > for the other low-level preparation done here...
> 
> I preferred to have a consistent API for all manipulations of POR_EL0,
> the idea being that if more registers are added to struct
> unpriv_access_state, only the *unpriv_access* helpers need to be amended.

Certainly if that struct grows more state, then the factoring will
help in future.  I wasn't clear on how we expect this all to evolve.

Either way, this is basically a non-issue, and keeping the symmetry is
probably a good idea.

Cheers
---Dave
Dave Martin Oct. 21, 2024, 1:44 p.m. UTC | #8
On Mon, Oct 21, 2024 at 12:05:30PM +0200, Kevin Brodsky wrote:
> On 17/10/2024 17:49, Dave Martin wrote:
> > On Thu, Oct 17, 2024 at 02:39:05PM +0100, Kevin Brodsky wrote:
> >> Commit 33f082614c34 ("arm64: signal: Allow expansion of the signal
> >> frame") introduced the BASE_SIGFRAME_SIZE macro but it has
> >> apparently never been used.
> > Nit: Should there be a statement of what the patch does?
> >
> > Same throughout the series.
> >
> > (Yes, I know it's in the subject line, but Mutt doesn't think that's
> > part of the message body, so I can't see it now that I'm replying...
> > and submitting-patches.rst and e.g., maintainer-tip.rst seem to take
> > the same policy, albeit without quite stating it explicitly.)
> 
> Ah good point, I didn't consider that. Will make it explicit in patch 1
> and 2.

Thanks.

(I have a patch for submitting-patches.rst knocking about to propose
making this more explicit, but I didn't dare to post it so far...)

Cheers
---Dave
Dave Martin Oct. 21, 2024, 2:38 p.m. UTC | #9
Hi,

Just in case the reply I thought I'd sent to this evaporated (or I
imagined it):

On Mon, Oct 21, 2024 at 12:06:07PM +0200, Kevin Brodsky wrote:
> On 17/10/2024 17:53, Dave Martin wrote:
> > [...]
> >> +/*
> >> + * Save the unpriv access state into ua_state and reset it to disable any
> >> + * restrictions.
> >> + */
> >> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)
> > Would _user_ be more consistent naming than _unpriv_ ?
> 
> I did ponder on the naming. I considered user_access/uaccess instead of
> unpriv_access, but my concern is that it might imply that only uaccess
> is concerned, while in reality loads/stores that userspace itself
> executes are impacted too. I thought using the "unpriv" terminology from
> the Arm ARM (used for stage 1 permissions) might avoid such
> misunderstanding. I'm interested to hear opinions on this, maybe
> accuracy sacrifices readability.
> 
> > Same elsewhere.

I think "user" covers these meanings, though including the word
"access" makes it sound like this is specific to uaccess.

Maybe something like:

save_reset_user_permissions()
restore_user_permissions()

would make sense?  (But again, it's not a big deal.)

> >
> >> +{
> >> +	if (system_supports_poe()) {
> >> +		/*
> >> +		 * Enable all permissions in all 8 keys
> >> +		 * (inspired by REPEAT_BYTE())
> >> +		 */
> >> +		u64 por_enable_all = (~0u / POE_MASK) * POE_RXW;
> > Yikes!
> >
> > Seriously though, why are we granting permissions that the signal
> > handler isn't itself going to have over its own stack?
> >
> > I think the logical thing to do is to think of the write/read of the
> > signal frame as being done on behalf of the signal handler, so the
> > permissions should be those we're going to give the signal handler:
> > not less, and (so far as we can approximate) not more.
> 
> Will continue that discussion on the cover letter.
> 
> >
> >> +
> >> +		ua_state->por_el0 = read_sysreg_s(SYS_POR_EL0);
> >> +		write_sysreg_s(por_enable_all, SYS_POR_EL0);
> >> +		/* Ensure that any subsequent uaccess observes the updated value */
> >> +		isb();
> >> +	}
> >> +}
> >> +
> >> +/*
> >> + * Set the unpriv access state for invoking the signal handler.
> >> + *
> >> + * No uaccess should be done after that function is called.
> >> + */
> >> +static void set_handler_unpriv_access_state(void)
> >> +{
> >> +	if (system_supports_poe())
> >> +		write_sysreg_s(POR_EL0_INIT, SYS_POR_EL0);
> >> +
> > Spurious blank line?
> 
> Thanks!
> 
> >> +}
> > [...]
> >
> >> @@ -1252,9 +1310,11 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
> >>  {
> >>  	struct rt_sigframe_user_layout user;
> >>  	struct rt_sigframe __user *frame;
> >> +	struct unpriv_access_state ua_state;
> >>  	int err = 0;
> >>  
> >>  	fpsimd_signal_preserve_current_state();
> >> +	save_reset_unpriv_access_state(&ua_state);
> > (Trivial nit: maybe put the blank line before this rather than after?
> > This has nothing to do with "settling" the kernel's internal context
> > switch state, and a lot to do with generaing the signal frame...)
> 
> In fact considering the concern Catalin brought up with POR_EL0 being
> reset even when we fail to deliver the signal [1], I'm realising this
> call should be moved after get_sigframe(), since the latter doesn't use
> uaccess and can fail.

Good point...

> [1] https://lore.kernel.org/linux-arm-kernel/Zw6D2waVyIwYE7wd@arm.com/
> 
> >>  
> >>  	if (get_sigframe(&user, ksig, regs))
> >>  		return 1;
> > [...]

I guess the call can be pushed to just before the first __put_user(),
after here?

> >
> >> @@ -1273,6 +1333,7 @@ static int setup_rt_frame(int usig, struct ksignal *ksig, sigset_t *set,
> >>  			regs->regs[1] = (unsigned long)&frame->info;
> >>  			regs->regs[2] = (unsigned long)&frame->uc;
> >>  		}
> >> +		set_handler_unpriv_access_state();
> > This bit feels prematurely factored?  We don't have separate functions
> > for the other low-level preparation done here...
> 
> I preferred to have a consistent API for all manipulations of POR_EL0,
> the idea being that if more registers are added to struct
> unpriv_access_state, only the *unpriv_access* helpers need to be amended.
> 
> > It works either way though, and I don't have a strong view.
> >
> > Overall, this all looks reasonable.

Keeping the symmetry seems generally a good idea, especially if we
expect that struct to grow more state over time.  I wasn't sure how we
anticipiate this evolving.

[...]

Cheers
---Dave
Catalin Marinas Oct. 21, 2024, 3:30 p.m. UTC | #10
On Mon, Oct 21, 2024 at 02:31:08PM +0100, Dave P Martin wrote:
> > > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
> > >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
> > >> series [1] that recently landed on mainline. The goal is to improve the
> > >> way we handle the register that governs which pkeys/POIndex are
> > >> accessible (POR_EL0) during signal delivery. As things stand, we may
> > >> unexpectedly fail to write the signal frame on the stack because POR_EL0
> > >> is not reset before the uaccess operations. See patch 3 for more details
> > >> and the main changes this series brings.
> > >>
> > >> A similar series landed recently for x86/MPK [2]; the present series
> > >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
> > >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
> > >> only. This means that a program that sets up an alternate signal stack
> > >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
> > >> before invoking the real signal handler, as discussed here [3].
[...]
> Memory with a non-zero pkey cannot be used 100% portably, period, and
> having non-RW(X) permissions on pkey 0 at any time is also not
> portable, period.  So I'm not sure that having libc magically guess
> what userspace's pkeys policy is supposed to be based on racily digging
> metadata out of /proc/self/maps or a cache of it etc. would be such a
> good idea.

I agree that changing RWX overlay permission for pkey 0 to anything else
is a really bad idea. We can't prevent it but we shouldn't actively try
to work around it in the kernel either. With the current signal ABI, I
don't think we should support anything other than pkey 0 for the stack.
Since the user shouldn't change the pkey 0 RWX overlay permission
anyway, I don't think we should reset POR_EL0 _prior_ to writing the
signal frame. The best we can do is document it somewhere.

So on patch 3 I'd only ensure that we have POR_EL0_INIT when invoking
the signal handler and not when performing the uaccess. If the uaccess
fails, we'd get a fatal SIGSEGV. The user may have got it already if it
made the stack read-only.

Currently the primary use of pkeys is for W^X and signal stacks
shouldn't fall into this category. If we ever have a strong case for
non-zero pkeys on the signal stack, we'll need to look into some new
ABI. I'm not sure about SS_* flags though, I think the signal POR_EL0
should be associated with the sigaction rather than the stack (the
latter would just be mapped by the user with the right pkey, the kernel
doesn't need to know which, only what POR_EL0 is needed by the handler).

Until such case turns up, I'd not put any effort into ABI improvements.
I can think of some light compartmentalisation where we have a pkey
that's "privileged" and all threads have a POR_EL0 that prevents access
to that pkey. The signal handler would have more permissive rights to
that privileged pkey. I'd not proactively add support for this though.
Will Deacon Oct. 21, 2024, 5:19 p.m. UTC | #11
On Mon, Oct 21, 2024 at 04:30:04PM +0100, Catalin Marinas wrote:
> On Mon, Oct 21, 2024 at 02:31:08PM +0100, Dave P Martin wrote:
> > > > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
> > > >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
> > > >> series [1] that recently landed on mainline. The goal is to improve the
> > > >> way we handle the register that governs which pkeys/POIndex are
> > > >> accessible (POR_EL0) during signal delivery. As things stand, we may
> > > >> unexpectedly fail to write the signal frame on the stack because POR_EL0
> > > >> is not reset before the uaccess operations. See patch 3 for more details
> > > >> and the main changes this series brings.
> > > >>
> > > >> A similar series landed recently for x86/MPK [2]; the present series
> > > >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
> > > >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
> > > >> only. This means that a program that sets up an alternate signal stack
> > > >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
> > > >> before invoking the real signal handler, as discussed here [3].
> [...]
> > Memory with a non-zero pkey cannot be used 100% portably, period, and
> > having non-RW(X) permissions on pkey 0 at any time is also not
> > portable, period.  So I'm not sure that having libc magically guess
> > what userspace's pkeys policy is supposed to be based on racily digging
> > metadata out of /proc/self/maps or a cache of it etc. would be such a
> > good idea.
> 
> I agree that changing RWX overlay permission for pkey 0 to anything else
> is a really bad idea. We can't prevent it but we shouldn't actively try
> to work around it in the kernel either. With the current signal ABI, I
> don't think we should support anything other than pkey 0 for the stack.
> Since the user shouldn't change the pkey 0 RWX overlay permission
> anyway, I don't think we should reset POR_EL0 _prior_ to writing the
> signal frame. The best we can do is document it somewhere.
> 
> So on patch 3 I'd only ensure that we have POR_EL0_INIT when invoking
> the signal handler and not when performing the uaccess. If the uaccess
> fails, we'd get a fatal SIGSEGV. The user may have got it already if it
> made the stack read-only.

Hmm, but based on what Kevin's saying, this would mean actively choosing
a different ABI than what x86 is trying to get to.

> Currently the primary use of pkeys is for W^X and signal stacks
> shouldn't fall into this category. If we ever have a strong case for
> non-zero pkeys on the signal stack, we'll need to look into some new
> ABI. I'm not sure about SS_* flags though, I think the signal POR_EL0
> should be associated with the sigaction rather than the stack (the
> latter would just be mapped by the user with the right pkey, the kernel
> doesn't need to know which, only what POR_EL0 is needed by the handler).
> 
> Until such case turns up, I'd not put any effort into ABI improvements.

Kevin -- do you know what prompted x86 to want the pkey to be reset early
in signal delivery? Perhaps such a use-case already exists.

> I can think of some light compartmentalisation where we have a pkey
> that's "privileged" and all threads have a POR_EL0 that prevents access
> to that pkey. The signal handler would have more permissive rights to
> that privileged pkey. I'd not proactively add support for this though.

I'd not proactively diverge from other architectures, either :p

Will
Pierre Langlois Oct. 22, 2024, 9:31 a.m. UTC | #12
Dave Martin <Dave.Martin@arm.com> writes:

> On Mon, Oct 21, 2024 at 12:06:25PM +0200, Kevin Brodsky wrote:
>> On 17/10/2024 17:48, Dave Martin wrote:
>> > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
>> >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
>> >> series [1] that recently landed on mainline. The goal is to improve the
>> >> way we handle the register that governs which pkeys/POIndex are
>> >> accessible (POR_EL0) during signal delivery. As things stand, we may
>> >> unexpectedly fail to write the signal frame on the stack because POR_EL0
>> >> is not reset before the uaccess operations. See patch 3 for more details
>> >> and the main changes this series brings.
>> >>
>> >> A similar series landed recently for x86/MPK [2]; the present series
>> >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
>> >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
>> >> only. This means that a program that sets up an alternate signal stack
>> >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
>> >> before invoking the real signal handler, as discussed here [3].
>> > This feels a bit bogus (though it's anyway orthogonal to this series).
>> 
>> I'm not very fond of this either. However I believe this is the correct
>> first step: bring arm64 in line with x86. Removing all restrictions
>> before uaccess and then setting POR_EL0 to POR_EL0_INIT enables
>> userspace to use any pkey for the alternate signal stack without an ABI
>> change, albeit not in a very comfortable way (if the pkey is not 0).
>
> I see: we try not to prevent userspace from using whatever pkey it
> likes for the alternate signal stack, but we are only permissive for
> the bare minimum operations that userspace can't possibly control for
> itself (i.e., writing the signal frame).
>
> This whole thing feels a bit of a botch, though.
>
> Do we know of anyone actually using a sigaltstack with a pkey other
> than 0?  Why the urgency?  Code relying on an asm shim on x86 is
> already nonportable, unless I've misunderstood something, so simply
> turning on arm64 pkeys support in the kernel and libc shouldn't break
> anything today?  (At least, nothing that wasn't asking to be broken.)

As far as I know, Chrome plans on using a sigaltstack with a non-zero
pkey as part of the V8 CFI and W^X work [0][1][2]. IIUC that was is part
of the motivation for the x86 change. I don't know if it's urgent
though.

I added Stephen on CC who might be able to comment on the current state
of things in Chrome. I don't think the code that uses a pkey on a
sigaltstack is upstream yet.

[0]: https://v8.dev/blog/control-flow-integrity#signal-frame-corruption
[1]: https://lore.kernel.org/lkml/CAEAAPHa3g0QwU=DZ2zVCqTCSh-+n2TtVKrQ07LvpwDjQ-F09gA@mail.gmail.com/
[2]: https://docs.google.com/document/d/1O2jwK4dxI3nRcOJuPYkonhTkNQfbmwdvxQMyXgeaRHo

>
>> 
>> > Really, we want some way for userspace to tell the kernel what
>> > permissions to use for the alternate signal stack and signal handler
>> > using it, and then honour that request consistently (just as we try to
>> > do for the main stack today).
>> >
>> > ss_flags is mostly unused... I wonder whether we could add something in
>> > there?  Or add a sigaltstack2()?
>> 
>> Yes, this would be sensible as a second step (backwards-compatible
>> extension). Exactly how that API would look like is not trivial though:
>> is the pkey implicitly derived from the pointer provided to
>> sigaltstack()? Is there a need to specify another pkey for code, or do
>> we just assume that the signal handler is only using code with pkey 0?
>> (Not a concern on x86 as MPK doesn't restrict execution.) Would be very
>> interested to hear opinions on this.

I hadn't considered setting a non-zero pkey for code, but it sounds
appealing.

The general goal, IIUC, is for signal handlers to run in an isolated
"context" using pkeys, in order to mitigate against an attacker trying
to corrupt the CPU state on the stack from another thread. Then use this
as a way to bypass any CFI mitigation, by setting an arbitrary PC and
registers.

So sigaltstack+pkey helps with isolating the stack. Then it's up to the
programmer to carefully write the signal handler code so it only uses
pkey-tagged data that other threads cannot corrupt in order to trick the
signal handler into writing to its own stack.

In this context, using a non-default pkey for code might be useful, in
order to differentiate between "valid" signal handlers and other
functions. It could help fend against an attacker being able to use
sigaction as a whole-function gadget to install any function as a signal
hander. Basically mitigating going from a limited CFI bypass to an
arbitrary CFI bypass.

That being said, regarding the kernel API, it might be possible to do
the above with this patch. We'd be using the proposed "assembly
prologues" that sets POR_EL0 as the first thing then continues to the
real signal handler. But if we can avoid those and directly ask the
kernel what POR_EL0 should be set to, it'd be simpler (and maybe safer).

>> 
>> Kevin
>
> I would vote for specifying the pkey (or, if feasible, PKRU or
> modifications to it) in some bits of ss_flags, or in an additional
> flags argument to sigaltstack2().
>
> Memory with a non-zero pkey cannot be used 100% portably, period, and
> having non-RW(X) permissions on pkey 0 at any time is also not
> portable, period.  So I'm not sure that having libc magically guess
> what userspace's pkeys policy is supposed to be based on racily digging
> metadata out of /proc/self/maps or a cache of it etc. would be such a
> good idea.
>
> There are other ways to approach (or not approach) this though --
> I would be interested to hear what other people think too...

Thinking about this, I'm not sure about tying this API to sigaltstack,
as this is about configuring the POR_EL0 register, which may control
more than the stack.

I actually have a concrete example of this in V8. There's a
SetDefaultPermissionsForSignalHandler [3] function that needs to be
called first thing on signal handlers to configure access to an
allocated non-zero key.  This is independent from having a pkey-tagged
sigaltstack or not, but I suppose later on it will need to be replaced
with assembly when the stack is no-longer accessible.

[3]: https://source.chromium.org/chromium/chromium/src/+/main:v8/include/v8-platform.h;l=665;drc=0abf23ec2a1bb475b1555790fdc72ef630a43c2a;bpv=1;bpt=1

Doing this via sigaction as Catalin suggested makes sense to me, but I'm
unsure how we express how POR_EL0 needs to be set solely using SA_*
flags. Are we able to add a new architecture-specific payload to
sigaction, or would that resort in a new syscall like sigaction2?

As an alternative, I was wondering if this would warrant a new syscall
like sigaltstack, but for CPU state.

Thanks,
Pierre
Stephen Röttger Oct. 22, 2024, 10:40 a.m. UTC | #13
On Tue, Oct 22, 2024 at 11:31 AM Pierre Langlois
<pierre.langlois@arm.com> wrote:
>
> Dave Martin <Dave.Martin@arm.com> writes:
>
> > On Mon, Oct 21, 2024 at 12:06:25PM +0200, Kevin Brodsky wrote:
> >> On 17/10/2024 17:48, Dave Martin wrote:
> >> > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
> >> >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
> >> >> series [1] that recently landed on mainline. The goal is to improve the
> >> >> way we handle the register that governs which pkeys/POIndex are
> >> >> accessible (POR_EL0) during signal delivery. As things stand, we may
> >> >> unexpectedly fail to write the signal frame on the stack because POR_EL0
> >> >> is not reset before the uaccess operations. See patch 3 for more details
> >> >> and the main changes this series brings.
> >> >>
> >> >> A similar series landed recently for x86/MPK [2]; the present series
> >> >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
> >> >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
> >> >> only. This means that a program that sets up an alternate signal stack
> >> >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
> >> >> before invoking the real signal handler, as discussed here [3].
> >> > This feels a bit bogus (though it's anyway orthogonal to this series).
> >>
> >> I'm not very fond of this either. However I believe this is the correct
> >> first step: bring arm64 in line with x86. Removing all restrictions
> >> before uaccess and then setting POR_EL0 to POR_EL0_INIT enables
> >> userspace to use any pkey for the alternate signal stack without an ABI
> >> change, albeit not in a very comfortable way (if the pkey is not 0).
> >
> > I see: we try not to prevent userspace from using whatever pkey it
> > likes for the alternate signal stack, but we are only permissive for
> > the bare minimum operations that userspace can't possibly control for
> > itself (i.e., writing the signal frame).
> >
> > This whole thing feels a bit of a botch, though.
> >
> > Do we know of anyone actually using a sigaltstack with a pkey other
> > than 0?  Why the urgency?  Code relying on an asm shim on x86 is
> > already nonportable, unless I've misunderstood something, so simply
> > turning on arm64 pkeys support in the kernel and libc shouldn't break
> > anything today?  (At least, nothing that wasn't asking to be broken.)
>
> As far as I know, Chrome plans on using a sigaltstack with a non-zero
> pkey as part of the V8 CFI and W^X work [0][1][2]. IIUC that was is part
> of the motivation for the x86 change. I don't know if it's urgent
> though.
>
> I added Stephen on CC who might be able to comment on the current state
> of things in Chrome. I don't think the code that uses a pkey on a
> sigaltstack is upstream yet.

We don't have any code for this in Chrome, since I believe it's not
supported by the kernel yet.

> [0]: https://v8.dev/blog/control-flow-integrity#signal-frame-corruption
> [1]: https://lore.kernel.org/lkml/CAEAAPHa3g0QwU=DZ2zVCqTCSh-+n2TtVKrQ07LvpwDjQ-F09gA@mail.gmail.com/
> [2]: https://docs.google.com/document/d/1O2jwK4dxI3nRcOJuPYkonhTkNQfbmwdvxQMyXgeaRHo
>
> >
> >>
> >> > Really, we want some way for userspace to tell the kernel what
> >> > permissions to use for the alternate signal stack and signal handler
> >> > using it, and then honour that request consistently (just as we try to
> >> > do for the main stack today).
> >> >
> >> > ss_flags is mostly unused... I wonder whether we could add something in
> >> > there?  Or add a sigaltstack2()?
> >>
> >> Yes, this would be sensible as a second step (backwards-compatible
> >> extension). Exactly how that API would look like is not trivial though:
> >> is the pkey implicitly derived from the pointer provided to
> >> sigaltstack()? Is there a need to specify another pkey for code, or do
> >> we just assume that the signal handler is only using code with pkey 0?
> >> (Not a concern on x86 as MPK doesn't restrict execution.) Would be very
> >> interested to hear opinions on this.
>
> I hadn't considered setting a non-zero pkey for code, but it sounds
> appealing.
>
> The general goal, IIUC, is for signal handlers to run in an isolated
> "context" using pkeys, in order to mitigate against an attacker trying
> to corrupt the CPU state on the stack from another thread. Then use this
> as a way to bypass any CFI mitigation, by setting an arbitrary PC and
> registers.

Right. We're mainly looking for a solution to protect the signal frame
against memory corruption.
I'm aware of two proposals on how to achieve this:
1) is using a pkey-protected sigaltstack, which requires a patchset
like [0] to allow xsave to write to the stack
2) is to store part of the sigframe on the shadow stack as Rick
Edgecombe proposed in [1]

[0] https://lore.kernel.org/lkml/20240802061318.2140081-1-aruna.ramakrishna@oracle.com/#t
[1] https://lore.kernel.org/lkml/2fb80876e286b4db8f9ef36bcce04bbf02af0de2.camel@intel.com/

> So sigaltstack+pkey helps with isolating the stack. Then it's up to the
> programmer to carefully write the signal handler code so it only uses
> pkey-tagged data that other threads cannot corrupt in order to trick the
> signal handler into writing to its own stack.
>
> In this context, using a non-default pkey for code might be useful, in
> order to differentiate between "valid" signal handlers and other
> functions. It could help fend against an attacker being able to use
> sigaction as a whole-function gadget to install any function as a signal
> hander. Basically mitigating going from a limited CFI bypass to an
> arbitrary CFI bypass.
>
> That being said, regarding the kernel API, it might be possible to do
> the above with this patch. We'd be using the proposed "assembly
> prologues" that sets POR_EL0 as the first thing then continues to the
> real signal handler. But if we can avoid those and directly ask the
> kernel what POR_EL0 should be set to, it'd be simpler (and maybe safer).
>
> >>
> >> Kevin
> >
> > I would vote for specifying the pkey (or, if feasible, PKRU or
> > modifications to it) in some bits of ss_flags, or in an additional
> > flags argument to sigaltstack2().
> >
> > Memory with a non-zero pkey cannot be used 100% portably, period, and
> > having non-RW(X) permissions on pkey 0 at any time is also not
> > portable, period.  So I'm not sure that having libc magically guess
> > what userspace's pkeys policy is supposed to be based on racily digging
> > metadata out of /proc/self/maps or a cache of it etc. would be such a
> > good idea.
> >
> > There are other ways to approach (or not approach) this though --
> > I would be interested to hear what other people think too...
>
> Thinking about this, I'm not sure about tying this API to sigaltstack,
> as this is about configuring the POR_EL0 register, which may control
> more than the stack.
>
> I actually have a concrete example of this in V8. There's a
> SetDefaultPermissionsForSignalHandler [3] function that needs to be
> called first thing on signal handlers to configure access to an
> allocated non-zero key.  This is independent from having a pkey-tagged
> sigaltstack or not, but I suppose later on it will need to be replaced
> with assembly when the stack is no-longer accessible.
>
> [3]: https://source.chromium.org/chromium/chromium/src/+/main:v8/include/v8-platform.h;l=665;drc=0abf23ec2a1bb475b1555790fdc72ef630a43c2a;bpv=1;bpt=1
>
> Doing this via sigaction as Catalin suggested makes sense to me, but I'm
> unsure how we express how POR_EL0 needs to be set solely using SA_*
> flags. Are we able to add a new architecture-specific payload to
> sigaction, or would that resort in a new syscall like sigaction2?
>
> As an alternative, I was wondering if this would warrant a new syscall
> like sigaltstack, but for CPU state.
>
> Thanks,
> Pierre
Catalin Marinas Oct. 22, 2024, 10:45 a.m. UTC | #14
On Mon, Oct 21, 2024 at 06:19:38PM +0100, Will Deacon wrote:
> On Mon, Oct 21, 2024 at 04:30:04PM +0100, Catalin Marinas wrote:
> > On Mon, Oct 21, 2024 at 02:31:08PM +0100, Dave P Martin wrote:
> > > > > On Thu, Oct 17, 2024 at 02:39:04PM +0100, Kevin Brodsky wrote:
> > > > >> This series is a follow-up to Joey's Permission Overlay Extension (POE)
> > > > >> series [1] that recently landed on mainline. The goal is to improve the
> > > > >> way we handle the register that governs which pkeys/POIndex are
> > > > >> accessible (POR_EL0) during signal delivery. As things stand, we may
> > > > >> unexpectedly fail to write the signal frame on the stack because POR_EL0
> > > > >> is not reset before the uaccess operations. See patch 3 for more details
> > > > >> and the main changes this series brings.
> > > > >>
> > > > >> A similar series landed recently for x86/MPK [2]; the present series
> > > > >> aims at aligning arm64 with x86. Worth noting: once the signal frame is
> > > > >> written, POR_EL0 is still set to POR_EL0_INIT, granting access to pkey 0
> > > > >> only. This means that a program that sets up an alternate signal stack
> > > > >> with a non-zero pkey will need some assembly trampoline to set POR_EL0
> > > > >> before invoking the real signal handler, as discussed here [3].
> > [...]
> > > Memory with a non-zero pkey cannot be used 100% portably, period, and
> > > having non-RW(X) permissions on pkey 0 at any time is also not
> > > portable, period.  So I'm not sure that having libc magically guess
> > > what userspace's pkeys policy is supposed to be based on racily digging
> > > metadata out of /proc/self/maps or a cache of it etc. would be such a
> > > good idea.
> > 
> > I agree that changing RWX overlay permission for pkey 0 to anything else
> > is a really bad idea. We can't prevent it but we shouldn't actively try
> > to work around it in the kernel either. With the current signal ABI, I
> > don't think we should support anything other than pkey 0 for the stack.
> > Since the user shouldn't change the pkey 0 RWX overlay permission
> > anyway, I don't think we should reset POR_EL0 _prior_ to writing the
> > signal frame. The best we can do is document it somewhere.
> > 
> > So on patch 3 I'd only ensure that we have POR_EL0_INIT when invoking
> > the signal handler and not when performing the uaccess. If the uaccess
> > fails, we'd get a fatal SIGSEGV. The user may have got it already if it
> > made the stack read-only.
> 
> Hmm, but based on what Kevin's saying, this would mean actively choosing
> a different ABI than what x86 is trying to get to.

I was more thinking of not relaxing the ABI further at this point in the
rc cycle rather than completely diverging (x86 did relax the ABI
subsequently to handle non-zero pkey sigaltstack).

> > Currently the primary use of pkeys is for W^X and signal stacks
> > shouldn't fall into this category. If we ever have a strong case for
> > non-zero pkeys on the signal stack, we'll need to look into some new
> > ABI. I'm not sure about SS_* flags though, I think the signal POR_EL0
> > should be associated with the sigaction rather than the stack (the
> > latter would just be mapped by the user with the right pkey, the kernel
> > doesn't need to know which, only what POR_EL0 is needed by the handler).
> > 
> > Until such case turns up, I'd not put any effort into ABI improvements.
> 
> Kevin -- do you know what prompted x86 to want the pkey to be reset early
> in signal delivery? Perhaps such a use-case already exists.

Given the email from Pierre with Chrome potentially using a sigaltstack
with a non-zero pkey, Kevin's patches (and the x86 changes) make more
sense. The question is whether we do this as a fix now or we leave the
relaxation for a subsequent kernel release. I guess we could squeeze it
now if we agree on the implementation.
Kevin Brodsky Oct. 22, 2024, 12:34 p.m. UTC | #15
On 21/10/2024 15:43, Dave Martin wrote:
> On Mon, Oct 21, 2024 at 12:06:07PM +0200, Kevin Brodsky wrote:
>> On 17/10/2024 17:53, Dave Martin wrote:
>>> [...]
>>>> +/*
>>>> + * Save the unpriv access state into ua_state and reset it to disable any
>>>> + * restrictions.
>>>> + */
>>>> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)
>>> Would _user_ be more consistent naming than _unpriv_ ?
>> I did ponder on the naming. I considered user_access/uaccess instead of
>> unpriv_access, but my concern is that it might imply that only uaccess
>> is concerned, while in reality loads/stores that userspace itself
>> executes are impacted too. I thought using the "unpriv" terminology from
>> the Arm ARM (used for stage 1 permissions) might avoid such
>> misunderstanding. I'm interested to hear opinions on this, maybe
>> accuracy sacrifices readability.
> "user_access" seemed natural to me: it parses equally as "[user
> access]" (i.e., uaccess) and "[user] access" (i.e., access by, to, or
> on behalf of user(space)).
>
> Introducing an architectural term when there is already a generic OS
> and Linux kernel term that means the right thing seemed not to improve
> readability, but I guess it's a matter of opinion.

Both good points. "user_access" seems to strike the right balance, plus
it's slightly shorter. Will switch to that naming in v2.

Kevin
Dave Martin Oct. 22, 2024, 12:38 p.m. UTC | #16
Hi,

On Tue, Oct 22, 2024 at 02:34:09PM +0200, Kevin Brodsky wrote:
> On 21/10/2024 15:43, Dave Martin wrote:
> > On Mon, Oct 21, 2024 at 12:06:07PM +0200, Kevin Brodsky wrote:
> >> On 17/10/2024 17:53, Dave Martin wrote:
> >>> [...]
> >>>> +/*
> >>>> + * Save the unpriv access state into ua_state and reset it to disable any
> >>>> + * restrictions.
> >>>> + */
> >>>> +static void save_reset_unpriv_access_state(struct unpriv_access_state *ua_state)
> >>> Would _user_ be more consistent naming than _unpriv_ ?
> >> I did ponder on the naming. I considered user_access/uaccess instead of
> >> unpriv_access, but my concern is that it might imply that only uaccess
> >> is concerned, while in reality loads/stores that userspace itself
> >> executes are impacted too. I thought using the "unpriv" terminology from
> >> the Arm ARM (used for stage 1 permissions) might avoid such
> >> misunderstanding. I'm interested to hear opinions on this, maybe
> >> accuracy sacrifices readability.
> > "user_access" seemed natural to me: it parses equally as "[user
> > access]" (i.e., uaccess) and "[user] access" (i.e., access by, to, or
> > on behalf of user(space)).
> >
> > Introducing an architectural term when there is already a generic OS
> > and Linux kernel term that means the right thing seemed not to improve
> > readability, but I guess it's a matter of opinion.
> 
> Both good points. "user_access" seems to strike the right balance, plus
> it's slightly shorter. Will switch to that naming in v2.

Suits me (wasn't sure I was going to win that one actually!)

Cheers
---Dave