Skip to contentSkip to conversation

S.A.R.A. a new stacked LSM

RFC Superseded Salvatore Mesoraca 3 participants 21 messages Jun 15, 2017 – Jun 29, 2017

Subsystems (8)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover S.A.R.A. a new stacked LSM

S.A.R.A. (S.A.R.A. is Another Recursive Acronym) is a stacked Linux Security Module that aims to collect heterogeneous security measures, providing a common interface to manage them.
It can be useful to allow minor security features to use advanced management options, like user-space configuration files and tools, without too much overhead.
Some submodules that use this framework are also introduced. The code is quite long, I apologize for this. Thank you in advance to anyone who will take the time to review this patchset.

S.A.R.A. is meant to be stacked but it needs cred blobs and the procattr interface, so I temporarily implemented those parts in a way that won't be acceptable for upstream, but it works for now. I know that there is some ongoing work to make cred blobs and procattr stackable, as soon as the new interfaces will be available I'll reimplement the involved parts.
At the moment I've been able to test it only on x86.

The only submodule introduced in this patchset is WX Protection.

The kernel-space part is complemented by its user-space counterpart:
saractl [1].
A test suite for WX Protection, called sara-test [2], is also available.

WX Protection aims to improve user-space programs security by applying:
- W^X enforcement: program can't have a page of memory that is marked, at the same time, writable and executable.
- W!->X restriction: any page that could have been marked as writable in the past won't ever be allowed to be marked as executable.
- Executable MMAP prevention: prevents the creation of new executable mmaps after the dynamic libraries have been loaded.
All of the above features can be enabled or disabled both system wide or on a per executable basis through the use of configuration files managed by "saractl".
It is important to note that some programs may have issues working with WX Protection. In particular:
- W^X enforcement will cause problems to any programs that needs memory pages mapped both as writable and executable at the same time e.g. programs with executable stack markings in the PT_GNU_STACK segment.
- W!->X restriction will cause problems to any program that needs to generate executable code at run time or to modify executable pages e.g. programs with a JIT compiler built-in or linked against a non-PIC library.
- Executable MMAP prevention can work only with programs that have at least partial RELRO support. It's disabled automatically for programs that lack this feature. It will cause problems to any program that uses dlopen or tries to do an executable mmap. Unfortunately this feature is the one that could create most problems and should be enabled only after careful evaluation.
To extend the scope of the above features, despite the issues that they may cause, they are complemented by:
- procattr interface: can be used by a program to discover which WX Protection features are enabled and/or to tighten them.
- Trampoline emulation: emulates the execution of well-known "trampolines" even when they are placed in non-executable memory.
Parts of WX Protection are inspired by some of the features available in PaX.

More information can be found in the documentation introduced in the first patch and in the "commit message" of the following emails.

Changes in v2:
- Removed USB filtering submodule and relative hook
- s/saralib/libsara/ typo
- STR macro renamed to avoid conflicts
- check_vmflags hook now returns an error code instead of just 1 or 0. (suggested by Casey Schaufler)
- pr_wxp macro rewritten as function for readability
- Fixed i386 compilation warnings
- Documentation now states clearly that changes done via procattr interface only apply to current thread. (suggested by Jann Horn)

[1] https://github.com/smeso/saractl
[2] https://github.com/smeso/sara-test

Salvatore Mesoraca (9):
S.A.R.A. Documentation
S.A.R.A. framework creation
Creation of "check_vmflags" LSM hook S.A.R.A. cred blob management
S.A.R.A. WX Protection
Creation of "pagefault_handler_x86" LSM hook Trampoline emulation
Allowing for stacking procattr support in S.A.R.A. S.A.R.A. WX Protection procattr interface

 Documentation/admin-guide/kernel-parameters.txt |  23 +
 Documentation/security/00-INDEX                 |   2 +
 Documentation/security/SARA.rst                 | 170 +++++
 arch/x86/mm/fault.c                             |   6 +
 fs/proc/base.c                                  |  38 +
 include/linux/cred.h                            |   3 +
 include/linux/lsm_hooks.h                       |  21 +
 include/linux/security.h                        |  17 +
 mm/mmap.c                                       |  13 +
 security/Kconfig                                |   1 +
 security/Makefile                               |   2 +
 security/sara/Kconfig                           | 134 ++++
 security/sara/Makefile                          |   4 +
 security/sara/include/sara.h                    |  29 +
 security/sara/include/sara_data.h               |  47 ++
 security/sara/include/securityfs.h              |  59 ++
 security/sara/include/trampolines.h             | 171 +++++
 security/sara/include/utils.h                   |  69 ++
 security/sara/include/wxprot.h                  |  27 +
 security/sara/main.c                            | 107 +++
 security/sara/sara_data.c                       |  79 ++
 security/sara/securityfs.c                      | 560 +++++++++++++++
 security/sara/utils.c                           | 151 ++++
 security/sara/wxprot.c                          | 910 ++++++++++++++++++++++++
 security/security.c                             |  37 +-
 25 files changed, 2678 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/security/SARA.rst
 create mode 100644 security/sara/Kconfig
 create mode 100644 security/sara/Makefile
 create mode 100644 security/sara/include/sara.h
 create mode 100644 security/sara/include/sara_data.h
 create mode 100644 security/sara/include/securityfs.h
 create mode 100644 security/sara/include/trampolines.h
 create mode 100644 security/sara/include/utils.h
 create mode 100644 security/sara/include/wxprot.h
 create mode 100644 security/sara/main.c
 create mode 100644 security/sara/sara_data.c
 create mode 100644 security/sara/securityfs.c
 create mode 100644 security/sara/utils.c
 create mode 100644 security/sara/wxprot.c
Signature · 1 line
1.9.1
#1 lore raw

RFC v2 1/9 S.A.R.A. Documentation

Adding documentation for S.A.R.A. LSM.

---
 Documentation/admin-guide/kernel-parameters.txt |  23 ++++
 Documentation/security/00-INDEX                 |   2 +
 Documentation/security/SARA.rst                 | 170 ++++++++++++++++++++++++
 3 files changed, 195 insertions(+)
 create mode 100644 Documentation/security/SARA.rst
Documentation/admin-guide/kernel-parameters.txt +23 -0
index 0f5c3b4..d8a8d57 100644
@@ -3702,6 +3702,29 @@
 			1 -- enable.
 			Default value is set via kernel config option.
 
+	sara=		[SARA] Disable or enable S.A.R.A. at boot time.
+			If disabled this way S.A.R.A. can't be enabled
+			again.
+			Format: { "0" | "1" }
+			See security/sara/Kconfig help text
+			0 -- disable.
+			1 -- enable.
+			Default value is set via kernel config option.
+
+	sara_wxprot=	[SARA] Disable or enable S.A.R.A. WX Protection
+			at boot time.
+			Format: { "0" | "1" }
+			See security/sara/Kconfig help text
+			0 -- disable.
+			1 -- enable.
+			Default value is 1.
+
+	sara_wxprot_default_flags= [SARA]
+			Set S.A.R.A. WX Protection default flags.
+			Format: <integer>
+			See S.A.R.A. documentation.
+			Default value is set via kernel config option.
+
 	serialnumber	[BUGS=X86-32]
 
 	shapers=	[NET]
Documentation/security/00-INDEX +2 -0
index 45c82fd..fe3583c 100644
@@ -10,6 +10,8 @@ Yama.txt
 	- documentation on the Yama Linux Security Module.
 apparmor.txt
 	- documentation on the AppArmor security extension.
+SARA.rst
+	- documentation on the S.A.R.A. Linux Security Module.
 credentials.txt
 	- documentation about credentials in Linux.
 keys-ecryptfs.txt
Documentation/security/SARA.rst new file +170 -0

170 lines not on this page · raw message

Signature · 1 line
1.9.1
#2 lore raw

RFC v2 2/9 S.A.R.A. framework creation

In reply to Salvatore Mesoraca

Initial S.A.R.A. framework setup.
Creation of a simplified interface to securityfs API to store and retrieve configurations and flags from user-space.
Creation of some generic functions and macros to handle concurrent access to configurations, memory allocation and path resolution.

---
 include/linux/lsm_hooks.h          |   5 +
 security/Kconfig                   |   1 +
 security/Makefile                  |   2 +
 security/sara/Kconfig              |  42 +++
 security/sara/Makefile             |   3 +
 security/sara/include/sara.h       |  29 ++
 security/sara/include/securityfs.h |  59 ++++
 security/sara/include/utils.h      |  69 +++++
 security/sara/main.c               |  95 +++++++
 security/sara/securityfs.c         | 560 +++++++++++++++++++++++++++++++++++++
 security/sara/utils.c              | 151 ++++++++++
 security/security.c                |   1 +
 12 files changed, 1017 insertions(+)
 create mode 100644 security/sara/Kconfig
 create mode 100644 security/sara/Makefile
 create mode 100644 security/sara/include/sara.h
 create mode 100644 security/sara/include/securityfs.h
 create mode 100644 security/sara/include/utils.h
 create mode 100644 security/sara/main.c
 create mode 100644 security/sara/securityfs.c
 create mode 100644 security/sara/utils.c
include/linux/lsm_hooks.h +5 -0
index 080f34e..bd274db 100644
@@ -1946,5 +1946,10 @@ static inline void __init yama_add_hooks(void) { }
 #else
 static inline void loadpin_add_hooks(void) { };
 #endif
+#ifdef CONFIG_SECURITY_SARA
+void __init sara_init(void);
+#else
+static inline void __init sara_init(void) { };
+#endif
 
 #endif /* ! __LINUX_LSM_HOOKS_H */
security/Kconfig +1 -0
index 93027fd..1c13545 100644
@@ -195,6 +195,7 @@ source security/tomoyo/Kconfig
 source security/apparmor/Kconfig
 source security/loadpin/Kconfig
 source security/yama/Kconfig
+source security/sara/Kconfig
 
 source security/integrity/Kconfig
 
security/Makefile +2 -0
index f2d71cd..5d3578e 100644
@@ -9,6 +9,7 @@ subdir-$(CONFIG_SECURITY_TOMOYO)        += tomoyo
 subdir-$(CONFIG_SECURITY_APPARMOR)	+= apparmor
 subdir-$(CONFIG_SECURITY_YAMA)		+= yama
 subdir-$(CONFIG_SECURITY_LOADPIN)	+= loadpin
+subdir-$(CONFIG_SECURITY_SARA)		+= sara
 
 # always enable default capabilities
 obj-y					+= commoncap.o
@@ -24,6 +25,7 @@ obj-$(CONFIG_SECURITY_TOMOYO)		+= tomoyo/
 obj-$(CONFIG_SECURITY_APPARMOR)		+= apparmor/
 obj-$(CONFIG_SECURITY_YAMA)		+= yama/
 obj-$(CONFIG_SECURITY_LOADPIN)		+= loadpin/
+obj-$(CONFIG_SECURITY_SARA)		+= sara/
 obj-$(CONFIG_CGROUP_DEVICE)		+= device_cgroup.o
 
 # Object integrity file lists
security/sara/Kconfig new file +42 -0

42 lines not on this page · raw message

security/sara/Makefile new file +3 -0
new file mode 100644
index 0000000..8acd291
@@ -0,0 +1,3 @@
+obj-$(CONFIG_SECURITY_SARA) := sara.o
+
+sara-y := main.o securityfs.o utils.o
security/sara/include/sara.h new file +29 -0
new file mode 100644
index 0000000..1001a8a
@@ -0,0 +1,29 @@
+/*
+ * S.A.R.A. Linux Security Module
+ *
+ * Copyright (C) 2017 Salvatore Mesoraca <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2, as
+ * published by the Free Software Foundation.
+ *
+ */
+
+#ifndef __SARA_H
+#define __SARA_H
+
+#include <linux/types.h>
+#include <uapi/linux/limits.h>
+
+#define SARA_VERSION 0
+#define SARA_PATH_MAX PATH_MAX
+
+#undef pr_fmt
+#define pr_fmt(fmt) "SARA: " fmt
+
+extern bool sara_config_locked __read_mostly;
+extern bool sara_enabled __read_mostly;
+
+void sara_init(void) __init;
+
+#endif /* __SARA_H */
security/sara/include/securityfs.h new file +59 -0

59 lines not on this page · raw message

security/sara/include/utils.h new file +69 -0

69 lines not on this page · raw message

security/sara/main.c new file +95 -0

95 lines not on this page · raw message

security/sara/securityfs.c new file +560 -0

560 lines not on this page · raw message

security/sara/utils.c new file +151 -0

151 lines not on this page · raw message

security/security.c +1 -0
index b9fea39..42c8028 100644
@@ -69,6 +69,7 @@ int __init security_init(void)
 	capability_add_hooks();
 	yama_add_hooks();
 	loadpin_add_hooks();
+	sara_init();
 
 	/*
 	 * Load all the remaining security modules.
Signature · 1 line
1.9.1
#3 lore raw

RFC v2 3/9 Creation of "check_vmflags" LSM hook

In reply to Salvatore Mesoraca

Creation of a new LSM hook to check if a given configuration of vmflags, for a new memory allocation request, should be allowed or not. It's placed in "do_mmap", "do_brk_flags" and "__install_special_mapping".

---
 include/linux/lsm_hooks.h |  7 +++++++
 include/linux/security.h  |  6 ++++++
 mm/mmap.c                 | 13 +++++++++++++
 security/security.c       |  5 +++++
 4 files changed, 31 insertions(+)
include/linux/lsm_hooks.h +7 -0
index bd274db..33dab16 100644
@@ -483,6 +483,11 @@
  *	@reqprot contains the protection requested by the application.
  *	@prot contains the protection that will be applied by the kernel.
  *	Return 0 if permission is granted.
+ * @check_vmflags:
+ *	Check if the requested @vmflags are allowed.
+ *	@vmflags contains requested the vmflags.
+ *	Return 0 if the operation is allowed to continue otherwise return
+ *	the appropriate error code.
  * @file_lock:
  *	Check permission before performing file locking operations.
  *	Note: this hook mediates both flock and fcntl style locks.
@@ -1477,6 +1482,7 @@
 				unsigned long prot, unsigned long flags);
 	int (*file_mprotect)(struct vm_area_struct *vma, unsigned long reqprot,
 				unsigned long prot);
+	int (*check_vmflags)(vm_flags_t vmflags);
 	int (*file_lock)(struct file *file, unsigned int cmd);
 	int (*file_fcntl)(struct file *file, unsigned int cmd,
 				unsigned long arg);
@@ -1747,6 +1753,7 @@ struct security_hook_heads {
 	struct list_head mmap_addr;
 	struct list_head mmap_file;
 	struct list_head file_mprotect;
+	struct list_head check_vmflags;
 	struct list_head file_lock;
 	struct list_head file_fcntl;
 	struct list_head file_set_fowner;
include/linux/security.h +6 -0
index af675b5..8701872 100644
@@ -300,6 +300,7 @@ int security_mmap_file(struct file *file, unsigned long prot,
 int security_mmap_addr(unsigned long addr);
 int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
 			   unsigned long prot);
+int security_check_vmflags(vm_flags_t vmflags);
 int security_file_lock(struct file *file, unsigned int cmd);
 int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg);
 void security_file_set_fowner(struct file *file);
@@ -823,6 +824,11 @@ static inline int security_file_mprotect(struct vm_area_struct *vma,
 	return 0;
 }
 
+static inline int security_check_vmflags(vm_flags_t vmflags)
+{
+	return 0;
+}
+
 static inline int security_file_lock(struct file *file, unsigned int cmd)
 {
 	return 0;
mm/mmap.c +13 -0
index f82741e..132061b 100644
@@ -1311,6 +1311,7 @@ unsigned long do_mmap(struct file *file, unsigned long addr,
 {
 	struct mm_struct *mm = current->mm;
 	int pkey = 0;
+	int error;
 
 	*populate = 0;
 
@@ -1363,6 +1364,10 @@ unsigned long do_mmap(struct file *file, unsigned long addr,
 	vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
 
+	error = security_check_vmflags(vm_flags);
+	if (error)
+		return error;
+
 	if (flags & MAP_LOCKED)
 		if (!can_do_mlock())
 			return -EPERM;
@@ -2833,6 +2838,10 @@ static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long
 		return -EINVAL;
 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
 
+	error = security_check_vmflags(flags);
+	if (error)
+		return error;
+
 	error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
 	if (offset_in_page(error))
 		return error;
@@ -3208,6 +3217,10 @@ static struct vm_area_struct *__install_special_mapping(
 	int ret;
 	struct vm_area_struct *vma;
 
+	ret = security_check_vmflags(vm_flags);
+	if (ret)
+		return ERR_PTR(ret);
+
 	vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
 	if (unlikely(vma == NULL))
 		return ERR_PTR(-ENOMEM);
security/security.c +5 -0
index 42c8028..7e45846 100644
@@ -900,6 +900,11 @@ int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
 	return call_int_hook(file_mprotect, 0, vma, reqprot, prot);
 }
 
+int security_check_vmflags(vm_flags_t vmflags)
+{
+	return call_int_hook(check_vmflags, 0, vmflags);
+}
+
 int security_file_lock(struct file *file, unsigned int cmd)
 {
 	return call_int_hook(file_lock, 0, file, cmd);
Signature · 1 line
1.9.1
#4 lore raw

Re: [RFC v2 3/9] Creation of "check_vmflags" LSM hook

Quoted 3 lines · Salvatore Mesoraca

Creation of a new LSM hook to check if a given configuration of vmflags, for a new memory allocation request, should be allowed or not. It's placed in "do_mmap", "do_brk_flags" and "__install_special_mapping".

I like this. I think this is something the other LSMs should be checking too. (Though I wonder if it would be helpful to include the VMA in the hook, though it does exist yet, so... hmm.)

-Kees

Quoted 129 lines
---
 include/linux/lsm_hooks.h |  7 +++++++
 include/linux/security.h  |  6 ++++++
 mm/mmap.c                 | 13 +++++++++++++
 security/security.c       |  5 +++++
 4 files changed, 31 insertions(+)
include/linux/lsm_hooks.h +7 -0
index bd274db..33dab16 100644
@@ -483,6 +483,11 @@
  *     @reqprot contains the protection requested by the application.
  *     @prot contains the protection that will be applied by the kernel.
  *     Return 0 if permission is granted.
+ * @check_vmflags:
+ *     Check if the requested @vmflags are allowed.
+ *     @vmflags contains requested the vmflags.
+ *     Return 0 if the operation is allowed to continue otherwise return
+ *     the appropriate error code.
  * @file_lock:
  *     Check permission before performing file locking operations.
  *     Note: this hook mediates both flock and fcntl style locks.
@@ -1477,6 +1482,7 @@
                                unsigned long prot, unsigned long flags);
        int (*file_mprotect)(struct vm_area_struct *vma, unsigned long reqprot,
                                unsigned long prot);
+       int (*check_vmflags)(vm_flags_t vmflags);
        int (*file_lock)(struct file *file, unsigned int cmd);
        int (*file_fcntl)(struct file *file, unsigned int cmd,
                                unsigned long arg);
@@ -1747,6 +1753,7 @@ struct security_hook_heads {
        struct list_head mmap_addr;
        struct list_head mmap_file;
        struct list_head file_mprotect;
+       struct list_head check_vmflags;
        struct list_head file_lock;
        struct list_head file_fcntl;
        struct list_head file_set_fowner;
include/linux/security.h +6 -0
index af675b5..8701872 100644
@@ -300,6 +300,7 @@ int security_mmap_file(struct file *file, unsigned long prot,
 int security_mmap_addr(unsigned long addr);
 int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
                           unsigned long prot);
+int security_check_vmflags(vm_flags_t vmflags);
 int security_file_lock(struct file *file, unsigned int cmd);
 int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg);
 void security_file_set_fowner(struct file *file);
@@ -823,6 +824,11 @@ static inline int security_file_mprotect(struct vm_area_struct *vma,
        return 0;
 }
 
+static inline int security_check_vmflags(vm_flags_t vmflags)
+{
+       return 0;
+}
+
 static inline int security_file_lock(struct file *file, unsigned int cmd)
 {
        return 0;
mm/mmap.c +13 -0
index f82741e..132061b 100644
@@ -1311,6 +1311,7 @@ unsigned long do_mmap(struct file *file, unsigned long addr,
 {
        struct mm_struct *mm = current->mm;
        int pkey = 0;
+       int error;
 
        *populate = 0;
 
@@ -1363,6 +1364,10 @@ unsigned long do_mmap(struct file *file, unsigned long addr,
        vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
                        mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
 
+       error = security_check_vmflags(vm_flags);
+       if (error)
+               return error;
+
        if (flags & MAP_LOCKED)
                if (!can_do_mlock())
                        return -EPERM;
@@ -2833,6 +2838,10 @@ static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long
                return -EINVAL;
        flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
 
+       error = security_check_vmflags(flags);
+       if (error)
+               return error;
+
        error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
        if (offset_in_page(error))
                return error;
@@ -3208,6 +3217,10 @@ static struct vm_area_struct *__install_special_mapping(
        int ret;
        struct vm_area_struct *vma;
 
+       ret = security_check_vmflags(vm_flags);
+       if (ret)
+               return ERR_PTR(ret);
+
        vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
        if (unlikely(vma == NULL))
                return ERR_PTR(-ENOMEM);
security/security.c +5 -1
index 42c8028..7e45846 100644
@@ -900,6 +900,11 @@ int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
        return call_int_hook(file_mprotect, 0, vma, reqprot, prot);
 }
 
+int security_check_vmflags(vm_flags_t vmflags)
+{
+       return call_int_hook(check_vmflags, 0, vmflags);
+}
+
 int security_file_lock(struct file *file, unsigned int cmd)
 {
        return call_int_hook(file_lock, 0, file, cmd);
--

1.9.1

Signature · 2 lines
Kees Cook
Pixel Security
#5 lore raw

Re: [RFC v2 3/9] Creation of "check_vmflags" LSM hook

2017-06-28 1:05 GMT+02:00 Kees Cook <[email protected]>:

Quoted 9 lines
Quoted 3 lines · Salvatore Mesoraca

Creation of a new LSM hook to check if a given configuration of vmflags, for a new memory allocation request, should be allowed or not. It's placed in "do_mmap", "do_brk_flags" and "__install_special_mapping".

I like this. I think this is something the other LSMs should be checking too. (Though I wonder if it would be helpful to include the VMA in the hook, though it does exist yet, so... hmm.)

For the particular case of my LSM and the type of check it does, the VMA isn't needed, of course.
Maybe some other LSM can benefit from it, but it depends on what they want to do with this hook.
Looking forward to feedback from potential future users. Thank you for your interest.

Salvatore

#6 lore raw

RFC v2 4/9 S.A.R.A. cred blob management

In reply to Salvatore Mesoraca

Creation of the S.A.R.A. cred blob management "API".
In order to allow S.A.R.A. to be stackable with other LSMs, it doesn't use the "security" field of struct cred, instead it uses an ad hoc field named security_sara.
This solution is probably not acceptable for upstream, so this part will be modified as soon as the LSM stackable cred blob management will be available.

---
 include/linux/cred.h              |  3 ++
 security/sara/Makefile            |  2 +-
 security/sara/include/sara_data.h | 47 +++++++++++++++++++++++
 security/sara/main.c              |  6 +++
 security/sara/sara_data.c         | 79 +++++++++++++++++++++++++++++++++++++++
 5 files changed, 136 insertions(+), 1 deletion(-)
 create mode 100644 security/sara/include/sara_data.h
 create mode 100644 security/sara/sara_data.c
include/linux/cred.h +3 -0
index b03e7d0..007feb5 100644
@@ -141,6 +141,9 @@ struct cred {
 #ifdef CONFIG_SECURITY
 	void		*security;	/* subjective LSM security */
 #endif
+#ifdef CONFIG_SECURITY_SARA
+	void		*security_sara;
+#endif
 	struct user_struct *user;	/* real user ID subscription */
 	struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
 	struct group_info *group_info;	/* supplementary groups for euid/fsgid */
security/sara/Makefile +1 -1
index 8acd291..14bf7a8 100644
@@ -1,3 +1,3 @@
 obj-$(CONFIG_SECURITY_SARA) := sara.o
 
-sara-y := main.o securityfs.o utils.o
+sara-y := main.o securityfs.o utils.o sara_data.o
security/sara/include/sara_data.h new file +47 -0

47 lines not on this page · raw message

security/sara/main.c +6 -0
index 2007735..644ff6d 100644
@@ -14,6 +14,7 @@
 #include <linux/printk.h>
 
 #include "include/sara.h"
+#include "include/sara_data.h"
 #include "include/securityfs.h"
 
 static const int sara_version = SARA_VERSION;
@@ -80,6 +81,11 @@ void __init sara_init(void)
 		goto error;
 	}
 
+	if (sara_data_init()) {
+		pr_crit("impossible to initialize creds.\n");
+		goto error;
+	}
+
 	pr_debug("initialized.\n");
 
 	if (sara_enabled)
security/sara/sara_data.c new file +79 -0

79 lines not on this page · raw message

Signature · 1 line
1.9.1
#7 lore raw

RFC v2 5/9 S.A.R.A. WX Protection

In reply to Salvatore Mesoraca

Introduction of S.A.R.A. WX Protection.
It aims to improve user-space programs security by applying:
- W^X enforcement
- W!->X (once writable never executable) mprotect restriction
- Executable MMAP prevention

All of the above features can be enabled or disabled both system wide or on a per executable basis through the use of configuration. W^X enforcement works by blocking any memory allocation or mprotect invocation with both the WRITE and the EXEC flags enabled. W!->X restriction works by preventing any mprotect invocation that makes executable any page that is flagged VM_MAYWRITE.
This feature can be configured separately for stack, heap and other allocations.
Executable MMAP prevention works by preventing any new executable allocation after the dynamic libraries have been loaded. It works under the assumption that, when the dynamic libraries have been finished loading, the RELRO section will be marked read only.

Parts of WX Protection are inspired by some of the features available in PaX.

---
 security/sara/Kconfig          |  75 +++++
 security/sara/Makefile         |   1 +
 security/sara/include/wxprot.h |  27 ++
 security/sara/main.c           |   6 +
 security/sara/wxprot.c         | 646 +++++++++++++++++++++++++++++++++++++++++
 5 files changed, 755 insertions(+)
 create mode 100644 security/sara/include/wxprot.h
 create mode 100644 security/sara/wxprot.c
security/sara/Kconfig +75 -0
index 5b61020..6c74069 100644
@@ -39,4 +39,79 @@ config SECURITY_SARA_NO_RUNTIME_ENABLE
 
 	  If unsure, answer Y.
 
+config SECURITY_SARA_WXPROT
+	bool "WX Protection: W^X and W!->X protections"
+	depends on SECURITY_SARA
+	default y
+	help
+	  WX Protection aims to improve user-space programs security by applying:
+	    - W^X memory restriction
+	    - W!->X (once writable never executable) mprotect restriction
+	    - Executable MMAP prevention
+	  See Documentation/security/SARA.rst. for further information.
+
+	  If unsure, answer Y.
+
+choice
+	prompt "Default action for W^X and W!->X protections"
+	depends on SECURITY_SARA
+	depends on SECURITY_SARA_WXPROT
+	default SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_COMPLAIN_VERBOSE
+
+        help
+	  Choose the default behaviour of WX Protection when no config
+	  rule matches or no rule is loaded.
+	  For further information on available flags and their meaning
+	  see Documentation/security/SARA.rst.
+
+	config SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_COMPLAIN_VERBOSE
+		bool "Protections enabled but not enforced."
+		help
+		  All features enabled except "Executable MMAP prevention",
+		  verbose reporting, but no actual enforce: it just complains.
+		  Its numeric value is 0x3f, for more information see
+		  Documentation/security/SARA.rst.
+
+        config SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_ENFORCE_VERBOSE
+		bool "Full protection, verbose."
+		help
+		  All features enabled except "Executable MMAP prevention".
+		  The enabled features will be enforced with verbose reporting.
+		  Its numeric value is 0x2f, for more information see
+		  Documentation/security/SARA.rst.
+
+        config SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_ENFORCE
+		bool "Full protection, quiet."
+		help
+		  All features enabled except "Executable MMAP prevention".
+		  The enabled features will be enforced quietly.
+		  Its numeric value is 0xf, for more information see
+		  Documentation/security/SARA.rst.
+
+	config SECURITY_SARA_WXPROT_DEFAULT_FLAGS_NONE
+		bool "No protection at all."
+		help
+		  All features disabled.
+		  Its numeric value is 0, for more information see
+		  Documentation/security/SARA.rst.
+endchoice
+
+config SECURITY_SARA_WXPROT_DISABLED
+	bool "WX protection will be disabled at boot."
+	depends on SECURITY_SARA_WXPROT
+	default n
+	help
+	  If you say Y here WX protection won't be enabled at startup. You can
+	  override this option via user-space utilities or at boot time via
+	  "sara_wxprot=[0|1]" kernel parameter.
+
+	  If unsure, answer N.
+
+config SECURITY_SARA_WXPROT_DEFAULT_FLAGS
+	hex
+	default "0x3f" if SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_COMPLAIN_VERBOSE
+	default "0x2f" if SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_ENFORCE_VERBOSE
+	default "0xf" if SECURITY_SARA_WXPROT_DEFAULT_FLAGS_ALL_ENFORCE
+	default "0" if SECURITY_SARA_WXPROT_DEFAULT_FLAGS_NONE
+
 endmenu
security/sara/Makefile +1 -0
index 14bf7a8..74a3338 100644
@@ -1,3 +1,4 @@
 obj-$(CONFIG_SECURITY_SARA) := sara.o
 
 sara-y := main.o securityfs.o utils.o sara_data.o
+sara-$(CONFIG_SECURITY_SARA_WXPROT) += wxprot.o
security/sara/include/wxprot.h new file +27 -0
new file mode 100644
index 0000000..23b8a7b
@@ -0,0 +1,27 @@
+/*
+ * S.A.R.A. Linux Security Module
+ *
+ * Copyright (C) 2017 Salvatore Mesoraca <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2, as
+ * published by the Free Software Foundation.
+ *
+ */
+
+#ifndef __SARA_WXPROT_H
+#define __SARA_WXPROT_H
+
+#ifdef CONFIG_SECURITY_SARA_WXPROT
+
+#include <linux/init.h>
+int sara_wxprot_init(void) __init;
+
+#else /* CONFIG_SECURITY_SARA_WXPROT */
+inline int sara_wxprot_init(void)
+{
+	return 0;
+}
+#endif /* CONFIG_SECURITY_SARA_WXPROT */
+
+#endif /* __SARA_WXPROT_H */
security/sara/main.c +6 -0
index 644ff6d..2512560 100644
@@ -16,6 +16,7 @@
 #include "include/sara.h"
 #include "include/sara_data.h"
 #include "include/securityfs.h"
+#include "include/wxprot.h"
 
 static const int sara_version = SARA_VERSION;
 
@@ -86,6 +87,11 @@ void __init sara_init(void)
 		goto error;
 	}
 
+	if (sara_wxprot_init()) {
+		pr_crit("impossible to initialize WX protections.\n");
+		goto error;
+	}
+
 	pr_debug("initialized.\n");
 
 	if (sara_enabled)
security/sara/wxprot.c new file +646 -0

646 lines not on this page · raw message

Signature · 1 line
1.9.1
#8 lore raw

Re: [RFC v2 5/9] S.A.R.A. WX Protection

Quoted 13 lines · Salvatore Mesoraca
security/sara/wxprot.c new file +13 -0
+static int sara_check_vmflags(vm_flags_t vm_flags)
+{
+       u16 sara_wxp_flags = get_current_sara_wxp_flags();
+
+       if (sara_enabled && wxprot_enabled) {
+               if (sara_wxp_flags & SARA_WXP_WXORX &&
+                   vm_flags & VM_WRITE &&
+                   vm_flags & VM_EXEC) {
+                       if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                               pr_wxp("W^X");
+                       if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                               return -EPERM;
+               }

security/sara/wxprot.c line 293

Quoted 10 lines
security/sara/wxprot.c new file +10 -0
+               if (sara_wxp_flags & SARA_WXP_MMAP &&
+                   (vm_flags & VM_EXEC ||
+                    (!(vm_flags & VM_MAYWRITE) && (vm_flags & VM_MAYEXEC))) &&
+                   get_current_sara_mmap_blocked()) {
+                       if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                               pr_wxp("executable mmap");
+                       if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                               return -EPERM;
+               }
+       }

Given the subtle differences between these various if blocks (here and in the other hook), I think it would be nice to have some beefy comments here to describe specifically what's being checked (and why). It'll help others review this code, and help validate code against intent.

I would also try to minimize the written code by creating a macro for a repeated pattern here:

security/sara/wxprot.c line 320

Quoted 4 lines
security/sara/wxprot.c new file +4 -0
+                               if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                                       pr_wxp("mprotect on file mmap");
+                               if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                                       return -EACCES;

These four lines are repeated several times with only the const char * and return value changing. Perhaps something like:

#define sara_return(err, msg) do { \
                               if ((sara_wxp_flags & SARA_WXP_VERBOSE)) \
                                       pr_wxp(err); \
                               if (!(sara_wxp_flags & SARA_WXP_COMPLAIN)) \
                                       return -err; \
} while (0)

Then each if block turns into something quite easier to parse:

               if (sara_wxp_flags & SARA_WXP_WXORX &&
                   vm_flags & VM_WRITE &&
                   vm_flags & VM_EXEC)
                       sara_return(EPERM, "W^X");

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#9 lore raw

Re: [RFC v2 5/9] S.A.R.A. WX Protection

2017-06-28 1:04 GMT+02:00 Kees Cook <[email protected]>:

Quoted 50 lines
Quoted 13 lines · Salvatore Mesoraca
security/sara/wxprot.c new file +13 -0
+static int sara_check_vmflags(vm_flags_t vm_flags)
+{
+       u16 sara_wxp_flags = get_current_sara_wxp_flags();
+
+       if (sara_enabled && wxprot_enabled) {
+               if (sara_wxp_flags & SARA_WXP_WXORX &&
+                   vm_flags & VM_WRITE &&
+                   vm_flags & VM_EXEC) {
+                       if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                               pr_wxp("W^X");
+                       if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                               return -EPERM;
+               }

security/sara/wxprot.c line 293

Quoted 10 lines
security/sara/wxprot.c new file +10 -0
+               if (sara_wxp_flags & SARA_WXP_MMAP &&
+                   (vm_flags & VM_EXEC ||
+                    (!(vm_flags & VM_MAYWRITE) && (vm_flags & VM_MAYEXEC))) &&
+                   get_current_sara_mmap_blocked()) {
+                       if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                               pr_wxp("executable mmap");
+                       if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                               return -EPERM;
+               }
+       }

Given the subtle differences between these various if blocks (here and in the other hook), I think it would be nice to have some beefy comments here to describe specifically what's being checked (and why). It'll help others review this code, and help validate code against intent.

I would also try to minimize the written code by creating a macro for a repeated pattern here:

security/sara/wxprot.c line 320

Quoted 4 lines
security/sara/wxprot.c new file +4 -0
+                               if ((sara_wxp_flags & SARA_WXP_VERBOSE))
+                                       pr_wxp("mprotect on file mmap");
+                               if (!(sara_wxp_flags & SARA_WXP_COMPLAIN))
+                                       return -EACCES;

These four lines are repeated several times with only the const char * and return value changing. Perhaps something like:

#define sara_return(err, msg) do { \
                               if ((sara_wxp_flags & SARA_WXP_VERBOSE)) \
                                       pr_wxp(err); \
                               if (!(sara_wxp_flags & SARA_WXP_COMPLAIN)) \
                                       return -err; \
} while (0)
Quoted 6 lines

Then each if block turns into something quite easier to parse:

               if (sara_wxp_flags & SARA_WXP_WXORX &&
                   vm_flags & VM_WRITE &&
                   vm_flags & VM_EXEC)
                       sara_return(EPERM, "W^X");

I absolutely agree with all of the above. These issues will be addressed in v3. Thank you for your contribution.

Salvatore

#10 lore raw

RFC v2 6/9 Creation of "pagefault_handler_x86" LSM hook

In reply to Salvatore Mesoraca

Creation of a new hook to let LSM modules handle user-space pagefaults on x86.
It can be used to avoid segfaulting the originating process. If it's the case it can modify process registers before returning. This is not a security feature by itself, it's a way to soften some unwanted side-effects of restrictive security features.
In particular this is used by S.A.R.A. can be used to implement what PaX call "trampoline emulation" that, in practice, allow for some specific code sequences to be executed even if they are in non executable memory. This may look like a bad thing at first, but you have to consider that:
- This allows for strict memory restrictions (e.g. W^X) to stay on even when they should be turned off. And, even if this emulation makes those features less effective, it's still better than having them turned off completely.
- The only code sequences emulated are trampolines used to make function calls. In many cases, when you have the chance to make arbitrary memory writes, you can already manipulate the control flow of the program by overwriting function pointers or return values. So, in many cases, the "trampoline emulation" doesn't introduce new exploit vectors.
- It's a feature that can be turned on only if needed, on a per executable file basis.

---
 arch/x86/mm/fault.c       |  6 ++++++
 include/linux/lsm_hooks.h |  9 +++++++++
 include/linux/security.h  | 11 +++++++++++
 security/security.c       | 11 +++++++++++
 4 files changed, 37 insertions(+)
arch/x86/mm/fault.c +6 -0
index 8ad91a0..b75b81a 100644
@@ -15,6 +15,7 @@
 #include <linux/prefetch.h>		/* prefetchw			*/
 #include <linux/context_tracking.h>	/* exception_enter(), ...	*/
 #include <linux/uaccess.h>		/* faulthandler_disabled()	*/
+#include <linux/security.h>		/* security_pagefault_handler	*/
 
 #include <asm/cpufeature.h>		/* boot_cpu_has, ...		*/
 #include <asm/traps.h>			/* dotraplinkage, ...		*/
@@ -1358,6 +1359,11 @@ static inline bool smap_violation(int error_code, struct pt_regs *regs)
 			local_irq_enable();
 	}
 
+	if (unlikely(security_pagefault_handler_x86(regs,
+						    error_code,
+						    address)))
+		return;
+
 	perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
 
 	if (error_code & PF_WRITE)
include/linux/lsm_hooks.h +9 -0
index 33dab16..da487e5 100644
@@ -488,6 +488,11 @@
  *	@vmflags contains requested the vmflags.
  *	Return 0 if the operation is allowed to continue otherwise return
  *	the appropriate error code.
+ * @pagefault_handler_x86:
+ *	Handle pagefaults on x86.
+ *	@regs contains process' registers.
+ *	@error_code contains error code for the pagefault.
+ *	@address contains the address that caused the pagefault.
  * @file_lock:
  *	Check permission before performing file locking operations.
  *	Note: this hook mediates both flock and fcntl style locks.
@@ -1483,6 +1488,9 @@
 	int (*file_mprotect)(struct vm_area_struct *vma, unsigned long reqprot,
 				unsigned long prot);
 	int (*check_vmflags)(vm_flags_t vmflags);
+	int (*pagefault_handler_x86)(struct pt_regs *regs,
+				     unsigned long error_code,
+				     unsigned long address);
 	int (*file_lock)(struct file *file, unsigned int cmd);
 	int (*file_fcntl)(struct file *file, unsigned int cmd,
 				unsigned long arg);
@@ -1754,6 +1762,7 @@ struct security_hook_heads {
 	struct list_head mmap_file;
 	struct list_head file_mprotect;
 	struct list_head check_vmflags;
+	struct list_head pagefault_handler_x86;
 	struct list_head file_lock;
 	struct list_head file_fcntl;
 	struct list_head file_set_fowner;
include/linux/security.h +11 -0
index 8701872..3b91999 100644
@@ -301,6 +301,9 @@ int security_mmap_file(struct file *file, unsigned long prot,
 int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
 			   unsigned long prot);
 int security_check_vmflags(vm_flags_t vmflags);
+int __maybe_unused security_pagefault_handler_x86(struct pt_regs *regs,
+						  unsigned long error_code,
+						  unsigned long address);
 int security_file_lock(struct file *file, unsigned int cmd);
 int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg);
 void security_file_set_fowner(struct file *file);
@@ -829,6 +832,14 @@ static inline int security_check_vmflags(vm_flags_t vmflags)
 	return 0;
 }
 
+static inline int __maybe_unused security_pagefault_handler_x86(
+						struct pt_regs *regs,
+						unsigned long error_code,
+						unsigned long address)
+{
+	return 0;
+}
+
 static inline int security_file_lock(struct file *file, unsigned int cmd)
 {
 	return 0;
security/security.c +11 -0
index 7e45846..f7df697 100644
@@ -905,6 +905,17 @@ int security_check_vmflags(vm_flags_t vmflags)
 	return call_int_hook(check_vmflags, 0, vmflags);
 }
 
+int __maybe_unused security_pagefault_handler_x86(struct pt_regs *regs,
+						  unsigned long error_code,
+						  unsigned long address)
+{
+	return call_int_hook(pagefault_handler_x86,
+			     0,
+			     regs,
+			     error_code,
+			     address);
+}
+
 int security_file_lock(struct file *file, unsigned int cmd)
 {
 	return call_int_hook(file_lock, 0, file, cmd);
Signature · 1 line
1.9.1
#11 lore raw

Re: [RFC v2 6/9] Creation of "pagefault_handler_x86" LSM hook

Quoted 15 lines · Salvatore Mesoraca

Creation of a new hook to let LSM modules handle user-space pagefaults on x86.
It can be used to avoid segfaulting the originating process. If it's the case it can modify process registers before returning. This is not a security feature by itself, it's a way to soften some unwanted side-effects of restrictive security features.
In particular this is used by S.A.R.A. can be used to implement what PaX call "trampoline emulation" that, in practice, allow for some specific code sequences to be executed even if they are in non executable memory. This may look like a bad thing at first, but you have to consider that:
- This allows for strict memory restrictions (e.g. W^X) to stay on even when they should be turned off. And, even if this emulation makes those features less effective, it's still better than having them turned off completely.

Quoted 8 lines

- The only code sequences emulated are trampolines used to make function calls. In many cases, when you have the chance to make arbitrary memory writes, you can already manipulate the control flow of the program by overwriting function pointers or return values. So, in many cases, the "trampoline emulation" doesn't introduce new exploit vectors.
- It's a feature that can be turned on only if needed, on a per executable file basis.

Can this be made arch-agnostic? It seems a per-arch register-handling routine would be needed, though. :(

-Kees

Quoted 121 lines
---
 arch/x86/mm/fault.c       |  6 ++++++
 include/linux/lsm_hooks.h |  9 +++++++++
 include/linux/security.h  | 11 +++++++++++
 security/security.c       | 11 +++++++++++
 4 files changed, 37 insertions(+)
arch/x86/mm/fault.c +6 -0
index 8ad91a0..b75b81a 100644
@@ -15,6 +15,7 @@
 #include <linux/prefetch.h>            /* prefetchw                    */
 #include <linux/context_tracking.h>    /* exception_enter(), ...       */
 #include <linux/uaccess.h>             /* faulthandler_disabled()      */
+#include <linux/security.h>            /* security_pagefault_handler   */
 
 #include <asm/cpufeature.h>            /* boot_cpu_has, ...            */
 #include <asm/traps.h>                 /* dotraplinkage, ...           */
@@ -1358,6 +1359,11 @@ static inline bool smap_violation(int error_code, struct pt_regs *regs)
                        local_irq_enable();
        }
 
+       if (unlikely(security_pagefault_handler_x86(regs,
+                                                   error_code,
+                                                   address)))
+               return;
+
        perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
 
        if (error_code & PF_WRITE)
include/linux/lsm_hooks.h +9 -0
index 33dab16..da487e5 100644
@@ -488,6 +488,11 @@
  *     @vmflags contains requested the vmflags.
  *     Return 0 if the operation is allowed to continue otherwise return
  *     the appropriate error code.
+ * @pagefault_handler_x86:
+ *     Handle pagefaults on x86.
+ *     @regs contains process' registers.
+ *     @error_code contains error code for the pagefault.
+ *     @address contains the address that caused the pagefault.
  * @file_lock:
  *     Check permission before performing file locking operations.
  *     Note: this hook mediates both flock and fcntl style locks.
@@ -1483,6 +1488,9 @@
        int (*file_mprotect)(struct vm_area_struct *vma, unsigned long reqprot,
                                unsigned long prot);
        int (*check_vmflags)(vm_flags_t vmflags);
+       int (*pagefault_handler_x86)(struct pt_regs *regs,
+                                    unsigned long error_code,
+                                    unsigned long address);
        int (*file_lock)(struct file *file, unsigned int cmd);
        int (*file_fcntl)(struct file *file, unsigned int cmd,
                                unsigned long arg);
@@ -1754,6 +1762,7 @@ struct security_hook_heads {
        struct list_head mmap_file;
        struct list_head file_mprotect;
        struct list_head check_vmflags;
+       struct list_head pagefault_handler_x86;
        struct list_head file_lock;
        struct list_head file_fcntl;
        struct list_head file_set_fowner;
include/linux/security.h +11 -0
index 8701872..3b91999 100644
@@ -301,6 +301,9 @@ int security_mmap_file(struct file *file, unsigned long prot,
 int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
                           unsigned long prot);
 int security_check_vmflags(vm_flags_t vmflags);
+int __maybe_unused security_pagefault_handler_x86(struct pt_regs *regs,
+                                                 unsigned long error_code,
+                                                 unsigned long address);
 int security_file_lock(struct file *file, unsigned int cmd);
 int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg);
 void security_file_set_fowner(struct file *file);
@@ -829,6 +832,14 @@ static inline int security_check_vmflags(vm_flags_t vmflags)
        return 0;
 }
 
+static inline int __maybe_unused security_pagefault_handler_x86(
+                                               struct pt_regs *regs,
+                                               unsigned long error_code,
+                                               unsigned long address)
+{
+       return 0;
+}
+
 static inline int security_file_lock(struct file *file, unsigned int cmd)
 {
        return 0;
security/security.c +11 -1
index 7e45846..f7df697 100644
@@ -905,6 +905,17 @@ int security_check_vmflags(vm_flags_t vmflags)
        return call_int_hook(check_vmflags, 0, vmflags);
 }
 
+int __maybe_unused security_pagefault_handler_x86(struct pt_regs *regs,
+                                                 unsigned long error_code,
+                                                 unsigned long address)
+{
+       return call_int_hook(pagefault_handler_x86,
+                            0,
+                            regs,
+                            error_code,
+                            address);
+}
+
 int security_file_lock(struct file *file, unsigned int cmd)
 {
        return call_int_hook(file_lock, 0, file, cmd);
--

1.9.1

Signature · 2 lines
Kees Cook
Pixel Security
#12 lore raw

Re: [RFC v2 6/9] Creation of "pagefault_handler_x86" LSM hook

2017-06-28 1:07 GMT+02:00 Kees Cook <[email protected]>:

Quoted 26 lines
Quoted 15 lines · Salvatore Mesoraca

Creation of a new hook to let LSM modules handle user-space pagefaults on x86.
It can be used to avoid segfaulting the originating process. If it's the case it can modify process registers before returning. This is not a security feature by itself, it's a way to soften some unwanted side-effects of restrictive security features.
In particular this is used by S.A.R.A. can be used to implement what PaX call "trampoline emulation" that, in practice, allow for some specific code sequences to be executed even if they are in non executable memory. This may look like a bad thing at first, but you have to consider that:
- This allows for strict memory restrictions (e.g. W^X) to stay on even when they should be turned off. And, even if this emulation makes those features less effective, it's still better than having them turned off completely.

Quoted 8 lines

- The only code sequences emulated are trampolines used to make function calls. In many cases, when you have the chance to make arbitrary memory writes, you can already manipulate the control flow of the program by overwriting function pointers or return values. So, in many cases, the "trampoline emulation" doesn't introduce new exploit vectors.
- It's a feature that can be turned on only if needed, on a per executable file basis.

Quoted 2 lines

Can this be made arch-agnostic? It seems a per-arch register-handling routine would be needed, though. :(

S.A.R.A.'s "pagefault_handler_x86" implementation is fully arch specific so it won't benefit too much from this change.
Anyway having a single hook for all archs is probably a cleaner solution, I'll change it in the v3.
Would it be OK if I make it arch-agnostic while I actually keep it only in arch/x86/mm/fault.c?
Thank you for your help.

Salvatore

#13 lore raw

Re: [RFC v2 6/9] Creation of "pagefault_handler_x86" LSM hook

Quoted 30 lines · Salvatore Mesoraca

2017-06-28 1:07 GMT+02:00 Kees Cook <[email protected]>:

Quoted 26 lines
Quoted 15 lines · Salvatore Mesoraca

Creation of a new hook to let LSM modules handle user-space pagefaults on x86.
It can be used to avoid segfaulting the originating process. If it's the case it can modify process registers before returning. This is not a security feature by itself, it's a way to soften some unwanted side-effects of restrictive security features.
In particular this is used by S.A.R.A. can be used to implement what PaX call "trampoline emulation" that, in practice, allow for some specific code sequences to be executed even if they are in non executable memory. This may look like a bad thing at first, but you have to consider that:
- This allows for strict memory restrictions (e.g. W^X) to stay on even when they should be turned off. And, even if this emulation makes those features less effective, it's still better than having them turned off completely.

Quoted 8 lines

- The only code sequences emulated are trampolines used to make function calls. In many cases, when you have the chance to make arbitrary memory writes, you can already manipulate the control flow of the program by overwriting function pointers or return values. So, in many cases, the "trampoline emulation" doesn't introduce new exploit vectors.
- It's a feature that can be turned on only if needed, on a per executable file basis.

Quoted 2 lines

Can this be made arch-agnostic? It seems a per-arch register-handling routine would be needed, though. :(

Quoted 7 lines

S.A.R.A.'s "pagefault_handler_x86" implementation is fully arch specific so it won't benefit too much from this change.
Anyway having a single hook for all archs is probably a cleaner solution, I'll change it in the v3.
Would it be OK if I make it arch-agnostic while I actually keep it only in arch/x86/mm/fault.c?
Thank you for your help.

It'd be nicer to wire it up unconditionally to all architectures, but I'm not entirely sure if that's feasible. Perhaps SARA (or this LSM hook) would be hidden behind some CONFIG_ARCH_HAS_LSM_PAGEFAULT or something that each architecture could "select" in its Kconfig.

Perhaps some other LSM folks have some better ideas?

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#14 lore raw

RFC v2 7/9 Trampoline emulation

In reply to Salvatore Mesoraca

Some programs need to generate part of their code at runtime. Luckily enough, in some cases they only generate well-known code sequences (the "trampolines") that can be easily recognized and emulated by the kernel. This way WX Protection can still be active, so a potential attacker won't be able to generate arbitrary sequences of code, but just those that are explicitly allowed. This is not ideal, but it's still better than having WX Protection completely disabled.
In particular S.A.R.A. is able to recognize trampolines used by GCC for nested C functions and libffi's trampolines.
This feature is implemented only on x86_32 and x86_64.
The assembly sequences used here were originally obtained from PaX source code.

---
 security/sara/Kconfig               |  17 ++++
 security/sara/include/trampolines.h | 171 ++++++++++++++++++++++++++++++++++++
 security/sara/wxprot.c              | 140 +++++++++++++++++++++++++++++
 3 files changed, 328 insertions(+)
 create mode 100644 security/sara/include/trampolines.h
security/sara/Kconfig +17 -0
index 6c74069..f406805 100644
@@ -96,6 +96,23 @@ choice
 		  Documentation/security/SARA.rst.
 endchoice
 
+config SECURITY_SARA_WXPROT_EMUTRAMP
+	bool "Enable emulation for some types of trampolines"
+	depends on SECURITY_SARA_WXPROT
+	depends on X86
+	default y
+	help
+	  Some programs and libraries need to execute special small code
+	  snippets from non-executable memory pages.
+	  Most notable examples are the GCC and libffi trampolines.
+	  This features make it possible to execute those trampolines even
+	  if they reside in non-executable memory pages.
+	  This features need to be enabled on a per-executable basis
+	  via user-space utilities.
+	  See Documentation/security/SARA.rst. for further information.
+
+	  If unsure, answer y.
+
 config SECURITY_SARA_WXPROT_DISABLED
 	bool "WX protection will be disabled at boot."
 	depends on SECURITY_SARA_WXPROT
security/sara/include/trampolines.h new file +171 -0

171 lines not on this page · raw message

security/sara/wxprot.c +140 -0

182 lines not on this page · raw message

Signature · 1 line
1.9.1
#15 lore raw

Re: [kernel-hardening] [RFC v2 7/9] Trampoline emulation

Thanks for doing this porting work. Look forward to using GRSecurity/PAX features on ARM eventually. ARM's taking over as we know. x86 is almost done.

Quoted 423 lines · Salvatore Mesoraca

Some programs need to generate part of their code at runtime. Luckily enough, in some cases they only generate well-known code sequences (the "trampolines") that can be easily recognized and emulated by the kernel. This way WX Protection can still be active, so a potential attacker won't be able to generate arbitrary sequences of code, but just those that are explicitly allowed. This is not ideal, but it's still better than having WX Protection completely disabled.
In particular S.A.R.A. is able to recognize trampolines used by GCC for nested C functions and libffi's trampolines.
This feature is implemented only on x86_32 and x86_64.
The assembly sequences used here were originally obtained from PaX source code.

---
 security/sara/Kconfig               |  17 ++++
 security/sara/include/trampolines.h | 171 
++++++++++++++++++++++++++++++++++++
 security/sara/wxprot.c              | 140 
+++++++++++++++++++++++++++++
 3 files changed, 328 insertions(+)
 create mode 100644 security/sara/include/trampolines.h
security/sara/Kconfig +17 -0
index 6c74069..f406805 100644
@@ -96,6 +96,23 @@ choice
 		  Documentation/security/SARA.rst.
 endchoice
 
+config SECURITY_SARA_WXPROT_EMUTRAMP
+	bool "Enable emulation for some types of trampolines"
+	depends on SECURITY_SARA_WXPROT
+	depends on X86
+	default y
+	help
+	  Some programs and libraries need to execute special small code
+	  snippets from non-executable memory pages.
+	  Most notable examples are the GCC and libffi trampolines.
+	  This features make it possible to execute those trampolines even
+	  if they reside in non-executable memory pages.
+	  This features need to be enabled on a per-executable basis
+	  via user-space utilities.
+	  See Documentation/security/SARA.rst. for further information.
+
+	  If unsure, answer y.
+
 config SECURITY_SARA_WXPROT_DISABLED
 	bool "WX protection will be disabled at boot."
 	depends on SECURITY_SARA_WXPROT
security/sara/include/trampolines.h new file +6 -0
new file mode 100644
index 0000000..eab0a85
@@ -0,0 +1,171 @@
+/*
+ * S.A.R.A. Linux Security Module
+ *
+ * Copyright (C) 2017 Salvatore Mesoraca <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or 

modify
+ * it under the terms of the GNU General Public License version 2, as
+ * published by the Free Software Foundation.
+ *
+ * Assembly sequences used here were copied from
+ * PaX patch by PaX Team <[email protected]>
+ *
+ */

security/sara/include/trampolines.h new file +158 -0
+
+#ifndef __SARA_TRAMPOLINES_H
+#define __SARA_TRAMPOLINES_H
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+
+
+/* x86_32 */
+
+
+struct libffi_trampoline_x86_32 {
+	unsigned char mov;
+	unsigned int addr1;
+	unsigned char jmp;
+	unsigned int addr2;
+} __packed;
+
+struct gcc_trampoline_x86_32_type1 {
+	unsigned char mov1;
+	unsigned int addr1;
+	unsigned char mov2;
+	unsigned int addr2;
+	unsigned short jmp;
+} __packed;
+
+struct gcc_trampoline_x86_32_type2 {
+	unsigned char mov;
+	unsigned int addr1;
+	unsigned char jmp;
+	unsigned int addr2;
+} __packed;
+
+union trampolines_x86_32 {
+	struct libffi_trampoline_x86_32 lf;
+	struct gcc_trampoline_x86_32_type1 g1;
+	struct gcc_trampoline_x86_32_type2 g2;
+};
+
+#define is_valid_libffi_trampoline_x86_32(UNION)	\
+	(UNION.lf.mov == 0xB8 &&			\
+	UNION.lf.jmp == 0xE9)
+
+#define emulate_libffi_trampoline_x86_32(UNION, REGS) do {	\
+	(REGS)->ax = UNION.lf.addr1;				\
+	(REGS)->ip = (unsigned int) ((REGS)->ip +		\
+				     UNION.lf.addr2 +		\
+				     sizeof(UNION.lf));		\
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type1(UNION, REGS)	\
+	(UNION.g1.mov1 == 0xB9 &&				\
+	UNION.g1.mov2 == 0xB8 &&				\
+	UNION.g1.jmp == 0xE0FF &&				\
+	REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type1(UNION, REGS) do {	\
+	(REGS)->cx = UNION.g1.addr1;				\
+	(REGS)->ax = UNION.g1.addr2;				\
+	(REGS)->ip = UNION.g1.addr2;				\
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type2(UNION, REGS)	\
+	(UNION.g2.mov == 0xB9 &&				\
+	UNION.g2.jmp == 0xE9 &&					\
+	REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type2(UNION, REGS) do {	\
+	(REGS)->cx = UNION.g2.addr1;				\
+	(REGS)->ip = (unsigned int) ((REGS)->ip +		\
+				     UNION.g2.addr2 +		\
+				     sizeof(UNION.g2));		\
+} while (0)
+
+
+
+#ifdef CONFIG_X86_64
+
+struct libffi_trampoline_x86_64 {
+	unsigned short mov1;
+	unsigned long addr1;
+	unsigned short mov2;
+	unsigned long addr2;
+	unsigned char stcclc;
+	unsigned short jmp1;
+	unsigned char jmp2;
+} __packed;
+
+struct gcc_trampoline_x86_64_type1 {
+	unsigned short mov1;
+	unsigned long addr1;
+	unsigned short mov2;
+	unsigned long addr2;
+	unsigned short jmp1;
+	unsigned char jmp2;
+} __packed;
+
+struct gcc_trampoline_x86_64_type2 {
+	unsigned short mov1;
+	unsigned int addr1;
+	unsigned short mov2;
+	unsigned long addr2;
+	unsigned short jmp1;
+	unsigned char jmp2;
+} __packed;
+
+union trampolines_x86_64 {
+	struct libffi_trampoline_x86_64 lf;
+	struct gcc_trampoline_x86_64_type1 g1;
+	struct gcc_trampoline_x86_64_type2 g2;
+};
+
+#define is_valid_libffi_trampoline_x86_64(UNION)	\
+	(UNION.lf.mov1 == 0xBB49 &&			\
+	UNION.lf.mov2 == 0xBA49 &&			\
+	(UNION.lf.stcclc == 0xF8 ||			\
+	 UNION.lf.stcclc == 0xF9) &&			\
+	UNION.lf.jmp1 == 0xFF49 &&			\
+	UNION.lf.jmp2 == 0xE3)
+
+#define emulate_libffi_trampoline_x86_64(UNION, REGS) do {	\
+	(REGS)->r11 = UNION.lf.addr1;				\
+	(REGS)->r10 = UNION.lf.addr2;				\
+	(REGS)->ip = UNION.lf.addr1;				\
+	if (UNION.lf.stcclc == 0xF8)				\
+		(REGS)->flags &= ~X86_EFLAGS_CF;		\
+	else							\
+		(REGS)->flags |= X86_EFLAGS_CF;			\
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_64_type1(UNION, REGS)	\
+	(UNION.g1.mov1 == 0xBB49 &&				\
+	UNION.g1.mov2 == 0xBA49 &&				\
+	UNION.g1.jmp1 == 0xFF49 &&				\
+	UNION.g1.jmp2 == 0xE3 &&				\
+	REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_64_type1(UNION, REGS) do {	\
+	(REGS)->r11 = UNION.g1.addr1;				\
+	(REGS)->r10 = UNION.g1.addr2;				\
+	(REGS)->ip = UNION.g1.addr1;				\
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_64_type2(UNION, REGS)	\
+	(UNION.g2.mov1 == 0xBB41 &&				\
+	UNION.g2.mov2 == 0xBA49 &&				\
+	UNION.g2.jmp1 == 0xFF49 &&				\
+	UNION.g2.jmp2 == 0xE3 &&				\
+	REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_64_type2(UNION, REGS) do {	\
+	(REGS)->r11 = UNION.g2.addr1;				\
+	(REGS)->r10 = UNION.g2.addr2;				\
+	(REGS)->ip = UNION.g2.addr1;				\
+} while (0)
+
+#endif /* CONFIG_X86_64 */
+
+#endif /* CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP */
+#endif /* __SARA_TRAMPOLINES_H */
security/sara/wxprot.c +140 -0
index f9233a5..38c86be 100644
@@ -22,6 +22,11 @@
 #include <linux/ratelimit.h>
 #include <linux/spinlock.h>
 
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+#include <linux/uaccess.h>
+#include "include/trampolines.h"
+#endif
+
 #include "include/sara.h"
 #include "include/sara_data.h"
 #include "include/utils.h"
@@ -37,6 +42,7 @@
 #define SARA_WXP_COMPLAIN	0x0010
 #define SARA_WXP_VERBOSE	0x0020
 #define SARA_WXP_MMAP		0x0040
+#define SARA_WXP_EMUTRAMP	0x0100
 #define SARA_WXP_TRANSFER	0x0200
 #define SARA_WXP_NONE		0x0000
 #define SARA_WXP_MPROTECT	(SARA_WXP_HEAP	| \
@@ -47,7 +53,12 @@
 				SARA_WXP_WXORX		| \
 				SARA_WXP_COMPLAIN	| \
 				SARA_WXP_VERBOSE)
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+#define SARA_WXP_ALL		(__SARA_WXP_ALL		| \
+				SARA_WXP_EMUTRAMP)
+#else /* CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP */
 #define SARA_WXP_ALL		__SARA_WXP_ALL
+#endif /* CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP */
 
 struct wxprot_rule {
 	char *path;
@@ -72,7 +83,11 @@ struct wxprot_config_container {
 static u16 default_flags __ro_after_init =
 				CONFIG_SECURITY_SARA_WXPROT_DEFAULT_FLAGS;
 
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+static const bool wxprot_emutramp = true;
+#else
 static const bool wxprot_emutramp;
+#endif
 
 static void pr_wxp(char *msg)
 {
@@ -97,6 +112,9 @@ static bool are_flags_valid(u16 flags)
 				SARA_WXP_WXORX |
 				SARA_WXP_MMAP))))
 		return false;
+	if (unlikely(flags & SARA_WXP_EMUTRAMP &&
+		     ((flags & SARA_WXP_MPROTECT) != SARA_WXP_MPROTECT)))
+		return false;
 	return true;
 }
 
@@ -366,10 +384,132 @@ static int sara_file_mprotect(struct 
 vm_area_struct *vma,
 	return 0;
 }
 
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+#define PF_PROT		(1 << 0)
+#define PF_USER		(1 << 2)
+#define PF_INSTR	(1 << 4)
+static int sara_pagefault_handler_x86_32(struct pt_regs *regs);
+static int sara_pagefault_handler_x86_64(struct pt_regs *regs);
+static int sara_pagefault_handler_x86(struct pt_regs *regs,
+					unsigned long error_code,
+					unsigned long address)
+{
+	int ret = 0;
+
+	if (!sara_enabled || !wxprot_enabled ||
+	    !(error_code & PF_USER) ||
+	    !(error_code & PF_INSTR) ||
+	    !(error_code & PF_PROT) ||
+	    !(get_current_sara_wxp_flags() & SARA_WXP_EMUTRAMP))
+		return 0;
+
+	local_irq_enable();
+	might_sleep();
+	might_fault();
+
+#ifdef	CONFIG_X86_32
+	ret = sara_pagefault_handler_x86_32(regs);
+#else
+	if (regs->cs == __USER32_CS ||
+	    regs->cs & (1<<2)) {
+		if (!(address >> 32))	/* K8 erratum #100 */
+			ret = sara_pagefault_handler_x86_32(regs);
+	} else
+		ret = sara_pagefault_handler_x86_64(regs);
+#endif
+
+	return ret;
+}
+
+static int sara_pagefault_handler_x86_32(struct pt_regs *regs)
+{
+	int ret;
+	void __user *ip = (void __user *) regs->ip;
+	union trampolines_x86_32 t;
+
+	BUILD_BUG_ON(sizeof(t.lf) > sizeof(t.g1));
+	BUILD_BUG_ON(sizeof(t.g2) > sizeof(t.lf));
+
+	ret = copy_from_user(&t, ip, sizeof(t.g1));
+	if (ret)
+		ret = copy_from_user(&t, ip, sizeof(t.lf));
+	if (ret)
+		ret = copy_from_user(&t, ip, sizeof(t.g2));
+	if (ret)
+		return 0;
+
+	if (is_valid_gcc_trampoline_x86_32_type1(t, regs)) {
+		pr_debug("Trampoline: gcc1 x86_32.\n");
+		emulate_gcc_trampoline_x86_32_type1(t, regs);
+		return 1;
+	} else if (is_valid_libffi_trampoline_x86_32(t)) {
+		pr_debug("Trampoline: libffi x86_32.\n");
+		emulate_libffi_trampoline_x86_32(t, regs);
+		return 1;
+	} else if (is_valid_gcc_trampoline_x86_32_type2(t, regs)) {
+		pr_debug("Trampoline: gcc2 x86_32.\n");
+		emulate_gcc_trampoline_x86_32_type2(t, regs);
+		return 1;
+	}
+
+	pr_debug("Not a trampoline (x86_32).\n");
+
+	return 0;
+}
+
+#ifdef CONFIG_X86_64
+static int sara_pagefault_handler_x86_64(struct pt_regs *regs)
+{
+	int ret;
+	void __user *ip = (void __user *) regs->ip;
+	union trampolines_x86_64 t;
+
+	BUILD_BUG_ON(sizeof(t.g1) > sizeof(t.lf));
+	BUILD_BUG_ON(sizeof(t.g2) > sizeof(t.g1));
+
+	ret = copy_from_user(&t, ip, sizeof(t.lf));
+	if (ret)
+		ret = copy_from_user(&t, ip, sizeof(t.g1));
+	if (ret)
+		ret = copy_from_user(&t, ip, sizeof(t.g2));
+	if (ret)
+		return 0;
+
+	if (is_valid_libffi_trampoline_x86_64(t)) {
+		pr_debug("Trampoline: libffi x86_64.\n");
+		emulate_libffi_trampoline_x86_64(t, regs);
+		return 1;
+	} else if (is_valid_gcc_trampoline_x86_64_type1(t, regs)) {
+		pr_debug("Trampoline: gcc1 x86_64.\n");
+		emulate_gcc_trampoline_x86_64_type1(t, regs);
+		return 1;
+	} else if (is_valid_gcc_trampoline_x86_64_type2(t, regs)) {
+		pr_debug("Trampoline: gcc2 x86_64.\n");
+		emulate_gcc_trampoline_x86_64_type2(t, regs);
+		return 1;
+	}
+
+	pr_debug("Not a trampoline (x86_64).\n");
+
+	return 0;
+
+}
+#else /* CONFIG_X86_64 */
+static inline int sara_pagefault_handler_x86_64(struct pt_regs *regs)
+{
+	return 0;
+}
+#endif /* CONFIG_X86_64 */
+
+#endif /* CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP */
+
 static struct security_hook_list wxprot_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(bprm_set_creds, sara_bprm_set_creds),
 	LSM_HOOK_INIT(check_vmflags, sara_check_vmflags),
 	LSM_HOOK_INIT(file_mprotect, sara_file_mprotect),
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+	LSM_HOOK_INIT(pagefault_handler_x86, sara_pagefault_handler_x86),
+#endif
 };
 

struct binary_config_header {

#16 lore raw

Re: [kernel-hardening] [RFC v2 7/9] Trampoline emulation

2017-06-15 18:47 GMT+02:00 <[email protected]>:

Quoted 3 lines

Thanks for doing this porting work. Look forward to using GRSecurity/PAX features on ARM eventually. ARM's taking over as we know. x86 is almost done.

Do you have any suggestion about potential use of trampoline emulation on ARM? Thank you for your comment.
--
To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to majordomo at vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html

#17 lore raw

Re: [RFC v2 7/9] Trampoline emulation

In reply to Salvatore Mesoraca
Quoted 4 lines · Salvatore Mesoraca

Some programs need to generate part of their code at runtime. Luckily enough, in some cases they only generate well-known code sequences (the "trampolines") that can be easily recognized and emulated by the kernel. This way WX Protection can still be active, so a potential attacker won't

Quoted 8 lines

be able to generate arbitrary sequences of code, but just those that are explicitly allowed. This is not ideal, but it's still better than having WX Protection completely disabled.
In particular S.A.R.A. is able to recognize trampolines used by GCC for nested C functions and libffi's trampolines.
This feature is implemented only on x86_32 and x86_64.
The assembly sequences used here were originally obtained from PaX source code.

See below about the language grsecurity has asked people to use in commit logs.

Quoted 44 lines
---
 security/sara/Kconfig               |  17 ++++
 security/sara/include/trampolines.h | 171 ++++++++++++++++++++++++++++++++++++
 security/sara/wxprot.c              | 140 +++++++++++++++++++++++++++++
 3 files changed, 328 insertions(+)
 create mode 100644 security/sara/include/trampolines.h
security/sara/Kconfig +17 -0
index 6c74069..f406805 100644
@@ -96,6 +96,23 @@ choice
                  Documentation/security/SARA.rst.
 endchoice
 
+config SECURITY_SARA_WXPROT_EMUTRAMP
+       bool "Enable emulation for some types of trampolines"
+       depends on SECURITY_SARA_WXPROT
+       depends on X86
+       default y
+       help
+         Some programs and libraries need to execute special small code
+         snippets from non-executable memory pages.
+         Most notable examples are the GCC and libffi trampolines.
+         This features make it possible to execute those trampolines even
+         if they reside in non-executable memory pages.
+         This features need to be enabled on a per-executable basis
+         via user-space utilities.
+         See Documentation/security/SARA.rst. for further information.
+
+         If unsure, answer y.
+
 config SECURITY_SARA_WXPROT_DISABLED
        bool "WX protection will be disabled at boot."
        depends on SECURITY_SARA_WXPROT
security/sara/include/trampolines.h new file +1 -0
new file mode 100644
index 0000000..eab0a85
@@ -0,0 +1,171 @@
+/*

security/sara/include/trampolines.h line 11

Quoted 10 lines
security/sara/include/trampolines.h new file +10 -0
+ * S.A.R.A. Linux Security Module
+ *
+ * Copyright (C) 2017 Salvatore Mesoraca <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2, as
+ * published by the Free Software Foundation.
+ *
+ * Assembly sequences used here were copied from
+ * PaX patch by PaX Team <[email protected]>

Given this copying, please include the grsecurity/PaX copyright notice too. Please see the recommendations here:
http://kernsec.org/wiki/index.php/Kernel_Self_Protection_Project/Get_Involved

Quoted 63 lines
security/sara/include/trampolines.h new file +63 -0
+ *
+ */
+
+#ifndef __SARA_TRAMPOLINES_H
+#define __SARA_TRAMPOLINES_H
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+
+
+/* x86_32 */
+
+
+struct libffi_trampoline_x86_32 {
+       unsigned char mov;
+       unsigned int addr1;
+       unsigned char jmp;
+       unsigned int addr2;
+} __packed;
+
+struct gcc_trampoline_x86_32_type1 {
+       unsigned char mov1;
+       unsigned int addr1;
+       unsigned char mov2;
+       unsigned int addr2;
+       unsigned short jmp;
+} __packed;
+
+struct gcc_trampoline_x86_32_type2 {
+       unsigned char mov;
+       unsigned int addr1;
+       unsigned char jmp;
+       unsigned int addr2;
+} __packed;
+
+union trampolines_x86_32 {
+       struct libffi_trampoline_x86_32 lf;
+       struct gcc_trampoline_x86_32_type1 g1;
+       struct gcc_trampoline_x86_32_type2 g2;
+};
+
+#define is_valid_libffi_trampoline_x86_32(UNION)       \
+       (UNION.lf.mov == 0xB8 &&                        \
+       UNION.lf.jmp == 0xE9)
+
+#define emulate_libffi_trampoline_x86_32(UNION, REGS) do {     \
+       (REGS)->ax = UNION.lf.addr1;                            \
+       (REGS)->ip = (unsigned int) ((REGS)->ip +               \
+                                    UNION.lf.addr2 +           \
+                                    sizeof(UNION.lf));         \
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type1(UNION, REGS)      \
+       (UNION.g1.mov1 == 0xB9 &&                               \
+       UNION.g1.mov2 == 0xB8 &&                                \
+       UNION.g1.jmp == 0xE0FF &&                               \
+       REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type1(UNION, REGS) do {  \
+       (REGS)->cx = UNION.g1.addr1;                            \
+       (REGS)->ax = UNION.g1.addr2;                            \
+       (REGS)->ip = UNION.g1.addr2;                            \
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type2(UNION, REGS)      \

security/sara/include/trampolines.h line 84

Quoted 10 lines
security/sara/include/trampolines.h new file +10 -0
+       (UNION.g2.mov == 0xB9 &&                                \
+       UNION.g2.jmp == 0xE9 &&                                 \
+       REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type2(UNION, REGS) do {  \
+       (REGS)->cx = UNION.g2.addr1;                            \
+       (REGS)->ip = (unsigned int) ((REGS)->ip +               \
+                                    UNION.g2.addr2 +           \
+                                    sizeof(UNION.g2));         \
+} while (0)

These all seem like they need to live in arch/x86/... somewhere rather than in the LSM, but maybe this isn't needed on other architectures? This seems to be very arch and compiler specific...

-Kees

Signature · 2 lines
Kees Cook
Pixel Security
#18 lore raw

Re: [RFC v2 7/9] Trampoline emulation

2017-06-28 1:13 GMT+02:00 Kees Cook <[email protected]>:

Quoted 15 lines
Quoted 4 lines · Salvatore Mesoraca

Some programs need to generate part of their code at runtime. Luckily enough, in some cases they only generate well-known code sequences (the "trampolines") that can be easily recognized and emulated by the kernel. This way WX Protection can still be active, so a potential attacker won't

Quoted 8 lines

be able to generate arbitrary sequences of code, but just those that are explicitly allowed. This is not ideal, but it's still better than having WX Protection completely disabled.
In particular S.A.R.A. is able to recognize trampolines used by GCC for nested C functions and libffi's trampolines.
This feature is implemented only on x86_32 and x86_64.
The assembly sequences used here were originally obtained from PaX source code.

Quoted 1 line

See below about the language grsecurity has asked people to use in commit logs.

OK, I'll change the commit message in v3.

Quoted 50 lines
Quoted 50 lines
---
 security/sara/Kconfig               |  17 ++++
 security/sara/include/trampolines.h | 171 ++++++++++++++++++++++++++++++++++++
 security/sara/wxprot.c              | 140 +++++++++++++++++++++++++++++
 3 files changed, 328 insertions(+)
 create mode 100644 security/sara/include/trampolines.h
security/sara/Kconfig +17 -0
index 6c74069..f406805 100644
@@ -96,6 +96,23 @@ choice
                  Documentation/security/SARA.rst.
 endchoice
 
+config SECURITY_SARA_WXPROT_EMUTRAMP
+       bool "Enable emulation for some types of trampolines"
+       depends on SECURITY_SARA_WXPROT
+       depends on X86
+       default y
+       help
+         Some programs and libraries need to execute special small code
+         snippets from non-executable memory pages.
+         Most notable examples are the GCC and libffi trampolines.
+         This features make it possible to execute those trampolines even
+         if they reside in non-executable memory pages.
+         This features need to be enabled on a per-executable basis
+         via user-space utilities.
+         See Documentation/security/SARA.rst. for further information.
+
+         If unsure, answer y.
+
 config SECURITY_SARA_WXPROT_DISABLED
        bool "WX protection will be disabled at boot."
        depends on SECURITY_SARA_WXPROT
security/sara/include/trampolines.h new file +7 -0
new file mode 100644
index 0000000..eab0a85
@@ -0,0 +1,171 @@
+/*
+ * S.A.R.A. Linux Security Module
+ *
+ * Copyright (C) 2017 Salvatore Mesoraca <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2, as
Quoted 8 lines

security/sara/include/trampolines.h line 11

Quoted 4 lines
security/sara/include/trampolines.h new file +4 -0
+ * published by the Free Software Foundation.
+ *
+ * Assembly sequences used here were copied from
+ * PaX patch by PaX Team <[email protected]>

Given this copying, please include the grsecurity/PaX copyright notice too. Please see the recommendations here:
http://kernsec.org/wiki/index.php/Kernel_Self_Protection_Project/Get_Involved

I understand your concern, but I don't think that the formula "Copyright (C) 2001-2017 PaX Team, Bradley Spengler, Open Source Security Inc" is appropriate in this context.
I don't think that any of the code written here is covered by Grsecurity's copyright. That line I wrote about "Assembly sequences" was just a courtesy note because I didn't gdb-ed my way through all of them, but if someone owns copyright on those "Assembly sequences" it's probably GCC and libffi authors. I have no problem in giving the most appropriate credits to the relevant people. And, for sure, I'm not going to get rich because of the attribution of this code.
I wrote this code without copying any actual line and I prefer to not give away my copyright without a good reason (let's call it a matter of principle). I don't want to start the umpteenth flame war about grsecurity and copyright. I'm acting in good faith and I hope this discussion can continue with constructive input from the interested parties.

Quoted 69 lines
Quoted 69 lines
security/sara/include/trampolines.h new file +69 -0
+ *
+ */
+
+#ifndef __SARA_TRAMPOLINES_H
+#define __SARA_TRAMPOLINES_H
+#ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
+
+
+/* x86_32 */
+
+
+struct libffi_trampoline_x86_32 {
+       unsigned char mov;
+       unsigned int addr1;
+       unsigned char jmp;
+       unsigned int addr2;
+} __packed;
+
+struct gcc_trampoline_x86_32_type1 {
+       unsigned char mov1;
+       unsigned int addr1;
+       unsigned char mov2;
+       unsigned int addr2;
+       unsigned short jmp;
+} __packed;
+
+struct gcc_trampoline_x86_32_type2 {
+       unsigned char mov;
+       unsigned int addr1;
+       unsigned char jmp;
+       unsigned int addr2;
+} __packed;
+
+union trampolines_x86_32 {
+       struct libffi_trampoline_x86_32 lf;
+       struct gcc_trampoline_x86_32_type1 g1;
+       struct gcc_trampoline_x86_32_type2 g2;
+};
+
+#define is_valid_libffi_trampoline_x86_32(UNION)       \
+       (UNION.lf.mov == 0xB8 &&                        \
+       UNION.lf.jmp == 0xE9)
+
+#define emulate_libffi_trampoline_x86_32(UNION, REGS) do {     \
+       (REGS)->ax = UNION.lf.addr1;                            \
+       (REGS)->ip = (unsigned int) ((REGS)->ip +               \
+                                    UNION.lf.addr2 +           \
+                                    sizeof(UNION.lf));         \
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type1(UNION, REGS)      \
+       (UNION.g1.mov1 == 0xB9 &&                               \
+       UNION.g1.mov2 == 0xB8 &&                                \
+       UNION.g1.jmp == 0xE0FF &&                               \
+       REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type1(UNION, REGS) do {  \
+       (REGS)->cx = UNION.g1.addr1;                            \
+       (REGS)->ax = UNION.g1.addr2;                            \
+       (REGS)->ip = UNION.g1.addr2;                            \
+} while (0)
+
+#define is_valid_gcc_trampoline_x86_32_type2(UNION, REGS)      \
+       (UNION.g2.mov == 0xB9 &&                                \
+       UNION.g2.jmp == 0xE9 &&                                 \
+       REGS->ip > REGS->sp)
+
+#define emulate_gcc_trampoline_x86_32_type2(UNION, REGS) do {  \
+       (REGS)->cx = UNION.g2.addr1;                            \
Quoted 8 lines

security/sara/include/trampolines.h line 84

Quoted 4 lines
security/sara/include/trampolines.h new file +4 -0
+       (REGS)->ip = (unsigned int) ((REGS)->ip +               \
+                                    UNION.g2.addr2 +           \
+                                    sizeof(UNION.g2));         \
+} while (0)

These all seem like they need to live in arch/x86/... somewhere rather than in the LSM, but maybe this isn't needed on other architectures? This seems to be very arch and compiler specific...

It is very arch and compiler specific. At some extent it can even be considered program specific, given that some of the trampolines are used only by libffi (AFAIK).
I put it in S.A.R.A.'s directory because I didn't want to pollute arch/x86 with code needed only by a single LSM.
In theory this feature could be useful on other archs too, but I'm not sure if there is actual demand for it.
Do you have any suggestion about the best place in "arch/x86/..." where it should be moved to?
Thank you very much for your time.

Salvatore

#19 lore raw

RFC v2 8/9 Allowing for stacking procattr support in S.A.R.A.

In reply to Salvatore Mesoraca

This allow S.A.R.A. to use the procattr interface without interfering with other LSMs.
This part should be reimplemented as soon as upstream procattr stacking support is available.

---
 fs/proc/base.c      | 38 ++++++++++++++++++++++++++++++++++++++
 security/security.c | 20 ++++++++++++++++++--
 2 files changed, 56 insertions(+), 2 deletions(-)
fs/proc/base.c +38 -0
index f1e1927..6d0fd1c 100644
@@ -2515,6 +2515,40 @@ static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
 	.llseek		= generic_file_llseek,
 };
 
+#ifdef CONFIG_SECURITY_SARA
+static const struct pid_entry sara_attr_dir_stuff[] = {
+	REG("wxprot", 0666, proc_pid_attr_operations),
+};
+
+static int proc_sara_attr_dir_readdir(struct file *file,
+				      struct dir_context *ctx)
+{
+	return proc_pident_readdir(file, ctx,
+				   sara_attr_dir_stuff,
+				   ARRAY_SIZE(sara_attr_dir_stuff));
+}
+
+static const struct file_operations proc_sara_attr_dir_ops = {
+	.read		= generic_read_dir,
+	.iterate_shared	= proc_sara_attr_dir_readdir,
+	.llseek		= generic_file_llseek,
+};
+
+static struct dentry *proc_sara_attr_dir_lookup(struct inode *dir,
+				struct dentry *dentry, unsigned int flags)
+{
+	return proc_pident_lookup(dir, dentry,
+				  sara_attr_dir_stuff,
+				  ARRAY_SIZE(sara_attr_dir_stuff));
+};
+
+static const struct inode_operations proc_sara_attr_dir_inode_ops = {
+	.lookup		= proc_sara_attr_dir_lookup,
+	.getattr	= pid_getattr,
+	.setattr	= proc_setattr,
+};
+#endif /* CONFIG_SECURITY_SARA */
+
 static const struct pid_entry attr_dir_stuff[] = {
 	REG("current",    S_IRUGO|S_IWUGO, proc_pid_attr_operations),
 	REG("prev",       S_IRUGO,	   proc_pid_attr_operations),
@@ -2522,6 +2556,10 @@ static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
 	REG("fscreate",   S_IRUGO|S_IWUGO, proc_pid_attr_operations),
 	REG("keycreate",  S_IRUGO|S_IWUGO, proc_pid_attr_operations),
 	REG("sockcreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
+#ifdef CONFIG_SECURITY_SARA
+	DIR("sara", 0555, proc_sara_attr_dir_inode_ops,
+				proc_sara_attr_dir_ops),
+#endif
 };
 
 static int proc_attr_dir_readdir(struct file *file, struct dir_context *ctx)
security/security.c +18 -2
index f7df697..c6c78dd 100644
@@ -1239,12 +1239,28 @@ void security_d_instantiate(struct dentry *dentry, struct inode *inode)
 
 int security_getprocattr(struct task_struct *p, char *name, char **value)
 {
-	return call_int_hook(getprocattr, -EINVAL, p, name, value);
+	struct security_hook_list *hp;
+	int rc;
+
+	list_for_each_entry(hp, &security_hook_heads.getprocattr, list) {
+		rc = hp->hook.getprocattr(p, name, value);
+		if (rc != -EINVAL)
+			return rc;
+	}
+	return -EINVAL;
 }
 
 int security_setprocattr(const char *name, void *value, size_t size)
 {
-	return call_int_hook(setprocattr, -EINVAL, name, value, size);
+	struct security_hook_list *hp;
+	int rc;
+
+	list_for_each_entry(hp, &security_hook_heads.setprocattr, list) {
+		rc = hp->hook.setprocattr(name, value, size);
+		if (rc != -EINVAL)
+			return rc;
+	}
+	return -EINVAL;
 }
 
 int security_netlink_send(struct sock *sk, struct sk_buff *skb)
Signature · 1 line
1.9.1
#20 lore raw

RFC v2 9/9 S.A.R.A. WX Protection procattr interface

In reply to Salvatore Mesoraca

This allow threads to get current WX Protection flags for themselves or for other threads (if they have CAP_MAC_ADMIN).
It also allow a thread to set itself flags to a stricter set of rules than the current one.
Via a new wxprot flag (SARA_WXP_FORCE_WXORX) is it possible to ask the kernel to rescan the memory and remove the VM_WRITE flag from any area that is marked both writable and executable.
Protections that prevent the runtime creation of executable code can be troublesome for all those programs that actually need to do it e.g. programs shipping with a JIT compiler built-in.
This feature can be use to run the JIT compiler with few restrictions while enforcing full WX Protection in the rest of the program.
To simplify access to this interface a CC0 licensed library is available
here: https://github.com/smeso/libsara

---
 security/sara/wxprot.c | 124 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 124 insertions(+)
security/sara/wxprot.c +124 -0
index 38c86be..0939591 100644
@@ -12,6 +12,7 @@
 #ifdef CONFIG_SECURITY_SARA_WXPROT
 
 #include <linux/binfmts.h>
+#include <linux/capability.h>
 #include <linux/cred.h>
 #include <linux/elf.h>
 #include <linux/kref.h>
@@ -42,6 +43,7 @@
 #define SARA_WXP_COMPLAIN	0x0010
 #define SARA_WXP_VERBOSE	0x0020
 #define SARA_WXP_MMAP		0x0040
+#define SARA_WXP_FORCE_WXORX	0x0080
 #define SARA_WXP_EMUTRAMP	0x0100
 #define SARA_WXP_TRANSFER	0x0200
 #define SARA_WXP_NONE		0x0000
@@ -503,6 +505,126 @@ static inline int sara_pagefault_handler_x86_64(struct pt_regs *regs)
 
 #endif /* CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP */
 
+static int sara_getprocattr(struct task_struct *p, char *name, char **value)
+{
+	int ret;
+	u16 flags;
+	char *buf;
+
+	ret = -EINVAL;
+	if (strcmp(name, "wxprot") != 0)
+		goto out;
+
+	ret = -EACCES;
+	if (unlikely(current != p &&
+		     !capable(CAP_MAC_ADMIN)))
+		goto out;
+
+	ret = -ENOMEM;
+	buf = kzalloc(8, GFP_KERNEL);
+	if (unlikely(buf == NULL))
+		goto out;
+
+	if (!sara_enabled || !wxprot_enabled) {
+		flags = 0x0;
+	} else {
+		rcu_read_lock();
+		flags = get_sara_wxp_flags(__task_cred(p));
+		rcu_read_unlock();
+	}
+
+	snprintf(buf, 8, "0x%04x\n", flags);
+	ret = strlen(buf);
+	*value = buf;
+
+out:
+	return ret;
+}
+
+static int sara_setprocattr(const char *name, void *value, size_t size)
+{
+	int ret;
+	struct vm_area_struct *vma;
+	struct cred *new = prepare_creds();
+	u16 cur_flags;
+	u16 req_flags;
+	char *buf = NULL;
+
+	ret = -EINVAL;
+	if (!sara_enabled || !wxprot_enabled)
+		goto error;
+	if (unlikely(new == NULL))
+		return -ENOMEM;
+	if (strcmp(name, "wxprot") != 0)
+		goto error;
+	if (unlikely(value == NULL || size == 0 || size > 7))
+		goto error;
+	ret = -ENOMEM;
+	buf = kmalloc(size+1, GFP_KERNEL);
+	if (unlikely(buf == NULL))
+		goto error;
+	buf[size] = '\0';
+	memcpy(buf, value, size);
+	ret = -EINVAL;
+	if (unlikely(strlen(buf) != size))
+		goto error;
+	if (unlikely(kstrtou16(buf, 16, &req_flags) != 0))
+		goto error;
+	if (unlikely(!are_flags_valid(req_flags & ~SARA_WXP_FORCE_WXORX)))
+		goto error;
+	if (unlikely(req_flags & SARA_WXP_FORCE_WXORX &&
+		     !(req_flags & SARA_WXP_WXORX)))
+		goto error;
+	if (unlikely(!get_current_sara_relro_page_found() &&
+		     req_flags & SARA_WXP_MMAP))
+		goto error;
+	cur_flags = get_current_sara_wxp_flags();
+	if (unlikely((req_flags & SARA_WXP_COMPLAIN) &&
+		     !(cur_flags & SARA_WXP_COMPLAIN)))
+		goto error;
+	if (unlikely((req_flags & SARA_WXP_EMUTRAMP) &&
+		     !(cur_flags & SARA_WXP_EMUTRAMP) &&
+		     (cur_flags & (SARA_WXP_MPROTECT |
+				   SARA_WXP_WXORX))))
+		goto error;
+	if (cur_flags & SARA_WXP_VERBOSE)
+		req_flags |= SARA_WXP_VERBOSE;
+	else
+		req_flags &= ~SARA_WXP_VERBOSE;
+	if (unlikely(cur_flags & (req_flags ^ cur_flags) &
+		     ~(SARA_WXP_COMPLAIN|SARA_WXP_EMUTRAMP)))
+		goto error;
+	ret = -EINTR;
+	if (req_flags & SARA_WXP_FORCE_WXORX) {
+		if (down_write_killable(&current->mm->mmap_sem))
+			goto error;
+		for (vma = current->mm->mmap; vma; vma = vma->vm_next) {
+			if (vma->vm_flags & VM_EXEC &&
+			    vma->vm_flags & VM_WRITE) {
+				vma->vm_flags &= ~VM_WRITE;
+				vma_set_page_prot(vma);
+				change_protection(vma,
+						  vma->vm_start,
+						  vma->vm_end,
+						  vma->vm_page_prot,
+						  0,
+						  0);
+			}
+		}
+		up_write(&current->mm->mmap_sem);
+	}
+	get_sara_wxp_flags(new) = req_flags & ~SARA_WXP_FORCE_WXORX;
+	commit_creds(new);
+	ret = size;
+	goto out;
+
+error:
+	abort_creds(new);
+out:
+	kfree(buf);
+	return ret;
+}
+
 static struct security_hook_list wxprot_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(bprm_set_creds, sara_bprm_set_creds),
 	LSM_HOOK_INIT(check_vmflags, sara_check_vmflags),
@@ -510,6 +632,8 @@ static inline int sara_pagefault_handler_x86_64(struct pt_regs *regs)
 #ifdef CONFIG_SECURITY_SARA_WXPROT_EMUTRAMP
 	LSM_HOOK_INIT(pagefault_handler_x86, sara_pagefault_handler_x86),
 #endif
+	LSM_HOOK_INIT(getprocattr, sara_getprocattr),
+	LSM_HOOK_INIT(setprocattr, sara_setprocattr),
 };
 
 struct binary_config_header {
Signature · 1 line
1.9.1