This is take 2 of an RFC series to demonstrate a possible infrastructure
for the "write rarely" memory storage type in the kernel (patch 1). The
intent is to further reduce the internal attack surface of the kernel
by making more variables read-only while "at rest". This is heavily
based on the "__read_only" portion of the KERNEXEC infrastructure from
PaX/grsecurity, though I tried to adjust it to be more in line with
the upstream discussions around the APIs.
Also included is the PaX/grsecurity constify plugin (patch 10) which will
automatically make all instances of certain structures read-only, to help
demonstrate more complex cases of "write rarely" targets. (The plugin in
this series is altered to only operate on marked structures, rather than
the full automatic constification.)
As part of the series I've included both x86 support (patch 4), exactly
as done in PaX, and ARM support (patches 5-7), similar to what is done in
grsecurity but without support for earlier ARM CPUs. Both are lightly
tested by me, though they need a bit more work, especially ARM as it is
missing the correct domain marking for kernel modules.
I've added an lkdtm test (patch 2), which serves as a stand-alone example
of the new infrastructure.
Included are two example "conversions" to the rare_write()-style of
variable manipulation: a simple one, which switches the inet diag handler
table to write-rarely during register/unregister calls (patch 3), and
a more complex one: cgroup types (patch 11), which is made read-only via
the constify plugin. The latter uses rare-write linked lists (patch 9)
and multi-field updates. Both examples are refactorings of what already
appears in PaX/grsecurity.
The patches are:
[PATCH 01/11] Introduce rare_write() infrastructure
[PATCH 02/11] lkdtm: add test for rare_write() infrastructure
[PATCH 03/11] net: switch sock_diag handlers to rare_write()
[PATCH 04/11] x86: Implement __arch_rare_write_begin/unmap()
[PATCH 05/11] ARM: mm: dump: Add domain to output
[PATCH 06/11] ARM: domains: Extract common USER domain init
[PATCH 07/11] ARM: mm: set DOMAIN_WR_RARE for rodata
[PATCH 08/11] ARM: Implement __arch_rare_write_begin/unmap()
[PATCH 09/11] list: add rare_write() list helpers
[PATCH 10/11] gcc-plugins: Add constify plugin
[PATCH 11/11] cgroups: force all struct cftype const
-Kees
@@ -20,12 +20,15 @@/* This is non-const, so it will end up in the .data section. */staticu8data_area[EXEC_SIZE];-/* This is cost, so it will end up in the .rodata section. */+/* This is const, so it will end up in the .rodata section. */staticconstunsignedlongrodata=0xAA55AA55;/* This is marked __ro_after_init, so it should ultimately be .rodata. */staticunsignedlongro_after_init__ro_after_init=0x55AA5500;+/* This is marked __wr_rare, so it should ultimately be .rodata. */+staticunsignedlongwr_rare__wr_rare=0xAA66AA66;+/**Thisjustreturnstothecaller.Itisdesignedtobecopiedinto*non-executablememoryregions.
@@ -103,6 +106,20 @@ void lkdtm_WRITE_RO_AFTER_INIT(void)*ptr^=0xabcd1234;}+voidlkdtm_WRITE_RARE_WRITE(void)+{+/* Explicitly cast away "const" for the test. */+unsignedlong*ptr=(unsignedlong*)&wr_rare;++pr_info("attempting good rare write at %p\n",ptr);+rare_write(*ptr,0x11335577);+if(wr_rare!=0x11335577)+pr_warn("Yikes: wr_rare did not actually change!\n");++pr_info("attempting bad rare write at %p\n",ptr);+*ptr^=0xbcd12345;+}+voidlkdtm_WRITE_KERN(void){size_tsize;
[...]
+/* This is marked __wr_rare, so it should ultimately be .rodata. */
+static unsigned long wr_rare __wr_rare = 0xAA66AA66;
[...]
+void lkdtm_WRITE_RARE_WRITE(void)
+{
+ /* Explicitly cast away "const" for the test. */
wr_rare isn't actually declared const above though? I don't think
__wr_rare includes a const, apologies if I missed it.
OOI, if wr_rare _were_ const then can the compiler optimise the a pair
of reads spanning the rare_write? i.e. adding const to the declaration
above to get:
static const unsigned long wr_rare __wr_rare = 0xAA66AA66;
x = wr_read;
rare_write(x, 0xf000baaa);
y = wr_read;
Is it possible that x == y == 0xaa66aa66 because gcc realises the x and
y came from the same const location? Have I missed a clobber somewhere
(I can't actually find a definition of __arch_rare_write_memcpy in this
series so maybe it's there), or is such code expected to always cast
away the const first?
I suppose such constructs are rare in practice in the sorts of places
where rare_write is appropriate, but with aggressive inlining it could
occur as an unexpected trap for the unwary perhaps.
Ian.
[...]
+/* This is marked __wr_rare, so it should ultimately be .rodata. */
+static unsigned long wr_rare __wr_rare = 0xAA66AA66;
[...]
+void lkdtm_WRITE_RARE_WRITE(void)
+{
+ /* Explicitly cast away "const" for the test. */
wr_rare isn't actually declared const above though? I don't think
__wr_rare includes a const, apologies if I missed it.
Yeah, good point. I think this was a left-over from an earlier version
where I'd forgotten about that detail.
OOI, if wr_rare _were_ const then can the compiler optimise the a pair
of reads spanning the rare_write? i.e. adding const to the declaration
above to get:
static const unsigned long wr_rare __wr_rare = 0xAA66AA66;
x = wr_read;
rare_write(x, 0xf000baaa);
y = wr_read;
Is it possible that x == y == 0xaa66aa66 because gcc realises the x and
y came from the same const location? Have I missed a clobber somewhere
(I can't actually find a definition of __arch_rare_write_memcpy in this
series so maybe it's there), or is such code expected to always cast
away the const first?
I suppose such constructs are rare in practice in the sorts of places
where rare_write is appropriate, but with aggressive inlining it could
occur as an unexpected trap for the unwary perhaps.
Right, __wr_rare is actually marked as .data..ro_after_init, which gcc
effectively ignores (thinking it's part of .data), but the linker
script later movies this section into the read-only portion with
.rodata. As a result, the compiler treats it as writable, but the
storage location is actually read-only.
(And, AIUI, the constify plugin makes things read-only in a similar
way, though I think it's more subtle but still avoids the
const-optimization dangers.)
-Kees
--
Kees Cook
Pixel Security
Several types of data storage exist in the kernel: read-write data (.data,
.bss), read-only data (.rodata), and RO-after-init. This introduces the
infrastructure for another type: write-rarely, which is intended for data
that is either only rarely modified or especially security-sensitive. The
goal is to further reduce the internal attack surface of the kernel by
making this storage read-only when "at rest". This makes it much harder
to be subverted by attackers who have a kernel-write flaw, since they
cannot directly change these memory contents.
This work is heavily based on PaX and grsecurity's pax_{open,close}_kernel
API, its __read_only annotations, its constify plugin, and the work done
to identify sensitive structures that should be moved from .data into
.rodata. This builds the initial infrastructure to support these kinds
of changes, though the API and naming has been adjusted in places for
clarity and maintainability.
Variables declared with the __wr_rare annotation will be moved to the
.rodata section if an architecture supports CONFIG_HAVE_ARCH_WRITE_RARE.
To change these variables, either a single rare_write() macro can be used,
or multiple uses of __rare_write(), wrapped in a matching pair of
rare_write_begin() and rare_write_end() macros can be used. These macros
are expanded into the arch-specific functions that perform the actions
needed to write to otherwise read-only memory.
As detailed in the Kconfig help, the arch-specific helpers have several
requirements to make them sensible/safe for use by the kernel: they must
not allow non-current CPUs to write the memory area, they must run
non-preemptible to avoid accidentally leaving memory writable, and must
be inline to avoid making them desirable ROP targets for attackers.
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 25 +++++++++++++++++++++++++
include/linux/compiler.h | 32 ++++++++++++++++++++++++++++++++
include/linux/preempt.h | 6 ++++--
3 files changed, 61 insertions(+), 2 deletions(-)
Of course, only after sending this do I realize that the MEMCPY case
will need to be further adjusted, since it currently can't take
literals. I guess something like this needs to be done:
#define __rare_write(var, val) ({ \
typeof(var) __src = (val); \
__rare_write_n(&(var), &(__src), sizeof(var)); \
})
-Kees
--
Kees Cook
Pixel Security
Of course, only after sending this do I realize that the MEMCPY case
will need to be further adjusted, since it currently can't take
literals. I guess something like this needs to be done:
#define __rare_write(var, val) ({ \
typeof(var) __src = (val); \
__rare_write_n(&(var), &(__src), sizeof(var)); \
})
Right, and it has a problem with BUILD_BUG, which causes compilation error when CONFIG_HABE_ARCH_RARE_WRITE_MEMCPY is true
BUILD_BUG is defined in <linux/bug.h> but <linux/bug.h> includes <linux/compiler.h>
Please see the following.
Of course, only after sending this do I realize that the MEMCPY case
will need to be further adjusted, since it currently can't take
literals. I guess something like this needs to be done:
#define __rare_write(var, val) ({ \
typeof(var) __src = (val); \
__rare_write_n(&(var), &(__src), sizeof(var)); \
})
Right, and it has a problem with BUILD_BUG, which causes compilation error when CONFIG_HABE_ARCH_RARE_WRITE_MEMCPY is true
BUILD_BUG is defined in <linux/bug.h> but <linux/bug.h> includes <linux/compiler.h>
Please see the following.
On 30 Mar 2017, at 3:15 AM, Kees Cook [off-list ref] wrote:
Several types of data storage exist in the kernel: read-write data (.data,
.bss), read-only data (.rodata), and RO-after-init. This introduces the
infrastructure for another type: write-rarely, which is intended for data
that is either only rarely modified or especially security-sensitive. The
goal is to further reduce the internal attack surface of the kernel by
making this storage read-only when "at rest". This makes it much harder
to be subverted by attackers who have a kernel-write flaw, since they
cannot directly change these memory contents.
This work is heavily based on PaX and grsecurity's pax_{open,close}_kernel
API, its __read_only annotations, its constify plugin, and the work done
to identify sensitive structures that should be moved from .data into
.rodata. This builds the initial infrastructure to support these kinds
of changes, though the API and naming has been adjusted in places for
clarity and maintainability.
Variables declared with the __wr_rare annotation will be moved to the
.rodata section if an architecture supports CONFIG_HAVE_ARCH_WRITE_RARE.
To change these variables, either a single rare_write() macro can be used,
or multiple uses of __rare_write(), wrapped in a matching pair of
rare_write_begin() and rare_write_end() macros can be used. These macros
are expanded into the arch-specific functions that perform the actions
needed to write to otherwise read-only memory.
As detailed in the Kconfig help, the arch-specific helpers have several
requirements to make them sensible/safe for use by the kernel: they must
not allow non-current CPUs to write the memory area, they must run
non-preemptible to avoid accidentally leaving memory writable, and must
be inline to avoid making them desirable ROP targets for attackers.
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 25 +++++++++++++++++++++++++
include/linux/compiler.h | 32 ++++++++++++++++++++++++++++++++
include/linux/preempt.h | 6 ++++--
3 files changed, 61 insertions(+), 2 deletions(-)
config ARCH_WANT_RELAX_ORDER
bool
+config HAVE_ARCH_RARE_WRITE
+ def_bool n
+ help
+ An arch should select this option if it has defined the functions
+ __arch_rare_write_begin() and __arch_rare_write_end() to
+ respectively enable and disable writing to read-only memory. The
+ routines must meet the following requirements:
+ - read-only memory writing must only be available on the current
+ CPU (to make sure other CPUs can't race to make changes too).
+ - the routines must be declared inline (to discourage ROP use).
+ - the routines must not be preemptible (likely they will call
+ preempt_disable() and preempt_enable_no_resched() respectively).
+ - the routines must validate expected state (e.g. when enabling
+ writes, BUG() if writes are already be enabled).
+
+config HAVE_ARCH_RARE_WRITE_MEMCPY
+ def_bool n
+ depends on HAVE_ARCH_RARE_WRITE
+ help
+ An arch should select this option if a special accessor is needed
+ to write to otherwise read-only memory, defined by the function
+ __arch_rare_write_memcpy(). Without this, the write-rarely
+ infrastructure will just attempt to write directly to the memory
+ using a const-ignoring assignment.
+
source "kernel/gcov/Kconfig"
How about we have a separate header file splitting section annotations and the actual APIs.
include/linux/compiler.h:
__wr_rare
__wr_rare_type
include/linux/rare_write.h:
__rare_write_n()
__rare_write()
rare_write_begin()
rare_write_end()
OR moving all of them to include/linux/rare_write.h.
I?m writing the arm64 port for rare_write feature and I?ve stucked in some header problems for the next version of the patch.
I need some other mmu related APIs (mostly defined in `arch/arm64/include/asm/mmu_context.h`) to implement those helpers.
but I cannot include the header in `include/linux/compiler.h` prior to definition of rare_write macros (huge compilation errors).
You know that `linux/compiler.h` header is mostly base of other headers not a user.
I have to define `__arch_rare_write_[begin/end/memcpy]()` functions as `static inline` in a header file somewhere in `arch/arm64/include/asm/`
to avoid making them ROP targets and the helpers need other mmu related APIs.
And the helpers and the mmu related APIs cannot be defined prior to definition of rare_write macros in `linux/compile.h`.
And I think I'll need `include/linux/module.h` for module related APIs like `is_module_address()` to support module address conversion
in `__arch_rare_write_memcpy()` and it?ll make the situation worse.
* make `include/linux/rare_write.h`
* the header defines rare_write APIs
* the header includes `include/asm/rare_write.h` for arch-specific helpers
* users using rare_write feature should include `linux/rare_write.h`
OR suggest other solutions please.
On Fri, Apr 7, 2017 at 1:09 AM, Ho-Eun Ryu [off-list ref] wrote:
quoted
On 30 Mar 2017, at 3:15 AM, Kees Cook [off-list ref] wrote:
Several types of data storage exist in the kernel: read-write data (.data,
.bss), read-only data (.rodata), and RO-after-init. This introduces the
infrastructure for another type: write-rarely, which is intended for data
that is either only rarely modified or especially security-sensitive. The
goal is to further reduce the internal attack surface of the kernel by
making this storage read-only when "at rest". This makes it much harder
to be subverted by attackers who have a kernel-write flaw, since they
cannot directly change these memory contents.
This work is heavily based on PaX and grsecurity's pax_{open,close}_kernel
API, its __read_only annotations, its constify plugin, and the work done
to identify sensitive structures that should be moved from .data into
.rodata. This builds the initial infrastructure to support these kinds
of changes, though the API and naming has been adjusted in places for
clarity and maintainability.
Variables declared with the __wr_rare annotation will be moved to the
.rodata section if an architecture supports CONFIG_HAVE_ARCH_WRITE_RARE.
To change these variables, either a single rare_write() macro can be used,
or multiple uses of __rare_write(), wrapped in a matching pair of
rare_write_begin() and rare_write_end() macros can be used. These macros
are expanded into the arch-specific functions that perform the actions
needed to write to otherwise read-only memory.
As detailed in the Kconfig help, the arch-specific helpers have several
requirements to make them sensible/safe for use by the kernel: they must
not allow non-current CPUs to write the memory area, they must run
non-preemptible to avoid accidentally leaving memory writable, and must
be inline to avoid making them desirable ROP targets for attackers.
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 25 +++++++++++++++++++++++++
include/linux/compiler.h | 32 ++++++++++++++++++++++++++++++++
include/linux/preempt.h | 6 ++++--
3 files changed, 61 insertions(+), 2 deletions(-)
config ARCH_WANT_RELAX_ORDER
bool
+config HAVE_ARCH_RARE_WRITE
+ def_bool n
+ help
+ An arch should select this option if it has defined the functions
+ __arch_rare_write_begin() and __arch_rare_write_end() to
+ respectively enable and disable writing to read-only memory. The
+ routines must meet the following requirements:
+ - read-only memory writing must only be available on the current
+ CPU (to make sure other CPUs can't race to make changes too).
+ - the routines must be declared inline (to discourage ROP use).
+ - the routines must not be preemptible (likely they will call
+ preempt_disable() and preempt_enable_no_resched() respectively).
+ - the routines must validate expected state (e.g. when enabling
+ writes, BUG() if writes are already be enabled).
+
+config HAVE_ARCH_RARE_WRITE_MEMCPY
+ def_bool n
+ depends on HAVE_ARCH_RARE_WRITE
+ help
+ An arch should select this option if a special accessor is needed
+ to write to otherwise read-only memory, defined by the function
+ __arch_rare_write_memcpy(). Without this, the write-rarely
+ infrastructure will just attempt to write directly to the memory
+ using a const-ignoring assignment.
+
source "kernel/gcov/Kconfig"
How about we have a separate header file splitting section annotations and the actual APIs.
include/linux/compiler.h:
__wr_rare
__wr_rare_type
include/linux/rare_write.h:
__rare_write_n()
__rare_write()
rare_write_begin()
rare_write_end()
This is a simple example a register/unregister case for __wr_rare markings,
which only needs a simple rare_write() call to make updates.
Signed-off-by: Kees Cook <redacted>
---
net/core/sock_diag.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
Everything but the USER domain is the same with CONFIG_CPU_SW_DOMAIN_PAN
or not. This extracts the differences for a common DACR_INIT macro so it
is easier to make future changes (like adding the WR_RARE domain).
Signed-off-by: Kees Cook <redacted>
---
arch/arm/include/asm/domain.h | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
As found in PaX, mark struct cftype with __do_const and add helpers
to deal with rare writes. This is a more complex example of a write-rarely
structure, which needs to use list helpers and blocks of begin/end pairs
to perform the needed updates.
With this change and the constify plugin enabled, the before/after
section byte sizes show:
before:
rodata: 0x2cc2f0
data: 0x130d00
after:
rodata: 0x2cf2f0 (+74478)
data: 0x12e5c0 (-65710)
Signed-off-by: Kees Cook <redacted>
---
include/linux/cgroup-defs.h | 2 +-
kernel/cgroup/cgroup.c | 35 +++++++++++++++++++++++------------
2 files changed, 24 insertions(+), 13 deletions(-)
This is a port of the PaX/grsecurity constify plugin. However, it has
the automatic function-pointer struct detection temporarily disabled. As
a result, this will only recognize the __do_const annotation, which
makes all instances of a marked structure read-only. The rare_write()
infrastructure can be used to make changes to such variables.
Signed-off-by: Kees Cook <redacted>
---
arch/Kconfig | 13 +
include/linux/compiler-gcc.h | 5 +
include/linux/compiler.h | 8 +
scripts/Makefile.gcc-plugins | 2 +
scripts/gcc-plugins/constify_plugin.c | 585 ++++++++++++++++++++++++++++++++++
5 files changed, 613 insertions(+)
create mode 100644 scripts/gcc-plugins/constify_plugin.c
@@ -0,0 +1,585 @@+/*+*Copyright2011byEmeseRevfy<re.emese@gmail.com>+*Copyright2011-2016byPaXTeam<pageexec@freemail.hu>+*LicensedundertheGPLv2,or(atyouroption)v3+*+*Thisgccpluginconstifiesallstructureswhichcontainonlyfunctionpointersorareexplicitlymarkedforconstification.+*+*Homepage:+*http://www.grsecurity.net/~ephox/const_plugin/+*+*Usage:+*$gcc-I`gcc-print-file-name=plugin`/include-fPIC-shared-O2-oconstify_plugin.soconstify_plugin.c+*$gcc-fplugin=constify_plugin.sotest.c-O2+*/++#include"gcc-common.h"++// unused C type flag in all versions 4.5-6+#define TYPE_CONSTIFY_VISITED(TYPE) TYPE_LANG_FLAG_4(TYPE)++__visibleintplugin_is_GPL_compatible;++staticboolenabled=true;++staticstructplugin_infoconst_plugin_info={+.version="201607241840vanilla",+.help="disable\tturn off constification\n",+};++staticstruct{+constchar*name;+constchar*asm_op;+}const_sections[]={+{".init.rodata","\t.section\t.init.rodata,\"a\""},+{".ref.rodata","\t.section\t.ref.rodata,\"a\""},+{".devinit.rodata","\t.section\t.devinit.rodata,\"a\""},+{".devexit.rodata","\t.section\t.devexit.rodata,\"a\""},+{".cpuinit.rodata","\t.section\t.cpuinit.rodata,\"a\""},+{".cpuexit.rodata","\t.section\t.cpuexit.rodata,\"a\""},+{".meminit.rodata","\t.section\t.meminit.rodata,\"a\""},+{".memexit.rodata","\t.section\t.memexit.rodata,\"a\""},+{".data..read_only","\t.section\t.data..read_only,\"a\""},+};++typedefstruct{+boolhas_fptr_field;+boolhas_writable_field;+boolhas_do_const_field;+boolhas_no_const_field;+}constify_info;++staticconst_treeget_field_type(const_treefield)+{+returnstrip_array_types(TREE_TYPE(field));+}++staticboolis_fptr(const_treefield)+{+/* XXX: disable automatic constification. */+returnfalse;++const_treeptr=get_field_type(field);++if(TREE_CODE(ptr)!=POINTER_TYPE)+returnfalse;++returnTREE_CODE(TREE_TYPE(ptr))==FUNCTION_TYPE;+}++/*+*determinewhetherthegivenstructuretypemeetstherequirementsforautomaticconstification,+*includingtheconstificationattributesonnestedstructuretypes+*/+staticvoidconstifiable(const_treenode,constify_info*cinfo)+{+const_treefield;++gcc_assert(TREE_CODE(node)==RECORD_TYPE||TREE_CODE(node)==UNION_TYPE);++// e.g., pointer to structure fields while still constructing the structure type+if(TYPE_FIELDS(node)==NULL_TREE)+return;++for(field=TYPE_FIELDS(node);field;field=TREE_CHAIN(field)){+const_treetype=get_field_type(field);+enumtree_codecode=TREE_CODE(type);++if(node==type)+continue;++if(is_fptr(field))+cinfo->has_fptr_field=true;+elseif(code==RECORD_TYPE||code==UNION_TYPE){+if(lookup_attribute("do_const",TYPE_ATTRIBUTES(type)))+cinfo->has_do_const_field=true;+elseif(lookup_attribute("no_const",TYPE_ATTRIBUTES(type)))+cinfo->has_no_const_field=true;+else+constifiable(type,cinfo);+}elseif(!TREE_READONLY(field))+cinfo->has_writable_field=true;+}+}++staticboolconstified(const_treenode)+{+constify_infocinfo={+.has_fptr_field=false,+.has_writable_field=false,+.has_do_const_field=false,+.has_no_const_field=false+};++gcc_assert(TREE_CODE(node)==RECORD_TYPE||TREE_CODE(node)==UNION_TYPE);++if(lookup_attribute("no_const",TYPE_ATTRIBUTES(node))){+// gcc_assert(!TYPE_READONLY(node));+returnfalse;+}++if(lookup_attribute("do_const",TYPE_ATTRIBUTES(node))){+gcc_assert(TYPE_READONLY(node));+returntrue;+}++constifiable(node,&cinfo);+if((!cinfo.has_fptr_field||cinfo.has_writable_field||cinfo.has_no_const_field)&&!cinfo.has_do_const_field)+returnfalse;++returnTYPE_READONLY(node);+}++staticvoiddeconstify_tree(treenode);++staticvoiddeconstify_type(treetype)+{+treefield;++gcc_assert(TREE_CODE(type)==RECORD_TYPE||TREE_CODE(type)==UNION_TYPE);++for(field=TYPE_FIELDS(type);field;field=TREE_CHAIN(field)){+const_treefieldtype=get_field_type(field);++// special case handling of simple ptr-to-same-array-type members+if(TREE_CODE(TREE_TYPE(field))==POINTER_TYPE){+treeptrtype=TREE_TYPE(TREE_TYPE(field));++if(TREE_TYPE(TREE_TYPE(field))==type)+continue;+if(TREE_CODE(ptrtype)!=RECORD_TYPE&&TREE_CODE(ptrtype)!=UNION_TYPE)+continue;+if(!constified(ptrtype))+continue;+if(TYPE_MAIN_VARIANT(ptrtype)==TYPE_MAIN_VARIANT(type))+TREE_TYPE(field)=build_pointer_type(build_qualified_type(type,TYPE_QUALS(ptrtype)&~TYPE_QUAL_CONST));+continue;+}+if(TREE_CODE(fieldtype)!=RECORD_TYPE&&TREE_CODE(fieldtype)!=UNION_TYPE)+continue;+if(!constified(fieldtype))+continue;++deconstify_tree(field);+TREE_READONLY(field)=0;+}+TYPE_READONLY(type)=0;+C_TYPE_FIELDS_READONLY(type)=0;+if(lookup_attribute("do_const",TYPE_ATTRIBUTES(type))){+TYPE_ATTRIBUTES(type)=copy_list(TYPE_ATTRIBUTES(type));+TYPE_ATTRIBUTES(type)=remove_attribute("do_const",TYPE_ATTRIBUTES(type));+}+}++staticvoiddeconstify_tree(treenode)+{+treeold_type,new_type,field;++old_type=TREE_TYPE(node);+while(TREE_CODE(old_type)==ARRAY_TYPE&&TREE_CODE(TREE_TYPE(old_type))!=ARRAY_TYPE){+node=TREE_TYPE(node)=copy_node(old_type);+old_type=TREE_TYPE(old_type);+}++gcc_assert(TREE_CODE(old_type)==RECORD_TYPE||TREE_CODE(old_type)==UNION_TYPE);+gcc_assert(TYPE_READONLY(old_type)&&(TYPE_QUALS(old_type)&TYPE_QUAL_CONST));++new_type=build_qualified_type(old_type,TYPE_QUALS(old_type)&~TYPE_QUAL_CONST);+TYPE_FIELDS(new_type)=copy_list(TYPE_FIELDS(new_type));+for(field=TYPE_FIELDS(new_type);field;field=TREE_CHAIN(field))+DECL_FIELD_CONTEXT(field)=new_type;++deconstify_type(new_type);++TREE_TYPE(node)=new_type;+}++statictreehandle_no_const_attribute(tree*node,treename,treeargs,intflags,bool*no_add_attrs)+{+treetype;+constify_infocinfo={+.has_fptr_field=false,+.has_writable_field=false,+.has_do_const_field=false,+.has_no_const_field=false+};++*no_add_attrs=true;+if(TREE_CODE(*node)==FUNCTION_DECL){+error("%qE attribute does not apply to functions (%qF)",name,*node);+returnNULL_TREE;+}++if(TREE_CODE(*node)==PARM_DECL){+error("%qE attribute does not apply to function parameters (%qD)",name,*node);+returnNULL_TREE;+}++if(TREE_CODE(*node)==VAR_DECL){+error("%qE attribute does not apply to variables (%qD)",name,*node);+returnNULL_TREE;+}++if(TYPE_P(*node)){+type=*node;+}else{+if(TREE_CODE(*node)!=TYPE_DECL){+error("%qE attribute does not apply to %qD (%qT)",name,*node,TREE_TYPE(*node));+returnNULL_TREE;+}+type=TREE_TYPE(*node);+}++if(TREE_CODE(type)!=RECORD_TYPE&&TREE_CODE(type)!=UNION_TYPE){+error("%qE attribute used on %qT applies to struct and union types only",name,type);+returnNULL_TREE;+}++if(lookup_attribute(IDENTIFIER_POINTER(name),TYPE_ATTRIBUTES(type))){+error("%qE attribute is already applied to the type %qT",name,type);+returnNULL_TREE;+}++if(TYPE_P(*node)){+if(lookup_attribute("do_const",TYPE_ATTRIBUTES(type)))+error("%qE attribute used on type %qT is incompatible with 'do_const'",name,type);+else+*no_add_attrs=false;+returnNULL_TREE;+}++constifiable(type,&cinfo);+if((cinfo.has_fptr_field&&!cinfo.has_writable_field&&!cinfo.has_no_const_field)||lookup_attribute("do_const",TYPE_ATTRIBUTES(type))){+if(enabled){+ifTYPE_P(*node)+deconstify_type(*node);+else+deconstify_tree(*node);+}+if(TYPE_P(*node))+TYPE_CONSTIFY_VISITED(*node)=1;+else+TYPE_CONSTIFY_VISITED(TREE_TYPE(*node))=1;+returnNULL_TREE;+}++if(enabled&&TYPE_FIELDS(type))+error("%qE attribute used on type %qT that is not constified",name,type);+returnNULL_TREE;+}++staticvoidconstify_type(treetype)+{+gcc_assert(type==TYPE_MAIN_VARIANT(type));+TYPE_READONLY(type)=1;+C_TYPE_FIELDS_READONLY(type)=1;+TYPE_CONSTIFY_VISITED(type)=1;+// TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));+// TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("do_const"), NULL_TREE, TYPE_ATTRIBUTES(type));+}++statictreehandle_do_const_attribute(tree*node,treename,treeargs,intflags,bool*no_add_attrs)+{+*no_add_attrs=true;+if(!TYPE_P(*node)){+error("%qE attribute applies to types only (%qD)",name,*node);+returnNULL_TREE;+}++if(TREE_CODE(*node)!=RECORD_TYPE&&TREE_CODE(*node)!=UNION_TYPE){+error("%qE attribute used on %qT applies to struct and union types only",name,*node);+returnNULL_TREE;+}++if(lookup_attribute(IDENTIFIER_POINTER(name),TYPE_ATTRIBUTES(*node))){+error("%qE attribute used on %qT is already applied to the type",name,*node);+returnNULL_TREE;+}++if(lookup_attribute("no_const",TYPE_ATTRIBUTES(*node))){+error("%qE attribute used on %qT is incompatible with 'no_const'",name,*node);+returnNULL_TREE;+}++*no_add_attrs=false;+returnNULL_TREE;+}++staticstructattribute_specno_const_attr={+.name="no_const",+.min_length=0,+.max_length=0,+.decl_required=false,+.type_required=false,+.function_type_required=false,+.handler=handle_no_const_attribute,+#if BUILDING_GCC_VERSION >= 4007+.affects_type_identity=true+#endif+};++staticstructattribute_specdo_const_attr={+.name="do_const",+.min_length=0,+.max_length=0,+.decl_required=false,+.type_required=false,+.function_type_required=false,+.handler=handle_do_const_attribute,+#if BUILDING_GCC_VERSION >= 4007+.affects_type_identity=true+#endif+};++staticvoidregister_attributes(void*event_data,void*data)+{+register_attribute(&no_const_attr);+register_attribute(&do_const_attr);+}++staticvoidfinish_type(void*event_data,void*data)+{+treetype=(tree)event_data;+constify_infocinfo={+.has_fptr_field=false,+.has_writable_field=false,+.has_do_const_field=false,+.has_no_const_field=false+};++if(type==NULL_TREE||type==error_mark_node)+return;++#if BUILDING_GCC_VERSION >= 5000+if(TREE_CODE(type)==ENUMERAL_TYPE)+return;+#endif++if(TYPE_FIELDS(type)==NULL_TREE||TYPE_CONSTIFY_VISITED(type))+return;++constifiable(type,&cinfo);++if(lookup_attribute("no_const",TYPE_ATTRIBUTES(type))){+if((cinfo.has_fptr_field&&!cinfo.has_writable_field&&!cinfo.has_no_const_field)||cinfo.has_do_const_field){+deconstify_type(type);+TYPE_CONSTIFY_VISITED(type)=1;+}else+error("'no_const' attribute used on type %qT that is not constified",type);+return;+}++if(lookup_attribute("do_const",TYPE_ATTRIBUTES(type))){+if(!cinfo.has_writable_field&&!cinfo.has_no_const_field){+error("'do_const' attribute used on type %qT that is%sconstified",type,cinfo.has_fptr_field?" ":" not ");+return;+}+constify_type(type);+return;+}++if(cinfo.has_fptr_field&&!cinfo.has_writable_field&&!cinfo.has_no_const_field){+if(lookup_attribute("do_const",TYPE_ATTRIBUTES(type))){+error("'do_const' attribute used on type %qT that is constified",type);+return;+}+constify_type(type);+return;+}++deconstify_type(type);+TYPE_CONSTIFY_VISITED(type)=1;+}++staticboolis_constified_var(varpool_node_ptrnode)+{+treevar=NODE_DECL(node);+treetype=TREE_TYPE(var);++if(node->alias)+returnfalse;++if(DECL_EXTERNAL(var))+returnfalse;++// XXX handle more complex nesting of arrays/structs+if(TREE_CODE(type)==ARRAY_TYPE)+type=TREE_TYPE(type);++if(TREE_CODE(type)!=RECORD_TYPE&&TREE_CODE(type)!=UNION_TYPE)+returnfalse;++if(!TYPE_READONLY(type)||!C_TYPE_FIELDS_READONLY(type))+returnfalse;++if(!TYPE_CONSTIFY_VISITED(type))+returnfalse;++returntrue;+}++staticvoidcheck_section_mismatch(varpool_node_ptrnode)+{+treevar,section;+size_ti;+constchar*name;++var=NODE_DECL(node);+name=get_decl_section_name(var);+section=lookup_attribute("section",DECL_ATTRIBUTES(var));+if(!section){+if(name){+fprintf(stderr,"DECL_SECTION [%s] ",name);+dump_varpool_node(stderr,node);+gcc_unreachable();+}+return;+}else+gcc_assert(name);++//fprintf(stderr, "SECTIONAME: [%s] ", get_decl_section_name(var));+//debug_tree(var);++gcc_assert(!TREE_CHAIN(section));+gcc_assert(TREE_VALUE(section));++section=TREE_VALUE(TREE_VALUE(section));+gcc_assert(!strcmp(TREE_STRING_POINTER(section),name));+//debug_tree(section);++for(i=0;i<ARRAY_SIZE(const_sections);i++)+if(!strcmp(const_sections[i].name,name))+return;++error_at(DECL_SOURCE_LOCATION(var),"constified variable %qD placed into writable section %E",var,section);+}++// this works around a gcc bug/feature where uninitialized globals+// are moved into the .bss section regardless of any constification+// see gcc/varasm.c:bss_initializer_p()+staticvoidfix_initializer(varpool_node_ptrnode)+{+treevar=NODE_DECL(node);+treetype=TREE_TYPE(var);++if(DECL_INITIAL(var))+return;++DECL_INITIAL(var)=build_constructor(type,NULL);+// inform(DECL_SOURCE_LOCATION(var), "constified variable %qE moved into .rodata", var);+}++staticvoidcheck_global_variables(void*event_data,void*data)+{+varpool_node_ptrnode;++FOR_EACH_VARIABLE(node){+if(!is_constified_var(node))+continue;++check_section_mismatch(node);+fix_initializer(node);+}+}++staticunsignedintcheck_local_variables_execute(void)+{+unsignedintret=0;+treevar;++unsignedinti;++FOR_EACH_LOCAL_DECL(cfun,i,var){+treetype=TREE_TYPE(var);++gcc_assert(DECL_P(var));+if(is_global_var(var))+continue;++if(TREE_CODE(type)!=RECORD_TYPE&&TREE_CODE(type)!=UNION_TYPE)+continue;++if(!TYPE_READONLY(type)||!C_TYPE_FIELDS_READONLY(type))+continue;++if(!TYPE_CONSTIFY_VISITED(type))+continue;++error_at(DECL_SOURCE_LOCATION(var),"constified variable %qE cannot be local",var);+ret=1;+}+returnret;+}++#define PASS_NAME check_local_variables+#define NO_GATE+#include"gcc-generate-gimple-pass.h"++staticunsignedint(*old_section_type_flags)(treedecl,constchar*name,intreloc);++staticunsignedintconstify_section_type_flags(treedecl,constchar*name,intreloc)+{+size_ti;++for(i=0;i<ARRAY_SIZE(const_sections);i++)+if(!strcmp(const_sections[i].name,name))+return0;++returnold_section_type_flags(decl,name,reloc);+}++staticvoidconstify_start_unit(void*gcc_data,void*user_data)+{+// size_t i;++// for (i = 0; i < ARRAY_SIZE(const_sections); i++)+// const_sections[i].section = get_unnamed_section(0, output_section_asm_op, const_sections[i].asm_op);+// const_sections[i].section = get_section(const_sections[i].name, 0, NULL);++old_section_type_flags=targetm.section_type_flags;+targetm.section_type_flags=constify_section_type_flags;+}++__visibleintplugin_init(structplugin_name_args*plugin_info,structplugin_gcc_version*version)+{+constchar*constplugin_name=plugin_info->base_name;+constintargc=plugin_info->argc;+conststructplugin_argument*constargv=plugin_info->argv;+inti;++structregister_pass_infocheck_local_variables_pass_info;++check_local_variables_pass_info.pass=make_check_local_variables_pass();+check_local_variables_pass_info.reference_pass_name="ssa";+check_local_variables_pass_info.ref_pass_instance_number=1;+check_local_variables_pass_info.pos_op=PASS_POS_INSERT_BEFORE;++if(!plugin_default_version_check(version,&gcc_version)){+error(G_("incompatible gcc/plugin versions"));+return1;+}++for(i=0;i<argc;++i){+if(!(strcmp(argv[i].key,"disable"))){+enabled=false;+continue;+}+error(G_("unknown option '-fplugin-arg-%s-%s'"),plugin_name,argv[i].key);+}++if(strncmp(lang_hooks.name,"GNU C",5)&&!strncmp(lang_hooks.name,"GNU C+",6)){+inform(UNKNOWN_LOCATION,G_("%s supports C only, not %s"),plugin_name,lang_hooks.name);+enabled=false;+}++register_callback(plugin_name,PLUGIN_INFO,NULL,&const_plugin_info);+if(enabled){+register_callback(plugin_name,PLUGIN_ALL_IPA_PASSES_START,check_global_variables,NULL);+register_callback(plugin_name,PLUGIN_FINISH_TYPE,finish_type,NULL);+register_callback(plugin_name,PLUGIN_PASS_MANAGER_SETUP,NULL,&check_local_variables_pass_info);+register_callback(plugin_name,PLUGIN_START_UNIT,constify_start_unit,NULL);+}+register_callback(plugin_name,PLUGIN_ATTRIBUTES,register_attributes,NULL);++return0;+}
Some structures that are intended to be made write-rarely are designed to
be linked by lists. As a result, there need to be rare_write()-supported
linked list primitives.
As found in PaX, this adds list management helpers for doing updates to
rarely-changed lists.
Signed-off-by: Kees Cook <redacted>
---
include/linux/list.h | 17 +++++++++++++++++
lib/Makefile | 2 +-
lib/list_debug.c | 37 +++++++++++++++++++++++++++++++++++++
3 files changed, 55 insertions(+), 1 deletion(-)
This creates DOMAIN_WR_RARE for the kernel's .rodata section, separate
from DOMAIN_KERNEL to avoid predictive fetching in device memory during
a DOMAIN_MANAGER transition.
TODO: handle kernel module vmalloc memory, which needs to be marked as
DOMAIN_WR_RARE too, for module .rodata sections.
Signed-off-by: Kees Cook <redacted>
---
arch/arm/include/asm/domain.h | 3 +++
arch/arm/mm/dump.c | 2 ++
arch/arm/mm/init.c | 7 ++++---
3 files changed, 9 insertions(+), 3 deletions(-)
This adds the memory domain (on non-LPAE) to the PMD and PTE dumps. This
isn't in the regular PMD bits because I couldn't find a clean way to
fall back to retain some of the PMD bits when reporting PTE. So this is
special-cased currently.
New output example:
---[ Modules ]---
0x7f000000-0x7f001000 4K KERNEL ro x SHD MEM/CACHED/WBWA
0x7f001000-0x7f002000 4K KERNEL ro NX SHD MEM/CACHED/WBWA
0x7f002000-0x7f004000 8K KERNEL RW NX SHD MEM/CACHED/WBWA
---[ Kernel Mapping ]---
0x80000000-0x80100000 1M KERNEL RW NX SHD
0x80100000-0x80800000 7M KERNEL ro x SHD
0x80800000-0x80b00000 3M KERNEL ro NX SHD
0x80b00000-0xa0000000 501M KERNEL RW NX SHD
...
---[ Vectors ]---
0xffff0000-0xffff1000 4K VECTORS USR ro x SHD MEM/CACHED/WBWA
0xffff1000-0xffff2000 4K VECTORS ro x SHD MEM/CACHED/WBWA
Signed-off-by: Kees Cook <redacted>
---
This patch is already queued in the ARM tree, but I'm including it here too
since a following patch updates the list of domain names from this patch...
---
arch/arm/mm/dump.c | 54 ++++++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 44 insertions(+), 10 deletions(-)
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
There is missing work to sort out some header file issues where preempt.h
is missing, though it can't be included in pg_table.h unconditionally...
some other solution will be needed, perhaps an entirely separate header
file for rare_write()-related defines...
This patch is also missing paravirt support.
Signed-off-by: Kees Cook <redacted>
---
arch/x86/Kconfig | 1 +
arch/x86/include/asm/pgtable.h | 31 +++++++++++++++++++++++++++++++
2 files changed, 32 insertions(+)
From: Andy Lutomirski <luto@amacapital.net> Date: 2017-03-29 22:39:07
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
--Andy
On Wed, Mar 29, 2017 at 3:38 PM, Andy Lutomirski [off-list ref] wrote:
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
quoted
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
quoted
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
Do you mean preempt_disable() isn't strong enough here? I'm open to
suggestions. The goal would be to make sure nothing between _begin and
_end would get executed without interruption...
-Kees
--
Kees Cook
Pixel Security
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-05 23:58:09
On Wed, Mar 29, 2017 at 6:41 PM, Kees Cook [off-list ref] wrote:
On Wed, Mar 29, 2017 at 3:38 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
quoted
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
quoted
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
Do you mean preempt_disable() isn't strong enough here? I'm open to
suggestions. The goal would be to make sure nothing between _begin and
_end would get executed without interruption...
Sorry for the very slow response.
preempt_disable() isn't strong enough to prevent interrupts, and an
interrupt here would run with WP off, causing unknown havoc. I tend
to think that the caller should be responsible for turning off
interrupts.
--Andy
On Wed, Apr 5, 2017 at 4:57 PM, Andy Lutomirski [off-list ref] wrote:
On Wed, Mar 29, 2017 at 6:41 PM, Kees Cook [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 3:38 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
quoted
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
quoted
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
Do you mean preempt_disable() isn't strong enough here? I'm open to
suggestions. The goal would be to make sure nothing between _begin and
_end would get executed without interruption...
Sorry for the very slow response.
preempt_disable() isn't strong enough to prevent interrupts, and an
interrupt here would run with WP off, causing unknown havoc. I tend
to think that the caller should be responsible for turning off
interrupts.
So, something like:
Top-level functions:
static __always_inline rare_write_begin(void)
{
preempt_disable();
local_irq_disable();
barrier();
__arch_rare_write_begin();
barrier();
}
static __always_inline rare_write_end(void)
{
barrier();
__arch_rare_write_end();
barrier();
local_irq_enable();
preempt_enable_no_resched();
}
x86-specific helpers:
static __always_inline unsigned long __arch_rare_write_begin(void)
{
unsigned long cr0;
cr0 = read_cr0() ^ X86_CR0_WP;
BUG_ON(cr0 & X86_CR0_WP);
write_cr0(cr0);
return cr0 ^ X86_CR0_WP;
}
static __always_inline unsigned long __arch_rare_write_end(void)
{
unsigned long cr0;
cr0 = read_cr0() ^ X86_CR0_WP;
BUG_ON(!(cr0 & X86_CR0_WP));
write_cr0(cr0);
return cr0 ^ X86_CR0_WP;
}
I can give it a spin...
-Kees
--
Kees Cook
Pixel Security
From: Andy Lutomirski <luto@amacapital.net> Date: 2017-04-06 15:59:29
On Wed, Apr 5, 2017 at 5:14 PM, Kees Cook [off-list ref] wrote:
On Wed, Apr 5, 2017 at 4:57 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 6:41 PM, Kees Cook [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 3:38 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
quoted
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
quoted
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
Do you mean preempt_disable() isn't strong enough here? I'm open to
suggestions. The goal would be to make sure nothing between _begin and
_end would get executed without interruption...
Sorry for the very slow response.
preempt_disable() isn't strong enough to prevent interrupts, and an
interrupt here would run with WP off, causing unknown havoc. I tend
to think that the caller should be responsible for turning off
interrupts.
Looks good, except you don't need preempt_disable().
local_irq_disable() also disables preemption. You might need to use
local_irq_save(), though, depending on whether any callers already
have IRQs off.
--Andy
On 6 April 2017 at 17:59, Andy Lutomirski [off-list ref] wrote:
On Wed, Apr 5, 2017 at 5:14 PM, Kees Cook [off-list ref] wrote:
quoted
On Wed, Apr 5, 2017 at 4:57 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 6:41 PM, Kees Cook [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 3:38 PM, Andy Lutomirski [off-list ref] wrote:
quoted
On Wed, Mar 29, 2017 at 11:15 AM, Kees Cook [off-list ref] wrote:
quoted
Based on PaX's x86 pax_{open,close}_kernel() implementation, this
allows HAVE_ARCH_RARE_WRITE to work on x86.
+
+static __always_inline unsigned long __arch_rare_write_begin(void)
+{
+ unsigned long cr0;
+
+ preempt_disable();
This looks wrong. DEBUG_LOCKS_WARN_ON(!irqs_disabled()) would work,
as would local_irq_disable(). There's no way that just disabling
preemption is enough.
(Also, how does this interact with perf nmis?)
Do you mean preempt_disable() isn't strong enough here? I'm open to
suggestions. The goal would be to make sure nothing between _begin and
_end would get executed without interruption...
Sorry for the very slow response.
preempt_disable() isn't strong enough to prevent interrupts, and an
interrupt here would run with WP off, causing unknown havoc. I tend
to think that the caller should be responsible for turning off
interrupts.
Looks good, except you don't need preempt_disable().
local_irq_disable() also disables preemption. You might need to use
local_irq_save(), though, depending on whether any callers already
have IRQs off.
Well, doesn't look good to me. NMIs will still be able to interrupt
this code and will run with CR0.WP = 0.
Shouldn't you instead question yourself why PaX can do it "just" with
preempt_disable() instead?!
Cheers,
Mathias
Looks good, except you don't need preempt_disable().
local_irq_disable() also disables preemption. You might need to use
local_irq_save(), though, depending on whether any callers already
have IRQs off.
Well, doesn't look good to me. NMIs will still be able to interrupt
this code and will run with CR0.WP = 0.
Shouldn't you instead question yourself why PaX can do it "just" with
preempt_disable() instead?!
That's silly. Just because PaX does it, doesn't mean it's correct. To be
honest, playing games with the CR0.WP bit is outright stupid to begin with.
Whether protected by preempt_disable or local_irq_disable, to make that
work it needs CR0 handling in the exception entry/exit at the lowest
level. And that's just a nightmare maintainence wise as it's prone to be
broken over time. Aside of that it's pointless overhead for the normal case.
The proper solution is:
write_rare(ptr, val)
{
mp = map_shadow_rw(ptr);
*mp = val;
unmap_shadow_rw(mp);
}
map_shadow_rw() is essentially the same thing as we do in the highmem case
where the kernel creates a shadow mapping of the user space pages via
kmap_atomic().
It's valid (at least on x86) to have a shadow map with the same page
attributes but write enabled. That does not require any fixups of CR0 and
just works.
Thanks,
tglx
Looks good, except you don't need preempt_disable().
local_irq_disable() also disables preemption. You might need to use
local_irq_save(), though, depending on whether any callers already
have IRQs off.
Well, doesn't look good to me. NMIs will still be able to interrupt
this code and will run with CR0.WP = 0.
Shouldn't you instead question yourself why PaX can do it "just" with
preempt_disable() instead?!
That's silly. Just because PaX does it, doesn't mean it's correct. To be
honest, playing games with the CR0.WP bit is outright stupid to begin with.
Why that? It allows fast and CPU local modifications of r/o memory.
OTOH, an approach that needs to fiddle with page table entries
requires global synchronization to keep the individual TLB states in
sync. Hmm.. Not that fast, I'd say.
Whether protected by preempt_disable or local_irq_disable, to make that
work it needs CR0 handling in the exception entry/exit at the lowest
level. And that's just a nightmare maintainence wise as it's prone to be
broken over time.
It seems to be working fine for more than a decade now in PaX. So it
can't be such a big maintenance nightmare ;)
Aside of that it's pointless overhead for the normal case.
The proper solution is:
write_rare(ptr, val)
{
mp = map_shadow_rw(ptr);
*mp = val;
unmap_shadow_rw(mp);
}
map_shadow_rw() is essentially the same thing as we do in the highmem case
where the kernel creates a shadow mapping of the user space pages via
kmap_atomic().
The "proper solution" seems to be much slower compared to just
toggling CR0.WP (which is costly in itself, already) because of the
TLB invalidation / synchronisation involved.
It's valid (at least on x86) to have a shadow map with the same page
attributes but write enabled. That does not require any fixups of CR0 and
just works.
"Just works", sure -- but it's not as tightly focused as the PaX
solution which is CPU local, while your proposed solution is globally
visible.
Cheers,
Mathias
From: Thomas Gleixner <hidden> Date: 2017-04-07 13:14:48
On Fri, 7 Apr 2017, Mathias Krause wrote:
On 7 April 2017 at 11:46, Thomas Gleixner [off-list ref] wrote:
quoted
Whether protected by preempt_disable or local_irq_disable, to make that
work it needs CR0 handling in the exception entry/exit at the lowest
level. And that's just a nightmare maintainence wise as it's prone to be
broken over time.
It seems to be working fine for more than a decade now in PaX. So it
can't be such a big maintenance nightmare ;)
I really do not care whether PaX wants to chase and verify that over and
over. I certainly don't want to take the chance to leak CR0.WP ever and I
very much care about extra stuff to check in the entry/exit path.
The "proper solution" seems to be much slower compared to just
toggling CR0.WP (which is costly in itself, already) because of the
TLB invalidation / synchronisation involved.
Why the heck should we care about rare writes being performant?
quoted
It's valid (at least on x86) to have a shadow map with the same page
attributes but write enabled. That does not require any fixups of CR0 and
just works.
"Just works", sure -- but it's not as tightly focused as the PaX
solution which is CPU local, while your proposed solution is globally
visible.
Making the world and some more writeable hardly qualifies as tightly
focussed. Making the mapping concept CPU local is not rocket science
either. The question is whethers it's worth the trouble.
Thanks,
tglx
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
On Fri, 7 Apr 2017, Mathias Krause wrote:
quoted
On 7 April 2017 at 11:46, Thomas Gleixner [off-list ref] wrote:
quoted
Whether protected by preempt_disable or local_irq_disable, to make that
work it needs CR0 handling in the exception entry/exit at the lowest
level. And that's just a nightmare maintainence wise as it's prone to be
broken over time.
It seems to be working fine for more than a decade now in PaX. So it
can't be such a big maintenance nightmare ;)
I really do not care whether PaX wants to chase and verify that over and
over. I certainly don't want to take the chance to leak CR0.WP ever and I
very much care about extra stuff to check in the entry/exit path.
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
quoted
The "proper solution" seems to be much slower compared to just
toggling CR0.WP (which is costly in itself, already) because of the
TLB invalidation / synchronisation involved.
Why the heck should we care about rare writes being performant?
As soon as they stop being rare and people start extending the r/o
protection to critical data structures accessed often. Then
performance matters.
quoted
quoted
It's valid (at least on x86) to have a shadow map with the same page
attributes but write enabled. That does not require any fixups of CR0 and
just works.
"Just works", sure -- but it's not as tightly focused as the PaX
solution which is CPU local, while your proposed solution is globally
visible.
Making the world and some more writeable hardly qualifies as tightly
focussed. Making the mapping concept CPU local is not rocket science
either. The question is whethers it's worth the trouble.
No, the question is if the value of the concept is well understood and
if people can see what could be done with such a strong primitive.
Apparently not...
Cheers,
Mathias
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-07 16:15:04
On Fri, Apr 7, 2017 at 6:30 AM, Mathias Krause [off-list ref] wrote:
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
quoted
On Fri, 7 Apr 2017, Mathias Krause wrote:
quoted
On 7 April 2017 at 11:46, Thomas Gleixner [off-list ref] wrote:
quoted
Whether protected by preempt_disable or local_irq_disable, to make that
work it needs CR0 handling in the exception entry/exit at the lowest
level. And that's just a nightmare maintainence wise as it's prone to be
broken over time.
It seems to be working fine for more than a decade now in PaX. So it
can't be such a big maintenance nightmare ;)
I really do not care whether PaX wants to chase and verify that over and
over. I certainly don't want to take the chance to leak CR0.WP ever and I
very much care about extra stuff to check in the entry/exit path.
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
quoted
quoted
quoted
It's valid (at least on x86) to have a shadow map with the same page
attributes but write enabled. That does not require any fixups of CR0 and
just works.
"Just works", sure -- but it's not as tightly focused as the PaX
solution which is CPU local, while your proposed solution is globally
visible.
Making the world and some more writeable hardly qualifies as tightly
focussed. Making the mapping concept CPU local is not rocket science
either. The question is whethers it's worth the trouble.
No, the question is if the value of the concept is well understood and
if people can see what could be done with such a strong primitive.
Apparently not...
I think we're approaching this all wrong, actually. The fact that x86
has this CR0.WP thing is arguably a historical accident, and the fact
that PaX uses it doesn't mean that PaX is doing it the best way for
upstream Linux.
Why don't we start at the other end and do a generic non-arch-specific
implementation: set up an mm_struct that contains an RW alias of the
relevant parts of rodata and use use_mm to access it. (That is,
get_fs() to back up the old fs, set_fs(USER_DS),
use_mm(&rare_write_mm), do the write using copy_to_user, undo
everything.)
Then someone who cares about performance can benchmark the CR0.WP
approach against it and try to argue that it's a good idea. This
benchmark should wait until I'm done with my PCID work, because PCID
is going to make use_mm() a whole heck of a lot faster.
--Andy
From: Mark Rutland <mark.rutland@arm.com> Date: 2017-04-07 16:23:10
On Fri, Apr 07, 2017 at 09:14:29AM -0700, Andy Lutomirski wrote:
I think we're approaching this all wrong, actually. The fact that x86
has this CR0.WP thing is arguably a historical accident, and the fact
that PaX uses it doesn't mean that PaX is doing it the best way for
upstream Linux.
Why don't we start at the other end and do a generic non-arch-specific
implementation: set up an mm_struct that contains an RW alias of the
relevant parts of rodata and use use_mm to access it. (That is,
get_fs() to back up the old fs, set_fs(USER_DS),
use_mm(&rare_write_mm), do the write using copy_to_user, undo
everything.)
FWIW, I completely agree with this approach.
That's largely the approach arm64 would have to take regardless (as per
Hoeun's patches), and having a consistent common implementation would be
desireable.
There are a couple of other complications to handle (e.g. a perf
interrupt coming in and trying to read from the mapping), but I think we
can handle that generically.
Thanks,
Mark.
On Fri, Apr 7, 2017 at 6:30 AM, Mathias Krause [off-list ref] wrote:
quoted
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
quoted
On Fri, 7 Apr 2017, Mathias Krause wrote:
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
can you please share those leaks that 'surely exist' and CC oss-security
while at it?
I think we're approaching this all wrong, actually. The fact that x86
has this CR0.WP thing is arguably a historical accident, and the fact
that PaX uses it doesn't mean that PaX is doing it the best way for
upstream Linux.
Why don't we start at the other end and do a generic non-arch-specific
implementation: set up an mm_struct that contains an RW alias of the
relevant parts of rodata and use use_mm to access it. (That is,
get_fs() to back up the old fs, set_fs(USER_DS),
use_mm(&rare_write_mm), do the write using copy_to_user, undo
everything.)
Then someone who cares about performance can benchmark the CR0.WP
approach against it and try to argue that it's a good idea. This
benchmark should wait until I'm done with my PCID work, because PCID
is going to make use_mm() a whole heck of a lot faster.
in my measurements switching PCID is hovers around 230 cycles for snb-ivb
and 200-220 for hsw-skl whereas cr0 writes are around 230-240 cycles. there's
of course a whole lot more impact for switching address spaces so it'll never
be fast enough to beat cr0.wp.
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-08 04:59:16
On Fri, Apr 7, 2017 at 12:58 PM, PaX Team [off-list ref] wrote:
On 7 Apr 2017 at 9:14, Andy Lutomirski wrote:
quoted
On Fri, Apr 7, 2017 at 6:30 AM, Mathias Krause [off-list ref] wrote:
quoted
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
quoted
On Fri, 7 Apr 2017, Mathias Krause wrote:
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
can you please share those leaks that 'surely exist' and CC oss-security
while at it?
I meant in the patchset here, not in grsecurity. grsecurity (on very,
very brief inspection) seems to read cr0 and fix it up in
pax_enter_kernel.
quoted
Then someone who cares about performance can benchmark the CR0.WP
approach against it and try to argue that it's a good idea. This
benchmark should wait until I'm done with my PCID work, because PCID
is going to make use_mm() a whole heck of a lot faster.
in my measurements switching PCID is hovers around 230 cycles for snb-ivb
and 200-220 for hsw-skl whereas cr0 writes are around 230-240 cycles. there's
of course a whole lot more impact for switching address spaces so it'll never
be fast enough to beat cr0.wp.
If I'm reading this right, you're saying that a non-flushing CR3 write
is about the same cost as a CR0.WP write. If so, then why should CR0
be preferred over the (arch-neutral) CR3 approach? And why would
switching address spaces obviously be much slower? There'll be a very
small number of TLB fills needed for the actual protected access.
--Andy
On Fri, Apr 7, 2017 at 12:58 PM, PaX Team [off-list ref] wrote:
quoted
On 7 Apr 2017 at 9:14, Andy Lutomirski wrote:
quoted
Then someone who cares about performance can benchmark the CR0.WP
approach against it and try to argue that it's a good idea. This
benchmark should wait until I'm done with my PCID work, because PCID
is going to make use_mm() a whole heck of a lot faster.
in my measurements switching PCID is hovers around 230 cycles for snb-ivb
and 200-220 for hsw-skl whereas cr0 writes are around 230-240 cycles. there's
of course a whole lot more impact for switching address spaces so it'll never
be fast enough to beat cr0.wp.
If I'm reading this right, you're saying that a non-flushing CR3 write
is about the same cost as a CR0.WP write. If so, then why should CR0
be preferred over the (arch-neutral) CR3 approach?
cr3 (page table switching) isn't arch neutral at all ;). you probably meant
the higher level primitives except they're not enough to implement the scheme
as discussed before since the enter/exit paths are very much arch dependent.
on x86 the cost of the pax_open/close_kernel primitives comes from the cr0
writes and nothing else, use_mm suffers not only from the cr3 writes but
also locking/atomic ops and cr4 writes on its path and the inevitable TLB
entry costs. and if cpu vendors cared enough, they could make toggling cr0.wp
a fast path in the microcode and reduce its overhead by an order of magnitude.
And why would switching address spaces obviously be much slower?
There'll be a very small number of TLB fills needed for the actual
protected access.
you'll be duplicating TLB entries in the alternative PCID for both code
and data, where they will accumulate (=take room away from the normal PCID
and expose unwanted memory for access) unless you also flush them when
switching back (which then will cost even more cycles). also i'm not sure
that processors implement all the 12 PCID bits so depending on how many PCIDs
you plan to use, you could be causing even more unnecessary TLB replacements.
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-10 00:10:46
On Sun, Apr 9, 2017 at 5:47 AM, PaX Team [off-list ref] wrote:
On 7 Apr 2017 at 21:58, Andy Lutomirski wrote:
quoted
On Fri, Apr 7, 2017 at 12:58 PM, PaX Team [off-list ref] wrote:
quoted
On 7 Apr 2017 at 9:14, Andy Lutomirski wrote:
quoted
Then someone who cares about performance can benchmark the CR0.WP
approach against it and try to argue that it's a good idea. This
benchmark should wait until I'm done with my PCID work, because PCID
is going to make use_mm() a whole heck of a lot faster.
in my measurements switching PCID is hovers around 230 cycles for snb-ivb
and 200-220 for hsw-skl whereas cr0 writes are around 230-240 cycles. there's
of course a whole lot more impact for switching address spaces so it'll never
be fast enough to beat cr0.wp.
If I'm reading this right, you're saying that a non-flushing CR3 write
is about the same cost as a CR0.WP write. If so, then why should CR0
be preferred over the (arch-neutral) CR3 approach?
cr3 (page table switching) isn't arch neutral at all ;). you probably meant
the higher level primitives except they're not enough to implement the scheme
as discussed before since the enter/exit paths are very much arch dependent.
Yes.
on x86 the cost of the pax_open/close_kernel primitives comes from the cr0
writes and nothing else, use_mm suffers not only from the cr3 writes but
also locking/atomic ops and cr4 writes on its path and the inevitable TLB
entry costs. and if cpu vendors cared enough, they could make toggling cr0.wp
a fast path in the microcode and reduce its overhead by an order of magnitude.
If the CR4 writes happen in for this use case, that's a bug.
quoted
And why would switching address spaces obviously be much slower?
There'll be a very small number of TLB fills needed for the actual
protected access.
you'll be duplicating TLB entries in the alternative PCID for both code
and data, where they will accumulate (=take room away from the normal PCID
and expose unwanted memory for access) unless you also flush them when
switching back (which then will cost even more cycles). also i'm not sure
that processors implement all the 12 PCID bits so depending on how many PCIDs
you plan to use, you could be causing even more unnecessary TLB replacements.
Unless the CPU is rather dumber than I expect, the only duplicated
entries should be for the writable aliases of pages that are written.
The rest of the pages are global and should be shared for all PCIDs.
--Andy
On Sun, Apr 9, 2017 at 5:47 AM, PaX Team [off-list ref] wrote:
quoted
on x86 the cost of the pax_open/close_kernel primitives comes from the cr0
writes and nothing else, use_mm suffers not only from the cr3 writes but
also locking/atomic ops and cr4 writes on its path and the inevitable TLB
entry costs. and if cpu vendors cared enough, they could make toggling cr0.wp
a fast path in the microcode and reduce its overhead by an order of magnitude.
If the CR4 writes happen in for this use case, that's a bug.
that depends on how you plan to handle perf/rdpmc users and how many
alternative mm structs you plan to manage (one global, one per cpu,
one per mm struct, etc).
quoted
you'll be duplicating TLB entries in the alternative PCID for both code
and data, where they will accumulate (=take room away from the normal PCID
and expose unwanted memory for access) unless you also flush them when
switching back (which then will cost even more cycles). also i'm not sure
that processors implement all the 12 PCID bits so depending on how many PCIDs
you plan to use, you could be causing even more unnecessary TLB replacements.
Unless the CPU is rather dumber than I expect, the only duplicated
entries should be for the writable aliases of pages that are written.
The rest of the pages are global and should be shared for all PCIDs.
well, 4.10.2.4 has language like this (4.10.3.2 implies similar):
A logical processor may use a global TLB entry to translate a linear
address, even if the TLB entry is associated with a PCID different
from the current PCID.
that to me says that global page entries are associated with a PCID and
may (not) be used while in another PCID. in Intel-speak that's not 'dumb'
but "tricks up our sleeve that we don't really want to tell you about in
detail, except perhaps under a NDA".
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-10 16:01:48
On Mon, Apr 10, 2017 at 3:42 AM, PaX Team [off-list ref] wrote:
On 9 Apr 2017 at 17:10, Andy Lutomirski wrote:
quoted
On Sun, Apr 9, 2017 at 5:47 AM, PaX Team [off-list ref] wrote:
quoted
on x86 the cost of the pax_open/close_kernel primitives comes from the cr0
writes and nothing else, use_mm suffers not only from the cr3 writes but
also locking/atomic ops and cr4 writes on its path and the inevitable TLB
entry costs. and if cpu vendors cared enough, they could make toggling cr0.wp
a fast path in the microcode and reduce its overhead by an order of magnitude.
If the CR4 writes happen in for this use case, that's a bug.
that depends on how you plan to handle perf/rdpmc users and how many
alternative mm structs you plan to manage (one global, one per cpu,
one per mm struct, etc).
I was thinking one global unless more are needed for some reason.
quoted
quoted
you'll be duplicating TLB entries in the alternative PCID for both code
and data, where they will accumulate (=take room away from the normal PCID
and expose unwanted memory for access) unless you also flush them when
switching back (which then will cost even more cycles). also i'm not sure
that processors implement all the 12 PCID bits so depending on how many PCIDs
you plan to use, you could be causing even more unnecessary TLB replacements.
Unless the CPU is rather dumber than I expect, the only duplicated
entries should be for the writable aliases of pages that are written.
The rest of the pages are global and should be shared for all PCIDs.
well, 4.10.2.4 has language like this (4.10.3.2 implies similar):
A logical processor may use a global TLB entry to translate a linear
address, even if the TLB entry is associated with a PCID different
from the current PCID.
I read this as: the CPU still semantically tags global TLB entries
with a PCID, but the CPU will use (probably) use those TLB entries
even if the PCIDs don't match. IIRC none of the TLB instructions have
any effect that makes the PCID associated with a global entry visible,
so the CPU could presumably omit the PCID tags entirely for global
entries. E.g. I don't think there's any way to say "flush global
entries with a given PCID".
--Andy
From: Thomas Gleixner <hidden> Date: 2017-04-07 20:45:02
On Fri, 7 Apr 2017, Andy Lutomirski wrote:
On Fri, Apr 7, 2017 at 6:30 AM, Mathias Krause [off-list ref] wrote:
quoted
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
quoted
I really do not care whether PaX wants to chase and verify that over and
over. I certainly don't want to take the chance to leak CR0.WP ever and I
very much care about extra stuff to check in the entry/exit path.
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
:)
I think we're approaching this all wrong, actually. The fact that x86
has this CR0.WP thing is arguably a historical accident, and the fact
that PaX uses it doesn't mean that PaX is doing it the best way for
upstream Linux.
As I said before. It should be fused to 1.
Why don't we start at the other end and do a generic non-arch-specific
implementation: set up an mm_struct that contains an RW alias of the
relevant parts of rodata and use use_mm to access it. (That is,
get_fs() to back up the old fs, set_fs(USER_DS),
use_mm(&rare_write_mm), do the write using copy_to_user, undo
everything.)
That works too, though I'm not sure that it's more efficient than
temporarily creating and undoing a single cpu local alias mapping similar
to the kmap_atomic mechanism in the highmem case.
Aside of that the alias mapping requires a full PGDIR entry unless you want
to get into the mess of keeping yet another identity mapping up to date.
Thanks,
tglx
On Fri, Apr 7, 2017 at 1:44 PM, Thomas Gleixner [off-list ref] wrote:
On Fri, 7 Apr 2017, Andy Lutomirski wrote:
quoted
On Fri, Apr 7, 2017 at 6:30 AM, Mathias Krause [off-list ref] wrote:
quoted
On 7 April 2017 at 15:14, Thomas Gleixner [off-list ref] wrote:
quoted
I really do not care whether PaX wants to chase and verify that over and
over. I certainly don't want to take the chance to leak CR0.WP ever and I
very much care about extra stuff to check in the entry/exit path.
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
:)
quoted
I think we're approaching this all wrong, actually. The fact that x86
has this CR0.WP thing is arguably a historical accident, and the fact
that PaX uses it doesn't mean that PaX is doing it the best way for
upstream Linux.
As I said before. It should be fused to 1.
quoted
Why don't we start at the other end and do a generic non-arch-specific
implementation: set up an mm_struct that contains an RW alias of the
relevant parts of rodata and use use_mm to access it. (That is,
get_fs() to back up the old fs, set_fs(USER_DS),
use_mm(&rare_write_mm), do the write using copy_to_user, undo
everything.)
That works too, though I'm not sure that it's more efficient than
temporarily creating and undoing a single cpu local alias mapping similar
to the kmap_atomic mechanism in the highmem case.
Aside of that the alias mapping requires a full PGDIR entry unless you want
to get into the mess of keeping yet another identity mapping up to date.
I probably chose the wrong name for this feature (write rarely).
That's _usually_ true, but "sensitive_write()" was getting rather
long. The things that we need to protect with this are certainly stuff
that doesn't get much writing, but some things are just plain
sensitive (like page tables) and we should still try to be as fast as
possible with them.
I'll try to include a third example in the next posting of the series
that makes this more obvious.
I'm all for a general case for the infrastructure (as Andy and Mark
has mentioned), but I don't want to get into the situation where
people start refusing to use it because it's "too slow" (for example,
see refcount_t vs net-dev right now).
-Kees
--
Kees Cook
Pixel Security
From: Daniel Micay <hidden> Date: 2017-04-08 04:13:03
I probably chose the wrong name for this feature (write rarely).
That's _usually_ true, but "sensitive_write()" was getting rather
long. The things that we need to protect with this are certainly stuff
that doesn't get much writing, but some things are just plain
sensitive (like page tables) and we should still try to be as fast as
possible with them.
Not too late to rename it. Scoped write? I think it makes change to
use a different API than PaX for portability too, but not a different
x86 implementation. It's quite important to limit the writes to the
calling thread and it needs to perform well to be introduced widely.
I'm all for a general case for the infrastructure (as Andy and Mark
has mentioned), but I don't want to get into the situation where
people start refusing to use it because it's "too slow" (for example,
see refcount_t vs net-dev right now).
Meanwhile, the PaX implementation has improved to avoid the issues
that were brought up while only introducing a single always-predicted
(due to code placement) branch on the overflow flag. That seems to
have gone unnoticed upstream, where there's now a much slower
implementation that's not more secure, and is blocked from
introduction in areas where it's most needed based on the performance.
Not to mention that it's opt-in... which is never going to work.
From: Daniel Micay <hidden> Date: 2017-04-08 04:22:00
quoted
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
That didn't seem to matter for landing a rewrite of KSTACKOVERFLOW
with a bunch of *known* DoS bugs dealt with in grsecurity and those
were known issues that were unfixed for no apparent reason other than
keeping egos intact. It looks like there are still some left...
In that case, there also wasn't a security/performance advantage.
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-08 05:07:57
On Fri, Apr 7, 2017 at 9:21 PM, Daniel Micay [off-list ref] wrote:
quoted
quoted
Fair enough. However, placing a BUG_ON(!(read_cr0() & X86_CR0_WP))
somewhere sensible should make those "leaks" visible fast -- and their
exploitation impossible, i.e. fail hard.
The leaks surely exist and now we'll just add an exploitable BUG.
That didn't seem to matter for landing a rewrite of KSTACKOVERFLOW
with a bunch of *known* DoS bugs dealt with in grsecurity and those
were known issues that were unfixed for no apparent reason other than
keeping egos intact. It looks like there are still some left...
In that case, there also wasn't a security/performance advantage.
This is wildly off topic, but I think it's worth answering anyway
because there's an important point here:
grsecurity and PaX are great projects. They have a lot of good ideas,
and they're put together quite nicely. The upstream kernel should
*not* do things differently from they way they are in grsecurity/PaX
just because it wants to be different. Conversely, the upstream
kernel should not do things the same way as PaX just to be more like
PaX.
Keep in mind that the upstream kernel and grsecurity/PaX operate under
different constraints. The upstream kernel tries to keep itself clean
and to make tree-wide updates rather that keeping compatibility stuff
around. PaX and grsecurity presumably want to retain some degree of
simplicity when porting to newer upstream versions.
In the context of virtually mapped stacks / KSTACKOVERFLOW, this
naturally leads to different solutions. The upstream kernel had a
bunch of buggy drivers that played badly with virtually mapped stacks.
grsecurity sensibly went for the approach where the buggy drivers kept
working. The upstream kernel went for the approach of fixing the
drivers rather than keeping a compatibility workaround. Different
constraints, different solutions.
The point being that, if someone sends a patch to the x86 entry code
that's justified by "be like PaX" or by "be different than PaX",
that's not okay. It needs a real justification that stands on its
own.
In the case of rare writes or pax_open_kernel [1] or whatever we want
to call it, CR3 would work without arch-specific code, and CR0 would
not. That's an argument for CR3 that would need to be countered by
something. (Sure, avoiding leaks either way might need arch changes.
OTOH, a *randomized* CR3-based approach might not have as much of a
leak issue to begin with.)
[1] Contrary to popular belief, I don't sit around reading grsecurity
code or config options, so I really don't know what this thing is
called.
From: Daniel Micay <hidden> Date: 2017-04-08 07:33:34
grsecurity and PaX are great projects. They have a lot of good ideas,
and they're put together quite nicely. The upstream kernel should
*not* do things differently from they way they are in grsecurity/PaX
just because it wants to be different. Conversely, the upstream
kernel should not do things the same way as PaX just to be more like
PaX.
Keep in mind that the upstream kernel and grsecurity/PaX operate under
different constraints. The upstream kernel tries to keep itself clean
and to make tree-wide updates rather that keeping compatibility stuff
around. PaX and grsecurity presumably want to retain some degree of
simplicity when porting to newer upstream versions.
In the context of virtually mapped stacks / KSTACKOVERFLOW, this
naturally leads to different solutions. The upstream kernel had a
bunch of buggy drivers that played badly with virtually mapped stacks.
grsecurity sensibly went for the approach where the buggy drivers kept
working. The upstream kernel went for the approach of fixing the
drivers rather than keeping a compatibility workaround. Different
constraints, different solutions.
Sure, but nothing is currently landed right now and the PaX
implementation is a known quantity with a lot of testing. The
submitted code is aimed at rare writes to globals, but this feature is
more than that and design decisions shouldn't be based on just the
short term. Kees is sensibly landing features by submitting them a
little bit at a time, but a negative side effect of that is too much
focus on just the initial proposed usage.
As a downstream that's going to be making heavy use of mainline
security features as a base due to PaX and grsecurity becoming
commercial only private patches (*because* of upstream and the
companies involved), I hope things go in the right direction i.e. not
weaker/slower implementations than PaX. For example, while USERCOPY
isn't entirely landed upstream (missing slab whitelisting and user
offset/size), it's the base for the full feature and is going to get
more testing. On the other hand, refcount_t and the slab/page
sanitization work is 100% useless if you're willing to incorporate the
changes to do it without needless performance loss and complexity. PAN
emulation on 64-bit ARM was fresh ground while on ARMv7 a weaker
implementation was used for no better reason than clashing egos. The
upstream virtual mapped stacks will probably be perfectly good, but I
just find it to be such a waste of time and effort to reinvent it and
retread the same ground in terms of finding the bugs.
I actually care a lot more about 64-bit ARM support than I do x86, but
using a portable API for pax_open_kernel (for the simple uses at
least) is separate from choosing the underlying implementation. There
might not be a great way to do it on the architectures I care about
but that doesn't need to hinder x86. It's really not that much code...
A weaker/slower implementation for x86 also encourages the same
elsewhere.
In the case of rare writes or pax_open_kernel [1] or whatever we want
to call it, CR3 would work without arch-specific code, and CR0 would
not. That's an argument for CR3 that would need to be countered by
something. (Sure, avoiding leaks either way might need arch changes.
OTOH, a *randomized* CR3-based approach might not have as much of a
leak issue to begin with.)
By randomized do you mean just ASLR? Even if the window of opportunity
to exploit it is small, it's really not the same and this has a lot
more use than just rare writes to small global variables.
I wouldn't consider stack ASLR to be a replacement for making them
readable/writable only by the current thread either (required for
race-free return CFI on x86, at least without not using actual
returns).
[1] Contrary to popular belief, I don't sit around reading grsecurity
code or config options, so I really don't know what this thing is
called.
Lots of the features aren't actually named. Maybe this could be
considered part of KERNEXEC but I don't think it is.
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-08 15:20:38
On Sat, Apr 8, 2017 at 12:33 AM, Daniel Micay [off-list ref] wrote:
The
submitted code is aimed at rare writes to globals, but this feature is
more than that and design decisions shouldn't be based on just the
short term.
Then, if you disagree with a proposed design, *explain why* in a
standalone manner. Say what future uses a different design would
have.
I actually care a lot more about 64-bit ARM support than I do x86, but
using a portable API for pax_open_kernel (for the simple uses at
least) is separate from choosing the underlying implementation. There
might not be a great way to do it on the architectures I care about
but that doesn't need to hinder x86. It's really not that much code...
A weaker/slower implementation for x86 also encourages the same
elsewhere.
No one has explained how CR0.WP is weaker or slower than my proposal.
Here's what I'm proposing:
At boot, choose a random address A. Create an mm_struct that has a
single VMA starting at A that represents the kernel's rarely-written
section. Compute O = (A - VA of rarely-written section). To do a
rare write, use_mm() the mm, write to (VA + O), then unuse_mm().
This should work on any arch that has an MMU that allows this type of
aliasing and that doesn't have PA-based protections on the
rarely-written section.
It'll be considerably slower than CR0.WP on a current x86 kernel, but,
with PCID landed, it shouldn't be much slower. It has the added
benefit that writes to non-rare-write data using the rare-write
primitive will fail.
--Andy
On Sat, Apr 8, 2017 at 12:33 AM, Daniel Micay [off-list ref] wrote:
quoted
The
submitted code is aimed at rare writes to globals, but this feature is
more than that and design decisions shouldn't be based on just the
short term.
Then, if you disagree with a proposed design, *explain why* in a
standalone manner. Say what future uses a different design would
have.
quoted
I actually care a lot more about 64-bit ARM support than I do x86, but
using a portable API for pax_open_kernel (for the simple uses at
least) is separate from choosing the underlying implementation. There
might not be a great way to do it on the architectures I care about
but that doesn't need to hinder x86. It's really not that much code...
A weaker/slower implementation for x86 also encourages the same
elsewhere.
No one has explained how CR0.WP is weaker or slower than my proposal.
Here's what I'm proposing:
At boot, choose a random address A. Create an mm_struct that has a
single VMA starting at A that represents the kernel's rarely-written
section. Compute O = (A - VA of rarely-written section). To do a
rare write, use_mm() the mm, write to (VA + O), then unuse_mm().
BTW., note that this is basically a pagetable based protection key variant.
It'll be considerably slower than CR0.WP on a current x86 kernel, but, with PCID
landed, it shouldn't be much slower. It has the added benefit that writes to
non-rare-write data using the rare-write primitive will fail.
... which is a security advantage of the use_mm() based design you suggest.
Thanks,
Ingo
From: Mark Rutland <mark.rutland@arm.com> Date: 2017-04-10 10:23:31
On Sat, Apr 08, 2017 at 08:20:03AM -0700, Andy Lutomirski wrote:
On Sat, Apr 8, 2017 at 12:33 AM, Daniel Micay [off-list ref] wrote:
quoted
The
submitted code is aimed at rare writes to globals, but this feature is
more than that and design decisions shouldn't be based on just the
short term.
Then, if you disagree with a proposed design, *explain why* in a
standalone manner. Say what future uses a different design would
have.
quoted
I actually care a lot more about 64-bit ARM support than I do x86, but
using a portable API for pax_open_kernel (for the simple uses at
least) is separate from choosing the underlying implementation. There
might not be a great way to do it on the architectures I care about
but that doesn't need to hinder x86. It's really not that much code...
A weaker/slower implementation for x86 also encourages the same
elsewhere.
No one has explained how CR0.WP is weaker or slower than my proposal.
Here's what I'm proposing:
At boot, choose a random address A. Create an mm_struct that has a
single VMA starting at A that represents the kernel's rarely-written
section. Compute O = (A - VA of rarely-written section). To do a
rare write, use_mm() the mm, write to (VA + O), then unuse_mm().
This should work on any arch that has an MMU that allows this type of
aliasing and that doesn't have PA-based protections on the
rarely-written section.
grsecurity and PaX are great projects. They have a lot of good ideas,
and they're put together quite nicely. The upstream kernel should
*not* do things differently from they way they are in grsecurity/PaX
just because it wants to be different. Conversely, the upstream
kernel should not do things the same way as PaX just to be more like
PaX.
so weit so gut.
Keep in mind that the upstream kernel and grsecurity/PaX operate under
different constraints. The upstream kernel tries to keep itself clean
so do we.
and to make tree-wide updates rather that keeping compatibility stuff
around.
so do we (e.g., fptr fixes for RAP, non-refcount atomic users, etc).
PaX and grsecurity presumably want to retain some degree of
simplicity when porting to newer upstream versions.
s/simplicity/minimality/ as the code itself can be complex but that'll be
of the minimal complexity we can come up with.
In the context of virtually mapped stacks / KSTACKOVERFLOW, this
naturally leads to different solutions. The upstream kernel had a
bunch of buggy drivers that played badly with virtually mapped stacks.
grsecurity sensibly went for the approach where the buggy drivers kept
working. The upstream kernel went for the approach of fixing the
drivers rather than keeping a compatibility workaround. Different
constraints, different solutions.
except that's not what happened at all. spender's first version did just
a vmalloc for the kstack like the totally NIH'd version upstream does
now. while we always anticipated buggy dma users and thus had code that
would detect them so that we could fix them, we quickly figured that the
upstream kernel wasn't quite up to snuff as we had assumed and faced with
the amount of buggy code, we went for the current vmap approach which
kept users' systems working instead of breaking them.
you're trying to imply that upstream fixed the drivers but as the facts
show, that's not true. you simply unleashed your code on the world and
hoped(?) that enough suckers would try it out during the -rc window. as
we all know several releases and almost a year later, that was a losing
bet as you still keep fixing those drivers (and something tells me that
we haven't seen the end of it). this is simply irresponsible engineering
for no technical reason.
In the case of rare writes or pax_open_kernel [1] or whatever we want
to call it, CR3 would work without arch-specific code, and CR0 would
not. That's an argument for CR3 that would need to be countered by
something. (Sure, avoiding leaks either way might need arch changes.
OTOH, a *randomized* CR3-based approach might not have as much of a
leak issue to begin with.)
i have yet to see anyone explain what they mean by 'leak' here but if it
is what i think it is then the arch specific entry/exit changes are not
optional but mandatory. see below for randomization.
[merging in your other mail as it's the same topic]
No one has explained how CR0.WP is weaker or slower than my proposal.
you misunderstood, Daniel was talking about your use_mm approach.
Here's what I'm proposing:
At boot, choose a random address A.
what is the threat that a random address defends against?
Create an mm_struct that has a
single VMA starting at A that represents the kernel's rarely-written
section. Compute O = (A - VA of rarely-written section). To do a
rare write, use_mm() the mm, write to (VA + O), then unuse_mm().
the problem is that the amount of __read_only data extends beyond vmlinux,
i.e., this approach won't scale. another problem is that it can't be used
inside use_mm and switch_mm themselves (no read-only task structs or percpu
pgd for you ;) and probably several other contexts.
last but not least, use_mm says this about itself:
(Note: this routine is intended to be called only
from a kernel thread context)
so using it will need some engineering (or the comment be fixed).
This should work on any arch that has an MMU that allows this type of
aliasing and that doesn't have PA-based protections on the rarely-written
section.
you didn't address the arch-specific changes needed in the enter/exit paths.
It'll be considerably slower than CR0.WP on a current x86 kernel, but,
with PCID landed, it shouldn't be much slower.
based on my experience with UDEREF on amd64, unfortunately PCID isn't all
it's cracked up to be (IIRC, it maybe halved the UDEREF overhead instead of
basically eliminating it as i had anticipated, and that was on snb, ivb and
later do even worse).
It has the added benefit that writes to non-rare-write data using the
rare-write primitive will fail.
what is the threat model you're assuming for this feature? based on what i
have for PaX (arbitrary read/write access exploited for data-only attacks),
the above makes no sense to me...
From: Andy Lutomirski <luto@kernel.org> Date: 2017-04-10 00:32:08
On Sun, Apr 9, 2017 at 1:24 PM, PaX Team [off-list ref] wrote:
quoted
In the context of virtually mapped stacks / KSTACKOVERFLOW, this
naturally leads to different solutions. The upstream kernel had a
bunch of buggy drivers that played badly with virtually mapped stacks.
grsecurity sensibly went for the approach where the buggy drivers kept
working. The upstream kernel went for the approach of fixing the
drivers rather than keeping a compatibility workaround. Different
constraints, different solutions.
except that's not what happened at all. spender's first version did just
a vmalloc for the kstack like the totally NIH'd version upstream does
now. while we always anticipated buggy dma users and thus had code that
would detect them so that we could fix them, we quickly figured that the
upstream kernel wasn't quite up to snuff as we had assumed and faced with
the amount of buggy code, we went for the current vmap approach which
kept users' systems working instead of breaking them.
you're trying to imply that upstream fixed the drivers but as the facts
show, that's not true. you simply unleashed your code on the world and
hoped(?) that enough suckers would try it out during the -rc window. as
we all know several releases and almost a year later, that was a losing
bet as you still keep fixing those drivers (and something tells me that
we haven't seen the end of it). this is simply irresponsible engineering
for no technical reason.
I consider breaking buggy drivers (in a way that they either generally
work okay or that they break with a nice OOPS depending on config) to
be better than having a special case in what's supposed to be a fast
path to keep them working. I did consider forcing the relevant debug
options on for a while just to help shake these bugs out the woodwork
faster.
quoted
In the case of rare writes or pax_open_kernel [1] or whatever we want
to call it, CR3 would work without arch-specific code, and CR0 would
not. That's an argument for CR3 that would need to be countered by
something. (Sure, avoiding leaks either way might need arch changes.
OTOH, a *randomized* CR3-based approach might not have as much of a
leak issue to begin with.)
i have yet to see anyone explain what they mean by 'leak' here but if it
is what i think it is then the arch specific entry/exit changes are not
optional but mandatory. see below for randomization.
By "leak" I mean that a bug or exploit causes unintended code to run
with CR0.WP or a special CR3 or a special PTE or whatever loaded. PaX
hooks the entry code to avoid leaks.
quoted
At boot, choose a random address A.
what is the threat that a random address defends against?
Makes it harder to exploit a case where the CR3 setting leaks.
quoted
Create an mm_struct that has a
single VMA starting at A that represents the kernel's rarely-written
section. Compute O = (A - VA of rarely-written section). To do a
rare write, use_mm() the mm, write to (VA + O), then unuse_mm().
the problem is that the amount of __read_only data extends beyond vmlinux,
i.e., this approach won't scale. another problem is that it can't be used
inside use_mm and switch_mm themselves (no read-only task structs or percpu
pgd for you ;) and probably several other contexts.
Can you clarify these uses that extend beyond vmlinux? I haven't
looked at the grsecurity patch extensively. Are you talking about the
BPF JIT stuff? If so, I think that should possibly be handled a bit
differently, since I think the normal
write-to-rare-write-vmlinux-sections primitive should preferably *not*
be usable to write to executable pages. Using a real mm_struct for
this could help.
last but not least, use_mm says this about itself:
(Note: this routine is intended to be called only
from a kernel thread context)
so using it will need some engineering (or the comment be fixed).
Indeed.
quoted
It has the added benefit that writes to non-rare-write data using the
rare-write primitive will fail.
what is the threat model you're assuming for this feature? based on what i
have for PaX (arbitrary read/write access exploited for data-only attacks),
the above makes no sense to me...
If I use the primitive to try to write a value to the wrong section
(write to kernel text, for example), IMO it would be nice to OOPS
instead of succeeding.
Please keep in mind that, unlike PaX, uses of a pax_open_kernel()-like
function will may be carefully audited by a friendly security expert
such as yourself. It would be nice to harden the primitive to a
reasonable extent against minor misuses such as putting it in a
context where the compiler will emit mov-a-reg-with-WP-set-to-CR0;
ret.