Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86 now).
Thanks!
-Kees
[1] https://grsecurity.net/download.php "grsecurity - test kernel patch"
[2] http://www.openwall.com/lists/kernel-hardening/2016/05/19/5
This is the start of porting PAX_USERCOPY into the mainline kernel. This
is the first set of features, controlled by CONFIG_HARDENED_USERCOPY. The
work is based on code by PaX Team and Brad Spengler, and an earlier port
from Casey Schaufler. Additional non-slab page tests are from Rik van Riel.
This patch contains the logic for validating several conditions when
performing copy_to_user() and copy_from_user() on the kernel object
being copied to/from:
- address range doesn't wrap around
- address range isn't NULL or zero-allocated (with a non-zero copy size)
- if on the slab allocator:
- object size must be less than or equal to copy size (when check is
implemented in the allocator, which appear in subsequent patches)
- otherwise, object must not span page allocations
- if on the stack
- object must not extend before/after the current process task
- object must be contained by the current stack frame (when there is
arch/build support for identifying stack frames)
- object must not overlap with kernel text
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 7 ++
include/linux/slab.h | 12 +++
include/linux/thread_info.h | 15 +++
mm/Makefile | 4 +
mm/usercopy.c | 239 ++++++++++++++++++++++++++++++++++++++++++++
security/Kconfig | 27 +++++
6 files changed, 304 insertions(+)
create mode 100644 mm/usercopy.c
@@ -21,6 +21,9 @@ KCOV_INSTRUMENT_memcontrol.o := nKCOV_INSTRUMENT_mmzone.o:=nKCOV_INSTRUMENT_vmstat.o:=n+# Since __builtin_frame_address does work as used, disable the warning.+CFLAGS_usercopy.o+=$(callcc-disable-warning,frame-address)+mmu-y:=nommu.ommu-$(CONFIG_MMU):=gup.ohighmem.omemory.omincore.o\mlock.ommap.omprotect.omremap.omsync.ormap.o\
@@ -0,0 +1,239 @@+/*+*ThisimplementsthevariouschecksforCONFIG_HARDENED_USERCOPY*,+*whicharedesignedtoprotectkernelmemoryfromneedlessexposure+*andoverwriteundermanyunintendedconditions.Thiscodeisbased+*onPAX_USERCOPY,whichis:+*+*Copyright(C)2001-2016PaXTeam,BradleySpengler,OpenSource+*SecurityInc.+*+*Thisprogramisfreesoftware;youcanredistributeitand/ormodify+*itunderthetermsoftheGNUGeneralPublicLicenseversion2as+*publishedbytheFreeSoftwareFoundation.+*+*/+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt++#include<linux/mm.h>+#include<linux/slab.h>+#include<asm/sections.h>++/*+*Checksifagivenpointerandlengthiscontainedbythecurrent+*stackframe(ifpossible).+*+*0:notatallonthestack+*1:fullyonthestack(whencan'tdoframe-checking)+*2:fullyinsidethecurrentstackframe+*-1:errorcondition(invalidstackpositionorbadstackframe)+*/+staticnoinlineintcheck_stack_object(constvoid*obj,unsignedlonglen)+{+constvoid*conststack=task_stack_page(current);+constvoid*conststackend=stack+THREAD_SIZE;++#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)+constvoid*frame=NULL;+constvoid*oldframe;+#endif++/* Object is not on the stack at all. */+if(obj+len<=stack||stackend<=obj)+return0;++/*+*Reject:objectpartiallyoverlapsthestack(passingthe+*thecheckabovemeansatleastoneendiswithinthestack,+*soifthischeckfails,theotherendisoutsidethestack).+*/+if(obj<stack||stackend<obj+len)+return-1;++#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)+oldframe=__builtin_frame_address(1);+if(oldframe)+frame=__builtin_frame_address(2);+/*+*low---------------------------------------------->high+*[savedbp][savedip][args][localvars][savedbp][savedip]+*^----------------^+*allowcopiesonlywithinhere+*/+while(stack<=frame&&frame<stackend){+/*+*Ifobj+lenextendspastthelastframe,this+*checkwon'tpassandthenextframewillbe0,+*causingustobailoutandcorrectlyreport+*thecopyasinvalid.+*/+if(obj+len<=frame)+returnobj>=oldframe+2*sizeof(void*)?2:-1;+oldframe=frame;+frame=*(constvoid*const*)frame;+}+return-1;+#else+return1;+#endif+}++staticvoidreport_usercopy(constvoid*ptr,unsignedlonglen,+boolto_user,constchar*type)+{+pr_emerg("kernel memory %s attempt detected %s %p (%s) (%lu bytes)\n",+to_user?"exposure":"overwrite",+to_user?"from":"to",ptr,type?:"unknown",len);+dump_stack();+do_group_exit(SIGKILL);+}++/* Returns true if any portion of [ptr,ptr+n) over laps with [low,high). */+staticbooloverlaps(constvoid*ptr,unsignedlongn,unsignedlonglow,+unsignedlonghigh)+{+unsignedlongcheck_low=(uintptr_t)ptr;+unsignedlongcheck_high=check_low+n;++/* Does not overlap if entirely above or entirely below. */+if(check_low>=high||check_high<low)+returnfalse;++returntrue;+}++/* Is this address range in the kernel text area? */+staticinlineconstchar*check_kernel_text_object(constvoid*ptr,+unsignedlongn)+{+unsignedlongtextlow=(unsignedlong)_stext;+unsignedlongtexthigh=(unsignedlong)_etext;++if(overlaps(ptr,n,textlow,texthigh))+return"<kernel text>";++#ifdef HAVE_ARCH_LINEAR_KERNEL_MAPPING+/* Check against linear mapping as well. */+if(overlaps(ptr,n,(unsignedlong)__va(__pa(textlow)),+(unsignedlong)__va(__pa(texthigh))))+return"<linear kernel text>";+#endif++returnNULL;+}++staticinlineconstchar*check_bogus_address(constvoid*ptr,unsignedlongn)+{+/* Reject if object wraps past end of memory. */+if(ptr+n<ptr)+return"<wrapped address>";++/* Reject if NULL or ZERO-allocation. */+if(ZERO_OR_NULL_PTR(ptr))+return"<null>";++returnNULL;+}++staticinlineconstchar*check_heap_object(constvoid*ptr,unsignedlongn)+{+structpage*page,*endpage;+constvoid*end=ptr+n-1;++if(!virt_addr_valid(ptr))+returnNULL;++page=virt_to_head_page(ptr);++/* Check slab allocator for flags and size. */+if(PageSlab(page))+return__check_heap_object(ptr,n,page);++/* Is the object wholly within one base page? */+if(likely(((unsignedlong)ptr&(unsignedlong)PAGE_MASK)==+((unsignedlong)end&(unsignedlong)PAGE_MASK)))+returnNULL;++/* Allow if start and end are inside the same compound page. */+endpage=virt_to_head_page(end);+if(likely(endpage==page))+returnNULL;++/* Allow special areas, device memory, and sometimes kernel data. */+if(PageReserved(page)&&PageReserved(endpage))+returnNULL;++/*+*SometimesthekerneldataregionsarenotmarkedReserved.And+*sometimes[_sdata,_edata)doesnotcoverrodataand/orbss,+*socheckeachrangeexplicitly.+*/++/* Allow kernel data region (if not marked as Reserved). */+if(ptr>=(constvoid*)_sdata&&end<=(constvoid*)_edata)+returnNULL;++/* Allow kernel rodata region (if not marked as Reserved). */+if(ptr>=(constvoid*)__start_rodata&&+end<=(constvoid*)__end_rodata)+returnNULL;++/* Allow kernel bss region (if not marked as Reserved). */+if(ptr>=(constvoid*)__bss_start&&+end<=(constvoid*)__bss_stop)+returnNULL;++/* Uh oh. The "object" spans several independently allocated pages. */+return"<spans multiple pages>";+}++/*+*Validatesthatthegivenobjectisoneof:+*-knownsafeheapobject+*-knownsafestackobject+*-notinkerneltext+*/+void__check_object_size(constvoid*ptr,unsignedlongn,boolto_user)+{+constchar*err;++/* Skip all tests if size is zero. */+if(!n)+return;++/* Check for invalid addresses. */+err=check_bogus_address(ptr,n);+if(err)+gotoreport;++/* Check for bad heap object. */+err=check_heap_object(ptr,n);+if(err)+gotoreport;++/* Check for bad stack object. */+switch(check_stack_object(ptr,n)){+case0:+/* Object is not touching the current process stack. */+break;+case1:+case2:+/*+*Objectiseitherinthecorrectframe(whenit+*ispossibletocheck)orjustgenerallyonthe+*processstack(whenframecheckingnotavailable).+*/+return;+default:+err="<process stack>";+gotoreport;+}++/* Check for object in kernel to avoid text exposure. */+err=check_kernel_text_object(ptr,n);+if(!err)+return;++report:+report_usercopy(ptr,n,to_user,err);+}+EXPORT_SYMBOL(__check_object_size);
Under CONFIG_HARDENED_USERCOPY, this adds object size checking to the
SLUB allocator to catch any copies that may span objects.
Based on code from PaX and grsecurity.
Signed-off-by: Kees Cook <redacted>
---
init/Kconfig | 1 +
mm/slub.c | 27 +++++++++++++++++++++++++++
2 files changed, 28 insertions(+)
Under CONFIG_HARDENED_USERCOPY, this adds object size checking to the
SLAB allocator to catch any copies that may span objects.
Based on code from PaX and grsecurity.
Signed-off-by: Kees Cook <redacted>
---
init/Kconfig | 1 +
mm/slab.c | 30 ++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+)
Enables CONFIG_HARDENED_USERCOPY checks on x86. This is done both in
copy_*_user() and __copy_*_user() because copy_*_user() actually calls
down to _copy_*_user() and not __copy_*_user().
Based on code from PaX and grsecurity.
Signed-off-by: Kees Cook <redacted>
---
arch/x86/Kconfig | 2 ++
arch/x86/include/asm/uaccess.h | 10 ++++++----
arch/x86/include/asm/uaccess_32.h | 2 ++
arch/x86/include/asm/uaccess_64.h | 2 ++
4 files changed, 12 insertions(+), 4 deletions(-)
@@ -762,9 +763,10 @@ copy_to_user(void __user *to, const void *from, unsigned long n)might_fault();/* See the comment in copy_from_user() above. */-if(likely(sz<0||sz>=n))+if(likely(sz<0||sz>=n)){+check_object_size(from,n,true);n=_copy_to_user(to,from,n);-elseif(__builtin_constant_p(n))+}elseif(__builtin_constant_p(n))copy_to_user_overflow();else__copy_to_user_overflow(sz,n);
Enables CONFIG_HARDENED_USERCOPY checks on arm64. As done by KASAN in -next,
renames the low-level functions to __arch_copy_*_user() so a static inline
can do additional work before the copy.
Signed-off-by: Kees Cook <redacted>
---
arch/arm64/Kconfig | 2 ++
arch/arm64/include/asm/uaccess.h | 18 ++++++++++++++++--
arch/arm64/kernel/arm64ksyms.c | 4 ++--
arch/arm64/lib/copy_from_user.S | 4 ++--
arch/arm64/lib/copy_to_user.S | 4 ++--
5 files changed, 24 insertions(+), 8 deletions(-)
@@ -34,8 +34,8 @@ EXPORT_SYMBOL(copy_page);EXPORT_SYMBOL(clear_page);/* user mem (segment) */-EXPORT_SYMBOL(__copy_from_user);-EXPORT_SYMBOL(__copy_to_user);+EXPORT_SYMBOL(__arch_copy_from_user);+EXPORT_SYMBOL(__arch_copy_to_user);EXPORT_SYMBOL(__clear_user);EXPORT_SYMBOL(__copy_in_user);
From: Michael Ellerman <mpe@ellerman.id.au> Date: 2016-07-07 04:35:17
Kees Cook [off-list ref] writes:
Under CONFIG_HARDENED_USERCOPY, this adds object size checking to the
SLUB allocator to catch any copies that may span objects.
Based on code from PaX and grsecurity.
Signed-off-by: Kees Cook <redacted>
@@ -3614,6 +3614,33 @@ void *__kmalloc_node(size_t size, gfp_t flags, int node)EXPORT_SYMBOL(__kmalloc_node);#endif+#ifdef CONFIG_HARDENED_USERCOPY+/*+*Rejectsobjectsthatareincorrectlysized.+*+*ReturnsNULLifcheckpasses,otherwiseconstchar*tonameofcache+*toindicateanerror.+*/+constchar*__check_heap_object(constvoid*ptr,unsignedlongn,+structpage*page)+{+structkmem_cache*s;+unsignedlongoffset;++/* Find object. */+s=page->slab_cache;++/* Find offset within object. */+offset=(ptr-page_address(page))%s->size;++/* Allow address range falling entirely within object size. */+if(offset<=s->object_size&&n<=s->object_size-offset)+returnNULL;++returns->name;+}
I gave this a quick spin on powerpc, it blew up immediately :)
Brought up 16 CPUs
usercopy: kernel memory overwrite attempt detected to c0000001fe023868 (kmalloc-16) (9 bytes)
CPU: 8 PID: 103 Comm: kdevtmpfs Not tainted 4.7.0-rc3-00098-g09d9556ae5d1 #55
Call Trace:
[c0000001fa0cfb40] [c0000000009bdbe8] dump_stack+0xb0/0xf0 (unreliable)
[c0000001fa0cfb80] [c00000000029cf44] __check_object_size+0x74/0x320
[c0000001fa0cfc00] [c00000000005d4d0] copy_from_user+0x60/0xd4
[c0000001fa0cfc40] [c00000000022b6cc] memdup_user+0x5c/0xf0
[c0000001fa0cfc80] [c00000000022b90c] strndup_user+0x7c/0x110
[c0000001fa0cfcc0] [c0000000002d6c28] SyS_mount+0x58/0x180
[c0000001fa0cfd10] [c0000000005ee908] devtmpfsd+0x98/0x210
[c0000001fa0cfd80] [c0000000000df810] kthread+0x110/0x130
[c0000001fa0cfe30] [c0000000000095e8] ret_from_kernel_thread+0x5c/0x74
SLUB tracing says:
TRACE kmalloc-16 alloc 0xc0000001fe023868 inuse=186 fp=0x (null)
Which is not 16-byte aligned, which seems to be caused by the red zone?
The following patch fixes it for me, but I don't know SLUB enough to say
if it's always correct.
From: Christian Borntraeger <hidden> Date: 2016-07-07 07:30:56
On 07/07/2016 12:25 AM, Kees Cook wrote:
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
+
+ /* Object is not on the stack at all. */
+ if (obj + len <= stack || stackend <= obj)
+ return 0;
+
+ /*
+ * Reject: object partially overlaps the stack (passing the
+ * the check above means at least one end is within the stack,
+ * so if this check fails, the other end is outside the stack).
+ */
+ if (obj < stack || stackend < obj + len)
+ return -1;
+
+#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)
+ oldframe = __builtin_frame_address(1);
+ if (oldframe)
+ frame = __builtin_frame_address(2);
+ /*
+ * low ----------------------------------------------> high
+ * [saved bp][saved ip][args][local vars][saved bp][saved ip]
+ * ^----------------^
+ * allow copies only within here
+ */
+ while (stack <= frame && frame < stackend) {
+ /*
+ * If obj + len extends past the last frame, this
+ * check won't pass and the next frame will be 0,
+ * causing us to bail out and correctly report
+ * the copy as invalid.
+ */
+ if (obj + len <= frame)
+ return obj >= oldframe + 2 * sizeof(void *) ? 2 : -1;
+ oldframe = frame;
+ frame = *(const void * const *)frame;
+ }
+ return -1;
+#else
+ return 1;
+#endif
I'd rather make that a weak function returning 1 which can be replaced by
x86 for CONFIG_FRAME_POINTER=y. That also allows other architectures to
implement their specific frame checks.
Thanks,
tglx
On Wednesday, July 6, 2016 3:25:20 PM CEST Kees Cook wrote:
This is the start of porting PAX_USERCOPY into the mainline kernel. This
is the first set of features, controlled by CONFIG_HARDENED_USERCOPY. The
work is based on code by PaX Team and Brad Spengler, and an earlier port
from Casey Schaufler. Additional non-slab page tests are from Rik van Riel.
This patch contains the logic for validating several conditions when
performing copy_to_user() and copy_from_user() on the kernel object
being copied to/from:
- address range doesn't wrap around
- address range isn't NULL or zero-allocated (with a non-zero copy size)
- if on the slab allocator:
- object size must be less than or equal to copy size (when check is
implemented in the allocator, which appear in subsequent patches)
- otherwise, object must not span page allocations
- if on the stack
- object must not extend before/after the current process task
- object must be contained by the current stack frame (when there is
arch/build support for identifying stack frames)
- object must not overlap with kernel text
Signed-off-by: Kees Cook <redacted>
Nice!
I have a few further thoughts, most of which have probably been
considered before:
+static inline const char *check_bogus_address(const void *ptr, unsigned long n)
+{
+ /* Reject if object wraps past end of memory. */
+ if (ptr + n < ptr)
+ return "<wrapped address>";
+
+ /* Reject if NULL or ZERO-allocation. */
+ if (ZERO_OR_NULL_PTR(ptr))
+ return "<null>";
+
+ return NULL;
+}
This checks against address (void*)16, but I guess on most architectures the
lowest possible kernel address is much higher. While there may not be much
that to exploit if the expected kernel address points to userland, forbidding
any obviously incorrect address that is outside of the kernel may be easier.
Even on architectures like s390 that start the kernel memory at (void *)0x0,
the lowest address to which we may want to do a copy_to_user would be much
higher than (void*)0x16.
+
+ /* Allow kernel rodata region (if not marked as Reserved). */
+ if (ptr >= (const void *)__start_rodata &&
+ end <= (const void *)__end_rodata)
+ return NULL;
Should we explicitly forbid writing to rodata, or is it enough to
rely on page protection here?
+ /* Allow kernel bss region (if not marked as Reserved). */
+ if (ptr >= (const void *)__bss_start &&
+ end <= (const void *)__bss_stop)
+ return NULL;
accesses to .data/.rodata/.bss are probably not performance critical,
so we could go further here and check the kallsyms table to ensure
that we are not spanning multiple symbols here.
For stuff that is performance critical, should there be a way to
opt out of the checks, or do we assume it already uses functions
that avoid the checks? I looked at the file and network I/O path
briefly and they seem to use kmap_atomic() to get to the user pages
at least in some of the common cases (but I may well be missing
important ones).
Arnd
From: Mark Rutland <mark.rutland@arm.com> Date: 2016-07-07 10:07:35
Hi,
On Wed, Jul 06, 2016 at 03:25:23PM -0700, Kees Cook wrote:
Enables CONFIG_HARDENED_USERCOPY checks on arm64. As done by KASAN in -next,
renames the low-level functions to __arch_copy_*_user() so a static inline
can do additional work before the copy.
The checks themselves look fine, but as with the KASAN checks, it seems
a shame that this logic is duplicated per arch, integrated in subtly
different ways.
Can we not __arch prefix all the arch uaccess helpers, and place
kasan_check_*() and check_object_size() calls in generic wrappers?
If we're going to update all the arch uaccess helpers anyway, doing that
would make it easier to fix things up, or to add new checks in future.
Thanks,
Mark.
@@ -34,8 +34,8 @@ EXPORT_SYMBOL(copy_page);EXPORT_SYMBOL(clear_page);/* user mem (segment) */-EXPORT_SYMBOL(__copy_from_user);-EXPORT_SYMBOL(__copy_to_user);+EXPORT_SYMBOL(__arch_copy_from_user);+EXPORT_SYMBOL(__arch_copy_to_user);EXPORT_SYMBOL(__clear_user);EXPORT_SYMBOL(__copy_in_user);
From: Rik van Riel <hidden> Date: 2016-07-07 16:19:56
On Wed, 2016-07-06 at 15:25 -0700, Kees Cook wrote:
This is the start of porting PAX_USERCOPY into the mainline kernel.
This
is the first set of features, controlled by CONFIG_HARDENED_USERCOPY.
The
work is based on code by PaX Team and Brad Spengler, and an earlier
port
from Casey Schaufler. Additional non-slab page tests are from Rik van
Riel.
Feel free to add my S-O-B for the code I wrote. The rest
looks good, too.
There may be some room for optimization later on, by putting
the most likely branches first, annotating with likely/unlikely,
etc, but I suspect the less likely checks are already towards
the ends of the functions.
Signed-off-by: Rik van Riel <redacted>
quoted hunk
This patch contains the logic for validating several conditions when
performing copy_to_user() and copy_from_user() on the kernel object
being copied to/from:
- address range doesn't wrap around
- address range isn't NULL or zero-allocated (with a non-zero copy
size)
- if on the slab allocator:
- object size must be less than or equal to copy size (when check
is
implemented in the allocator, which appear in subsequent patches)
- otherwise, object must not span page allocations
- if on the stack
- object must not extend before/after the current process task
- object must be contained by the current stack frame (when there
is
arch/build support for identifying stack frames)
- object must not overlap with kernel text
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 7 ++
include/linux/slab.h | 12 +++
include/linux/thread_info.h | 15 +++
mm/Makefile | 4 +
mm/usercopy.c | 239
++++++++++++++++++++++++++++++++++++++++++++
security/Kconfig | 27 +++++
6 files changed, 304 insertions(+)
create mode 100644 mm/usercopy.c
endchoice
+config HAVE_ARCH_LINEAR_KERNEL_MAPPING
+ bool
+ help
+ An architecture should select this if it has a secondary
linear
+ mapping of the kernel text. This is used to verify that
kernel
+ text exposures are not visible under
CONFIG_HARDENED_USERCOPY.
+
config HAVE_CONTEXT_TRACKING
bool
help
void kzfree(const void *);
size_t ksize(const void *);
+#ifdef CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR
+const char *__check_heap_object(const void *ptr, unsigned long n,
+ struct page *page);
+#else
+static inline const char *__check_heap_object(const void *ptr,
+ unsigned long n,
+ struct page *page)
+{
+ return NULL;
+}
+#endif
+
/*
* Some archs want to perform DMA into kmalloc caches and need a
guaranteed
* alignment larger than the alignment of a 64-bit integer.
diff --git a/include/linux/thread_info.h
b/include/linux/thread_info.h
index b4c2a485b28a..a02200db9c33 100644
exposure
+ * and overwrite under many unintended conditions. This code is
based
+ * on PAX_USERCOPY, which is:
+ *
+ * Copyright (C) 2001-2016 PaX Team, Bradley Spengler, Open Source
+ * Security Inc.
+ *
+ * This program is free software; you can redistribute it and/or
modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ */
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <asm/sections.h>
+
+/*
+ * Checks if a given pointer and length is contained by the current
+ * stack frame (if possible).
+ *
+ * 0: not at all on the stack
+ * 1: fully on the stack (when can't do frame-checking)
+ * 2: fully inside the current stack frame
+ * -1: error condition (invalid stack position or bad stack
frame)
+ */
+static noinline int check_stack_object(const void *obj, unsigned
long len)
+{
+ const void * const stack = task_stack_page(current);
+ const void * const stackend = stack + THREAD_SIZE;
+
+#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)
+ const void *frame = NULL;
+ const void *oldframe;
+#endif
+
+ /* Object is not on the stack at all. */
+ if (obj + len <= stack || stackend <= obj)
+ return 0;
+
+ /*
+ * Reject: object partially overlaps the stack (passing the
+ * the check above means at least one end is within the
stack,
+ * so if this check fails, the other end is outside the
stack).
+ */
+ if (obj < stack || stackend < obj + len)
+ return -1;
+
+#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)
+ oldframe = __builtin_frame_address(1);
+ if (oldframe)
+ frame = __builtin_frame_address(2);
+ /*
+ * low ----------------------------------------------> high
+ * [saved bp][saved ip][args][local vars][saved bp][saved
ip]
+ * ^----------------^
+ * allow copies only within here
+ */
+ while (stack <= frame && frame < stackend) {
+ /*
+ * If obj + len extends past the last frame, this
+ * check won't pass and the next frame will be 0,
+ * causing us to bail out and correctly report
+ * the copy as invalid.
+ */
+ if (obj + len <= frame)
+ return obj >= oldframe + 2 * sizeof(void *)
? 2 : -1;
+ oldframe = frame;
+ frame = *(const void * const *)frame;
+ }
+ return -1;
+#else
+ return 1;
+#endif
+}
+
+static void report_usercopy(const void *ptr, unsigned long len,
+ bool to_user, const char *type)
+{
+ pr_emerg("kernel memory %s attempt detected %s %p (%s) (%lu
bytes)\n",
+ to_user ? "exposure" : "overwrite",
+ to_user ? "from" : "to", ptr, type ? : "unknown",
len);
+ dump_stack();
+ do_group_exit(SIGKILL);
+}
+
+/* Returns true if any portion of [ptr,ptr+n) over laps with
[low,high). */
+static bool overlaps(const void *ptr, unsigned long n, unsigned long
low,
+ unsigned long high)
+{
+ unsigned long check_low = (uintptr_t)ptr;
+ unsigned long check_high = check_low + n;
+
+ /* Does not overlap if entirely above or entirely below. */
+ if (check_low >= high || check_high < low)
+ return false;
+
+ return true;
+}
+
+/* Is this address range in the kernel text area? */
+static inline const char *check_kernel_text_object(const void *ptr,
+ unsigned long n)
+{
+ unsigned long textlow = (unsigned long)_stext;
+ unsigned long texthigh = (unsigned long)_etext;
+
+ if (overlaps(ptr, n, textlow, texthigh))
+ return "<kernel text>";
+
+#ifdef HAVE_ARCH_LINEAR_KERNEL_MAPPING
+ /* Check against linear mapping as well. */
+ if (overlaps(ptr, n, (unsigned long)__va(__pa(textlow)),
+ (unsigned long)__va(__pa(texthigh))))
+ return "<linear kernel text>";
+#endif
+
+ return NULL;
+}
+
+static inline const char *check_bogus_address(const void *ptr,
unsigned long n)
+{
+ /* Reject if object wraps past end of memory. */
+ if (ptr + n < ptr)
+ return "<wrapped address>";
+
+ /* Reject if NULL or ZERO-allocation. */
+ if (ZERO_OR_NULL_PTR(ptr))
+ return "<null>";
+
+ return NULL;
+}
+
+static inline const char *check_heap_object(const void *ptr,
unsigned long n)
+{
+ struct page *page, *endpage;
+ const void *end = ptr + n - 1;
+
+ if (!virt_addr_valid(ptr))
+ return NULL;
+
+ page = virt_to_head_page(ptr);
+
+ /* Check slab allocator for flags and size. */
+ if (PageSlab(page))
+ return __check_heap_object(ptr, n, page);
+
+ /* Is the object wholly within one base page? */
+ if (likely(((unsigned long)ptr & (unsigned long)PAGE_MASK)
==
+ ((unsigned long)end & (unsigned long)PAGE_MASK)))
+ return NULL;
+
+ /* Allow if start and end are inside the same compound page.
*/
+ endpage = virt_to_head_page(end);
+ if (likely(endpage == page))
+ return NULL;
+
+ /* Allow special areas, device memory, and sometimes kernel
data. */
+ if (PageReserved(page) && PageReserved(endpage))
+ return NULL;
+
+ /*
+ * Sometimes the kernel data regions are not marked
Reserved. And
+ * sometimes [_sdata,_edata) does not cover rodata and/or
bss,
+ * so check each range explicitly.
+ */
+
+ /* Allow kernel data region (if not marked as Reserved). */
+ if (ptr >= (const void *)_sdata && end <= (const void
*)_edata)
+ return NULL;
+
+ /* Allow kernel rodata region (if not marked as Reserved).
*/
+ if (ptr >= (const void *)__start_rodata &&
+ end <= (const void *)__end_rodata)
+ return NULL;
+
+ /* Allow kernel bss region (if not marked as Reserved). */
+ if (ptr >= (const void *)__bss_start &&
+ end <= (const void *)__bss_stop)
+ return NULL;
+
+ /* Uh oh. The "object" spans several independently allocated
pages. */
+ return "<spans multiple pages>";
+}
+
+/*
+ * Validates that the given object is one of:
+ * - known safe heap object
+ * - known safe stack object
+ * - not in kernel text
+ */
+void __check_object_size(const void *ptr, unsigned long n, bool
to_user)
+{
+ const char *err;
+
+ /* Skip all tests if size is zero. */
+ if (!n)
+ return;
+
+ /* Check for invalid addresses. */
+ err = check_bogus_address(ptr, n);
+ if (err)
+ goto report;
+
+ /* Check for bad heap object. */
+ err = check_heap_object(ptr, n);
+ if (err)
+ goto report;
+
+ /* Check for bad stack object. */
+ switch (check_stack_object(ptr, n)) {
+ case 0:
+ /* Object is not touching the current process stack.
*/
+ break;
+ case 1:
+ case 2:
+ /*
+ * Object is either in the correct frame (when it
+ * is possible to check) or just generally on the
+ * process stack (when frame checking not
available).
+ */
+ return;
+ default:
+ err = "<process stack>";
+ goto report;
+ }
+
+ /* Check for object in kernel to avoid text exposure. */
+ err = check_kernel_text_object(ptr, n);
+ if (!err)
+ return;
+
+report:
+ report_usercopy(ptr, n, to_user, err);
+}
+EXPORT_SYMBOL(__check_object_size);
this low address space will need the permission specific
to the
systems running LSM.
+config HAVE_HARDENED_USERCOPY_ALLOCATOR
+ bool
+ help
+ The heap allocator implements __check_heap_object() for
+ validating memory ranges against heap object sizes in
+ support of CONFIG_HARDENED_USERCOPY.
+
+config HAVE_ARCH_HARDENED_USERCOPY
+ bool
+ help
+ The architecture supports CONFIG_HARDENED_USERCOPY by
+ calling check_object_size() just before performing the
+ userspace copies in the low level implementation of
+ copy_to_user() and copy_from_user().
+
+config HARDENED_USERCOPY
+ bool "Harden memory copies between kernel and userspace"
+ depends on HAVE_ARCH_HARDENED_USERCOPY
+ help
+ This option checks for obviously wrong memory regions when
+ copying memory to/from the kernel (via copy_to_user() and
+ copy_from_user() functions) by rejecting memory ranges
that
+ are larger than the specified heap object, span multiple
+ separately allocates pages, are not on the process stack,
+ or are part of the kernel text. This kills entire classes
+ of heap overflow exploits and similar kernel memory
exposures.
+
source security/selinux/Kconfig
source security/smack/Kconfig
source security/tomoyo/Kconfig
From: Rik van Riel <hidden> Date: 2016-07-07 16:35:41
On Wed, 2016-07-06 at 15:25 -0700, Kees Cook wrote:
+ /* Allow kernel rodata region (if not marked as Reserved).
*/
+ if (ptr >= (const void *)__start_rodata &&
+ end <= (const void *)__end_rodata)
+ return NULL;
One comment here.
__check_object_size gets "to_user" as an argument.
It may make sense to pass that to check_heap_object, and
only allow copy_to_user from rodata, never copy_from_user,
since that section should be read only.
+void __check_object_size(const void *ptr, unsigned long n, bool
to_user)
+{
On Thu, Jul 7, 2016 at 6:07 AM, Mark Rutland [off-list ref] wrote:
Hi,
On Wed, Jul 06, 2016 at 03:25:23PM -0700, Kees Cook wrote:
quoted
Enables CONFIG_HARDENED_USERCOPY checks on arm64. As done by KASAN in -next,
renames the low-level functions to __arch_copy_*_user() so a static inline
can do additional work before the copy.
The checks themselves look fine, but as with the KASAN checks, it seems
a shame that this logic is duplicated per arch, integrated in subtly
different ways.
Can we not __arch prefix all the arch uaccess helpers, and place
kasan_check_*() and check_object_size() calls in generic wrappers?
If we're going to update all the arch uaccess helpers anyway, doing that
would make it easier to fix things up, or to add new checks in future.
Yeah, I totally agree, and my work on the next step of this hardening
will require something like this to separate the "check" logic from
the "copy" logic, as I want to introduce a set of constant-sized
copy_*_user helpers.
Though currently x86 poses a weird problem in this regard (they have
separate code paths for copy_* and __copy*, but I think it's actually
a harmless(?) mistake.
For now, I'd like to leave this as-is, and then do the copy_* cleanup,
then do step 2 (slab whitelisting).
-Kees
--
Kees Cook
Chrome OS & Brillo Security
On Thu, Jul 7, 2016 at 1:37 AM, Baruch Siach [off-list ref] wrote:
Hi Kees,
On Wed, Jul 06, 2016 at 03:25:20PM -0700, Kees Cook wrote:
quoted
+#ifdef CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR
Should be CONFIG_HARDENED_USERCOPY to match the slab/slub implementation
condition.
quoted
+const char *__check_heap_object(const void *ptr, unsigned long n,
+ struct page *page);
+#else
+static inline const char *__check_heap_object(const void *ptr,
+ unsigned long n,
+ struct page *page)
+{
+ return NULL;
+}
+#endif
Hmm, I think what I have is correct: if the allocator supports the
heap object checking, it defines __check_heap_object as existing via
CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR. If usercopy checking is done
at all is controlled by CONFIG_HARDENED_USERCOPY.
I.e. you can have the other usercopy checks even if your allocator
doesn't support object size checking.
-Kees
--
Kees Cook
Chrome OS & Brillo Security
On Thu, Jul 7, 2016 at 3:30 AM, Christian Borntraeger
[off-list ref] wrote:
On 07/07/2016 12:25 AM, Kees Cook wrote:
quoted
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
Was there a reason why you did not change s390?
No reason -- just didn't have a good build setup for testing it.
(Everything but arm64 was already in grsecurity, and I was able to
build-test arm64 when I added it there.) I would love to include s390
too!
-Kees
--
Kees Cook
Chrome OS & Brillo Security
Yeah, I'd like to have this be controlled by a specific CONFIG, like I
invented for the linear mapping, but I wasn't sure what was the best
approach.
quoted
+
+ /* Object is not on the stack at all. */
+ if (obj + len <= stack || stackend <= obj)
+ return 0;
+
+ /*
+ * Reject: object partially overlaps the stack (passing the
+ * the check above means at least one end is within the stack,
+ * so if this check fails, the other end is outside the stack).
+ */
+ if (obj < stack || stackend < obj + len)
+ return -1;
+
+#if defined(CONFIG_FRAME_POINTER) && defined(CONFIG_X86)
+ oldframe = __builtin_frame_address(1);
+ if (oldframe)
+ frame = __builtin_frame_address(2);
+ /*
+ * low ----------------------------------------------> high
+ * [saved bp][saved ip][args][local vars][saved bp][saved ip]
+ * ^----------------^
+ * allow copies only within here
+ */
+ while (stack <= frame && frame < stackend) {
+ /*
+ * If obj + len extends past the last frame, this
+ * check won't pass and the next frame will be 0,
+ * causing us to bail out and correctly report
+ * the copy as invalid.
+ */
+ if (obj + len <= frame)
+ return obj >= oldframe + 2 * sizeof(void *) ? 2 : -1;
+ oldframe = frame;
+ frame = *(const void * const *)frame;
+ }
+ return -1;
+#else
+ return 1;
+#endif
I'd rather make that a weak function returning 1 which can be replaced by
x86 for CONFIG_FRAME_POINTER=y. That also allows other architectures to
implement their specific frame checks.
Yeah, though I prefer CONFIG-controlled stuff over weak functions, but
I agree, something like arch_check_stack_frame(...) or similar. I'll
build something for this on the next revision.
-Kees
--
Kees Cook
Chrome OS & Brillo Security
On Thu, Jul 7, 2016 at 4:01 AM, Arnd Bergmann [off-list ref] wrote:
On Wednesday, July 6, 2016 3:25:20 PM CEST Kees Cook wrote:
quoted
This is the start of porting PAX_USERCOPY into the mainline kernel. This
is the first set of features, controlled by CONFIG_HARDENED_USERCOPY. The
work is based on code by PaX Team and Brad Spengler, and an earlier port
from Casey Schaufler. Additional non-slab page tests are from Rik van Riel.
This patch contains the logic for validating several conditions when
performing copy_to_user() and copy_from_user() on the kernel object
being copied to/from:
- address range doesn't wrap around
- address range isn't NULL or zero-allocated (with a non-zero copy size)
- if on the slab allocator:
- object size must be less than or equal to copy size (when check is
implemented in the allocator, which appear in subsequent patches)
- otherwise, object must not span page allocations
- if on the stack
- object must not extend before/after the current process task
- object must be contained by the current stack frame (when there is
arch/build support for identifying stack frames)
- object must not overlap with kernel text
Signed-off-by: Kees Cook <redacted>
Nice!
I have a few further thoughts, most of which have probably been
considered before:
quoted
+static inline const char *check_bogus_address(const void *ptr, unsigned long n)
+{
+ /* Reject if object wraps past end of memory. */
+ if (ptr + n < ptr)
+ return "<wrapped address>";
+
+ /* Reject if NULL or ZERO-allocation. */
+ if (ZERO_OR_NULL_PTR(ptr))
+ return "<null>";
+
+ return NULL;
+}
This checks against address (void*)16, but I guess on most architectures the
lowest possible kernel address is much higher. While there may not be much
that to exploit if the expected kernel address points to userland, forbidding
any obviously incorrect address that is outside of the kernel may be easier.
Even on architectures like s390 that start the kernel memory at (void *)0x0,
the lowest address to which we may want to do a copy_to_user would be much
higher than (void*)0x16.
Yeah, that's worth exploring, but given the shenanigans around
set_fs(), I'd like to leave this as-is, and we can add to these checks
as we remove as much of the insane usage of set_fs().
quoted
+
+ /* Allow kernel rodata region (if not marked as Reserved). */
+ if (ptr >= (const void *)__start_rodata &&
+ end <= (const void *)__end_rodata)
+ return NULL;
Should we explicitly forbid writing to rodata, or is it enough to
rely on page protection here?
Hm, interesting. That's a very small check to add. My knee-jerk is to
just leave it up to page protection. I'm on the fence. :)
quoted
+ /* Allow kernel bss region (if not marked as Reserved). */
+ if (ptr >= (const void *)__bss_start &&
+ end <= (const void *)__bss_stop)
+ return NULL;
accesses to .data/.rodata/.bss are probably not performance critical,
so we could go further here and check the kallsyms table to ensure
that we are not spanning multiple symbols here.
Oh, interesting! Yeah, would you be willing to put together that patch
and test it? I wonder if there are any cases where there are
legitimate usercopys across multiple symbols.
For stuff that is performance critical, should there be a way to
opt out of the checks, or do we assume it already uses functions
that avoid the checks? I looked at the file and network I/O path
briefly and they seem to use kmap_atomic() to get to the user pages
at least in some of the common cases (but I may well be missing
important ones).
I don't want to start with an exemption here, so until such a case is
found, I'd rather leave this as-is. That said, the primary protection
here tends to be buggy lengths (which is why put/get_user() is
untouched). For constant-sized copies, some checks could be skipped.
In the second part of this protection (what I named
CONFIG_HARDENED_USERCOPY_WHITELIST in the RFC version of this series),
there are cases where we want to skip the whitelist checking since it
is for a constant-sized copy the code understands is okay to pull out
of an otherwise disallowed allocator object.
-Kees
--
Kees Cook
Chrome OS & Brillo Security
On Thu, Jul 7, 2016 at 12:35 PM, Rik van Riel [off-list ref] wrote:
On Wed, 2016-07-06 at 15:25 -0700, Kees Cook wrote:
quoted
+ /* Allow kernel rodata region (if not marked as Reserved).
*/
+ if (ptr >= (const void *)__start_rodata &&
+ end <= (const void *)__end_rodata)
+ return NULL;
One comment here.
__check_object_size gets "to_user" as an argument.
It may make sense to pass that to check_heap_object, and
only allow copy_to_user from rodata, never copy_from_user,
since that section should be read only.
Well, that's two votes for this extra check, but I'm still not sure
since it may already be allowed by the Reserved check, but I can
reorder things to _reject_ on rodata writes before the Reserved check,
etc.
I'll see what could work here...
-Kees
quoted
+void __check_object_size(const void *ptr, unsigned long n, bool
to_user)
+{
Hi Kees,
On Thu, Jul 07, 2016 at 01:25:21PM -0400, Kees Cook wrote:
On Thu, Jul 7, 2016 at 1:37 AM, Baruch Siach [off-list ref] wrote:
quoted
On Wed, Jul 06, 2016 at 03:25:20PM -0700, Kees Cook wrote:
quoted
+#ifdef CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR
Should be CONFIG_HARDENED_USERCOPY to match the slab/slub implementation
condition.
quoted
+const char *__check_heap_object(const void *ptr, unsigned long n,
+ struct page *page);
+#else
+static inline const char *__check_heap_object(const void *ptr,
+ unsigned long n,
+ struct page *page)
+{
+ return NULL;
+}
+#endif
Hmm, I think what I have is correct: if the allocator supports the
heap object checking, it defines __check_heap_object as existing via
CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR. If usercopy checking is done
at all is controlled by CONFIG_HARDENED_USERCOPY.
I.e. you can have the other usercopy checks even if your allocator
doesn't support object size checking.
Right. I missed the fact that usercopy.c build also depends on
CONFIG_HARDENED_USERCOPY. Sorry for the noise.
baruch
--
http://baruch.siach.name/blog/ ~. .~ Tk Open Systems
=}------------------------------------------------ooO--U--Ooo------------{=
- baruch@tkos.co.il - tel: +972.52.368.4656, http://www.tkos.co.il -
From: Thomas Gleixner <hidden> Date: 2016-07-07 19:37:55
On Thu, 7 Jul 2016, Kees Cook wrote:
On Thu, Jul 7, 2016 at 3:42 AM, Thomas Gleixner [off-list ref] wrote:
quoted
I'd rather make that a weak function returning 1 which can be replaced by
x86 for CONFIG_FRAME_POINTER=y. That also allows other architectures to
implement their specific frame checks.
Yeah, though I prefer CONFIG-controlled stuff over weak functions, but
I agree, something like arch_check_stack_frame(...) or similar. I'll
build something for this on the next revision.
I'm fine with CONFIG_CONTROLLED as long as the ifdeffery is limited to header
files.
Thanks,
tglx
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
Could you please try to find some syscall workload that does many small user
copies and thus excercises this code path aggressively?
If that measurement works out fine then I'd prefer to enable these security checks
by default.
Thaks,
Ingo
On Thursday, July 7, 2016 1:37:43 PM CEST Kees Cook wrote:
quoted
quoted
+ /* Allow kernel bss region (if not marked as Reserved). */
+ if (ptr >= (const void *)__bss_start &&
+ end <= (const void *)__bss_stop)
+ return NULL;
accesses to .data/.rodata/.bss are probably not performance critical,
so we could go further here and check the kallsyms table to ensure
that we are not spanning multiple symbols here.
Oh, interesting! Yeah, would you be willing to put together that patch
and test it?
Not at the moment, sorry.
I've given it a closer look and unfortunately realized that kallsyms
today only covers .text and .init.text, so it's currently useless because
those sections are already disallowed.
We could extend kallsyms to also cover all other sections, but doing
that right will likely cause a number of problems (most likely
kallsyms size mismatch) that will have to be debugged first.\
I think it's doable but time-consuming. The check function should
actually be trivial:
static bool usercopy_spans_multiple_symbols(void *ptr, size_t len)
{
unsigned long size, offset;
if (kallsyms_lookup_size_offset((unsigned long)ptr, &size, &offset))
return 0; /* no symbol found or kallsyms disabled */
if (size - offset <= len)
return 0; /* range is within one symbol */
return 1;
}
This part would also be trivial:
but I fear that if you actually try that, things start falling apart
in a big way, so I didn't try ;-)
I wonder if there are any cases where there are
legitimate usercopys across multiple symbols.
The only possible use case I can think of is for reading out the entire
kernel memory from /dev/kmem, but your other checks in here already
define that as illegitimate. On that subject, we probably want to
make CONFIG_DEVKMEM mutually exclusive with CONFIG_HARDENED_USERCOPY.
Arnd
On Fri, Jul 8, 2016 at 1:46 AM, Ingo Molnar [off-list ref] wrote:
Could you please try to find some syscall workload that does many small user
copies and thus excercises this code path aggressively?
Any stat()-heavy path will hit cp_new_stat() very heavily. Think the
usual kind of "traverse the whole tree looking for something". "git
diff" will do it, just checking that everything is up-to-date.
That said, other things tend to dominate.
Linus
On Fri, Jul 8, 2016 at 1:46 AM, Ingo Molnar [off-list ref] wrote:
quoted
Could you please try to find some syscall workload that does many small user
copies and thus excercises this code path aggressively?
Any stat()-heavy path will hit cp_new_stat() very heavily. Think the
usual kind of "traverse the whole tree looking for something". "git
diff" will do it, just checking that everything is up-to-date.
That said, other things tend to dominate.
So I think a cached 'find /usr >/dev/null' might be a good one as well:
triton:~/tip> strace -c find /usr >/dev/null
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
47.09 0.006518 0 254697 newfstatat
26.20 0.003627 0 254795 getdents
14.45 0.002000 0 1147411 fcntl
7.33 0.001014 0 509811 close
3.28 0.000454 0 128220 1 openat
1.52 0.000210 0 128230 fstat
0.27 0.000016 0 12810 write
0.00 0.000000 0 10 read
triton:~/tip> perf stat --repeat 3 -e cycles:u,cycles:k,cycles find /usr >/dev/null
Performance counter stats for 'find /usr' (3 runs):
1,594,437,143 cycles:u ( +- 2.76% )
2,570,544,009 cycles:k ( +- 2.50% )
4,164,981,152 cycles ( +- 2.59% )
0.929883686 seconds time elapsed ( +- 2.57% )
... and it's dominated by kernel overhead, with a fair amount of memcpy overhead
as well:
1.22% find [kernel.kallsyms] [k] copy_user_enhanced_fast_string
But maybe there are simple shell commands that are even more user-memcpy intense?
Thanks,
Ingo
From: Laura Abbott <hidden> Date: 2016-07-09 02:23:06
On 07/06/2016 03:25 PM, Kees Cook wrote:
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86 now).
Even with the SLUB fixup I'm still seeing this blow up on my arm64 system. This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted: G W 4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS 1.1.0 Nov 24 2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>] call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out of town
all of next week so all I have is the report unfortunately. config attached.
Thanks,
Laura
From: Rik van Riel <hidden> Date: 2016-07-09 02:44:23
On Fri, 2016-07-08 at 19:22 -0700, Laura Abbott wrote:
Even with the SLUB fixup I'm still seeing this blow up on my arm64
system. This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted:
G W 4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS
1.1.0 Nov 24 2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>]
call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out
of town
all of next week so all I have is the report unfortunately. config
attached.
That's odd, this should be copying a piece of kernel data (not text)
to userspace.
from fs/binfmt_elf.c
const char *k_platform = ELF_PLATFORM;
...
size_t len = strlen(k_platform) + 1;
u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
if (__copy_to_user(u_platform, k_platform, len))
return -EFAULT;
from arch/arm/include/asm/elf.h:
#define ELF_PLATFORM_SIZE 8
#define ELF_PLATFORM (elf_platform)
extern char elf_platform[];
from arch/arm/kernel/setup.c:
char elf_platform[ELF_PLATFORM_SIZE];
EXPORT_SYMBOL(elf_platform);
...
snprintf(elf_platform, ELF_PLATFORM_SIZE, "%s%c",
list->elf_name, ENDIANNESS);
How does that end up in the .text section of the
image, instead of in one of the various data sections?
What kind of linker oddity is going on with ARM?
--
All Rights Reversed.
On Fri, 2016-07-08 at 19:22 -0700, Laura Abbott wrote:
quoted
Even with the SLUB fixup I'm still seeing this blow up on my arm64
system. This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted:
G W 4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS
1.1.0 Nov 24 2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>]
call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out
of town
all of next week so all I have is the report unfortunately. config
attached.
That's odd, this should be copying a piece of kernel data (not text)
to userspace.
from fs/binfmt_elf.c
const char *k_platform = ELF_PLATFORM;
...
size_t len = strlen(k_platform) + 1;
u_platform = (elf_addr_t __user *)STACK_ALLOC(p, len);
if (__copy_to_user(u_platform, k_platform, len))
return -EFAULT;
from arch/arm/include/asm/elf.h:
#define ELF_PLATFORM_SIZE 8
#define ELF_PLATFORM (elf_platform)
extern char elf_platform[];
from arch/arm/kernel/setup.c:
char elf_platform[ELF_PLATFORM_SIZE];
EXPORT_SYMBOL(elf_platform);
...
snprintf(elf_platform, ELF_PLATFORM_SIZE, "%s%c",
list->elf_name, ENDIANNESS);
How does that end up in the .text section of the
image, instead of in one of the various data sections?
What kind of linker oddity is going on with ARM?
I think the crash happened on ARM64, not ARM.
Thanks,
Ingo
On 9 July 2016 at 04:22, Laura Abbott [off-list ref] wrote:
On 07/06/2016 03:25 PM, Kees Cook wrote:
quoted
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86 now).
Even with the SLUB fixup I'm still seeing this blow up on my arm64 system.
This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted: G W
4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS 1.1.0 Nov 24
2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>] call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out of town
all of next week so all I have is the report unfortunately. config attached.
This is a known issue, and a fix is already queued for v4.8 in the arm64 tree:
9fdc14c55c arm64: mm: fix location of _etext [0]
which moves _etext up in the linker script so that it does not cover .rodata
ARM was suffering from the same problem, and Kees proposed a fix for
it. I don't know what the status of that patch is, though.
Note that on arm64, we have
#define ELF_PLATFORM ("aarch64")
which explains why k_platform points into .rodata in this case. On
ARM, it points to a writable string (as the code quoted by Rik shows),
so there it will likely explode elsewhere without the linker script
fix.
[0] https://git.kernel.org/cgit/linux/kernel/git/arm64/linux.git/commit/?h=for-next/core&id=9fdc14c55c
--
Ard.
From: Laura Abbott <hidden> Date: 2016-07-09 12:58:26
On Sat, Jul 9, 2016 at 1:25 AM, Ard Biesheuvel [off-list ref]
wrote:
On 9 July 2016 at 04:22, Laura Abbott [off-list ref] wrote:
quoted
On 07/06/2016 03:25 PM, Kees Cook wrote:
quoted
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user().
These
quoted
quoted
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS
covers
quoted
quoted
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within
the
quoted
quoted
current stack frame (if such checking is possible) or at least
entirely
quoted
quoted
within the current process's stack. (This could catch large lengths
that
quoted
quoted
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86
now).
quoted
quoted
Even with the SLUB fixup I'm still seeing this blow up on my arm64
system.
quoted
This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted: G W
4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS 1.1.0 Nov
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out of
town
quoted
all of next week so all I have is the report unfortunately. config
attached.
quoted
This is a known issue, and a fix is already queued for v4.8 in the arm64
tree:
9fdc14c55c arm64: mm: fix location of _etext [0]
which moves _etext up in the linker script so that it does not cover
.rodata
ARM was suffering from the same problem, and Kees proposed a fix for
it. I don't know what the status of that patch is, though.
Note that on arm64, we have
#define ELF_PLATFORM ("aarch64")
which explains why k_platform points into .rodata in this case. On
ARM, it points to a writable string (as the code quoted by Rik shows),
so there it will likely explode elsewhere without the linker script
fix.
[0]
https://git.kernel.org/cgit/linux/kernel/git/arm64/linux.git/commit/?h=for-next/core&id=9fdc14c55c
--
Ard.
Ugh, I completely missed that note about the patch on arm64. Sorry for the
noise.
Thanks,
Laura
On Fri, Jul 8, 2016 at 7:22 PM, Laura Abbott [off-list ref] wrote:
On 07/06/2016 03:25 PM, Kees Cook wrote:
quoted
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86 now).
Even with the SLUB fixup I'm still seeing this blow up on my arm64 system.
This is a
Fedora rawhide kernel + the patches
Is this on top of -next? The recent _etext change ("arm64: mm: fix
location of _etext") is needed to fix the kernel text test for arm64.
-Kees
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted: G W
4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS 1.1.0 Nov
24 2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>]
call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out of town
all of next week so all I have is the report unfortunately. config attached.
Thanks,
Laura
On Sat, Jul 9, 2016 at 1:25 AM, Ard Biesheuvel
[off-list ref] wrote:
On 9 July 2016 at 04:22, Laura Abbott [off-list ref] wrote:
quoted
On 07/06/2016 03:25 PM, Kees Cook wrote:
quoted
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
Based on my understanding, PAX_USERCOPY was designed to catch a few
classes of flaws around the use of copy_to_user()/copy_from_user(). These
changes don't touch get_user() and put_user(), since these operate on
constant sized lengths, and tend to be much less vulnerable. There
are effectively three distinct protections in the whole series,
each of which I've given a separate CONFIG, though this patch set is
only the first of the three intended protections. (Generally speaking,
PAX_USERCOPY covers what I'm calling CONFIG_HARDENED_USERCOPY (this) and
CONFIG_HARDENED_USERCOPY_WHITELIST (future), and PAX_USERCOPY_SLABS covers
CONFIG_HARDENED_USERCOPY_SPLIT_KMALLOC (future).)
This series, which adds CONFIG_HARDENED_USERCOPY, checks that objects
being copied to/from userspace meet certain criteria:
- if address is a heap object, the size must not exceed the object's
allocated size. (This will catch all kinds of heap overflow flaws.)
- if address range is in the current process stack, it must be within the
current stack frame (if such checking is possible) or at least entirely
within the current process's stack. (This could catch large lengths that
would have extended beyond the current process stack, or overflows if
their length extends back into the original stack.)
- if the address range is part of kernel data, rodata, or bss, allow it.
- if address range is page-allocated, that it doesn't span multiple
allocations.
- if address is within the kernel text, reject it.
- everything else is accepted
The patches in the series are:
- The core copy_to/from_user() checks, without the slab object checks:
1- mm: Hardened usercopy
- Per-arch enablement of the protection:
2- x86/uaccess: Enable hardened usercopy
3- ARM: uaccess: Enable hardened usercopy
4- arm64/uaccess: Enable hardened usercopy
5- ia64/uaccess: Enable hardened usercopy
6- powerpc/uaccess: Enable hardened usercopy
7- sparc/uaccess: Enable hardened usercopy
- The heap allocator implementation of object size checking:
8- mm: SLAB hardened usercopy support
9- mm: SLUB hardened usercopy support
Some notes:
- This is expected to apply on top of -next which contains fixes for the
position of _etext on both arm and arm64.
- I couldn't detect a measurable performance change with these features
enabled. Kernel build times were unchanged, hackbench was unchanged,
etc. I think we could flip this to "on by default" at some point.
- The SLOB support extracted from grsecurity seems entirely broken. I
have no idea what's going on there, I spent my time testing SLAB and
SLUB. Having someone else look at SLOB would be nice, but this series
doesn't depend on it.
Additional features that would be nice, but aren't blocking this series:
- Needs more architecture support for stack frame checking (only x86 now).
Even with the SLUB fixup I'm still seeing this blow up on my arm64 system.
This is a
Fedora rawhide kernel + the patches
[ 0.666700] usercopy: kernel memory exposure attempt detected from
fffffc0008b4dd58 (<kernel text>) (8 bytes)
[ 0.666720] CPU: 2 PID: 79 Comm: modprobe Tainted: G W
4.7.0-0.rc6.git1.1.hardenedusercopy.fc25.aarch64 #1
[ 0.666733] Hardware name: AppliedMicro Mustang/Mustang, BIOS 1.1.0 Nov 24
2015
[ 0.666744] Call trace:
[ 0.666756] [<fffffc0008088a20>] dump_backtrace+0x0/0x1e8
[ 0.666765] [<fffffc0008088c2c>] show_stack+0x24/0x30
[ 0.666775] [<fffffc0008455344>] dump_stack+0xa4/0xe0
[ 0.666785] [<fffffc000828d874>] __check_object_size+0x6c/0x230
[ 0.666795] [<fffffc00083a5748>] create_elf_tables+0x74/0x420
[ 0.666805] [<fffffc00082fb1f0>] load_elf_binary+0x828/0xb70
[ 0.666814] [<fffffc0008298b4c>] search_binary_handler+0xb4/0x240
[ 0.666823] [<fffffc0008299864>] do_execveat_common+0x63c/0x950
[ 0.666832] [<fffffc0008299bb4>] do_execve+0x3c/0x50
[ 0.666841] [<fffffc00080e3720>] call_usermodehelper_exec_async+0xe8/0x148
[ 0.666850] [<fffffc0008084a80>] ret_from_fork+0x10/0x50
This happens on every call to execve. This seems to be the first
copy_to_user in
create_elf_tables. I didn't get a chance to debug and I'm going out of town
all of next week so all I have is the report unfortunately. config attached.
This is a known issue, and a fix is already queued for v4.8 in the arm64 tree:
9fdc14c55c arm64: mm: fix location of _etext [0]
which moves _etext up in the linker script so that it does not cover .rodata
Oops, I missed this reply, sorry for the redundant answer. :)
ARM was suffering from the same problem, and Kees proposed a fix for
it. I don't know what the status of that patch is, though.
This is also in -next "ARM: 8583/1: mm: fix location of _etext".
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
I like the series, but I have one minor nit to pick. The effect of
this series is to harden usercopy, but most of the code is really
about infrastructure to validate that a pointed-to object is valid.
Might it make sense to call the infrastructure part something else?
After all, this could be extended in the future for memcpy or even for
some GCC plugin to check pointers passed to ordinary (non-allocator)
functions.
Hi,
This is a start of the mainline port of PAX_USERCOPY[1]. After I started
writing tests (now in lkdtm in -next) for Casey's earlier port[2], I
kept tweaking things further and further until I ended up with a whole
new patch series. To that end, I took Rik's feedback and made a number
of other changes and clean-ups as well.
I like the series, but I have one minor nit to pick. The effect of
this series is to harden usercopy, but most of the code is really
about infrastructure to validate that a pointed-to object is valid.
actually USERCOPY has never been about validating pointers. its sole purpose
is to validate the *size* argument of copy*user calls, a very specific form
of runtime bounds checking. it's only really relevant for slab objects and the
pointer checks (that one might mistake for being a part of the defense mechanism)
are only there to determine whether the kernel pointer refers to a slab object
or not (the stack part is a small bonus and was never the main goal either).
Might it make sense to call the infrastructure part something else?
yes, more bikeshedding will surely help, like the renaming of .data..read_only
to .data..ro_after_init which also had nothing to do with init but everything
to do with objects being conceptually read-only...
After all, this could be extended in the future for memcpy or even for
some GCC plugin to check pointers passed to ordinary (non-allocator)
functions.
what kind of checks are you thinking of here? and more fundamentally, against
what kind of threats? as for memcpy, it's the standard mandated memory copying
function, what security related properties can it check on its pointer arguments?
I like the series, but I have one minor nit to pick. The effect of this
series is to harden usercopy, but most of the code is really about
infrastructure to validate that a pointed-to object is valid.
actually USERCOPY has never been about validating pointers. its sole purpose is
to validate the *size* argument of copy*user calls, a very specific form of
runtime bounds checking.
What this code has been about originally is largely immaterial, unless you can
formulate it into a technical argument.
There are a number of cheap tests we can do and there are a number of ways how a
'pointer' can be validated runtime, without any 'size' information:
- for example if a pointer points into a red zone straight away then we know it's
bogus.
- or if a kernel pointer is points outside the valid kernel virtual memory range
we know it's bogus as well.
So while only doing a bounds check might have been the original purpose of the
patch set, Andy's point is that it might make sense to treat this facility as a
more generic 'object validation' code of (pointer,size) object and not limit it to
'runtime bounds checking'. That kind of extended purpose behind a facility should
be reflected in the naming.
Confusing names are often the source of misunderstandings and bugs.
The 9-patch series as submitted here is neither just 'bounds checking' nor just
pure 'pointer checking', it's about validating that a (pointer,size) range of
memory passed to a (user) memory copy function is fully within a valid object the
kernel might know about (in an fast to check fashion).
This necessary means:
- the start of the range points to a valid object to begin with (if known)
- the range itself does not point beyond the end of the object (if known)
- even if the kernel does not know anything about the pointed to object it can
do a pointer check (for example is it pointing inside kernel virtual memory)
and do a bounds check on the size.
Do you disagree with that?
quoted
Might it make sense to call the infrastructure part something else?
yes, more bikeshedding will surely help, [...]
Insulting and ridiculing a reviewer who explicitly qualified his comments with
"one minor nit to pick" sure does not help upstream integration either. (Unless
the goal is to prevent upstream integration.)
[...] like the renaming of .data..read_only to .data..ro_after_init which also
had nothing to do with init but everything to do with objects being conceptually
read-only...
.data..ro_after_init objects get written to during bootup so it's conceptually
quite confusing to name it "read-only" without any clear qualifiers.
That it's named consistently with its role of "read-write before init and read
only after init" on the other hand is not confusing at all. Not sure what your
problem is with the new name.
Names within submitted patches get renamed on a routine basis during review. It's
often only minor improvements in naming (which you can consider bike shedding),
but in this particular case the rename was clearly useful in not just improving
the name but in avoiding an actively confusing name. So I disagree not just with
the hostile tone of your reply but with your underlying technical point as well.
Thanks,
Ingo
I like the series, but I have one minor nit to pick. The effect of this
series is to harden usercopy, but most of the code is really about
infrastructure to validate that a pointed-to object is valid.
actually USERCOPY has never been about validating pointers. its sole purpose is
to validate the *size* argument of copy*user calls, a very specific form of
runtime bounds checking.
What this code has been about originally is largely immaterial, unless you can
formulate it into a technical argument.
we design defense mechanisms for specific and clear purposes, starting with
a threat model, evaluating defense options based on various criteria, etc.
USERCOPY underwent this same process and taking it out of its original context
means that all you get in the end is cargo cult security (wouldn't be the first
time it has happened (ExecShield, ASLR, etc)).
that said, i actually started that discussion but for some reason you chose
not to respond to that one part of my mail so let me ask it again:
what kind of checks are you thinking of here? and more fundamentally, against
what kind of threats?
as far as i'm concerned, a defense mechanism is only as good as its underlying
threat model. by validating pointers (for yet to be stated security related
properties) you're presumably assuming some kind of threat and unless stated
clearly what that threat is (unintended pointer modification through memory
corruption and/or other bugs?) noone can tell whether the proposed defense
mechanism will actually be effective in preventing exploitation. it is the
worst kind of defense that doesn't actually achieve its stated goals, that
way lies false sense of security and i hope noone here is in that business.
i note that this analysis is also missing from this USERCOPY submission except
for stating what Kees assumed about USERCOPY (and apparently noone could be
bothered to read the original Kconfig help of it which clearly states that the
purpose is copy size checking, not some elaborate pointer validation, the latter
is an implementation detail only and is necessary to be able to derive the
underlying slab object's intended size).
There are a number of cheap tests we can do and there are a number of ways how a
'pointer' can be validated runtime, without any 'size' information:
- for example if a pointer points into a red zone straight away then we know it's
bogus.
it's not pointer validation but bounds checking: you already know which memory
object the pointer is supposed to point to, you only check its bounds. if it was
an attacker controlled pointer then all this would be a pointless check of course,
trivial for an attacker to circumvent (and this is why it's not part of the
USERCOPY design).
- or if a kernel pointer is points outside the valid kernel virtual memory range
we know it's bogus as well.
accesses outside of valid virtual memory will cause a page fault ('oops' in linux
terms), there's no need to explicitly check for that.
So while only doing a bounds check might have been the original purpose of the
patch set, Andy's point is that it might make sense to treat this facility as a
more generic 'object validation' code of (pointer,size) object and not limit it to
'runtime bounds checking'.
FYI, 'runtime bounds checking' is a terminus technicus and it is about validating
both the pointer and underlying object's size. that's the reason i called USERCOPY
a 'very specific form' of it only since it doesn't validate each part equally well
(or well enough at all, even the size check is not as precise as it could be).
as for what does or doesn't make sense, first you'll have to define a threat
model and evaluate everything else based on that. since noone has solved the
general bounds checking problem with acceptable properties (mostly performance
impact, but also memory overhead, etc), i'm all ears to hear what you guys have
come up with.
That kind of extended purpose behind a facility should be reflected in the naming.
Confusing names are often the source of misunderstandings and bugs.
definitely, but before you bikeshed on naming, you should figure out what and why
you want to do, whether it's even feasible, meaningful, useful, etc. answering the
opening question and digging into the details is the first step of any design
process, not its naming.
The 9-patch series as submitted here is neither just 'bounds checking' nor just
pure 'pointer checking', it's about validating that a (pointer,size) range of
memory passed to a (user) memory copy function is fully within a valid object the
kernel might know about (in an fast to check fashion).
This necessary means:
- the start of the range points to a valid object to begin with (if known)
- the range itself does not point beyond the end of the object (if known)
- even if the kernel does not know anything about the pointed to object it can
do a pointer check (for example is it pointing inside kernel virtual memory)
and do a bounds check on the size.
Do you disagree with that?
as i explained above, you're confusing implementation with design: USERCOPY is
about size checking, not pointer validation. if you want to do the latter as well,
you'll have to first define a threat model, etc. so the answer is 'it depends'
but as the current implementation stands, it's circumventible if an attacker
can control the pointer (which has to be assumed otherwise there's no reason
to validate the pointer, right?).
quoted
quoted
Might it make sense to call the infrastructure part something else?
yes, more bikeshedding will surely help, [...]
Insulting and ridiculing a reviewer who explicitly qualified his comments with
"one minor nit to pick" sure does not help upstream integration either.
sorry Ingo, but calling a spade a spade isn't insulting, at best it's exposing
some painful truth. you yourself used that term several times in the past, were
you insulting and ridiculing people then?
as for the ad hominem that you displayed here and later, i hope that in the
future you will display the same professional conduct that you apparently expect
from others.
(Unless the goal is to prevent upstream integration.)
not sure how a properly licensed patch can be prevented from such integration
(as long as you comply with the license, e.g., acknowledge our copyright), but
i'll voice my opinion when you guys are about to screw it up (as it happened in
the past and apparently history keeps repeating itself). if you don't want my
opinion then don't ask for it (in that case we'll write a blog at most ;).
quoted
[...] like the renaming of .data..read_only to .data..ro_after_init which also
had nothing to do with init but everything to do with objects being conceptually
read-only...
.data..ro_after_init objects get written to during bootup so it's conceptually
quite confusing to name it "read-only" without any clear qualifiers.
That it's named consistently with its role of "read-write before init and read
only after init" on the other hand is not confusing at all. Not sure what your
problem is with the new name.
the new name reflects a complete misunderstanding of the PaX feature it was based
on (typical case of cargo cult security). in particular, the __read_only facility
in PaX is part of a defense mechanism that attempts to solve a specific problem
(like everything else) and that problem has nothing whatsoever to do with what
happens before/after the kernel init process. enforcing read-ony kernel memory at
the end of kernel initialization is an implementation detail only and wasn't even
true always (and still isn't true for kernel modules for example): in the linux 2.4
days PaX actually enforced read-only kernel memory properties in startup_32 already
but i relaxed that for the 2.6+ port as the maintenance cost (finding out and
handling new exceptional cases) wasn't worth it.
also naming things after their implementation is poor taste and can result in
even bigger problems down the line since as soon as the implementation changes,
you will have a flag day or have to keep a bad name. this is a lesson that the
REFCOUNT submission will learn too since the kernel's atomic*_t types (an
implementation detail) are used extensively for different purposes, instead of
using specialized types (kref is a good example of that). for .data..ro_after_init
the lesson will happen when you try to add back the remaining pieces from PaX,
such as module handling and not-always-const-in-the-C-sense objects and associated
accessors.
cheers,
PaX Team
From: Andy Lutomirski <luto@amacapital.net> Date: 2016-07-10 12:38:56
On Sun, Jul 10, 2016 at 5:03 AM, PaX Team [off-list ref] wrote:
On 10 Jul 2016 at 11:16, Ingo Molnar wrote:
quoted
* PaX Team [off-list ref] wrote:
quoted
On 9 Jul 2016 at 14:27, Andy Lutomirski wrote:
quoted
I like the series, but I have one minor nit to pick. The effect of this
series is to harden usercopy, but most of the code is really about
infrastructure to validate that a pointed-to object is valid.
actually USERCOPY has never been about validating pointers. its sole purpose is
to validate the *size* argument of copy*user calls, a very specific form of
runtime bounds checking.
What this code has been about originally is largely immaterial, unless you can
formulate it into a technical argument.
we design defense mechanisms for specific and clear purposes, starting with
a threat model, evaluating defense options based on various criteria, etc.
USERCOPY underwent this same process and taking it out of its original context
means that all you get in the end is cargo cult security (wouldn't be the first
time it has happened (ExecShield, ASLR, etc)).
that said, i actually started that discussion but for some reason you chose
not to respond to that one part of my mail so let me ask it again:
what kind of checks are you thinking of here? and more fundamentally, against
what kind of threats?
as far as i'm concerned, a defense mechanism is only as good as its underlying
threat model. by validating pointers (for yet to be stated security related
properties) you're presumably assuming some kind of threat and unless stated
clearly what that threat is (unintended pointer modification through memory
corruption and/or other bugs?) noone can tell whether the proposed defense
mechanism will actually be effective in preventing exploitation. it is the
worst kind of defense that doesn't actually achieve its stated goals, that
way lies false sense of security and i hope noone here is in that business.
I'm imaging security bugs that involve buffer length corruption but
that don't call copy_to/from_user. Hardened usercopy shuts
expoitation down if the first use of the corrupt size is
copy_to/from_user or similar. I bet that a bit better coverage could
be achieved by instrumenting more functions.
To be clear: I'm not objecting to calling the overall feature hardened
usercopy or similar. I object to
CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR. That feature is *used* for
hardened usercopy but is not, in and of itself, a usercopy thing.
It's an object / memory range validation thing. So we'll feel silly
down the road if we use it for something else and the config option
name has nothing to do with the feature.
quoted
quoted
[...] like the renaming of .data..read_only to .data..ro_after_init which also
had nothing to do with init but everything to do with objects being conceptually
read-only...
.data..ro_after_init objects get written to during bootup so it's conceptually
quite confusing to name it "read-only" without any clear qualifiers.
That it's named consistently with its role of "read-write before init and read
only after init" on the other hand is not confusing at all. Not sure what your
problem is with the new name.
the new name reflects a complete misunderstanding of the PaX feature it was based
on (typical case of cargo cult security). in particular, the __read_only facility
in PaX is part of a defense mechanism that attempts to solve a specific problem
(like everything else) and that problem has nothing whatsoever to do with what
happens before/after the kernel init process. enforcing read-ony kernel memory at
the end of kernel initialization is an implementation detail only and wasn't even
true always (and still isn't true for kernel modules for example): in the linux 2.4
days PaX actually enforced read-only kernel memory properties in startup_32 already
but i relaxed that for the 2.6+ port as the maintenance cost (finding out and
handling new exceptional cases) wasn't worth it.
also naming things after their implementation is poor taste and can result in
even bigger problems down the line since as soon as the implementation changes,
you will have a flag day or have to keep a bad name. this is a lesson that the
REFCOUNT submission will learn too since the kernel's atomic*_t types (an
implementation detail) are used extensively for different purposes, instead of
using specialized types (kref is a good example of that). for .data..ro_after_init
the lesson will happen when you try to add back the remaining pieces from PaX,
such as module handling and not-always-const-in-the-C-sense objects and associated
accessors.
The name is related to how the thing works. If I understand
correctly, in PaX, the idea is to make some things readonly and use
pax_open_kernel(), etc to write it as needed. This is a nifty
mechanism, but it's *not* what .data..ro_after_init does upstream. If
I mark something __ro_after_init, then I can write it freely during
boot, but I can't write it thereafter. In contrast, if I put
something in .rodata (using 'const', for example), then I must not
write it *at all* unless I use special helpers (kmap, pax_open_kernel,
etc). So the practical effect from a programer's perspective of
__ro_after_init is quite different from .rodata, and I think the names
should reflect that.
(And yes, the upstream kernel should soon have __ro_after_init working
in modules. And the not-always-const-in-the-C-sense objects using
accessors will need changes to add those accessors, and we can and
should change the annotation on the object itself at the same time.
But if I mark something __ro_after_init, I can write it using normal C
during init, and there's nothing wrong with that.)
--Andy
On Sun, Jul 10, 2016 at 8:03 AM, PaX Team [off-list ref] wrote:
i note that this analysis is also missing from this USERCOPY submission except
for stating what Kees assumed about USERCOPY (and apparently noone could be
bothered to read the original Kconfig help of it which clearly states that the
purpose is copy size checking, not some elaborate pointer validation, the latter
is an implementation detail only and is necessary to be able to derive the
underlying slab object's intended size).
I read the Kconfig text, but it's not entirely accurate. While size is
being checked, it's all nonsense without also the address, so it's
really an object checker. The original design intent may have been the
slab size checks, but it grew beyond that (both within PaX and within
Grsecurity which explicitly added the check for pointers into kernel
text).
I'm just trying to explain as fully as possible what the resulting
code does and why.
it's not pointer validation but bounds checking: you already know which memory
object the pointer is supposed to point to, you only check its bounds. if it was
an attacker controlled pointer then all this would be a pointless check of course,
trivial for an attacker to circumvent (and this is why it's not part of the
USERCOPY design).
Agreed: but the pointer is being checked to attempt to figure out what
KIND of object is being copied. It is part of the logic. If it helps
people understand it more clearly, I can describe them as separate
steps: identify the object type, then perform bounds checking of the
size on that type.
quoted
quoted
yes, more bikeshedding will surely help, [...]
Insulting and ridiculing a reviewer who explicitly qualified his comments with
"one minor nit to pick" sure does not help upstream integration either.
sorry Ingo, but calling a spade a spade isn't insulting, at best it's exposing
some painful truth. you yourself used that term several times in the past, were
you insulting and ridiculing people then?
as for the ad hominem that you displayed here and later, i hope that in the
future you will display the same professional conduct that you apparently expect
from others.
There's a long history of misunderstanding and miscommunication
(intentional or otherwise) by everyone on these topics. I'd love it if
we can just side-step all of it, and try to stick as closely to the
technical discussions as possible. Everyone involved in these
discussions wants better security, even if we go about it in different
ways. If anyone finds themselves feeling insulted, just try to let it
go, and focus on the places where we can find productive common
ground, remembering that any fighting just distracts from the more
important issues at hand.
i'll voice my opinion when you guys are about to screw it up (as it happened in
the past and apparently history keeps repeating itself). if you don't want my
opinion then don't ask for it (in that case we'll write a blog at most ;).
I am hugely interested in your involvement in these discussions:
you're by far the most knowledgeable about them. You generally give
very productive feedback, and for that I'm thankful. I prefer that to
just saying something is wrong/broken without any actionable
follow-up. :)
quoted
quoted
[...] like the renaming of .data..read_only to .data..ro_after_init which also
had nothing to do with init but everything to do with objects being conceptually
read-only...
.data..ro_after_init objects get written to during bootup so it's conceptually
quite confusing to name it "read-only" without any clear qualifiers.
That it's named consistently with its role of "read-write before init and read
only after init" on the other hand is not confusing at all. Not sure what your
problem is with the new name.
the new name reflects a complete misunderstanding of the PaX feature it was based
on (typical case of cargo cult security). in particular, the __read_only facility
in PaX is part of a defense mechanism that attempts to solve a specific problem
(like everything else) and that problem has nothing whatsoever to do with what
happens before/after the kernel init process. enforcing read-ony kernel memory at
the end of kernel initialization is an implementation detail only and wasn't even
true always (and still isn't true for kernel modules for example): in the linux 2.4
days PaX actually enforced read-only kernel memory properties in startup_32 already
but i relaxed that for the 2.6+ port as the maintenance cost (finding out and
handling new exceptional cases) wasn't worth it.
Part of getting protections into upstream is doing them in ways that
make them palatable for incremental work. As it happened, the
read-after-init piece of the larger read-only attack surface reduction
effort was small enough to make it in. As more work is done, we can
continue to build on it.
Making rodata read-only before mark_rodata() is part of my longer goal
since other architectures (e.g. s390) already do this, and is
technically the more correct thing to do: rodata should start its life
read-only. It's a weird hack that it is delayed at all.
also naming things after their implementation is poor taste and can result in
even bigger problems down the line since as soon as the implementation changes,
On the surface, I don't disagree, but as upstream is a large-scale
collaborative effort, I tend to focus on what things are specifically
critical, and naming isn't one of them. :)
you will have a flag day or have to keep a bad name. this is a lesson that the
REFCOUNT submission will learn too since the kernel's atomic*_t types (an
implementation detail) are used extensively for different purposes, instead of
using specialized types (kref is a good example of that).
Right, and I think part of this is a failure of documentation and
examples. As we make progress with REFCOUNT, we can learn about the
best way to approach these kinds of larger tree-wide changes under the
constraints of the existing upstream development process.
For .data..ro_after_init
the lesson will happen when you try to add back the remaining pieces from PaX,
such as module handling and not-always-const-in-the-C-sense objects and associated
accessors.
Do you mean the rest of the KERNEXEC (hopefully I'm not confusing
implementation names) code that uses pax_open/close_kernel()? I expect
that to be a gradual addition too, and I'd love participation to get
it and the constify plugin into the kernel.
-Kees
--
Kees Cook
Chrome OS & Brillo Security
On Sun, Jul 10, 2016 at 8:38 AM, Andy Lutomirski [off-list ref] wrote:
On Sun, Jul 10, 2016 at 5:03 AM, PaX Team [off-list ref] wrote:
quoted
On 10 Jul 2016 at 11:16, Ingo Molnar wrote:
quoted
* PaX Team [off-list ref] wrote:
quoted
On 9 Jul 2016 at 14:27, Andy Lutomirski wrote:
quoted
I like the series, but I have one minor nit to pick. The effect of this
series is to harden usercopy, but most of the code is really about
infrastructure to validate that a pointed-to object is valid.
actually USERCOPY has never been about validating pointers. its sole purpose is
to validate the *size* argument of copy*user calls, a very specific form of
runtime bounds checking.
What this code has been about originally is largely immaterial, unless you can
formulate it into a technical argument.
we design defense mechanisms for specific and clear purposes, starting with
a threat model, evaluating defense options based on various criteria, etc.
USERCOPY underwent this same process and taking it out of its original context
means that all you get in the end is cargo cult security (wouldn't be the first
time it has happened (ExecShield, ASLR, etc)).
that said, i actually started that discussion but for some reason you chose
not to respond to that one part of my mail so let me ask it again:
what kind of checks are you thinking of here? and more fundamentally, against
what kind of threats?
as far as i'm concerned, a defense mechanism is only as good as its underlying
threat model. by validating pointers (for yet to be stated security related
properties) you're presumably assuming some kind of threat and unless stated
clearly what that threat is (unintended pointer modification through memory
corruption and/or other bugs?) noone can tell whether the proposed defense
mechanism will actually be effective in preventing exploitation. it is the
worst kind of defense that doesn't actually achieve its stated goals, that
way lies false sense of security and i hope noone here is in that business.
I'm imaging security bugs that involve buffer length corruption but
that don't call copy_to/from_user. Hardened usercopy shuts
expoitation down if the first use of the corrupt size is
copy_to/from_user or similar. I bet that a bit better coverage could
be achieved by instrumenting more functions.
To be clear: I'm not objecting to calling the overall feature hardened
usercopy or similar. I object to
CONFIG_HAVE_HARDENED_USERCOPY_ALLOCATOR. That feature is *used* for
hardened usercopy but is not, in and of itself, a usercopy thing.
It's an object / memory range validation thing. So we'll feel silly
down the road if we use it for something else and the config option
name has nothing to do with the feature.
Well, the CONFIG_HAVE* stuff is almost entirely invisible to the
end-user, and I feel like it's better to be specific about names now,
and when they change their meaning, we can change their names with it.
I intend to extend the HARDENED_USERCOPY logic in similar ways to how
it is extended in Grsecurity: parts can be used for the "is this
destined for a userspace memory buffer?" test when rejecting writing
pointers or other sensitive information during sprintf (see the
HIDESYM work in grsecurity).
But, I don't like to over-think it: right now, it is named for what it
does, and we can adjust as we need to.
quoted
quoted
quoted
[...] like the renaming of .data..read_only to .data..ro_after_init which also
had nothing to do with init but everything to do with objects being conceptually
read-only...
.data..ro_after_init objects get written to during bootup so it's conceptually
quite confusing to name it "read-only" without any clear qualifiers.
That it's named consistently with its role of "read-write before init and read
only after init" on the other hand is not confusing at all. Not sure what your
problem is with the new name.
the new name reflects a complete misunderstanding of the PaX feature it was based
on (typical case of cargo cult security). in particular, the __read_only facility
in PaX is part of a defense mechanism that attempts to solve a specific problem
(like everything else) and that problem has nothing whatsoever to do with what
happens before/after the kernel init process. enforcing read-ony kernel memory at
the end of kernel initialization is an implementation detail only and wasn't even
true always (and still isn't true for kernel modules for example): in the linux 2.4
days PaX actually enforced read-only kernel memory properties in startup_32 already
but i relaxed that for the 2.6+ port as the maintenance cost (finding out and
handling new exceptional cases) wasn't worth it.
also naming things after their implementation is poor taste and can result in
even bigger problems down the line since as soon as the implementation changes,
you will have a flag day or have to keep a bad name. this is a lesson that the
REFCOUNT submission will learn too since the kernel's atomic*_t types (an
implementation detail) are used extensively for different purposes, instead of
using specialized types (kref is a good example of that). for .data..ro_after_init
the lesson will happen when you try to add back the remaining pieces from PaX,
such as module handling and not-always-const-in-the-C-sense objects and associated
accessors.
The name is related to how the thing works. If I understand
correctly, in PaX, the idea is to make some things readonly and use
pax_open_kernel(), etc to write it as needed. This is a nifty
mechanism, but it's *not* what .data..ro_after_init does upstream. If
I mark something __ro_after_init, then I can write it freely during
boot, but I can't write it thereafter. In contrast, if I put
something in .rodata (using 'const', for example), then I must not
write it *at all* unless I use special helpers (kmap, pax_open_kernel,
etc). So the practical effect from a programer's perspective of
__ro_after_init is quite different from .rodata, and I think the names
should reflect that.
I expect that if/when we add the open/close_kernel logic, we'll have a
new section and it will be named accordingly (since it, too, is not
const-in-the-C-sense, and shouldn't live in the standard .rodata
section).
(And yes, the upstream kernel should soon have __ro_after_init working
in modules. And the not-always-const-in-the-C-sense objects using
accessors will need changes to add those accessors, and we can and
should change the annotation on the object itself at the same time.
But if I mark something __ro_after_init, I can write it using normal C
during init, and there's nothing wrong with that.)