System Calls for Memory Protection Keys
Subsystems (14)
v4 cover System Calls for Memory Protection Keys
I'm resending these because Ingo has said that he'd "love to have some high level MM review & ack for these syscall ABI extensions." The only changes to the code in months have been in the selftests. So, if anyone has been putting off taking a look at these, I'd appreciate a look now.
I also feel compelled to mention this, since I haven't before and it gives me confidence that these interfaces are good enough:
Among other things, this feature was designed to help fix a class of bugs in long-running applications where data corruption is detected long after it occurs. Today, applications either live with the corruption, or eat a huge performance penalty from calling mprotect() frequently. The developers of these applications are already running *this* *code* and are very eager to see this feature merged and picked up in future distributions where their customers can use it.
Other than this message, a good place to start with a review is in the pkey(7) manpage, which I've published in HTML form here:
https://www.sr71.net/~dave/intel/manpages/
--
Memory Protection Keys for User pages (pkeys) is a CPU feature which will first appear on Skylake Servers, but will also be supported on future non-server parts. It provides a mechanism for enforcing page-based protections, but without requiring modification of the page tables when an application changes wishes to change permissions.
Among other things, this feature was designed to help fix a class of bugs in long-running applications where data corruption is detected long after it occurs. Applications today either live with the corruption, or eat a huge performance penalty from calling mprotect() frequently. The developers of these applications are already running this code and are very eager to see this feature merged and picked up in future distributions where their customers can use it.
Patches to implement execute-only mapping support using pkeys were merged in to 4.6. But, to do anything else useful with pkeys, an application needs to be able to set the pkey field in the PTE (obviously has to be done in-kernel) and make changes to the "rights" register (using unprivileged instructions).
An application also needs to have an an allocator for the keys themselves. If two different parts of an application both want to protect their data with pkeys, they first need to know which key to use for their individual purposes.
This set introduces 5 system calls, in 3 logical groups:
1. PTE pkey setting (sys_pkey_mprotect(), patches #1-3)
2. Key allocation (sys_pkey_alloc() / sys_pkey_free(), patch #4)
3. Rights register manipulation (sys_pkey_set/get(), patch #5)
I have manpages written for some of these syscalls, and have had multiple rounds of reviews on the manpages list.
This set is also available here:
git://git.kernel.org/pub/scm/linux/kernel/git/daveh/x86-pkeys.git pkeys-v040
I've written a set of unit tests for these interfaces, which is available as the last patch in the series and integrated in to kselftests.
=== diffstat ===
Dave Hansen (9):
x86, pkeys: add fault handling for PF_PK page fault bit
mm: implement new pkey_mprotect() system call x86, pkeys: make mprotect_key() mask off additional vm_flags
x86: wire up mprotect_key() system call
x86, pkeys: allocation/free syscalls
x86, pkeys: add pkey set/get syscalls
generic syscalls: wire up memory protection keys syscalls
pkeys: add details of system call use to Documentation/ x86, pkeys: add self-tests
Documentation/x86/protection-keys.txt | 63 + arch/alpha/include/uapi/asm/mman.h | 5 + arch/mips/include/uapi/asm/mman.h | 5 + arch/parisc/include/uapi/asm/mman.h | 5 + arch/x86/entry/syscalls/syscall_32.tbl | 5 + arch/x86/entry/syscalls/syscall_64.tbl | 5 + arch/x86/include/asm/mmu.h | 8 + arch/x86/include/asm/mmu_context.h | 25 +- arch/x86/include/asm/pgtable.h | 13 +- arch/x86/include/asm/pgtable_64.h | 26 +- arch/x86/include/asm/pgtable_types.h | 6 - arch/x86/include/asm/pkeys.h | 80 +- arch/x86/kernel/fpu/xstate.c | 73 +- arch/x86/mm/fault.c | 9 + arch/x86/mm/pkeys.c | 38 +- arch/xtensa/include/uapi/asm/mman.h | 5 + include/linux/pkeys.h | 39 +- include/linux/syscalls.h | 8 + include/uapi/asm-generic/mman-common.h | 5 + include/uapi/asm-generic/unistd.h | 12 +- mm/mprotect.c | 134 +- tools/testing/selftests/x86/Makefile | 3 +- tools/testing/selftests/x86/pkey-helpers.h | 191 +++ tools/testing/selftests/x86/protection_keys.c | 1316 +++++++++++++++++ 24 files changed, 2012 insertions(+), 67 deletions(-)
=== changelog ===
Changes from v3:
* added generic syscalls declarations to include/linux/syscalls.h to fix arm64 compile issue.
Changes from v2:
* selftest updates:
* formatting changes like what Ingo asked for with MPX
* actually call WRPKRU in __wrpkru()
* once __wrpkru() was fixed, revealed a bug in the ptrace test where we were testing against the wrong pointer during the "baseline" test
* Man-pages that match this set are here:
http://marc.info/?l=linux-man&m=146540723525616&w=2
Changes from v1:
* updates to alloc/free patch description calling out that "in-use" pkeys may still be pkey_free()'d successfully.
* Fixed a bug in the selftest where the 'flags' argument was not passed to pkey_get().
* Added all syscalls to generic syscalls header
* Added extra checking to selftests so it doesn't fall over when 1G pages are made the hugetlbfs default.
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 1/9 x86, pkeys: add fault handling for PF_PK page fault bit
From: Dave Hansen <[email protected]>
PF_PK means that a memory access violated the protection key access restrictions. It is unconditionally an access_error() because the permissions set on the VMA don't matter (the PKRU value overrides it), and we never "resolve" PK faults (like how a COW can "resolve write fault).
---
b/arch/x86/mm/fault.c | 9 +++++++++ 1 file changed, 9 insertions(+)
arch/x86/mm/fault.c renamed from arch/x86/mm/fault.c~pkeys-105-add-pk-to-fault +9 -0
@@ -1112,6 +1112,15 @@ access_error(unsigned long error_code, s {/* This is only called for the current mm, so: */ bool foreign = false; + +/* +* Read or write was blocked by protection keys. This is +* always an unconditional error and can never result in +* a follow-up action to resolve the fault, like a COW. +*/ +if (error_code &PF_PK ) +return 1 ; +/* * Make sure to check the VMA so that we do not perform * faults just to hit a PF_PK as soon as we fill in a
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 1/9] x86, pkeys: add fault handling for PF_PK page fault bit
Quoted 10 lines · Dave Hansen
From: Dave Hansen <[email protected]>
PF_PKmeans that a memory access violated the protection key access restrictions. It is unconditionally anaccess_error()because the permissions set on the VMA don't matter (the PKRU value overrides it), and we never "resolve" PK faults (like how a COW can "resolve write fault).Signed-off-by Dave Hansen <[email protected]>
An access fault gets propgated as SEGV_PKUERR. What happens if glibc does not recognise it?
Signature · 8 lines
Mel Gorman SUSE Labs -- To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM, see: http://www.linux-mm.org/ . Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 1/9] x86, pkeys: add fault handling for PF_PK page fault bit
Quoted 8 lines · Mel Gorman
Quoted 7 lines · Dave Hansen
From: Dave Hansen <[email protected]>
PF_PKmeans that a memory access violated the protection key access restrictions. It is unconditionally anaccess_error()because the permissions set on the VMA don't matter (the PKRU value overrides it), and we never "resolve" PK faults (like how a COW can "resolve write fault).
Quoted 4 lines
Quoted 1 line
Signed-off-by Dave Hansen <[email protected]>An access fault gets propgated as
SEGV_PKUERR. What happens if glibc does not recognise it?
It passes it through to the handler without any side-effects. I don't think it does anything differently with SEGV_* codes that it knows about vs. unknown ones. The only negative side-effect that I can think of is that it won't have a nice error message for it.
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 2/9 mm: implement new pkey_mprotect() system call
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
pkey_mprotect() is just like mprotect, except it also takes a protection key as an argument. On systems that do not support protection keys, it still works, but requires that key=0. Otherwise it does exactly what mprotect does.
I expect it to get used like this, if you want to guarantee that any mapping you create can *never* be accessed without the right protection keys set up.
int real_prot = PROT_READ|PROT_WRITE; pkey = pkey_alloc(0, PKEY_DENY_ACCESS); ptr = mmap(NULL, PAGE_SIZE, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); ret = pkey_mprotect(ptr, PAGE_SIZE, real_prot, pkey);
This way, there is *no* window where the mapping is accessible since it was always either PROT_NONE or had a protection key set that denied all access.
We settled on 'unsigned long' for the type of the key here. We only need 4 bits on x86 today, but I figured that other architectures might need some more space.
Semantically, we have a bit of a problem if we combine this syscall with our previously-introduced execute-only support:
What do we do when we mix execute-only pkey use with pkey_mprotect() use? For instance:
pkey_mprotect(ptr, PAGE_SIZE, PROT_WRITE, 6); // set pkey=6 mprotect(ptr, PAGE_SIZE, PROT_EXEC); // set pkey=X_ONLY_PKEY? mprotect(ptr, PAGE_SIZE, PROT_WRITE); // is pkey=6 again?
To solve that, we make the plain-mprotect()-initiated execute-only support only apply to VMAs that have the default protection key (0) set on them.
Proposed semantics:
1. protection key 0 is special and represents the default, "unassigned" protection key. It is always allocated.
2. mprotect() never affects a mapping's pkey_mprotect()-assigned protection key. A protection key of 0 (even if set explicitly) represents an unassigned protection key.
2a. mprotect(PROT_EXEC) on a mapping with an assigned protection
key may or may not result in a mapping with execute-only properties. pkey_mprotect() plus pkey_set() on all threads should be used to _guarantee_ execute-only semantics if this is not a strong enough semantic.
3. mprotect(PROT_EXEC) may result in an "execute-only" mapping. The kernel will internally attempt to allocate and dedicate a protection key for the purpose of execute-only mappings. This may not be possible in cases where there are no free protection keys available. It can also happen, of course, in situations where there is no hardware support for protection keys.
---
b/arch/x86/include/asm/mmu_context.h | 15 ++++++++++----- b/arch/x86/include/asm/pkeys.h | 11 +++++++++-- b/arch/x86/kernel/fpu/xstate.c | 15 ++++++++++++++- b/arch/x86/mm/pkeys.c | 2 +- b/mm/mprotect.c | 27 +++++++++++++++++++++++---- 5 files changed, 57 insertions(+), 13 deletions(-)
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-110-syscalls-mprotect_pkey +10 -5
@@ -4,6 +4,7 @@#include <asm/desc.h> #include <linux/atomic.h> #include <linux/mm_types.h> +#include <linux/pkeys.h> #include <trace/events/tlb.h>
@@ -195,16 +196,20 @@ static inline void arch_unmap(struct mm_mpx_notify_unmap (mm, vma, start, end); } +#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS static inline int vma_pkey (struct vm_area_struct *vma) { -u16 pkey =0 ; -#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS unsigned long vma_pkey_mask =VM_PKEY_BIT0 |VM_PKEY_BIT1 |VM_PKEY_BIT2 |VM_PKEY_BIT3 ; - pkey = (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ; -#endif -return pkey; + +return (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ; +} +#else +static inline int vma_pkey (struct vm_area_struct *vma) +{ +return 0 ; } +#endif static inline bool __pkru_allows_pkey (u16 pkey,bool write) {
arch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-110-syscalls-mprotect_pkey +9 -2
@@ -1,7 +1,12 @@#ifndef _ASM_X86_PKEYS_H#define _ASM_X86_PKEYS_H -#define arch_max_pkey () (boot_cpu_has(X86_FEATURE_OSPKE) ? 16 : 1) +#define PKEY_DEDICATED_EXECUTE_ONLY 15 +/* +* Consider the PKEY_DEDICATED_EXECUTE_ONLY key unavailable. +*/ +#define arch_max_pkey () (boot_cpu_has(X86_FEATURE_OSPKE) ? \ + PKEY_DEDICATED_EXECUTE_ONLY : 1)extern int arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val);
@@ -10,7 +15,6 @@ extern int arch_set_user_pkey_access(str* Try to dedicate one of the protection keys to be used as an * execute-only protection key. */ -#define PKEY_DEDICATED_EXECUTE_ONLY 15extern int __execute_only_pkey (struct mm_struct *mm);static inline int execute_only_pkey (struct mm_struct *mm) {
@@ -31,4 +35,7 @@ static inline int arch_override_mprotect return __arch_override_mprotect_pkey(vma, prot, pkey); } +extern int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val); +#endif /*_ASM_X86_PKEYS_H */
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +14 -1
@@ -889,7 +889,7 @@ out:* not modfiy PKRU *itself* here, only the XSAVE state that will * be restored in to PKRU when we return back to userspace. */ -int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val) {struct xregs_state *xsave = &tsk->thread.fpu.state.xsave;
@@ -948,3 +948,16 @@ int arch_set_user_pkey_access(struct tasreturn 0 ; } + +/* +* When setting a userspace-provided value, we need to ensure +* that it is valid. The __ version can get used by +* kernel-internal uses like the execute-only support. +*/ +int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val) +{ +if (!validate_pkey (pkey)) +return -EINVAL ; +return __arch_set_user_pkey_access (tsk, pkey, init_val); +}
arch/x86/mm/pkeys.c renamed from arch/x86/mm/pkeys.c~pkeys-110-syscalls-mprotect_pkey +1 -1
@@ -38,7 +38,7 @@ int __execute_only_pkey(struct mm_structreturn PKEY_DEDICATED_EXECUTE_ONLY ; }preempt_enable (); - ret =arch_set_user_pkey_access (current,PKEY_DEDICATED_EXECUTE_ONLY , + ret =__arch_set_user_pkey_access (current,PKEY_DEDICATED_EXECUTE_ONLY ,PKEY_DISABLE_ACCESS );/* * If the PKRU-set operation failed somehow, just return
mm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +23 -4
@@ -352,8 +352,11 @@ fail:return error; } -SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len, - unsigned long, prot) +/* +* pkey==-1 when doing a legacy mprotect() +*/ +static int do_mprotect_pkey (unsigned long start,size_t len, +unsigned long prot,int pkey) {unsigned long nstart, end, tmp, reqprot;struct vm_area_struct *vma, *prev;
@@ -409,7 +412,7 @@ SYSCALL_DEFINE3(mprotect, unsigned long,for (nstart = start ; ; ) {unsigned long newflags; -int pkey =arch_override_mprotect_pkey (vma, prot,-1 ); +int new_vma_pkey;/* Here we know that vma->vm_start <= nstart < vma->vm_end. */
@@ -417,7 +420,8 @@ SYSCALL_DEFINE3(mprotect, unsigned long,if (rier && (vma->vm_flags &VM_MAYEXEC )) prot |=PROT_EXEC ; - newflags =calc_vm_prot_bits (prot, pkey); + new_vma_pkey =arch_override_mprotect_pkey (vma, prot, pkey); + newflags =calc_vm_prot_bits (prot, new_vma_pkey); newflags |= (vma->vm_flags & ~(VM_READ |VM_WRITE |VM_EXEC ));/* newflags >> 4 shift VM_MAY% in place of VM_% */
@@ -454,3 +458,18 @@ out:up_write (¤t->mm->mmap_sem);return error; } + +SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len, + unsigned long, prot) +{ +return do_mprotect_pkey (start, len, prot,-1 ); +} + +SYSCALL_DEFINE4(pkey_mprotect, unsigned long, start, size_t, len, + unsigned long, prot, int, pkey) +{ +if (!validate_pkey (pkey)) +return -EINVAL ; + +return do_mprotect_pkey (start, len, prot, pkey); +}
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 2/9] mm: implement new pkey_mprotect() system call
Quoted 27 lines · Dave Hansen
diff -puN
arch/x86/include/asm/mmu_context.h~pkeys-110-syscalls-mprotect_pkeyarch/x86/include/asm/mmu_context.harch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-110-syscalls-mprotect_pkey +4
-5@@ -4,6 +4,7 @@#include <asm/desc.h> #include <linux/atomic.h> #include <linux/mm_types.h> +#include <linux/pkeys.h> #include <trace/events/tlb.h> @@ -195,16 +196,20 @@ static inline void arch_unmap(struct mm_mpx_notify_unmap (mm, vma, start, end); } +#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS static inline int vma_pkey (struct vm_area_struct *vma) { -u16 pkey =0 ; -#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS unsigned long vma_pkey_mask =VM_PKEY_BIT0 |VM_PKEY_BIT1 |VM_PKEY_BIT2 |VM_PKEY_BIT3 ; - pkey = (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ; -#endif -return pkey; + +return (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ;
arch/x86/include/asm/mmu_context.h static inline void arch_unmap(struct mm_ · line 215
Quoted 10 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-110-syscalls-mprotect_pkey +6
-0+} +#else +static inline int vma_pkey (struct vm_area_struct *vma) +{ +return 0 ; } +#endif static inline bool __pkru_allows_pkey (u16 pkey,bool write) {
Looks like MASK could have been statically defined and be a simple shift and mask known at compile time. Minor though.
Quoted 37 lines
diff -puN
arch/x86/include/asm/pkeys.h~pkeys-110-syscalls-mprotect_pkeyarch/x86/include/asm/pkeys.harch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-110-syscalls-mprotect_pkey +9
-2@@ -1,7 +1,12 @@#ifndef _ASM_X86_PKEYS_H#define _ASM_X86_PKEYS_H -#define arch_max_pkey () (boot_cpu_has(X86_FEATURE_OSPKE) ? 16 : 1) +#define PKEY_DEDICATED_EXECUTE_ONLY 15 +/* +* Consider the PKEY_DEDICATED_EXECUTE_ONLY key unavailable. +*/ +#define arch_max_pkey () (boot_cpu_has(X86_FEATURE_OSPKE) ? \ + PKEY_DEDICATED_EXECUTE_ONLY : 1)extern int arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val);@@ -10,7 +15,6 @@ extern int arch_set_user_pkey_access(str* Try to dedicate one of the protection keys to be used as an * execute-only protection key. */ -#define PKEY_DEDICATED_EXECUTE_ONLY 15extern int __execute_only_pkey (struct mm_struct *mm);static inline int execute_only_pkey (struct mm_struct *mm) {@@ -31,4 +35,7 @@ static inline int arch_override_mprotect return __arch_override_mprotect_pkey(vma, prot, pkey); } +extern int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val); +#endif /*_ASM_X86_PKEYS_H */ diff -puN
arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkeyarch/x86/kernel/fpu/xstate.c
arch/x86/kernel/fpu/xstate.c out: · line 894
Quoted 7 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +1
-1@@ -889,7 +889,7 @@ out:* not modfiy PKRU *itself* here, only the XSAVE state that will * be restored in to PKRU when we return back to userspace. */ -int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val) {
In the changelog, you state that the key is unsigned long yet here and in the documentation you linked, it's int. Minimally, it's surprising that the key is signed.
Quoted 8 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +3
-0struct xregs_state *xsave = &tsk->thread.fpu.state.xsave;@@ -948,3 +948,16 @@ int arch_set_user_pkey_access(struct tasreturn 0 ; } + +/* +* When setting a userspace-provided value, we need to ensure
arch/x86/kernel/fpu/xstate.c int arch_set_user_pkey_access(struct tas · line 963
Quoted 10 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +10
-0+* that it is valid. The __ version can get used by +* kernel-internal uses like the execute-only support. +*/ +int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val) +{ +if (!validate_pkey (pkey)) +return -EINVAL ; +return __arch_set_user_pkey_access (tsk, pkey, init_val); +}
There appears to be a subtle bug fixed for validate_key. It appears there wasn't protection of the dedicated key before but nothing could reach it.
The arch_max_pkey and PKEY_DEDICATE_EXECUTE_ONLY interaction is subtle but I can't find a problem with it either.
That aside, the validate_pkey check looks weak. It might be a number that works but no guarantee it's an allocated key or initialised properly. At this point, garbage can be handed into the system call potentially but maybe that gets fixed later.
Quoted 39 lines
diff -puN
arch/x86/mm/pkeys.c~pkeys-110-syscalls-mprotect_pkeyarch/x86/mm/pkeys.carch/x86/mm/pkeys.c renamed from arch/x86/mm/pkeys.c~pkeys-110-syscalls-mprotect_pkey +1
-1@@ -38,7 +38,7 @@ int __execute_only_pkey(struct mm_structreturn PKEY_DEDICATED_EXECUTE_ONLY ; }preempt_enable (); - ret =arch_set_user_pkey_access (current,PKEY_DEDICATED_EXECUTE_ONLY , + ret =__arch_set_user_pkey_access (current,PKEY_DEDICATED_EXECUTE_ONLY ,PKEY_DISABLE_ACCESS );/* * If the PKRU-set operation failed somehow, just return diff -puN
mm/mprotect.c~pkeys-110-syscalls-mprotect_pkeymm/mprotect.cmm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +6
-3@@ -352,8 +352,11 @@ fail:return error; } -SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len, - unsigned long, prot) +/* +* pkey==-1 when doing a legacy mprotect() +*/ +static int do_mprotect_pkey (unsigned long start,size_t len, +unsigned long prot,int pkey) {unsigned long nstart, end, tmp, reqprot;struct vm_area_struct *vma, *prev;@@ -409,7 +412,7 @@ SYSCALL_DEFINE3(mprotect, unsigned long,for (nstart = start ; ; ) {unsigned long newflags; -int pkey =arch_override_mprotect_pkey (vma, prot,-1 ); +int new_vma_pkey;/* Here we know that vma->vm_start <= nstart < vma->vm_end. */
mm/mprotect.c SYSCALL_DEFINE3(mprotect, unsigned long, · line 426
Quoted 8 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +2
-1@@ -417,7 +420,8 @@ SYSCALL_DEFINE3(mprotect, unsigned long,if (rier && (vma->vm_flags &VM_MAYEXEC )) prot |=PROT_EXEC ; - newflags =calc_vm_prot_bits (prot, pkey); + new_vma_pkey =arch_override_mprotect_pkey (vma, prot, pkey); + newflags =calc_vm_prot_bits (prot, new_vma_pkey); newflags |= (vma->vm_flags & ~(VM_READ |VM_WRITE |VM_EXEC ));
On CPUs that do not support the feature, arch_override_mprotect_pkey returns 0 and the normal protections are used. It's not clear how an application is meant to detect if the operation succeeded or not. What if the application relies on pkeys to be working?
Should pkey_mprotect return ENOSYS if the CPU does not support the requested feature or is that handled somewhere else?
Quoted 21 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +15
-0/* newflags >> 4 shift VM_MAY% in place of VM_% */ @@ -454,3 +458,18 @@ out:up_write (¤t->mm->mmap_sem);return error; } + +SYSCALL_DEFINE3(mprotect, unsigned long, start, size_t, len, + unsigned long, prot) +{ +return do_mprotect_pkey (start, len, prot,-1 ); +} + +SYSCALL_DEFINE4(pkey_mprotect, unsigned long, start, size_t, len, + unsigned long, prot, int, pkey) +{ +if (!validate_pkey (pkey)) +return -EINVAL ; + +return do_mprotect_pkey (start, len, prot, pkey); +}_
Signature · 8 lines
Mel Gorman SUSE Labs -- To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM, see: http://www.linux-mm.org/ . Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 2/9] mm: implement new pkey_mprotect() system call
Quoted 21 lines · Mel Gorman
Quoted 20 lines · Dave Hansen
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-110-syscalls-mprotect_pkey +9
-5+#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS static inline int vma_pkey (struct vm_area_struct *vma) { -u16 pkey =0 ; -#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS unsigned long vma_pkey_mask =VM_PKEY_BIT0 |VM_PKEY_BIT1 |VM_PKEY_BIT2 |VM_PKEY_BIT3 ; - pkey = (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ; -#endif -return pkey; + +return (vma->vm_flags & vma_pkey_mask) >>VM_PKEY_SHIFT ; +} +#else +static inline int vma_pkey (struct vm_area_struct *vma) +{ +return 0 ; } +#endif
Quoted 5 lines
Quoted 2 lines
static inline bool
__pkru_allows_pkey(u16 pkey, bool write){Looks like MASK could have been statically defined and be a simple shift and mask known at compile time. Minor though.
The VM_PKEY_BIT*'s are only ever defined as masks and not bit numbers. So, if you want to use a mask, you end up doing something like:
unsigned long mask = (NR_PKEYS-1) << ffz(~VM_PKEY_BIT0);
Which ends up with the same thing, but I think ends up being pretty on par for ugliness.
...
Quoted 8 lines
Quoted 8 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +8
-0+/* +* When setting a userspace-provided value, we need to ensure +* that it is valid. The __ version can get used by +* kernel-internal uses like the execute-only support. +*/ +int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val) +{
Quoted 8 lines
arch/x86/kernel/fpu/xstate.c int arch_set_user_pkey_access(struct tas · line 963
Quoted 4 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +4
-0+if (!validate_pkey (pkey)) +return -EINVAL ; +return __arch_set_user_pkey_access (tsk, pkey, init_val); +}There appears to be a subtle bug fixed for
validate_key. It appears there wasn't protection of the dedicated key before but nothing could reach it.
Right. There was no user interface that took a key and we trusted that the kernel knew what it was doing.
Quoted 7 lines
The
arch_max_pkeyandPKEY_DEDICATE_EXECUTE_ONLYinteraction is subtle but I can't find a problem with it either.That aside, the
validate_pkeycheck looks weak. It might be a number that works but no guarantee it's an allocated key or initialised properly. At this point, garbage can be handed into the system call potentially but maybe that gets fixed later.
It's called in three paths:
1. by the kernel when setting up execute-only support
2. by pkey_alloc() on the pkey we just allocated
3. by pkey_set() on a pkey we just checked was allocated
So, it isn't broken, but it's also not clear at all why it is safe and what validate_pkey() is actually validating.
But, that said, this does make me realize that with pkey_alloc()/pkey_free(), this is probably redundant. We verify that the key is allocated, and we only allow valid keys to be allocated.
IOW, I think I can remove validate_pkey(), but only if we keep pkey_alloc().
...
Quoted 10 lines
mm/mprotect.c SYSCALL_DEFINE3(mprotect, unsigned long, · line 425
Quoted 5 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +2
-1- newflags =calc_vm_prot_bits (prot, pkey); + new_vma_pkey =arch_override_mprotect_pkey (vma, prot, pkey); + newflags =calc_vm_prot_bits (prot, new_vma_pkey); newflags |= (vma->vm_flags & ~(VM_READ |VM_WRITE |VM_EXEC ));On CPUs that do not support the feature,
arch_override_mprotect_pkeyreturns 0 and the normal protections are used. It's not clear how an application is meant to detect if the operation succeeded or not. What if the application relies on pkeys to be working?
It actually shows up as -ENOSPC from pkey_alloc(). This sounds goofy, but it teaches programs something very important: they always have to look for ENOSPC, and must always be prepared to function without protection keys. A library might have stolen all the keys, or an LD_PRELOAD, so an app can never be sure what is available.
If we teach them to check for ENOSPC from day one, they'll never be surprised.
I've tried to spell this out a bit more clearly in the manpages. I'll also add it to the changelog.
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 2/9] mm: implement new pkey_mprotect() system call
Quoted 11 lines · Dave Hansen
Quoted 2 lines
Looks like MASK could have been statically defined and be a simple shift and mask known at compile time. Minor though.
The VM_PKEY_BIT*'s are only ever defined as masks and not bit numbers. So, if you want to use a mask, you end up doing something like:
unsigned long mask = (NR_PKEYS-1) << ffz(~VM_PKEY_BIT0);Which ends up with the same thing, but I think ends up being pretty on par for ugliness.
Fair enough.
Quoted 17 lines
Quoted 8 lines
Quoted 8 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +8
-0+/* +* When setting a userspace-provided value, we need to ensure +* that it is valid. The __ version can get used by +* kernel-internal uses like the execute-only support. +*/ +int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val) +{Quoted 8 lines
arch/x86/kernel/fpu/xstate.c int arch_set_user_pkey_access(struct tas · line 963
Quoted 4 lines
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-110-syscalls-mprotect_pkey +4
-0+if (!validate_pkey (pkey)) +return -EINVAL ; +return __arch_set_user_pkey_access (tsk, pkey, init_val); +}There appears to be a subtle bug fixed for
validate_key. It appears there wasn't protection of the dedicated key before but nothing could reach it.
Quoted 3 lines
Right. There was no user interface that took a key and we trusted that the kernel knew what it was doing.
Ok. I was fairly sure that was the thinking behind it but wanted to be suire.
Quoted 13 lines
Quoted 7 lines
The
arch_max_pkeyandPKEY_DEDICATE_EXECUTE_ONLYinteraction is subtle but I can't find a problem with it either.That aside, the
validate_pkeycheck looks weak. It might be a number that works but no guarantee it's an allocated key or initialised properly. At this point, garbage can be handed into the system call potentially but maybe that gets fixed later.It's called in three paths:
1. by the kernel when setting up execute-only support
2. bypkey_alloc()on the pkey we just allocated
3. bypkey_set()on a pkey we just checked was allocated
Quoted 9 lines
So, it isn't broken, but it's also not clear at all why it is safe and what
validate_pkey()is actually validating.But, that said, this does make me realize that with pkey_alloc()/pkey_free(), this is probably redundant. We verify that the key is allocated, and we only allow valid keys to be allocated.
IOW, I think I can remove
validate_pkey(), but only if we keeppkey_alloc().
Ok, it's not a major problem. I simply worried that the protection of key slots is pretty weak as it can be interfered with from userspace. On the other hand, the kernel never interprets the information so it's unlikely to cause a security problem. Applications can still shoot themselves in the foot but hopefully the developers are aware that the protection they get with keys is not absolute.
Quoted 12 lines
...
Quoted 10 lines
mm/mprotect.c SYSCALL_DEFINE3(mprotect, unsigned long, · line 425
Quoted 5 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-110-syscalls-mprotect_pkey +2
-1- newflags =calc_vm_prot_bits (prot, pkey); + new_vma_pkey =arch_override_mprotect_pkey (vma, prot, pkey); + newflags =calc_vm_prot_bits (prot, new_vma_pkey); newflags |= (vma->vm_flags & ~(VM_READ |VM_WRITE |VM_EXEC ));On CPUs that do not support the feature,
arch_override_mprotect_pkeyreturns 0 and the normal protections are used. It's not clear how an application is meant to detect if the operation succeeded or not. What if the application relies on pkeys to be working?
Quoted 4 lines
It actually shows up as
-ENOSPCfrompkey_alloc(). This sounds goofy, but it teaches programs something very important: they always have to look for ENOSPC, and must always be prepared to function without protection keys.
Ok, that makes sense. I don't think it's goofy. Sure, they cannot detect the CPU support directly from the interface but it's close enough.
Signature · 8 lines
Mel Gorman SUSE Labs -- To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM, see: http://www.linux-mm.org/ . Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 3/9 x86, pkeys: make mprotect_key() mask off additional vm_flags
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
Today, mprotect() takes 4 bits of data: PROT_READ/WRITE/EXEC/NONE. Three of those bits: READ/WRITE/EXEC get translated directly in to vma->vm_flags by calc_vm_prot_bits(). If a bit is unset in mprotect()'s 'prot' argument then it must be cleared in vma->vm_flags during the mprotect() call.
We do this clearing today by first calculating the VMA flags we want set, then clearing the ones we do not want to inherit from the original VMA:
vm_flags = calc_vm_prot_bits(prot, key); ... newflags = vm_flags; newflags |= (vma->vm_flags & ~(VM_READ | VM_WRITE | VM_EXEC));
However, we *also* want to mask off the original VMA's vm_flags in which we store the protection key.
To do that, this patch adds a new macro:
ARCH_VM_PKEY_FLAGS
which allows the architecture to specify additional bits that it would like cleared. We use that to ensure that the VM_PKEY_BIT* bits get cleared.
---
b/arch/x86/include/asm/pkeys.h | 2 ++ b/include/linux/pkeys.h | 1 + b/mm/mprotect.c | 11 ++++++++++- 3 files changed, 13 insertions(+), 1 deletion(-)
arch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-112-mask-off-correct-vm_flags +2 -0
@@ -38,4 +38,6 @@ static inline int arch_override_mprotectextern int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val); +#define ARCH_VM_PKEY_FLAGS (VM_PKEY_BIT0 | VM_PKEY_BIT1 | VM_PKEY_BIT2 | VM_PKEY_BIT3) +#endif /*_ASM_X86_PKEYS_H */
include/linux/pkeys.h renamed from include/linux/pkeys.h~pkeys-112-mask-off-correct-vm_flags +1 -0
@@ -16,6 +16,7 @@#define execute_only_pkey (mm) (0)#define arch_override_mprotect_pkey (vma, prot, pkey) (0)#define PKEY_DEDICATED_EXECUTE_ONLY 0 +#define ARCH_VM_PKEY_FLAGS 0#endif /* ! CONFIG_ARCH_HAS_PKEYS */ /*
mm/mprotect.c renamed from mm/mprotect.c~pkeys-112-mask-off-correct-vm_flags +10 -1
@@ -411,6 +411,7 @@ static int do_mprotect_pkey(unsigned lon prev = vma;for (nstart = start ; ; ) { +unsigned long mask_off_old_flags;unsigned long newflags;int new_vma_pkey;
@@ -420,9 +421,17 @@ static int do_mprotect_pkey(unsigned lonif (rier && (vma->vm_flags &VM_MAYEXEC )) prot |=PROT_EXEC ; +/* +* Each mprotect() call explicitly passes r/w/x permissions. +* If a permission is not passed to mprotect(), it must be +* cleared from the VMA. +*/ + mask_off_old_flags =VM_READ |VM_WRITE |VM_EXEC | +ARCH_VM_PKEY_FLAGS ; + new_vma_pkey =arch_override_mprotect_pkey (vma, prot, pkey); newflags =calc_vm_prot_bits (prot, new_vma_pkey); - newflags |= (vma->vm_flags & ~(VM_READ |VM_WRITE |VM_EXEC )); + newflags |= (vma->vm_flags & ~mask_off_old_flags);/* newflags >> 4 shift VM_MAY% in place of VM_% */ if ((newflags & ~(newflags >>4 )) & (VM_READ |VM_WRITE |VM_EXEC )) {
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 4/9 x86: wire up mprotect_key() system call
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
This is all that we need to get the new system call itself working on x86.
---
b/arch/x86/entry/syscalls/syscall_32.tbl | 1 + b/arch/x86/entry/syscalls/syscall_64.tbl | 1 + 2 files changed, 2 insertions(+)
arch/x86/entry/syscalls/syscall_32.tbl renamed from arch/x86/entry/syscalls/syscall_32.tbl~pkeys-114-x86-mprotect_key +1 -0
@@ -386,3 +386,4 @@ 377 i386 copy_file_range sys_copy_file_range 378 i386 preadv2 sys_preadv2 compat_sys_preadv2 379 i386 pwritev2 sys_pwritev2 compat_sys_pwritev2 +380 i386 pkey_mprotect sys_pkey_mprotect
arch/x86/entry/syscalls/syscall_64.tbl renamed from arch/x86/entry/syscalls/syscall_64.tbl~pkeys-114-x86-mprotect_key +1 -0
@@ -335,6 +335,7 @@ 326 common copy_file_range sys_copy_file_range 327 64 preadv2 sys_preadv2 328 64 pwritev2 sys_pwritev2 +329 common pkey_mprotect sys_pkey_mprotect # # x32-specific system call numbers start at 512 to avoid cache impact
_
PATCH v4 5/9 x86, pkeys: allocation/free syscalls
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
This patch adds two new system calls:
int pkey_alloc(unsigned long flags, unsigned long init_access_rights) int pkey_free(int pkey);
These implement an "allocator" for the protection keys themselves, which can be thought of as analogous to the allocator that the kernel has for file descriptors. The kernel tracks which numbers are in use, and only allows operations on keys that are valid. A key which was not obtained by pkey_alloc() may not, for instance, be passed to pkey_mprotect() (or the forthcoming get/set syscalls).
These system calls are also very important given the kernel's use of pkeys to implement execute-only support. These help ensure that userspace can never assume that it has control of a key unless it first asks the kernel.
The 'init_access_rights' argument to pkey_alloc() specifies the rights that will be established for the returned pkey. For instance:
pkey = pkey_alloc(flags, PKEY_DENY_WRITE);
will allocate 'pkey', but also sets the bits in PKRU[1] such that writing to 'pkey' is already denied. This keeps userspace from needing to have knowledge about manipulating PKRU with the RDPKRU/WRPKRU instructions. Userspace is still free to use these instructions as it wishes, but this facility ensures it is no longer required.
The kernel does _not_ enforce that this interface must be used for changes to PKRU, even for keys it does not control.
The kernel does not prevent pkey_free() from successfully freeing in-use pkeys (those still assigned to a memory range by pkey_mprotect()). It would be expensive to implement the checks for this, so we instead say, "Just don't do it" since sane software will never do it anyway.
This allocation mechanism could be implemented in userspace. Even if we did it in userspace, we would still need additional user/kernel interfaces to tell userspace which keys are being used by the kernel internally (such as for execute-only mappings). Having the kernel provide this facility completely removes the need for these additional interfaces, or having an implementation of this in userspace at all.
Note that we have to make changes to all of the architectures that do not use mman-common.h because we use the new PKEY_DENY_ACCESS/WRITE macros in arch-independent code.
1. PKRU is the Protection Key Rights User register. It is a usermode-accessible register that controls whether writes and/or access to each individual pkey is allowed or denied.
---
b/arch/alpha/include/uapi/asm/mman.h | 5 + b/arch/mips/include/uapi/asm/mman.h | 5 + b/arch/parisc/include/uapi/asm/mman.h | 5 + b/arch/x86/entry/syscalls/syscall_32.tbl | 2 b/arch/x86/entry/syscalls/syscall_64.tbl | 2 b/arch/x86/include/asm/mmu.h | 8 +++ b/arch/x86/include/asm/mmu_context.h | 10 +++ b/arch/x86/include/asm/pkeys.h | 79 ++++++++++++++++++++++++++++--- b/arch/x86/kernel/fpu/xstate.c | 3 + b/arch/x86/mm/pkeys.c | 38 +++++++++++--- b/arch/xtensa/include/uapi/asm/mman.h | 5 + b/include/linux/pkeys.h | 30 +++++++++-- b/include/uapi/asm-generic/mman-common.h | 5 + b/mm/mprotect.c | 55 +++++++++++++++++++++ 14 files changed, 231 insertions(+), 21 deletions(-)
arch/alpha/include/uapi/asm/mman.h renamed from arch/alpha/include/uapi/asm/mman.h~pkeys-116-syscalls-allocation +5 -0
@@ -78,4 +78,9 @@#define MAP_HUGE_SHIFT 26#define MAP_HUGE_MASK 0x3f +#define PKEY_DISABLE_ACCESS 0x1 +#define PKEY_DISABLE_WRITE 0x2 +#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ + PKEY_DISABLE_WRITE) +#endif /* __ALPHA_MMAN_H__ */
arch/mips/include/uapi/asm/mman.h renamed from arch/mips/include/uapi/asm/mman.h~pkeys-116-syscalls-allocation +5 -0
@@ -105,4 +105,9 @@#define MAP_HUGE_SHIFT 26#define MAP_HUGE_MASK 0x3f +#define PKEY_DISABLE_ACCESS 0x1 +#define PKEY_DISABLE_WRITE 0x2 +#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ + PKEY_DISABLE_WRITE) +#endif /* _ASM_MMAN_H */
arch/parisc/include/uapi/asm/mman.h renamed from arch/parisc/include/uapi/asm/mman.h~pkeys-116-syscalls-allocation +5 -0
@@ -75,4 +75,9 @@#define MAP_HUGE_SHIFT 26#define MAP_HUGE_MASK 0x3f +#define PKEY_DISABLE_ACCESS 0x1 +#define PKEY_DISABLE_WRITE 0x2 +#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ + PKEY_DISABLE_WRITE) +#endif /* __PARISC_MMAN_H__ */
arch/x86/entry/syscalls/syscall_32.tbl renamed from arch/x86/entry/syscalls/syscall_32.tbl~pkeys-116-syscalls-allocation +2 -0
@@ -387,3 +387,5 @@ 378 i386 preadv2 sys_preadv2 compat_sys_preadv2 379 i386 pwritev2 sys_pwritev2 compat_sys_pwritev2 380 i386 pkey_mprotect sys_pkey_mprotect +381 i386 pkey_alloc sys_pkey_alloc +382 i386 pkey_free sys_pkey_free
arch/x86/entry/syscalls/syscall_64.tbl renamed from arch/x86/entry/syscalls/syscall_64.tbl~pkeys-116-syscalls-allocation +2 -0
@@ -336,6 +336,8 @@ 327 64 preadv2 sys_preadv2 328 64 pwritev2 sys_pwritev2 329 common pkey_mprotect sys_pkey_mprotect +330 common pkey_alloc sys_pkey_alloc +331 common pkey_free sys_pkey_free # # x32-specific system call numbers start at 512 to avoid cache impact
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +9 -1
@@ -108,7 +108,16 @@ static inline void enter_lazy_tlb(structstatic inline int init_new_context (struct task_struct *tsk,struct mm_struct *mm) { +#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS +if (cpu_feature_enabled (X86_FEATURE_OSPKE )) { +/* pkey 0 is the default and always allocated */ + mm->context.pkey_allocation_map =0x1 ; +/* -1 means unallocated or invalid */ + mm->context.execute_only_pkey =-1 ; + } +#endif init_new_context_ldt (tsk, mm); +return 0 ; }static inline void destroy_context (struct mm_struct *mm)
@@ -263,5 +272,4 @@ static inline bool arch_pte_access_permi {return __pkru_allows_pkey (pte_flags_pkey (pte_flags (pte)), write); } -#endif /* _ASM_X86_MMU_CONTEXT_H */
arch/x86/include/asm/mmu.h renamed from arch/x86/include/asm/mmu.h~pkeys-116-syscalls-allocation +8 -0
@@ -23,6 +23,14 @@ typedef struct {const struct vdso_image *vdso_image;/* vdso image in use */ atomic_t perf_rdpmc_allowed;/* nonzero if rdpmc is allowed */ +#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS +/* +* One bit per protection key says whether userspace can +* use it or not. protected by mmap_sem. +*/ +u16 pkey_allocation_map; +s16 execute_only_pkey; +#endif } mm_context_t;#ifdef CONFIG_SMP
arch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-116-syscalls-allocation +73 -6
89 lines not on this page · raw message
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-116-syscalls-allocation +3 -0
@@ -5,6 +5,7 @@*/ #include <linux/compat.h> #include <linux/cpu.h> +#include <linux/mman.h> #include <linux/pkeys.h> #include <asm/fpu/api.h>
@@ -796,6 +797,7 @@ const void *get_xsave_field_ptr(int xsavreturn get_xsave_addr (&fpu->state.xsave, xsave_state); } +#ifdef CONFIG_ARCH_HAS_PKEYS /* * Set xfeatures (aka XSTATE_BV) bit for a feature that we want
@@ -961,3 +963,4 @@ int arch_set_user_pkey_access(struct tasreturn -EINVAL ; return __arch_set_user_pkey_access(tsk, pkey, init_val); } +#endif /* CONFIG_ARCH_HAS_PKEYS */
arch/x86/mm/pkeys.c renamed from arch/x86/mm/pkeys.c~pkeys-116-syscalls-allocation +30 -8
@@ -21,8 +21,19 @@int __execute_only_pkey (struct mm_struct *mm) { +bool need_to_set_mm_pkey = false; +int execute_only_pkey = mm->context.execute_only_pkey;int ret; +/* Do we need to assign a pkey for mm's execute-only maps? */ +if (execute_only_pkey ==-1 ) { +/* Go allocate one to use, which might fail */ + execute_only_pkey =mm_pkey_alloc (mm); +if (!validate_pkey (execute_only_pkey)) +return -1 ; + need_to_set_mm_pkey = true; + } +/* * We do not want to go through the relatively costly * dance to set PKRU if we do not need to. Check it
@@ -32,22 +43,33 @@ int __execute_only_pkey(struct mm_struct* can make fpregs inactive. */ preempt_disable (); -if (fpregs_active () && - !__pkru_allows_read (read_pkru (),PKEY_DEDICATED_EXECUTE_ONLY )) { +if (!need_to_set_mm_pkey && +fpregs_active () && + !__pkru_allows_read (read_pkru (), execute_only_pkey)) {preempt_enable (); -return PKEY_DEDICATED_EXECUTE_ONLY ; +return execute_only_pkey; }preempt_enable (); - ret =__arch_set_user_pkey_access (current,PKEY_DEDICATED_EXECUTE_ONLY , + +/* +* Set up PKRU so that it denies access for everything +* other than execution. +*/ + ret =__arch_set_user_pkey_access (current, execute_only_pkey,PKEY_DISABLE_ACCESS );/* * If the PKRU-set operation failed somehow, just return * 0 and effectively disable execute-only support. */ -if (ret) -return 0 ; +if (ret) { +mm_set_pkey_free (mm, execute_only_pkey); +return -1 ; + } -return PKEY_DEDICATED_EXECUTE_ONLY ; +/* We got one, store it and use it from here on out */ +if (need_to_set_mm_pkey) + mm->context.execute_only_pkey = execute_only_pkey; +return execute_only_pkey; }static inline bool vma_is_pkey_exec_only (struct vm_area_struct *vma)
@@ -55,7 +77,7 @@ static inline bool vma_is_pkey_exec_only/* Do this check first since the vm_flags should be hot */ if ((vma->vm_flags & (VM_READ |VM_WRITE |VM_EXEC )) !=VM_EXEC )return false; -if (vma_pkey (vma) !=PKEY_DEDICATED_EXECUTE_ONLY ) +if (vma_pkey (vma) != vma->vm_mm->context.execute_only_pkey)return false;return true;
arch/xtensa/include/uapi/asm/mman.h renamed from arch/xtensa/include/uapi/asm/mman.h~pkeys-116-syscalls-allocation +5 -0
@@ -117,4 +117,9 @@#define MAP_HUGE_SHIFT 26#define MAP_HUGE_MASK 0x3f +#define PKEY_DISABLE_ACCESS 0x1 +#define PKEY_DISABLE_WRITE 0x2 +#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ + PKEY_DISABLE_WRITE) +#endif /* _XTENSA_MMAN_H */
include/linux/pkeys.h renamed from include/linux/pkeys.h~pkeys-116-syscalls-allocation +24 -6
@@ -4,11 +4,6 @@#include <linux/mm_types.h> #include <asm/mmu_context.h> -#define PKEY_DISABLE_ACCESS 0x1 -#define PKEY_DISABLE_WRITE 0x2 -#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ - PKEY_DISABLE_WRITE) -#ifdef CONFIG_ARCH_HAS_PKEYS #include <asm/pkeys.h> #else /* ! CONFIG_ARCH_HAS_PKEYS */
@@ -17,7 +12,6 @@#define arch_override_mprotect_pkey (vma, prot, pkey) (0)#define PKEY_DEDICATED_EXECUTE_ONLY 0#define ARCH_VM_PKEY_FLAGS 0 -#endif /* ! CONFIG_ARCH_HAS_PKEYS */ /* * This is called from mprotect_pkey().
@@ -31,4 +25,28 @@ static inline bool validate_pkey(int pkereturn (pkey <arch_max_pkey ()); } +static inline bool mm_pkey_is_allocated (struct mm_struct *mm,int pkey) +{ +return (pkey ==0 ); +} + +static inline int mm_pkey_alloc (struct mm_struct *mm) +{ +return -1 ; +} + +static inline int mm_pkey_free (struct mm_struct *mm,int pkey) +{ +WARN_ONCE (1 ,"free of protection key when disabled" ); +return -EINVAL ; +} + +static inline int arch_set_user_pkey_access (struct task_struct *tsk,int pkey, +unsigned long init_val) +{ +return 0 ; +} + +#endif /* ! CONFIG_ARCH_HAS_PKEYS */ +#endif /* _LINUX_PKEYS_H */
include/uapi/asm-generic/mman-common.h renamed from include/uapi/asm-generic/mman-common.h~pkeys-116-syscalls-allocation +5 -0
@@ -72,4 +72,9 @@#define MAP_HUGE_SHIFT 26#define MAP_HUGE_MASK 0x3f +#define PKEY_DISABLE_ACCESS 0x1 +#define PKEY_DISABLE_WRITE 0x2 +#define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ + PKEY_DISABLE_WRITE) +#endif /* __ASM_GENERIC_MMAN_COMMON_H */
mm/mprotect.c renamed from mm/mprotect.c~pkeys-116-syscalls-allocation +55 -0
75 lines not on this page · raw message
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 5/9] x86, pkeys: allocation/free syscalls
Quoted 8 lines · Dave Hansen
From: Dave Hansen <[email protected]>
This patch adds two new system calls:
int pkey_alloc(unsigned long flags, unsigned long init_access_rights) int pkey_free(int pkey);
Quoted 8 lines
These implement an "allocator" for the protection keys themselves, which can be thought of as analogous to the allocator that the kernel has for file descriptors. The kernel tracks which numbers are in use, and only allows operations on keys that are valid. A key which was not obtained by
pkey_alloc()may not, for instance, be passed topkey_mprotect()(or the forthcoming get/set syscalls).
Ok, so the last patch wired up the system call before the kernel was tracking which numbers were in use. It doesn't really matter as such but the patches should be swapped around and only expose the systemcall when it's actually safe.
Quoted 18 lines
These system calls are also very important given the kernel's use of pkeys to implement execute-only support. These help ensure that userspace can never assume that it has control of a key unless it first asks the kernel.
The '
init_access_rights' argument topkey_alloc()specifies the rights that will be established for the returned pkey. For instance:pkey = pkey_alloc(flags, PKEY_DENY_WRITE);will allocate 'pkey', but also sets the bits in PKRU[1] such that writing to 'pkey' is already denied. This keeps userspace from needing to have knowledge about manipulating PKRU with the RDPKRU/WRPKRU instructions. Userspace is still free to use these instructions as it wishes, but this facility ensures it is no longer required.
Quoted 9 lines
The kernel does _not_ enforce that this interface must be used for changes to PKRU, even for keys it does not control.
The kernel does not prevent
pkey_free()from successfully freeing in-use pkeys (those still assigned to a memory range bypkey_mprotect()). It would be expensive to implement the checks for this, so we instead say, "Just don't do it" since sane software will never do it anyway.
Unfortunately, it could manifest as either corruption due to an area expected to be protected being accessible or an unexpected SEGV.
I accept the expensive arguement but it opens a new class of problems that userspace debuggers will need to evaluate.
Quoted 10 lines
diff -puN
arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocationarch/x86/include/asm/mmu_context.harch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +3
-0@@ -108,7 +108,16 @@ static inline void enter_lazy_tlb(structstatic inline int init_new_context (struct task_struct *tsk,struct mm_struct *mm) { +#ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS +if (cpu_feature_enabled (X86_FEATURE_OSPKE )) { +/* pkey 0 is the default and always allocated */
arch/x86/include/asm/mmu_context.h static inline void enter_lazy_tlb(struct · line 123
Quoted 10 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +6
-0+ mm->context.pkey_allocation_map =0x1 ; +/* -1 means unallocated or invalid */ + mm->context.execute_only_pkey = -1; + } +#endif init_new_context_ldt (tsk, mm); +return 0 ; }static inline void destroy_context (struct mm_struct *mm)
I prevents userspace modifying the default key from userspace with WRPKRU or an unallocated key for that matter. However, I also cannot find a case where it really matters. An application screwing it up may ask mprotect to do something very unexpected but that's about it.
arch/x86/include/asm/mmu_context.h
Quoted 9 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +9
-0+static inline +bool mm_pkey_is_allocated (struct mm_struct *mm,unsigned long pkey) +{ +if (!validate_pkey (pkey)) +return true; + +return mm_pkey_allocation_map (mm) & (1 << pkey); +} +
We flip-flop between whether pkey is signed or unsigned.
Quoted 19 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +19
-0+SYSCALL_DEFINE2(pkey_alloc, unsigned long, flags, unsigned long, init_val) +{ +int pkey; +int ret; + +/* No flags supported yet. */ +if (flags) +return -EINVAL ; +/* check for unsupported init values */ +if (init_val & ~PKEY_ACCESS_MASK ) +return -EINVAL ; + +down_write (¤t->mm->mmap_sem); + pkey =mm_pkey_alloc (current->mm); + + ret = -ENOSPC ; +if (pkey ==-1 ) + goto out; +
arch/x86/include/asm/mmu_context.h
Quoted 10 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +10
-0+ ret =arch_set_user_pkey_access (current, pkey, init_val); +if (ret) { +mm_pkey_free (current->mm, pkey); + goto out; + } + ret = pkey; +out: +up_write (¤t->mm->mmap_sem); +return ret; +}
It's not wrong as such but mmap_sem taken for write seems *extremely* heavy to protect the allocation mask. If userspace is racing a key allocation with mprotect, it's already game over in terms of random behaviour.
I've no idea what the frequency of pkey alloc/free is expected to be. If it's really low then maybe it doesn't matter but if it's high this is going to be a bottleneck later.
Quoted 16 lines
arch/x86/include/asm/mmu_context.h renamed from arch/x86/include/asm/mmu_context.h~pkeys-116-syscalls-allocation +15
-0+ +SYSCALL_DEFINE1(pkey_free, int, pkey) +{ +int ret; + +down_write (¤t->mm->mmap_sem); + ret =mm_pkey_free (current->mm, pkey); +up_write (¤t->mm->mmap_sem); + +/* +* We could provie warnings or errors if any VMA still +* has the pkey set here. +*/ +return ret; +}_
Signature · 8 lines
Mel Gorman SUSE Labs -- To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM, see: http://www.linux-mm.org/ . Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 5/9] x86, pkeys: allocation/free syscalls
Quoted 4 lines · Mel Gorman
Ok, so the last patch wired up the system call before the kernel was tracking which numbers were in use. It doesn't really matter as such but the patches should be swapped around and only expose the systemcall when it's actually safe.
I can do that.
Quoted 27 lines
Quoted 18 lines
These system calls are also very important given the kernel's use of pkeys to implement execute-only support. These help ensure that userspace can never assume that it has control of a key unless it first asks the kernel.
The '
init_access_rights' argument topkey_alloc()specifies the rights that will be established for the returned pkey. For instance:pkey = pkey_alloc(flags, PKEY_DENY_WRITE);will allocate 'pkey', but also sets the bits in PKRU[1] such that writing to 'pkey' is already denied. This keeps userspace from needing to have knowledge about manipulating PKRU with the RDPKRU/WRPKRU instructions. Userspace is still free to use these instructions as it wishes, but this facility ensures it is no longer required.
Quoted 8 lines
The kernel does _not_ enforce that this interface must be used for changes to PKRU, even for keys it does not control.
The kernel does not prevent
pkey_free()from successfully freeing in-use pkeys (those still assigned to a memory range bypkey_mprotect()). It would be expensive to implement the checks for this, so we instead say, "Just don't do it" since sane software will never do it anyway.
Quoted 5 lines
Unfortunately, it could manifest as either corruption due to an area expected to be protected being accessible or an unexpected SEGV.
I accept the expensive arguement but it opens a new class of problems that userspace debuggers will need to evaluate.
Yeah. I guess it would be good to have a debugging mechanism here at least.
Quoted 11 lines
arch/x86/include/asm/pkeys.h extern int __arch_set_user_pkey_access(s · line 66
Quoted 9 lines
arch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-116-syscalls-allocation +9
-0+static inline +bool mm_pkey_is_allocated (struct mm_struct *mm,unsigned long pkey) +{ +if (!validate_pkey (pkey)) +return true; + +return mm_pkey_allocation_map (mm) & (1 << pkey); +} +We flip-flop between whether pkey is signed or unsigned.
Yeah, I can add some consistency here, for sure.
Quoted 35 lines
Quoted 19 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-116-syscalls-allocation +19
-0+SYSCALL_DEFINE2(pkey_alloc, unsigned long, flags, unsigned long, init_val) +{ +int pkey; +int ret; + +/* No flags supported yet. */ +if (flags) +return -EINVAL ; +/* check for unsupported init values */ +if (init_val & ~PKEY_ACCESS_MASK ) +return -EINVAL ; + +down_write (¤t->mm->mmap_sem); + pkey =mm_pkey_alloc (current->mm); + + ret = -ENOSPC ; +if (pkey ==-1 ) + goto out; +mm/mprotect.c SYSCALL_DEFINE4(pkey_mprotect, unsigned · line 524
Quoted 10 lines
mm/mprotect.c renamed from mm/mprotect.c~pkeys-116-syscalls-allocation +10
-0+ ret =arch_set_user_pkey_access (current, pkey, init_val); +if (ret) { +mm_pkey_free (current->mm, pkey); + goto out; + } + ret = pkey; +out: +up_write (¤t->mm->mmap_sem); +return ret; +}It's not wrong as such but
mmap_semtaken for write seems *extremely* heavy to protect the allocation mask. If userspace is racing a key allocation with mprotect, it's already game over in terms of random behaviour.
Quoted 3 lines
I've no idea what the frequency of pkey alloc/free is expected to be. If it's really low then maybe it doesn't matter but if it's high this is going to be a bottleneck later.
I think pkey_alloc() is fundamentally less frequent than mprotect(). If you're doing a pkey_alloc() it's because you want to set it on at least one memory area, which means at least one mprotect(). So, at _worst_, it's 1:1. If you've got more than one thing you're protecting, you'll have many mprotect()s for each pkey_alloc().
The real reason I did this, though, was to avoid having _some_ other lock. It'll cost more storage space, have more locking rules and I need exclusion against pkey_mprotect() which already holds mmap_sem for write. IOW, I think this was the simplest thing to do.
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 6/9 x86, pkeys: add pkey set/get syscalls
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
This establishes two more system calls for protection key management:
unsigned long pkey_get(int pkey); int pkey_set(int pkey, unsigned long access_rights);
The return value from pkey_get() and the 'access_rights' passed to pkey_set() are the same format: a bitmask containing PKEY_DENY_WRITE and/or PKEY_DENY_ACCESS, or nothing set at all.
These can replace userspace's direct use of the new rdpkru/wrpkru instructions.
With current hardware, the kernel can not enforce that it has control over a given key. But, this at least allows the kernel to indicate to userspace that userspace does not control a given protection key. This makes it more likely that situations like using a pkey after sys_pkey_free() can be detected.
The kernel does _not_ enforce that this interface must be used for changes to PKRU, whether or not a key has been "allocated".
This syscall interface could also theoretically be replaced with a pair of vsyscalls. The vsyscalls would just call WRPKRU/RDPKRU directly in situations where they are drop-in equivalents for what the kernel would be doing.
---
b/arch/x86/entry/syscalls/syscall_32.tbl | 2 + b/arch/x86/entry/syscalls/syscall_64.tbl | 2 + b/arch/x86/include/asm/pkeys.h | 4 +- b/arch/x86/kernel/fpu/xstate.c | 55 +++++++++++++++++++++++++++++-- b/include/linux/pkeys.h | 8 ++++ b/mm/mprotect.c | 41 +++++++++++++++++++++++ 6 files changed, 109 insertions(+), 3 deletions(-)
arch/x86/entry/syscalls/syscall_32.tbl renamed from arch/x86/entry/syscalls/syscall_32.tbl~pkeys-118-syscalls-set-get +2 -0
@@ -389,3 +389,5 @@ 380 i386 pkey_mprotect sys_pkey_mprotect 381 i386 pkey_alloc sys_pkey_alloc 382 i386 pkey_free sys_pkey_free +383 i386 pkey_get sys_pkey_get +384 i386 pkey_set sys_pkey_set
arch/x86/entry/syscalls/syscall_64.tbl renamed from arch/x86/entry/syscalls/syscall_64.tbl~pkeys-118-syscalls-set-get +2 -0
@@ -338,6 +338,8 @@ 329 common pkey_mprotect sys_pkey_mprotect 330 common pkey_alloc sys_pkey_alloc 331 common pkey_free sys_pkey_free +332 common pkey_get sys_pkey_get +333 common pkey_set sys_pkey_set # # x32-specific system call numbers start at 512 to avoid cache impact
arch/x86/include/asm/pkeys.h renamed from arch/x86/include/asm/pkeys.h~pkeys-118-syscalls-set-get +3 -1
@@ -56,7 +56,7 @@ static inline bool validate_pkey(int pke }static inline -bool mm_pkey_is_allocated (struct mm_struct *mm,unsigned long pkey) +bool mm_pkey_is_allocated (struct mm_struct *mm,int pkey) {if (!validate_pkey (pkey))return true;
@@ -107,4 +107,6 @@ extern int arch_set_user_pkey_access(strextern int __arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val); +extern unsigned long arch_get_user_pkey_access (struct task_struct *tsk, +int pkey);#endif /*_ASM_X86_PKEYS_H */
arch/x86/kernel/fpu/xstate.c renamed from arch/x86/kernel/fpu/xstate.c~pkeys-118-syscalls-set-get +53 -2
83 lines not on this page · raw message
include/linux/pkeys.h renamed from include/linux/pkeys.h~pkeys-118-syscalls-set-get +8 -0
@@ -44,6 +44,14 @@ static inline int mm_pkey_free(struct mmstatic inline int arch_set_user_pkey_access (struct task_struct *tsk,int pkey,unsigned long init_val) { +return -EINVAL ; +} + +static inline +unsigned long arch_get_user_pkey_access (struct task_struct *tsk,int pkey) +{ +if (pkey) +return -1 ;return 0 ; }
mm/mprotect.c renamed from mm/mprotect.c~pkeys-118-syscalls-set-get +41 -0
44 lines not on this page · raw message
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 21 lines · Dave Hansen
From: Dave Hansen <[email protected]>
This establishes two more system calls for protection key management:
unsigned long pkey_get(int pkey); int pkey_set(int pkey, unsigned long access_rights);The return value from
pkey_get()and the 'access_rights' passed topkey_set()are the same format: a bitmask containingPKEY_DENY_WRITEand/orPKEY_DENY_ACCESS, or nothing set at all.These can replace userspace's direct use of the new rdpkru/wrpkru instructions.
With current hardware, the kernel can not enforce that it has control over a given key. But, this at least allows the kernel to indicate to userspace that userspace does not control a given protection key. This makes it more likely that situations like using a pkey after
sys_pkey_free()can be detected.
Quoted 8 lines
The kernel does _not_ enforce that this interface must be used for changes to PKRU, whether or not a key has been "allocated".
This syscall interface could also theoretically be replaced with a pair of vsyscalls. The vsyscalls would just call WRPKRU/RDPKRU directly in situations where they are drop-in equivalents for what the kernel would be doing.
This one feels like something that can or should be implemented in glibc.
There is no real enforcement of the values yet looking them up or setting them takes mmap_sem for write. Applications that frequently get called will get hammed into the ground with serialisation on mmap_sem not to mention the cost of the syscall entry/exit.
RIght now, I'm seeing a lot of cost and not much benefit with this specific patch.
Signature · 8 lines
Mel Gorman SUSE Labs -- To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM, see: http://www.linux-mm.org/ . Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 15 lines · Mel Gorman
Quoted 14 lines · Dave Hansen
Quoted 14 lines
From: Dave Hansen <[email protected]>
This establishes two more system calls for protection key management:
unsigned long pkey_get(int pkey); int pkey_set(int pkey, unsigned long access_rights);The return value from
pkey_get()and the 'access_rights' passed topkey_set()are the same format: a bitmask containingPKEY_DENY_WRITEand/orPKEY_DENY_ACCESS, or nothing set at all.These can replace userspace's direct use of the new rdpkru/wrpkru instructions.
...
Quoted 2 lines
This one feels like something that can or should be implemented in glibc.
I generally agree, except that glibc doesn't have any visibility into whether a pkey is currently valid or not.
Quoted 2 lines
There is no real enforcement of the values yet looking them up or setting them takes
mmap_semfor write.
There are checks for mm_pkey_is_allocated(). That's the main thing these syscalls add on top of the raw instructions.
Quoted 3 lines
Applications that frequently get
called will get hammed into the ground with serialisation onmmap_semnot to mention the cost of the syscall entry/exit.
I think we can do both of them without mmap_sem, as long as we resign ourselves to this just being fundamentally racy (which it is already, I think). But, is it worth performance-tuning things that we don't expect performance-sensitive apps to be using in the first place? They'll just use the RDPKRU/WRPKRU instructions directly.
Ingo, do you still feel strongly that these syscalls (pkey_set/get()) should be included? Of the 5, they're definitely the two with the weakest justification.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 11 lines · Dave Hansen
Quoted 2 lines
Applications that frequently get called will get hammed into the ground with serialisation on
mmap_semnot to mention the cost of the syscall entry/exit.I think we can do both of them without
mmap_sem, as long as we resign ourselves to this just being fundamentally racy (which it is already, I think). But, is it worth performance-tuning things that we don't expect performance-sensitive apps to be using in the first place? They'll just use the RDPKRU/WRPKRU instructions directly.Ingo, do you still feel strongly that these syscalls (pkey_set/get()) should be included? Of the 5, they're definitely the two with the weakest justification.
Firstly, I'd like to thank Mel for the review, having this kind of high level interface discussion was exactly what I was hoping for before we merged any ABI patches.
So my hope was that we'd also grow some debugging features: such as a periodic watchdog timer clearing all non-allocated pkeys of a task and re-setting them to their (kernel-)known values and thus forcing user-space to coordinate key allocation/freeing.
While allocation/freeing of keys is very likely a slow path in any reasonable workload, _setting_ the values of pkeys could easily be a fast path. The whole point of pkeys is to allow both thread local and dynamic mapping and unmapping of memory ranges, without having to touch any page table attributes in the hot path.
Now another, more fundamental question is that pkeys are per-CPU (per thread) on the hardware side - so why do we even care about the mmap_sem in the syscalls in the first place? If we want any serialization wouldn't a pair of get_cpu()/put_cpu() preemption control calls be enough? Those would also be much cheaper.
The idea behind my suggestion to manage all pkey details via a kernel interface and 'shadow' the pkeys state in the kernel was that if we don't even offer a complete system call interface then user-space is _forced_ into using the raw instructions and into implementing a (potentially crappy) uncoordinated API or not implementing any API at all but randomly using fixed pkey indices.
My hope was to avoid that, especially since currently _all_ memory mapping details on x86 are controlled via system calls. If we don't offer that kind of facility then we force user-space into using the raw instructions and will likely end up with a poor user-space interface.
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
Thanks,
Ingo
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 3 lines · Ingo Molnar
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
My goal at the moment is to get folks enabled to the point that they can start modifying apps to use pkeys without having to patch their kernels.
I don't have confidence that we can design good high-level userspace
interfaces without seeing some real apps try to use the low-level ones and seeing how they struggle.
I had some glibc code to do the pkey alloc/free operations, but those aren't necessary if we're doing it in the kernel. Other than getting the syscall wrappers in place, I don't have any immediate plans to do anything in glibc.
Was there something you were expecting to see?
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 11 lines · Dave Hansen
Quoted 2 lines · Ingo Molnar
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
My goal at the moment is to get folks enabled to the point that they can start modifying apps to use pkeys without having to patch their kernels.
I don't have confidence that we can design good high-level userspace interfaces
without seeing some real apps try to use the low-level ones and seeing how they struggle.
Quoted 5 lines
I had some glibc code to do the pkey alloc/free operations, but those aren't necessary if we're doing it in the kernel. Other than getting the syscall wrappers in place, I don't have any immediate plans to do anything in glibc.
Was there something you were expecting to see?
Yeah, so (as you probably guessed!) I'm starting to have second thoughts about the complexity of the alloc/free/set/get interface I suggested, and Mel's review certainly strengthened that feeling.
I have two worries:
1)
A technical worry I have is that the 'pkey allocation interface' does not seem to be taking the per thread property of pkeys into account - while that property would be useful for apps. That is a limitation that seems unjustified.
The reason for this is that we are storing the key allocation bitmap in struct_mm, in mm->context.pkey_allocation_map - while we should be storing it in task_struct or thread_info.
We could solve this by moving the allocation bitmap to the task struct, but:
2)
My main worry is that it appears at this stage that we are still pretty far away from completely shadowing the hardware pkey state in the kernel - and without that we cannot really force user-space to use the 'proper' APIs. They can just use the raw instructions, condition them on a CPUID and be done with it: everything can be organized in user-space.
Furthermore, implementing it in a high performance fashion would be pretty complex
- at minimum we'd have to register a per thread read-write user-space data area where the kernel could store pkeys management data so that vsyscalls can access it ... None of that facility exists today.
And without vsyscall optimizations user-space might legitimately use its own implementation for performance reasons and we'd end up with twice the complexity and a largely unused piece of kernel infrastructure ...
So how about the following minimalistic approach instead, to get the ball rolling without making ABI decisions we might regret:
- There are 16 pkey indices on x86 currently. We already use index 15 for the true PROT_EXEC implementation. Let's set aside another pkey index for the kernel's potential future use (index 14), and clear it explicitly in the FPU context on every context switch if CONFIG_X86_DEBUG_FPU is enabled to make sure it remains unallocated.
- Expose just the new mprotect_pkey() system call to install a pkey index into the page tables - but we let user-space organize its key allocations.
- Give user-space an idea about limits:
"ALL THESE WORLDS ARE YOURS—EXCEPT EUROPA ATTEMPT NO LANDING THERE"
Ooops, wrong one. Lets try this instead:
Expose the current maximum user-space usable pkeys index in some programmatically accessible fashion. Maybe mprotect_pkey() could reject a permanently allocated kernel pkey index via a distinctive error code?
I.e. this pattern:
ret = pkey_mprotect(NULL, PAGE_SIZE, real_prot, pkey);
... would validate the pkey and we'd return -EOPNOTSUPP for pkey that is not available? This would allow maximum future flexibility as it would not define kernel allocated pkeys as a 'range'.
- ... and otherwise leave the remaining 14 pkey indices for user-space to manage.
If in the future user-space pkeys usage grows to such a level that kernel arbitration becomes desirable then we can still implement the get/set/alloc/free system calls as well: the first use of those system calls would switch on the kernel's pkey management facilities and from that point on user-space is supposed to use the published system calls only. Applications using pkey instructions directly would still work just fine: they'd never use the new system calls.
I.e. we can actually keep a bigger ABI flexibility by introducing the simplest possible ABI at this stage. Maybe user-space usage of this hardware feature will never grow beyond that simple ABI - in which case we've saved quite a bit of ongoing maintenance complexity...
And yes, I realize that we've come a full round since the very first version of this patch set, but I think the extra hoops were still worth it, because the true-PROT_EXEC feature came out of it which is very useful IMHO. But my more complex pkey management syscall ideas don't seem to be all that useful anymore.
So what do you think about this direction? This would simplify the patch set quite a bit and would touch very little MM code beyond the mprotect_pkey() bits.
Thanks,
Ingo
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 29 lines · Ingo Molnar
Quoted 11 lines · Dave Hansen
Quoted 2 lines · Ingo Molnar
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
My goal at the moment is to get folks enabled to the point that they can start modifying apps to use pkeys without having to patch their kernels.
I don't have confidence that we can design good high-level userspace interfaces
without seeing some real apps try to use the low-level ones and seeing how they struggle.Quoted 5 lines
I had some glibc code to do the pkey alloc/free operations, but those aren't necessary if we're doing it in the kernel. Other than getting the syscall wrappers in place, I don't have any immediate plans to do anything in glibc.
Was there something you were expecting to see?
Yeah, so (as you probably guessed!) I'm starting to have second thoughts about the complexity of the alloc/free/set/get interface I suggested, and Mel's review certainly strengthened that feeling.
I have two worries:
1)
Quoted 7 lines
A technical worry I have is that the 'pkey allocation interface' does not seem to be taking the per thread property of pkeys into account - while that property would be useful for apps. That is a limitation that seems unjustified.
The reason for this is that we are storing the key allocation bitmap in
struct_mm, inmm->context.pkey_allocation_map- while we should be storing it intask_structorthread_info.
Huh? Doesn't this have to be per mm? Sure, PKRU is per thread, but the page tables are shared.
Quoted 8 lines
2)
My main worry is that it appears at this stage that we are still pretty far away from completely shadowing the hardware pkey state in the kernel - and without that we cannot really force user-space to use the 'proper' APIs. They can just use the raw instructions, condition them on a CPUID and be done with it: everything can be organized in user-space.
My vote would be to keep the allocation mechanism but get rid of pkey_set.
Also, I think the debug poisoning feature is overcomplicated. Let's just forbid mprotect_key with an unallocated key.
There are still two issues that I think we need to address, though:
1. Signal delivery shouldn't unconditionally clear PKRU. That's what the current patches do, and it's unsafe. I'd rather set PKRU to the maximally locked down state on signal delivery (except for the PROT_EXEC key), although that might cause its own set of problems.
2. When thread A allocates a pkey, how does it lock down thread B?
#2 could be addressed by using fully-locked-down as the initial state post-exec() and copying the state on clone(). Dave, are there any cases in practice where one thread would allocate a pkey and want other threads to immediately have access to the memory with that key?
I find myself wondering whether we should stop using XSAVE for PKRU sooner rather than later. If we do anything like the above, we completely lose the init optimization, and the code would be a good deal simpler if we switched PKRU directly in switch_to and could therefore treat it like a normal register everywhere else.
--Andy
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 34 lines · Andy Lutomirski
Quoted 33 lines · Ingo Molnar
Quoted 11 lines · Dave Hansen
Quoted 2 lines · Ingo Molnar
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
My goal at the moment is to get folks enabled to the point that they can start modifying apps to use pkeys without having to patch their kernels.
I don't have confidence that we can design good high-level userspace interfaces
without seeing some real apps try to use the low-level ones and seeing how they struggle.Quoted 5 lines
I had some glibc code to do the pkey alloc/free operations, but those aren't necessary if we're doing it in the kernel. Other than getting the syscall wrappers in place, I don't have any immediate plans to do anything in glibc.
Was there something you were expecting to see?
Yeah, so (as you probably guessed!) I'm starting to have second thoughts about the complexity of the alloc/free/set/get interface I suggested, and Mel's review certainly strengthened that feeling.
I have two worries:
1)
A technical worry I have is that the 'pkey allocation interface' does not seem to be taking the per thread property of pkeys into account - while that property would be useful for apps. That is a limitation that seems unjustified.
Quoted 6 lines
Quoted 3 lines
The reason for this is that we are storing the key allocation bitmap in
struct_mm, inmm->context.pkey_allocation_map- while we should be storing it intask_structorthread_info.Huh? Doesn't this have to be per mm? Sure, PKRU is per thread, but the page tables are shared.
But the keys are not shared, and they carry meaningful per thread information.
mprotect_pkey()'s effects are per MM, but the system calls related to managing the keys (alloc/free/get/set) are fundamentally per CPU.
Here's an example of how this could matter to applications:
- 'writer thread' gets a RW- key into index 1 to a specific data area
- a pool of 'reader threads' may get the same pkey index 1 R-- to read the data area.
Same page tables, same index, two protections and two purposes.
With a global, per MM allocation of keys we'd have to use two indices: index 1 and 2.
Depending on how scarce the index space turns out to be making the key indices per thread is probably the right model.
Quoted 6 lines
There are still two issues that I think we need to address, though:
1. Signal delivery shouldn't unconditionally clear PKRU. That's what the current patches do, and it's unsafe. I'd rather set PKRU to the maximally locked down state on signal delivery (except for the
PROT_EXECkey), although that might cause its own set of problems.
Right now the historic pattern for signal handlers is that they safely and transparently stack on top of existing FPU related resources and do a save/restore of them. In that sense saving+clearing+restoring the pkeys state would be the correct approach that follows that pattern. There are two extra considerations:
- If we think of pkeys as a temporary register that can be used to access/unaccess normally unaccessible memory regions then this makes sense, in fact it's more
secure: signal handlers cannot accidentally stomp on an encryption key or on a database area, unless they intentionally gain access to them.
- If we think of pkeys as permanent memory mappings that enhance existing MM permissions then it would be correct to let them leak into signal handler state. The globl true-PROT_EXEC key would fall into this category.
So I agree, mostly: the correct approach is to save+clear+restore the first 14 pkey indices, and to leave alone the two 'global' indices.
Quoted 1 line
2. When thread A allocates a pkey, how does it lock down thread B?
So see above, I think the temporary key space should be per thread, so there would be no inter thread interactions: each thread is responsible for its own key management (via per thread management data in the library that implments it).
Thanks,
Ingo
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 6 lines · Ingo Molnar
* Andy Lutomirski <[email protected]> wrote:
mprotect_pkey()'s effects are per MM, but the system calls related to managing the keys (alloc/free/get/set) are fundamentally per CPU.Here's an example of how this could matter to applications:
Quoted 7 lines
- 'writer thread' gets a RW- key into index 1 to a specific data area
- a pool of 'reader threads' may get the same pkey index 1 R-- to read the data area.Same page tables, same index, two protections and two purposes.
With a global, per MM allocation of keys we'd have to use two indices: index 1 and 2.
I'm not sure how this would work. A piece of data mapped at only one virtual address can have only one key associated with it. For a data area, you would need to indicate between threads which key they needed in order to access the data. Both threads need to agree on the virtual address *and* the key used for access.
Remember, PKRU is just a *bitmap*. The only place keys are stored is in the page tables.
Here's how this ends up looking in practice when we have an initializer, a reader and a writer:
/* allocator: */ pkey = pkey_alloc(); data = mmap(PAGE_SIZE, PROT_NONE, ...); pkey_mprotect(data, PROT_WRITE|PROT_READ, pkey); metadata[data].pkey = pkey; /* reader */ pkey_set(metadata[data].pkey, PKEY_DENY_WRITE); readerfoo = *data; pkey_set(metadata[data].pkey, PKEY_DENY_WRITE|ACCESS); /* writer */ pkey_set(metadata[data].pkey, 0); /* 0 == deny nothing */ *data = bar; pkey_set(metadata[data].pkey, PKEY_DENY_WRITE|ACCESS);
I'm also not sure what the indexes are that you're referring to.
Quoted 2 lines
Depending on how scarce the index space turns out to be making the key indices per thread is probably the right model.
Yeah, I'm totally confused about what you mean by indexes.
Quoted 17 lines
Quoted 6 lines
There are still two issues that I think we need to address, though:
1. Signal delivery shouldn't unconditionally clear PKRU. That's what the current patches do, and it's unsafe. I'd rather set PKRU to the maximally locked down state on signal delivery (except for the
PROT_EXECkey), although that might cause its own set of problems.Right now the historic pattern for signal handlers is that they safely and transparently stack on top of existing FPU related resources and do a save/restore of them. In that sense saving+clearing+restoring the pkeys state would be the correct approach that follows that pattern. There are two extra considerations:
- If we think of pkeys as a temporary register that can be used to access/unaccess normally unaccessible memory regions then this makes sense, in fact it's more
secure: signal handlers cannot accidentally stomp on an encryption key or on a database area, unless they intentionally gain access to them.
Quoted 6 lines
- If we think of pkeys as permanent memory mappings that enhance existing MM permissions then it would be correct to let them leak into signal handler state. The globl true-PROT_EXEC key would fall into this category.
So I agree, mostly: the correct approach is to save+clear+restore the first 14 pkey indices, and to leave alone the two 'global' indices.
The current scheme is the most permissive, but it has an important
property: it's the most _flexible_. You can implement almost any scheme you want in userspace on top of it. The first userspace instruction of the handler could easily be WRKRU to fully lock down access in whatever scheme a program wants.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 11 lines · Dave Hansen
Quoted 10 lines · Ingo Molnar
* Andy Lutomirski <[email protected]> wrote:
mprotect_pkey()'s effects are per MM, but the system calls related to managing the keys (alloc/free/get/set) are fundamentally per CPU.Here's an example of how this could matter to applications:
- 'writer thread' gets a RW- key into index 1 to a specific data area
- a pool of 'reader threads' may get the same pkey index 1 R-- to read the data area.
Quoted 6 lines
Quoted 3 lines
Same page tables, same index, two protections and two purposes.
With a global, per MM allocation of keys we'd have to use two indices: index 1 and 2.
I'm not sure how this would work. A piece of data mapped at only one virtual address can have only one key associated with it.
Yeah, indeed, got myself confused there - but the actual protection bits are per CPU (per task).
Quoted 2 lines
Remember, PKRU is just a *bitmap*. The only place keys are stored is in the page tables.
A pkey is an index *and* a protection mask. So by representing it as a bitmask we lose per thread information. This is what I meant by 'incomplete shadowing' - for example the debug code couldn't work: if we cleared a pkey in a task we wouldn't know what to restore it to with the current data structures, right?
Thanks,
Ingo
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 6 lines · Ingo Molnar
Quoted 2 lines
Quoted 2 lines
Remember, PKRU is just a *bitmap*. The only place keys are stored is in the page tables.
A pkey is an index *and* a protection mask. So by representing it as a bitmask we lose per thread information. This is what I meant by 'incomplete shadowing' - for example the debug code couldn't work: if we cleared a pkey in a task we wouldn't know what to restore it to with the current data structures, right?
Right. I actually have some code to do the shadowing that I wrote to explore how to do different PKRU values in signal handlers. The code only shadowed the keys that were currently allocated, and used the (mm-wide) allocation map to figure that out. It did not have a separate per-thread concept of which parts of PKRU need to be shadowed.
It essentially populated the shadow value on all pkru_set() calls.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Ingo MolnarQuoted 46 lines · Ingo Molnar
Quoted 34 lines · Andy Lutomirski
Quoted 33 lines · Ingo Molnar
Quoted 11 lines · Dave Hansen
Quoted 2 lines · Ingo Molnar
So the question is, what is user-space going to do? Do any glibc patches exist? How are the user-space library side APIs going to look like?
My goal at the moment is to get folks enabled to the point that they can start modifying apps to use pkeys without having to patch their kernels.
I don't have confidence that we can design good high-level userspace interfaces
without seeing some real apps try to use the low-level ones and seeing how they struggle.Quoted 5 lines
I had some glibc code to do the pkey alloc/free operations, but those aren't necessary if we're doing it in the kernel. Other than getting the syscall wrappers in place, I don't have any immediate plans to do anything in glibc.
Was there something you were expecting to see?
Yeah, so (as you probably guessed!) I'm starting to have second thoughts about the complexity of the alloc/free/set/get interface I suggested, and Mel's review certainly strengthened that feeling.
I have two worries:
1)
A technical worry I have is that the 'pkey allocation interface' does not seem to be taking the per thread property of pkeys into account - while that property would be useful for apps. That is a limitation that seems unjustified.
Quoted 6 lines
Quoted 3 lines
The reason for this is that we are storing the key allocation bitmap in
struct_mm, inmm->context.pkey_allocation_map- while we should be storing it intask_structorthread_info.Huh? Doesn't this have to be per mm? Sure, PKRU is per thread, but the page tables are shared.
But the keys are not shared, and they carry meaningful per thread information.
Quoted 8 lines
mprotect_pkey()'s effects are per MM, but the system calls related to managing the keys (alloc/free/get/set) are fundamentally per CPU.
Here's an example of how this could matter to applications:
- 'writer thread' gets a RW- key into index 1 to a specific data area
- a pool of 'reader threads' may get the same pkey index 1 R-- to read the data area.
Sure, but this means you allocate index 1 once and then use it in both threads. If you allocate separately in each thread, nothing guarantees you'll get the same index both times, and if you don't then the code doesn't work.
Quoted 13 lines
Quoted 7 lines
There are still two issues that I think we need to address, though:
1. Signal delivery shouldn't unconditionally clear PKRU. That's what the current patches do, and it's unsafe. I'd rather set PKRU to the maximally locked down state on signal delivery (except for the
PROT_EXECkey), although that might cause its own set of problems.Right now the historic pattern for signal handlers is that they safely and transparently stack on top of existing FPU related resources and do a save/restore of them. In that sense saving+clearing+restoring the pkeys state would be the correct approach that follows that pattern. There are two extra considerations:
Quoted 5 lines
- If we think of pkeys as a temporary register that can be used to access/unaccess normally unaccessible memory regions then this makes sense, in fact it's more
secure: signal handlers cannot accidentally stomp on an encryption key or on a database area, unless they intentionally gain access to them.
That how I think I would think of them, but for this to be fully safe, we'd want to lock them down in signal handlers by default, which is what I'm suggesting.
--Andy
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Andy LutomirskiQuoted 6 lines · Andy Lutomirski
2. When thread A allocates a pkey, how does it lock down thread B?
#2 could be addressed by using fully-locked-down as the initial state post-exec() and copying the state on
clone(). Dave, are there any cases in practice where one thread would allocate a pkey and want other threads to immediately have access to the memory with that key?
The only one I can think of is a model where pkeys are used more in a "denial" mode rather than an "allow" mode.
For instance, perhaps you don't want to modify your app to use pkeys, except for a small routine where you handle untrusted user data. You would, in that routine, deny access to a bunch of keys, but otherwise allow access to all so you didn't have to change any other parts of the app.
Should we instead just recommend to userspace that they lock down access to keys by default in all threads as a best practice?
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 11 lines · Dave Hansen
Quoted 6 lines · Andy Lutomirski
2. When thread A allocates a pkey, how does it lock down thread B?
#2 could be addressed by using fully-locked-down as the initial state post-exec() and copying the state on
clone(). Dave, are there any cases in practice where one thread would allocate a pkey and want other threads to immediately have access to the memory with that key?The only one I can think of is a model where pkeys are used more in a "denial" mode rather than an "allow" mode.
Quoted 7 lines
For instance, perhaps you don't want to modify your app to use pkeys, except for a small routine where you handle untrusted user data. You would, in that routine, deny access to a bunch of keys, but otherwise allow access to all so you didn't have to change any other parts of the app.
Should we instead just recommend to userspace that they lock down access to keys by default in all threads as a best practice?
Is that really better than doing it in-kernel? My concern is that we'll find library code that creates a thread, and that code could run before the pkey-aware part of the program even starts running. So how is user code supposed lock down all of its threads?
seccomp has TSYNC for this, but I don't think that PKRU allows something like that.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 7 lines · Andy Lutomirski
Quoted 2 lines · Dave Hansen
Should we instead just recommend to userspace that they lock down access to keys by default in all threads as a best practice?
Is that really better than doing it in-kernel? My concern is that we'll find library code that creates a thread, and that code could run before the pkey-aware part of the program even starts running.
Yeah, so let's assume we have some pkey-unaware thread. The upside of a scheme where the kernel preemptively (and transparently to the thread) locks down PKRU is that the thread can't go corrupting any non-zero-pkey structures that came from other threads.
But, the downside is that the thread can not access any non-zero-pkey structures without taking some kind of action with PKRU. That obviously won't happen since the thread is pkeys-unaware to begin with. Would that break these libraries unless everything using pkeys knows to only share pkey=0 data with those threads?
Quoted 4 lines
So how is user code supposed lock down all of its threads?
seccomp has TSYNC for this, but I don't think that PKRU allows something like that.
I'm not sure this is possible for PKRU. Think of a simple PKRU manipulation in userspace:
pkru = rdpkru(); pkru |= PKEY_DENY_ACCESS<<key*2; wrpkru(pkru);
If we push a PKRU value into a thread between the rdpkru() and wrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 15 lines · Dave Hansen
Quoted 7 lines · Andy Lutomirski
Quoted 2 lines · Dave Hansen
Should we instead just recommend to userspace that they lock down access to keys by default in all threads as a best practice?
Is that really better than doing it in-kernel? My concern is that we'll find library code that creates a thread, and that code could run before the pkey-aware part of the program even starts running.
Yeah, so let's assume we have some pkey-unaware thread. The upside of a scheme where the kernel preemptively (and transparently to the thread) locks down PKRU is that the thread can't go corrupting any non-zero-pkey structures that came from other threads.
Quoted 6 lines
But, the downside is that the thread can not access any non-zero-pkey structures without taking some kind of action with PKRU. That obviously won't happen since the thread is pkeys-unaware to begin with. Would that break these libraries unless everything using pkeys knows to only share pkey=0 data with those threads?
Yes, but at least for the cases I can think of, that's probably a good thing. OTOH, I can see cases where you want everyone to be able to read but only specific code paths to be able to write.
I think it's more or less impossible to get sensible behavior passing pkey != 0 data to legacy functions. If you call:
void frob(struct foo *p);
If frob in turn passes p to a thread, what PKRU is it supposed to use?
Quoted 8 lines
Quoted 4 lines
So how is user code supposed lock down all of its threads?
seccomp has TSYNC for this, but I don't think that PKRU allows something like that.
I'm not sure this is possible for PKRU. Think of a simple PKRU manipulation in userspace:
Quoted 7 lines
pkru = rdpkru(); pkru |= PKEY_DENY_ACCESS<<key*2; wrpkru(pkru);If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.
We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
We could also arbitrarily partition the key space into initially-wide-open, initially-read-only, and initially-no-access and let pkey_alloc say which kind it wants.
--Andy
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 6 lines · Andy Lutomirski
I think it's more or less impossible to get sensible behavior passing pkey != 0 data to legacy functions. If you call:
void
frob(struct foo *p);If frob in turn passes p to a thread, what PKRU is it supposed to use?
The thread inheritance of PKRU can be nice. It actually gives things a good chance of working if you can control PKRU before clone(). I'd describe the semantics like this:
PKRU values are inherited at the time of a clone() system call. Threads unaware of protection keys may work on protection-key-protected data as long as PKRU is set up in advance of the clone() and never needs to be changed inside the thread.
If a thread is created before PKRU is set appropriately, the thread may not be able to act on protection-key-protected data.
Otherwise, the semantics are simpler, but they basically give threads no chance of ever working:
Threads unaware of protection keys and which can not manage PKRU may not operate on data where a non-zero key has been passed to pkey_mprotect().
It isn't clear to me that one of these is substantially better than the other. It's fairly easy in either case for an app that cares to get the behavior of the other.
But, one is clearly easier to implement in the kernel. :)
Quoted 12 lines
Quoted 12 lines
Quoted 4 lines
So how is user code supposed lock down all of its threads?
seccomp has TSYNC for this, but I don't think that PKRU allows something like that.
I'm not sure this is possible for PKRU. Think of a simple PKRU manipulation in userspace:
pkru = rdpkru(); pkru |= PKEY_DENY_ACCESS<<key*2; wrpkru(pkru);
Quoted 6 lines
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Yeah, doable, but not without some new data going out to userspace, plus the vsyscall code itself.
Quoted 3 lines
We could also arbitrarily partition the key space into initially-wide-open, initially-read-only, and initially-no-access and let
pkey_allocsay which kind it wants.
The point is still that wrpkru destroyed the 'push' operation. You always end up with a PKRU that (at least temporarily) ignored the 'push'.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 12 lines · Dave Hansen
Quoted 6 lines · Andy Lutomirski
I think it's more or less impossible to get sensible behavior passing pkey != 0 data to legacy functions. If you call:
void
frob(struct foo *p);If frob in turn passes p to a thread, what PKRU is it supposed to use?
The thread inheritance of PKRU can be nice. It actually gives things a good chance of working if you can control PKRU before
clone(). I'd describe the semantics like this:
Quoted 8 lines
PKRU values are inherited at the time of a
clone()system call. Threads unaware of protection keys may work on protection-key-protected data as long as PKRU is set up in advance of theclone()and never needs to be changed inside the thread.If a thread is created before PKRU is set appropriately, the thread may not be able to act on protection-key-protected data.
Given the apparent need for seccomp's TSYNC, I'm a bit nervous that this will be restrictive to a problematic degree.
Quoted 36 lines
Otherwise, the semantics are simpler, but they basically give threads no chance of ever working:
Threads unaware of protection keys and which can not manage PKRU may not operate on data where a non-zero key has been passed to
pkey_mprotect().It isn't clear to me that one of these is substantially better than the other. It's fairly easy in either case for an app that cares to get the behavior of the other.
But, one is clearly easier to implement in the kernel. :)
Quoted 12 lines
Quoted 12 lines
Quoted 4 lines
So how is user code supposed lock down all of its threads?
seccomp has TSYNC for this, but I don't think that PKRU allows something like that.
I'm not sure this is possible for PKRU. Think of a simple PKRU manipulation in userspace:
pkru = rdpkru(); pkru |= PKEY_DENY_ACCESS<<key*2; wrpkru(pkru);Quoted 6 lines
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Yeah, doable, but not without some new data going out to userspace, plus the vsyscall code itself.
Quoted 7 lines
Quoted 3 lines
We could also arbitrarily partition the key space into initially-wide-open, initially-read-only, and initially-no-access and let
pkey_allocsay which kind it wants.The point is still that wrpkru destroyed the 'push' operation. You always end up with a PKRU that (at least temporarily) ignored the 'push'.
Not with my partitioning proposal. We'd never asynchronously modify another thread's state -- we'd start start with a mask that gives us a good chance of having the initial state always be useful. To be completely precise, the initial state would be something like:
0 = all access, 1 (PROT_EXEC) = deny read and write, 2-11: deny read and write, 12-21: deny write, 22-31: all access
Then pkru_alloc would take a parameter giving the requested initial state, and it would only work if a key with that initial state is available.
If we went with the vdso approach, the API could look like:
pkru_state_t prev = pkru_push(mask, value);
...
pkru_pop(prev); // or pkru_pop(mask, prev)?
This doesn't fundamentally require the vdso, except that implementing bitwise operations on PKRU can't be done atomically with RDPKRU / WRPKRU. Grr. This also falls apart pretty badly when sigreturn happens, so I don't think I like this approach.
--Andy
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Andy LutomirskiQuoted 6 lines · Andy Lutomirski
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Actually, if we turned the vDSO into something more like a minimal user-space library with the ability to run at process startup as well to prepare stuff then it's painful to get right only *once*, and there will be tons of other areas where a proper per thread data storage on the user-space side would be immensely useful!
Thanks,
Ingo
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 7 lines · Ingo Molnar
Quoted 4 lines · Andy Lutomirski
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.
Quoted 7 lines
Quoted 2 lines
We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Actually, if we turned the vDSO into something more like a minimal user-space library with the ability to run at process startup as well to prepare stuff then it's painful to get right only *once*, and there will be tons of other areas where a proper per thread data storage on the user-space side would be immensely useful!
Doing this could be tricky: how exactly is the vDSO supposed to find per-thread data without breaking existing glibc?
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 11 lines · Andy Lutomirski
Quoted 10 lines · Ingo Molnar
Quoted 6 lines · Andy Lutomirski
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Quoted 8 lines
Quoted 5 lines
Actually, if we turned the vDSO into something more like a minimal user-space library with the ability to run at process startup as well to prepare stuff then it's painful to get right only *once*, and there will be tons of other areas where a proper per thread data storage on the user-space side would be immensely useful!
Doing this could be tricky: how exactly is the vDSO supposed to find per-thread data without breaking existing glibc?
So I think the way this could be done is by allocating it itself. The vDSO vma itself is 'external' to glibc as well to begin with - this would be a small extension to that concept.
Thanks,
Ingo
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 20 lines · Ingo Molnar
Quoted 17 lines · Andy Lutomirski
Quoted 15 lines · Ingo Molnar
Quoted 6 lines · Andy Lutomirski
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Actually, if we turned the vDSO into something more like a minimal user-space library with the ability to run at process startup as well to prepare stuff then it's painful to get right only *once*, and there will be tons of other areas where a proper per thread data storage on the user-space side would be immensely useful!
Quoted 6 lines
Quoted 2 lines
Doing this could be tricky: how exactly is the vDSO supposed to find per-thread data without breaking existing glibc?
So I think the way this could be done is by allocating it itself. The vDSO vma itself is 'external' to glibc as well to begin with - this would be a small extension to that concept.
But how does the vdso code find it? FS and GS are both spoken for by existing userspace.
--Andy
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
Quoted 24 lines · Andy Lutomirski
Quoted 23 lines · Ingo Molnar
Quoted 19 lines · Andy Lutomirski
Quoted 7 lines · Ingo Molnar
Quoted 4 lines · Andy Lutomirski
Quoted 3 lines
If we push a PKRU value into a thread between the
rdpkru()andwrpkru(), we'll lose the content of that "push". I'm not sure there's any way to guarantee this with a user-controlled register.Quoted 8 lines
Quoted 2 lines
We could try to insist that user code uses some vsyscall helper that tracks which bits are as-yet-unassigned. That's quite messy, though.
Actually, if we turned the vDSO into something more like a minimal user-space library with the ability to run at process startup as well to prepare stuff then it's painful to get right only *once*, and there will be tons of other areas where a proper per thread data storage on the user-space side would be immensely useful!
Doing this could be tricky: how exactly is the vDSO supposed to find per-thread data without breaking existing glibc?
Quoted 6 lines
Quoted 3 lines
So I think the way this could be done is by allocating it itself. The vDSO vma itself is 'external' to glibc as well to begin with - this would be a small extension to that concept.
But how does the vdso code find it? FS and GS are both spoken for by existing userspace.
Minimally relinking itself on a per mm basis?
Thanks,
Ingo
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Ingo MolnarQuoted 7 lines · Ingo Molnar
I.e. this pattern:
ret = pkey_mprotect(NULL, PAGE_SIZE, real_prot, pkey);... would validate the pkey and we'd return
-EOPNOTSUPPfor pkey that is not available? This would allow maximum future flexibility as it would not define kernel allocated pkeys as a 'range'.
Isn't this multiplexing an otherwise straightforward system call? In addition to providing pkey assignment to memory, it would also being used to pass pkey allocation information independently from any use for memory assignment.
The complexity of the ABI comes from its behavior, not from the raw number of system calls that are needed to implement it. IOW, this makes the ABI *more* complicated.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Ingo MolnarQuoted 5 lines · Ingo Molnar
- There are 16 pkey indices on x86 currently. We already use index 15 for the true
PROT_EXECimplementation. Let's set aside another pkey index for the kernel's potential future use (index 14), and clear it explicitly in the FPU context on every context switch ifCONFIG_X86_DEBUG_FPUis enabled to make sure it remains unallocated.
After mulling over this for a week: I really don't think we want to pre-reserve any keys.
The one bit of consistent feedback I've heard from the folks that are going to use this is that they want more keys. The current code does not reserve any keys (except 0 of course).
Virtually every feature that we've talked about adding on top of this _requires_ having this allocation mechanism and kernel knowledge of which keys are in use. Even having kernel-reserved keys requires telling userspace about allocation, whether we use pkey_mprotect() for it or not.
I'd like to resubmit this set with pkey_get/set() removed, but with pkey_alloc/free() still in place.
Why are folks so sensitive to the number of keys? There are a few modes this will get used in when folks want more pkeys that hardware provides.
Both of them are harmed in a meaningful way if we take some of their
keys away. Here's how they will use pkeys:
1. As an accelerator for existing mprotect()-provided guarantees. Let's say you want 100 pieces of data, but you only get 15 pkeys in hardware. The app picks the 15 most-frequently accessed pieces, and uses pkeys to control access to them, and uses mprotect() for the other 85. Each pkey you remove means a smaller "working set" covered by pkeys, more mprotect()s and lower performance.
2. To provide stronger access guarantees. Let's say you have 100 pieces of data. To access a given piece of data, you hash its key in to a pkey: hash(92)%NR_PKEYS. Accessing a random bit of data, you have a 1/NR_PKEYS chance of a hash collision and access to data you should not have access to. Fewer keys means more data corruption. Losing 2/16 keys means a 15% greater chance of a collision on a given access.
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Ingo MolnarQuoted 4 lines · Ingo Molnar
So my hope was that we'd also grow some debugging features: such as a periodic watchdog timer clearing all non-allocated pkeys of a task and re-setting them to their (kernel-)known values and thus forcing user-space to coordinate key allocation/freeing.
I'm glad you mentioned this. I've explicitly called out this behavior in the manpages now, or at least called out the fact that the kernel will not preserve PKRU contents for unallocated keys.
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Re: [PATCH 6/9] x86, pkeys: add pkey set/get syscalls
In reply to Dave HansenQuoted 14 lines · Dave Hansen
Quoted 13 lines · Mel Gorman
Quoted 12 lines · Dave Hansen
Quoted 12 lines
From: Dave Hansen <dave.hansen-VuQAYsv1563Yd54FQh9/[email protected]>
This establishes two more system calls for protection key management:
unsigned long pkey_get(int pkey); int pkey_set(int pkey, unsigned long access_rights);The return value from
pkey_get()and the 'access_rights' passed topkey_set()are the same format: a bitmask containingPKEY_DENY_WRITEand/orPKEY_DENY_ACCESS, or nothing set at all.
Quoted 9 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
These can replace userspace's direct use of the new rdpkru/wrpkru instructions.
...
Quoted 2 lines
This one feels like something that can or should be implemented in glibc.
I generally agree, except that glibc doesn't have any visibility into whether a pkey is currently valid or not.
Well, it could if it tracked the pkey_alloc/pkey_free calls too. I accept that's not perfect as nothing prevents the syscalls being used directly.
Quoted 10 lines
Quoted 3 lines
Applications that frequently get
called will get hammed into the ground with serialisation onmmap_semnot to mention the cost of the syscall entry/exit.I think we can do both of them without
mmap_sem, as long as we resign ourselves to this just being fundamentally racy (which it is already, I think). But, is it worth performance-tuning things that we don't expect performance-sensitive apps to be using in the first place? They'll just use the RDPKRU/WRPKRU instructions directly.
I accept the premature optimisation arguement but I think it'll eventually bite us. Why this red-flagged for me was because so many people have complained about just system call overhead when using particular types of hardware -- DAX springs to mind with the MAP_PMEM_AWARE discussions. Using mmap_sem means that pkey operations stop parallel faults, mmaps and so on. If the applications that care are trying to minimise page table operations, TLB flushes and so on, they might not be that happy if parallel faults are stalled.
I think whether you serialise pkey_get/pkey_set operations or not, it's going to be inherently racy with different sized windows. A sequence counter would be sufficient to protect it to prevent partial reads. If userspace cares about the race, then userspace is going to have to serialise its threads access to the keys anyway.
Signature · 2 lines
Mel Gorman SUSE Labs
PATCH v4 7/9 generic syscalls: wire up memory protection keys syscalls
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
These new syscalls are implemented as generic code, so enable them for architectures like arm64 which use the generic syscall table.
According to Arnd:
Even if the support is x86 specific for the forseeable future, it may be good to reserve the number just in case. The other architecture specific syscall lists are usually left to the individual arch maintainers, most a lot of the newer architectures share this table.
---
b/include/linux/syscalls.h | 8 ++++++++ b/include/uapi/asm-generic/unistd.h | 12 +++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-)
include/linux/syscalls.h renamed from include/linux/syscalls.h~pkeys-119-syscalls-generic +8 -0
@@ -898,4 +898,12 @@ asmlinkage long sys_copy_file_range(intasmlinkage long sys_mlock2 (unsigned long start,size_t len,int flags); +asmlinkage long sys_pkey_mprotect (unsigned long start,size_t len, +unsigned long prot,int pkey); +asmlinkage long sys_pkey_alloc (unsigned long flags,unsigned long init_val); +asmlinkage long sys_pkey_free (int pkey); +asmlinkage long sys_pkey_get (int pkey,unsigned long flags); +asmlinkage long sys_pkey_set (int pkey,unsigned long access_rights, +unsigned long flags); +#endif
include/uapi/asm-generic/unistd.h renamed from include/uapi/asm-generic/unistd.h~pkeys-119-syscalls-generic +11 -1
@@ -724,9 +724,19 @@ __SYSCALL(__NR_copy_file_range, sys_copy __SC_COMP(__NR_preadv2, sys_preadv2, compat_sys_preadv2)#define __NR_pwritev2 287 __SC_COMP(__NR_pwritev2, sys_pwritev2, compat_sys_pwritev2) +#define __NR_pkey_mprotect 288 +__SYSCALL(__NR_pkey_mprotect, sys_pkey_mprotect) +#define __NR_pkey_alloc 289 +__SYSCALL(__NR_pkey_alloc, sys_pkey_alloc) +#define __NR_pkey_free 290 +__SYSCALL(__NR_pkey_free, sys_pkey_free) +#define __NR_pkey_get 291 +__SYSCALL(__NR_pkey_get, sys_pkey_get) +#define __NR_pkey_set 292 +__SYSCALL(__NR_pkey_set, sys_pkey_set)#undef __NR_syscalls -#define __NR_syscalls 288 +#define __NR_syscalls 293/* * All syscalls below here should go away really,
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 8/9 pkeys: add details of system call use to Documentation/
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
This spells out all of the pkey-related system calls that we have and provides some example code fragments to demonstrate how we expect them to be used.
---
b/Documentation/x86/protection-keys.txt | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+)
Documentation/x86/protection-keys.txt renamed from Documentation/x86/protection-keys.txt~pkeys-120-syscall-docs +63 -0
@@ -18,6 +18,69 @@ even though there is theoretically space permissions are enforced on data access only and have no effect on instruction fetches. +=========================== Syscalls =========================== + +There are 5 system calls which directly interact with pkeys: + + int pkey_alloc(unsigned long flags, unsigned long init_access_rights) + int pkey_free(int pkey); + int pkey_mprotect(unsigned long start, size_t len, + unsigned long prot, int pkey); + unsigned long pkey_get(int pkey); + int pkey_set(int pkey, unsigned long access_rights); + +Before a pkey can be used, it must first be allocated with +pkey_alloc(). An application may either call pkey_set() or the +WRPKRU instruction directly in order to change access permissions +to memory covered with a key. + + int real_prot = PROT_READ|PROT_WRITE; + pkey = pkey_alloc(0, PKEY_DENY_WRITE); + ptr = mmap(NULL, PAGE_SIZE, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); + ret = pkey_mprotect(ptr, PAGE_SIZE, real_prot, pkey); + ... application runs here + +Now, if the application needs to update the data at 'ptr', it can +gain access, do the update, then remove its write access: + + pkey_set(pkey, 0); // clear PKEY_DENY_WRITE + *ptr = foo; // assign something + pkey_set(pkey, PKEY_DENY_WRITE); // set PKEY_DENY_WRITE again + +Now when it frees the memory, it will also free the pkey since it +is no longer in use: + + munmap(ptr, PAGE_SIZE); + pkey_free(pkey); + +=========================== Behavior =========================== + +The kernel attempts to make protection keys consistent with the +behavior of a plain mprotect(). For instance if you do this: + + mprotect(ptr, size, PROT_NONE); + something(ptr); + +you can expect the same effects with protection keys when doing this: + + pkey = pkey_alloc(0, PKEY_DISABLE_WRITE | PKEY_DISABLE_READ); + pkey_mprotect(ptr, size, PROT_READ|PROT_WRITE, pkey); + something(ptr); + +That should be true whether something() is a direct access to 'ptr' +like: + + *ptr = foo; + +or when the kernel does the access on the application's behalf like +with a read(): + + read(fd, ptr, 1); + +The kernel will send a SIGSEGV in both cases, but si_code will be set +to SEGV_PKERR when violating protection keys versus SEGV_ACCERR when +the plain mprotect() permissions are violated. + =========================== Config Option =========================== This config option adds approximately 1.5kb of text. and 50 bytes of
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
PATCH v4 9/9 x86, pkeys: add self-tests
In reply to Dave HansenFrom: Dave Hansen <[email protected]>
This code should be a good demonstration of how to use the new system calls as well as how to use protection keys in general.
This code shows how to:
1. Manipulate the Protection Keys Rights User (PKRU) register with sys_pkey_get/set()
2. Set a protection key on memory
3. Fetch and/or modify PKRU from the signal XSAVE state
4. Read the kernel-provided protection key in the siginfo
5. Set up an execute-only mapping
There are currently 13 tests:
test_read_of_write_disabled_region test_read_of_access_disabled_region test_write_of_write_disabled_region test_write_of_access_disabled_region test_kernel_write_of_access_disabled_region test_kernel_write_of_write_disabled_region test_kernel_gup_of_access_disabled_region test_kernel_gup_write_to_write_disabled_region test_executing_on_unreadable_memory test_ptrace_of_child test_pkey_syscalls_on_non_allocated_pkey test_pkey_syscalls_bad_args test_pkey_alloc_exhaust
Each of the tests is run with plain memory (via mmap(MAP_ANON)), transparent huge pages, and hugetlb.
---
b/tools/testing/selftests/x86/Makefile | 3 b/tools/testing/selftests/x86/pkey-helpers.h | 191 +++ b/tools/testing/selftests/x86/protection_keys.c | 1316 ++++++++++++++++++++++++ 3 files changed, 1509 insertions(+), 1 deletion(-)
tools/testing/selftests/x86/Makefile renamed from tools/testing/selftests/x86/Makefile~pkeys-130-selftests +2 -1
@@ -5,7 +5,8 @@ include ../lib.mk .PHONY: all all_32 all_64 warn_32bit_failure clean TARGETS_C_BOTHBITS := single_step_syscall sysret_ss_attrs syscall_nt ptrace_syscall \ - check_initial_reg_state sigreturn ldt_gdt iopl mpx-mini-test + check_initial_reg_state sigreturn ldt_gdt iopl mpx-mini-test \ + protection_keys TARGETS_C_32BIT_ONLY := entry_from_vm86 syscall_arg_fault test_syscall_vdso unwind_vdso \ test_FCMOV test_FCOMI test_FISTTP \ vdso_restorer
tools/testing/selftests/x86/pkey-helpers.h new file +191 -0
191 lines not on this page · raw message
tools/testing/selftests/x86/protection_keys.c new file +1316 -0
1,316 lines not on this page · raw message
_
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
Quoted 6 lines · Dave Hansen
I'm resending these because Ingo has said that he'd "love to have some high level MM review & ack for these syscall ABI extensions." The only changes to the code in months have been in the selftests. So, if anyone has been putting off taking a look at these, I'd appreciate a look now.
I took a look at the patches other than the self-tests and the documentation. I did not see any major problems other than thinking there is a lot of ways for userspace to shoot itself in the foot and lose the protection pkeys is meant to give.
That said, consider the review to be unreliable on the grounds I haven't followed pkeys development and this is my first time looking in its general direction.
Signature · 2 lines
Mel Gorman SUSE Labs
Quoted 5 lines · Dave Hansen
I'm resending these because Ingo has said that he'd "love to have some high level MM review & ack for these syscall ABI extensions." The only changes to the code in months have been in the selftests. So, if anyone has been putting off taking a look at these, I'd appreciate a look now.
Please expect nothing from me. I've paid no attention to memory protection keys, and they're way off my radar of interest. Sorry, if I spend my time looking at stuff I have little to contribute to, then I'm left with no time at all for what I should really be doing.
Hugh