Difference between revisions of "Grsecurity"

From ArchWiki
Jump to: navigation, search
(Displaced statement to proper section.)
(Compatibility: Added incompatibility of RAP protection with out-of-tree binary code)
 
(180 intermediate revisions by 21 users not shown)
Line 1: Line 1:
 
[[Category:Kernel]]
 
[[Category:Kernel]]
 
[[Category:Security]]
 
[[Category:Security]]
 +
[[ja:Grsecurity]]
 +
{{Related articles start}}
 +
{{Related|PaX}}
 +
{{Related|Security}}
 +
{{Related|sysctl}}
 +
{{Related articles end}}
  
 +
[https://grsecurity.net/ Grsecurity] is an extensive security enhancement to the Linux kernel that defends against a wide range of security threats. The [[PaX]] project is included, hardening both userspace applications and the kernel against memory corruption-based exploits. Grsecurity includes a powerful Mandatory Access Control system with an effortless automatic learning mode and a host of other miscellaneous hardening features.
  
From [http://grsecurity.net/ Grsecurity homepage]:
+
== Installation ==
  
:''Unlike other expensive security "solutions" that pretend to achieve security through known-vulnerability patching, signature-based detection, or other reactive methods, grsecurity provides real proactive security. The only solution that hardens both your applications and operating system, grsecurity is essential for public-facing servers and shared-hosting environments.''
+
The {{pkg|linux-grsec}} package provides the grsecurity hardened kernel. In most cases, this package is a drop-in replacement for the vanilla kernel and will not cause any issues. By default, many of the user-facing features are disabled, but there is significant hardening of the kernel itself against exploitation.
  
The grsecurity project provides patches to the Linux kernel which enhance security further than many other solutions. The main advantage is a "learning mode" designed to configure a tight Mandatory Access Control almost effortlessly. Comparable security implementations include SELinux and Apparmor. It is up to the user to decide which one is appropriate.
+
{{Note|[https://grsecurity.net/announce.php Upstream] no longer provides a long-term support version of ''grsecurity'', which it calls the "stable" series. The package {{pkg|linux-grsec}} is known at upstream as the "test" series.}}
  
In order to utilize grsecurity most effectively, it is understood that the reader has a working knowledge of computer security in general.
+
After [[install]]ing the {{pkg|linux-grsec}} package, edit your [[bootloader]] settings to load {{ic|vmlinuz-linux-grsec}} and {{ic|initramfs-linux-grsec.img}}.
  
== Build Options ==
+
Installing the optional {{pkg|paxd}} package causes the PaX exploit mitigations to be enabled, protecting userspace processes. It automatically applies the necessary exceptions for packages in the repositories. See [[PaX#PaX exceptions]] for more details.
  
There are three ways you can install a grsecurity hardened kernel in Arch. The first is by adding a repository to install the binary kernel. The second option is to build it from the AUR package. The third option is to patch and build the kernel all by hand.
+
Also included are {{pkg|checksec}}, {{pkg|pax-utils}} and {{pkg|paxtest}} packages providing useful tooling for working with PaX and verifying that the exploit mitigation techniques are active.
  
Your best bet is probably to use the binary grsecurity kernel repository. If you have the time, build the AUR package yourself for added security.
+
The optional {{pkg|gradm}} package provides the userspace tooling for managing RBAC policies. RBAC is disabled by default, and the sample policy is not usable without significant configuration (likely via heavy use of the learning mode).
  
{{note|Any way you choose to install the grsecurity kernel you will need to also install {{AUR|gradm}}, {{AUR|paxctl}}, and {{AUR|linux-pax-flags}}}}
+
=== Custom kernel ===
  
=== Install binary kernel packages ===
+
Compiling a custom kernel based on the official package with [[ABS]] is worth considering. There are several important compromises to make between performance and security, so while the official configuration is solid it is not perfect for every use case. See [[PaX#Performance]] for coverage of the PaX options with a significant performance impact. The official package prioritizes security over performance.
  
Add the [http://arsch.orgizm.net/ Arsch Arch Linux Repository] to your package sources and install the kernel with {{ic|pacman -Sy linux-grsec}} (or the PaX only kernel with {{ic|pacman -Sy linux-pax}}). Finish by adding the new kernel to your bootloader menu (with {{ic|grub-mkconfig -o /boot/grub/grub.cfg}} for example) and reboot.
+
The /proc and /sys restrictions are unacceptable for a general purpose package due to breaking too much software, but can be worth enabling to plug potential information leaks.
  
If you rely on specific hooks, like {{AUR|catalyst-hook}}, you have to install the headers first with {{ic|pacman -Sy linux-grsec-headers}}.
+
Some features like the RANDSTRUCT plugin and hiding symbol addresses are only truly useful with a custom kernel, since the pre-built kernel is available for analysis by any attacker. The {{pkg|linux-grsec}} package enables {{ic|CONFIG_RANDOMIZE_BASE}}, but a custom build can provide unique symbol offsets in addition to the randomized base, making {{ic|CONFIG_GRKERNSEC_HIDESYM}} valuable.
  
After configuration of grsecurity sysctl options, set {{ic|kernel.grsecurity.grsec_lock = 1}} in {{ic|/etc/sysctl.d/10-grsecurity.conf}}, so no hardening option can be deactivated later (even by root).
+
{{AUR|linux-libre-grsec}} and {{AUR|linux-zen-grsec}} are also available.
  
=== Build kernel from AUR ===
+
== Compatibility ==
  
To build the AUR package we will follow this general game plan. First, download all needed files and check GPG signatures. Second, configure kernel and compile. Third, copy a backup of these files to the Root users home folder. Forth, install utilities needed for PaX and RBAC. Fifth, install the kernel package. Sixth, run linux-pax-flags to poke security holes in applications that will not run without them. Finally, reboot into your hardened system.
+
{{Note|An incompatibility between {{pkg|linux-grsec}} and another package should not be reported as a bug in that package. It should be filed against the {{pkg|linux-grsec}} package and will either be fixed or documented as a compatibility issue here.}}
  
The AUR has all the utilities and kernel packages you need to run a hardened Arch Linux system. There is even a script called {{AUR|linux-pax-flags}} which will make using PaX as painless as possible by setting all the PaX flags automatically.
+
The following incompatibilities require building a custom kernel with fewer features enabled:
  
==== Download Files ====
+
* hibernation is not supported (conflicts with {{ic|CONFIG_GRKERNSEC_KMEM}}, {{ic|CONFIG_PAX_MEMORY_SANITIZE}} and {{ic|CONFIG_RANDOMIZE_BASE}})
 +
* Xen and {{pkg|virtualbox}} are not supported (conflicts with {{ic|CONFIG_PAX_KERNEXEC}} and {{ic|CONFIG_PAX_MEMORY_UDEREF}})
 +
* The code reuse attacks protection (RAP), enabled with {{ic|CONFIG_PAX_RAP}}, is not compatible with out-of-tree binary code, as, for example, the patched proprietary nvidia driver {{aur|nvidia-grsec}} in the [[AUR]].
  
Download the packages
+
Known incompatibilities with other packages:
{{AUR|linux-grsec}}
+
Or
+
{{AUR|linux-grsec-lts}}
+
  
Kernel linux-3.X.tar.xz and current patch-3.X.X.tar.xz also the .sign signature files for each.
+
* {{pkg|pkgstats}} - tries to list the loaded modules as non-root and treats it as a fatal error when it fails
[https://www.kernel.org/pub/linux/kernel/v3.x/ kernel.org]
+
* {{aur|broadcom-wl-dkms}} - fails to be compiled with {{pkg|linux-grsec-headers}} due to illegal memory access
  
Download the current grsecurity patch and Signatures
+
Out-of-tree modules may require patches for compatibility with kernel hardening features like {{ic|CONFIG_PAX_SIZE_OVERFLOW}}:
[https://grsecurity.net/test.php grsecurity Test]
+
Or
+
[https://grsecurity.net/download_stable.php grsecurity Stable] for LTS kernel
+
  
{{tip|The Grsecurity Test is in fact stable. The Stable Grsecurity version is just for the LTS}}
+
* the {{aur|nvidia-grsec}} package in the [[AUR]] patches the proprietary [[NVIDIA]] driver for compatibility with the {{ic|CONFIG_PAX_USERCOPY}} and {{ic|CONFIG_PAX_CONSTIFY_PLUGIN}} features
  
==== Verify The GPG Signatures ====
+
== PaX ==
  
With the .sign files in the same directory as the file it is a a signature of, verify the signature like so...
+
The [[Wikipedia:PaX|PaX]] project provides many of the exploit mitigations offered by grsecurity. See [[PaX|the documentation on PaX]] for more information.
  
$ gpg2 --verify linux-3.10.tar.sign
+
== Configuration ==
  
==== Setup Build Environment ====
+
The user-facing features are configurable at runtime via [[sysctl]] settings. Sane defaults are set in the {{ic|/etc/sysctl.d/05-grsecurity.conf}} configuration file and it can be modified as desired.
  
Unpack the linux-grsec.tar.gz and copy all the files into it
+
== Trusted path execution ==
  
$ tar xzf linux-grsec.tar.gz
+
Trusted path execution (TPE) is an opt-in feature restricting file execution. It can be enabled by setting the {{ic|kernel.grsecurity.tpe}} [[sysctl]] switch to {{ic|1}}. TPE prevents users from executing any file writeable by a non-root user. By tightening up the rules for executing files, some exploits (such as upload + CGI exploits on a web server) and persistent backdoors will be prevented.
$ cp ~/Downloads/linux-3.10.tar.xz ~/linux-grsec
+
$ cp ~/Downloads/patch-3.10.9.tar.xz ~/linux-grsec
+
$ cp ~/Downloads/grsecurity-2.9.1-3.10.9-201308202015.patch ~/linux-grsec
+
+
Change into the build directory
+
  
$ cd ~/linux-grsec
+
=== Using the {{ic|tpe}} group as a whitelist or blacklist ===
  
==== Build the Kernel Package ====
+
By default, {{ic|kernel.grsecurity.tpe_invert}} is set to {{ic|1}}, causing TPE to operate with a whitelist-based model. It will be applied to every user that is not a member of the {{ic|tpe}} group. If {{ic|kernel.grsecurity.tpe_invert}} is set to {{ic|0}}, the {{ic|tpe}} group will instead function as a blacklist of users with the restriction, with users not in the group unaffected.
  
It is going to take a long time to build the kernel because it is based on the default Arch kernel config with has about ten times as make modules enabled then your system actually needs. However, it is a known working config and to eliminate any more variables it is advisable to just live with the extra build time.
+
The whitelist model is recommended, and adding non-system users to the whitelist is usually enough. It will slightly improve the isolation of services running as non-root while not getting in anyone's way.
  
Build the package
+
=== Compatibility ===
  
$ MENUCONFIG=2 makepkg
+
[[Linux Containers|Containers]] or plain [[chroot]]s can throw a wrench into the ease of using TPE, as each one has a local {{ic|/etc/group}}. A group with the same id in the container will still work as a whitelist, but this will be broken if the container makes use of user namespaces (not yet supported by Arch kernels).
  
You should be dropped into the ncurses GUI now. Navigate to the grsecurity settings to verify the configuration and/or change things as needed. These setting can be found in {{ic|Security options ---> grsecurity ---> Customize Configuration --->}}
+
=== Partially restrict all non-root users ===
  
For both Desktops and Servers after you are sure you will not need to change any of the Grsecurity settings with sysctl, disable {{ic|Sysctl support}} found in {{ic|Sysctl Support}}.
+
Setting the {{ic|kernel.grsecurity.tpe_restrict_all}} [[sysctl]] switch to {{ic|1}} will prevent non-root users from executing files writeable by a user other than themselves or root. This feature is enabled by the default {{ic|/etc/sysctl.d/05-grsecurity.conf}}.
  
If this kernel is for a Server also enable {{ic|Disable privileged I/O}} found in {{ic|Memory Protections}}.
+
== chroot hardening ==
  
All other setting should be optimal as they are, so now exit out of the ncurses GUI config and Save. Now the package should start to build. If all goes well you will have two .pkg.tar.xz packages one for the kernel and one for the kernel-headers.
+
A [[chroot]] is a common isolation mechanism for services. Grsecurity includes features for eliminating many common escape routes from chroots and can lock them down to the point where the confinement is equivalent to a container. These features can all be toggled on and off via sysctl switches. For a detailed explanantion of these features, see the [https://en.wikibooks.org/wiki/Grsecurity/Appendix/Grsecurity_and_PaX_Configuration_Options#Chroot_jail_restrictions configuration documentation].
  
==== Make a Backup ====
+
The following features are enabled in {{ic|/etc/sysctl.d/05-grsecurity.conf}} by default and are unlikely to cause any compatibility issues:
  
Keep all linux-grsec.tar.gz files along with the grsecruity patch and compiled packages in the Root users home folder. That way you can roll back if needed. Every time a new grsecurity patch is release you will not be able to download outdated patches every again.
+
kernel.grsecurity.chroot_deny_fchdir = 1
 +
kernel.grsecurity.chroot_deny_shmat = 1
 +
kernel.grsecurity.chroot_deny_sysctl = 1
 +
kernel.grsecurity.chroot_deny_unix = 1
 +
kernel.grsecurity.chroot_enforce_chdir = 1
 +
kernel.grsecurity.chroot_findtask = 1
  
# mkdir /root/3.10.9
+
The remaining features are left off by default, to remain compatible with containers:
# cp -r /home/USER/linux-grsec /root/3.10.9
+
  
==== Install PaX and RBAC Utilities ====
+
#kernel.grsecurity.chroot_caps = 1
 +
#kernel.grsecurity.chroot_deny_chmod = 1
 +
#kernel.grsecurity.chroot_deny_chroot = 1
 +
#kernel.grsecurity.chroot_deny_mknod = 1
 +
#kernel.grsecurity.chroot_deny_mount = 1
 +
#kernel.grsecurity.chroot_deny_pivot = 1
 +
#kernel.grsecurity.chroot_restrict_nice = 1
  
The AUR has three utilities you will need to install. They are {{AUR|paxctl}}, {{AUR|gradm}}, and {{AUR|linux-pax-flags}}.
+
== Socket restrictions ==
  
==== Set PaX Flags ====
+
There are 3 groups for restricting access to sockets. Users in the {{ic|socket-deny-client}} group are forbidden from connecting to other hosts. Users in the {{ic|socket-deny-server}} group are unable to listen on a port. The {{ic|socket-deny-all}} group includes both of the restrictions.
  
Use the linux-pax-flags program to configure all the PaX flags for troublesome programs.
+
== Auditing ==
More information can be found in the Using linux-pax-flags AUR Package section.
+
  
# linux-pax-flags
+
There are a few security-related logging features added to the kernel.
  
==== Install Hardened Kernel ====
+
By default, only {{ic|kernel.grsecurity.rwxmap_logging}} is enabled. It logs an error whenever an application has an {{ic|mprotect}} or {{ic|mmap}} system call rejected due to the PaX MPROTECT feature along with some other edge cases. In most cases, the application is intentionally doing dynamic machine code generation and just needs an exception. However, it may indicate a compiler / linker bug or a bug in application / library code and the errors will also be logged when an exploit attempt is prevented by the MPROTECT feature. See [[PaX]] for more information about exceptions.
  
Now that all the needed utilities are installed and the system is configured for PaX, install the hardened kernel and headers.
+
The remaining audit features are currently disabled by default due to the high number of false positives, but can be enabled via [[sysctl]]. The {{ic|kernel.grsecurity.audit_group}} switch can be set to {{ic|1}} to limit {{ic|kernel.grsecurity.audit_chdir}} and {{ic|kernel.grsecurity.exec_logging}} to users in the {{ic|audit}} group as they will generate a LOT of log messages.
  
# pacman -U /root/3.10.9/*.pkg.tar.xz
+
== Hide information from /proc ==
  
Finish by adding the new kernel to your bootloader menu (with {{ic|grub-mkconfig -o /boot/grub/grub.cfg}} for example) and reboot.
+
The {{pkg|linux-grsec}} package does not enable the strict {{ic|/proc}} restrictions ({{ic|CONFIG_GRKERNSEC_PROC}}). Instead, the {{ic|1=hidepid=2}} mount option can be set on {{ic|/proc}} to hide processes of other users and the {{ic|gid}} option can be used to make a group with an exception from the restrictions. The {{ic|hidepid}} mount option is less invasive because it's local to each process namespace so it can be set per [[systemd-nspawn|container]]. However, it's missing the additional miscellaneous information hiding so compiling a custom kernel may be desired.
+
You should now be in your hardened system. Just make sure to run {{ic|linux-pax-flags}} after every time you update your system or install a new program and you should have a trouble free experience.
+
  
=== Build Kernel without the AUR ===
+
The {{pkg|hidepid}} package can be installed to set up the necessary {{ic|systemd-logind}} exception and enable {{ic|1=hidepid=2}}. It will also work with {{ic|CONFIG_GRKERNSEC_PROC}} in a custom kernel configured to use the correct proc group gid.
  
Throughout this document we will talk about kernel configuration using the kernel variables like CONFIG_GRKERNSEC_PAX_NO_ACL_FLAGS. These are the variables that the kernel build process uses to determine if a certain feature needs to be compiled.
+
== RBAC ==
  
When you configure your kernel through make menuconfig or similar, you receive a user interface through which you can select the various kernel options. If you select the Help button at a certain kernel feature you will see at the top that it lists such a kernel variable.
+
{{poor writing|reason=This section needs an overhaul, including fixing some inaccuracies.}}
 
+
You can therefore still configure your kernel as you like - with a bit of thinking. And if you cannot find a certain option, there is always the possibility to edit /usr/src/linux/.config by hand :)
+
 
+
Of course, to be able to select the various grsecurity kernel options, you must enable grsecurity in your kernel.
+
See [[default grsecurity kernel configuration]]
+
 
+
== RBAC ==
+
  
 
Role Based Access Control
 
Role Based Access Control
Line 132: Line 130:
 
The MAC implementation grsecurity supports is called Role Based Access Control. RBAC associates roles with each user. Each role defines what operations can be performed on certain objects. Given a well-written collection of roles and operations your users will be restricted to perform only those tasks that you tell them they can do. The default "deny-all" ensures you that a user cannot perform an action you have not thought of.
 
The MAC implementation grsecurity supports is called Role Based Access Control. RBAC associates roles with each user. Each role defines what operations can be performed on certain objects. Given a well-written collection of roles and operations your users will be restricted to perform only those tasks that you tell them they can do. The default "deny-all" ensures you that a user cannot perform an action you have not thought of.
  
=== Configuring the Kernel ===
 
 
The recommended kernel setting for RBAC is:
 
 
#
 
# Role Based Access Control Options
 
#
 
CONFIG_GRKERNSEC_ACL_HIDEKERN=y
 
CONFIG_GRKERNSEC_ACL_MAXTRIES=3
 
CONFIG_GRKERNSEC_ACL_TIMEOUT=30
 
 
 
=== Working with gradm ===
 
=== Working with gradm ===
  
gradm is a tool which allows you to administer and maintain a policy for your system. With it, you can enable or disable the RBAC system, reload the RBAC roles, change your role, set a password for admin mode, etc.
+
{{pkg|gradm}} is a tool which allows you to administer and maintain a policy for your system. With it, you can enable or disable the RBAC system, reload the RBAC roles, change your role, set a password for admin mode, etc.
  
When you install gradm a default policy will be installed in /etc/grsec/policy. Please see in AUR for gradm package.
+
When you install gradm a default policy will be installed in /etc/grsec/policy.
  
 
By default, the RBAC policies are not activated. It is the sysadmin's job to determine when the system should have an RBAC policy enforced. Before activating the RBAC system you should set an admin password.
 
By default, the RBAC policies are not activated. It is the sysadmin's job to determine when the system should have an RBAC policy enforced. Before activating the RBAC system you should set an admin password.
Line 168: Line 155:
 
  # gradm -u admin
 
  # gradm -u admin
  
=== Generating a Policy ===
+
=== Generating a policy ===
  
 
The RBAC system comes with a great feature called "learning mode". The learning mode can generate an anticipatory least privilege policy for your system. This allows for time and money savings by being able to rapidly deploy multiple secure servers.
 
The RBAC system comes with a great feature called "learning mode". The learning mode can generate an anticipatory least privilege policy for your system. This allows for time and money savings by being able to rapidly deploy multiple secure servers.
Line 180: Line 167:
 
When you believe you have used your system sufficiently to obtain a good policy, let gradm process them and propose roles under {{ic|/etc/grsec/learning.roles}}:
 
When you believe you have used your system sufficiently to obtain a good policy, let gradm process them and propose roles under {{ic|/etc/grsec/learning.roles}}:
  
 +
# gradm -D
 
  # gradm -F -L /etc/grsec/learning.log -O /etc/grsec/learning.roles
 
  # gradm -F -L /etc/grsec/learning.log -O /etc/grsec/learning.roles
  
Line 189: Line 177:
 
You will now be able to enable the RBAC system with your new learned policy.
 
You will now be able to enable the RBAC system with your new learned policy.
  
=== Tweaking your Policy ===
+
# gradm -E
 +
 
 +
{{Tip|If you receive the error '''Viewing access is allowed by role <insert user> to /etc/grsec, the directory which stores RBAC policies and RBAC password information.''', add the following to your '''subject /''' under '''# Role: <insert user>''':
 +
 
 +
/etc/grsec h
 +
 
 +
Example:
 +
 
 +
# Role: root
 +
subject /  {
 +
        /                              h
 +
        /etc                            rx
 +
        /etc/grsec                      h
 +
}}
 +
The reasoning for this can be found [https://forums.grsecurity.net/viewtopic.php?f=5&t=1607 here]
 +
 
 +
=== Tweaking your policy ===
  
 
An interesting feature of grsecurity 2.x is Set Operation Support for the configuration file. Currently it supports unions, intersections and differences of sets (of objects in this case).
 
An interesting feature of grsecurity 2.x is Set Operation Support for the configuration file. Currently it supports unions, intersections and differences of sets (of objects in this case).
Line 260: Line 264:
  
 
  (($set1 - $set2) | $set3) & $set4
 
  (($set1 - $set2) | $set3) & $set4
 
  
== PaX ==
+
=== Tweaking /etc/grsec/policy directly ===
  
==== Fighting the Exploitation of Software Bugs ====
+
Sometimes, full learning mode doesnt work for a particular program and direct revisions to the policy file will need to be made. One might simply want to tweak the policy file to add or remove access to directories without requiring one to reinitiate learning mode or recreating a policy file. The file itself is composed of Roles and Subjects. A Role determines what user the ruleset applies to, while the Subject could be seen as what process/program the ruleset applies to.
  
PaX introduces a couple of security mechanisms that make it harder for attackers to exploit software bugs that involve memory corruption (so do not treat PaX as if it protects against all possible software bugs). The PaX introduction document talks about three possible exploit techniques:
+
Consider a situation where the role is "username", while the subject is /usr/lib/firefox/firefox. Within the curly braces of this role/subject rule, directories will be listed, along with flags that dictate what capacities (read, write, execute, etc) you wish to give that subject (firefox for example) under that role (username, when firefox is ran under the user "username" for example). Here is a list of flags and what they do:
  
# introduce/execute arbitrary code
+
  a This object can be opened for appending.
# execute existing code out of original program order
+
  c Allow creation of the file/directory.
# execute existing code in original program order with arbitrary data
+
  d Allow deletion of the file/directory.
 +
  f Needed to mark the pipe used for communication with init to transfer the privilege of the persistent role; only valid within a persistent role. Transfer only occurs when the file is opened for writing.
 +
  h This object is hidden.
 +
  i This mode only applies to binaries. When the object is executed, it inherits the ACL of the    subject in which it was contained.
 +
  l Lowercase L. Allow a hardlink at this path. Hardlinking requires a minimum of c and l modes, and the target link cannot have any greater permission than the source file.
 +
  m Allow creation of setuid/setgid files/directories and modification of files/directories to be setuid/setgid.
 +
  p Reject all ptraces to this object.
 +
  r This object can be opened for reading.
 +
  t This object can be ptraced, but cannot modify the running task. This is referred to as a 'read-only ptrace'.
 +
  w This object can be opened for writing or appending.
 +
  x This object can be executed (or mmap'd with PROT_EXEC into a task).
  
One prevention method disallows executable code to be stored in writable memory. When we look at a process, it requires five memory regions:
+
So for example, if you want firefox to have read access to the home folder of the user username, be able to do everything (read, write, create and destroy files, execute) in /home/username/Downloads, but not be able to see /home/username/secretstuff or anything in /, your ruleset might look like this:
 +
  # Role: username
 +
  subject /usr/lib/firefox/firefox o {
 +
      /                                              h
 +
      /home/username                      r
 +
      /home/username/Downloads    rwxcd
 +
      /home/username/secretstuff      h
 +
  }
 +
Of course, a Firefox ruleset will need more than just the above (like access to directories it needs to run in /usr for example); compare the above with what is generated by full-learning-mode and you quickly see the pattern. The idea is that you want to limit each process as much as possible to limit the changes it can make to the filesystem in the event it is compromised. Much more info is available on the [http://en.wikibooks.org/wiki/Grsecurity/The_RBAC_System GRsecurity RBAC wiki page.]
  
# a data section which contains the statically allocated and global data
+
=== Using Wine; Changes needed to /etc/grsec/policy ===
# a BSS region (Block Started by Symbol) which contains information about the zero-initialized data of the process
+
# a code region, also called the text segment, which contains the executable instructions
+
# a heap which contains the dynamically allocated memory
+
# a stack which contains the local variables
+
  
The first PaX prevention method, called NOEXEC, is meant to give control over the runtime code generation. It marks memory pages that do not contain executable code as non-executable. This means that the heap and the stack, which only contain variable data and should not contain executable code, are marked as non-executable. Exploits that place code in these areas with the intention of running it will fail.
+
In the event you use wine, your executables for wine apps are on an NTFS partition, and you want it to work while RBAC is enabled, you will need to append "O" to the Subject mode of /usr/bin/wine-preloader for the Role (user) using this subject. I am unsure if this applies to executables in .wine as I do not have the free space to test it. I put my system into full-learning mode and ran wine, and after generating a /etc/grsec/policy from this session RBAC still prevented my wine program from running with:
 +
grsec: (username:U:/usr/bin/wine-preloader) denied load of writable library /mnt/winblows/Program Files (x86)/Diablo II/Game.exe by /usr/bin/wine-preloader[Game.exe:7518] uid...
  
NOEXEC does more than this actually, interested readers should focus their attention to the [http://pax.grsecurity.net/docs/noexec.txt PaX NOEXEC documentation].
+
Appending "O" to the end of the Subject mode will fix this problem. An example of a working ruleset (notice the capital O after subject /usr/bin/wine-preloader):
 
+
  # Role: username
The second PaX prevention method, called ASLR (Address Space Layout Randomization), randomize the addresses given to memory requests. Where previously memory was assigned contiguously (which means exploits know where the tasks' memory regions are situated) ASLR randomizes this allocation, rendering techniques that rely on this information useless.
+
  subject /usr/bin/wine-preloader O {
 
+
  / r
More information about ASLR can be found [http://pax.grsecurity.net/docs/aslr.txt online].
+
  <other listed files generated by full-learning mode>  rwcdx
 
+
}
==== PaX kernel configuration ====
+
 
+
The recommended kernel setting for PaX is:
+
 
+
#
+
# Security options
+
#
+
#
+
# PaX
+
#
+
CONFIG_PAX=y
+
#
+
# PaX Control
+
#
+
# CONFIG_PAX_SOFTMODE is not set
+
CONFIG_PAX_EI_PAX=y
+
CONFIG_PAX_PT_PAX_FLAGS=y
+
CONFIG_PAX_NO_ACL_FLAGS=y
+
# CONFIG_PAX_HAVE_ACL_FLAGS is not set
+
# CONFIG_PAX_HOOK_ACL_FLAGS is not set
+
#
+
# Non-executable pages
+
#
+
CONFIG_PAX_NOEXEC=y
+
CONFIG_PAX_PAGEEXEC=y
+
CONFIG_PAX_SEGMEXEC=y
+
# CONFIG_PAX_DEFAULT_PAGEEXEC is not set
+
CONFIG_PAX_DEFAULT_SEGMEXEC=y
+
CONFIG_PAX_EMUTRAMP=y
+
CONFIG_PAX_MPROTECT=y
+
# CONFIG_PAX_NOELFRELOCS is not set
+
#
+
# Address Space Layout Randomization
+
#
+
CONFIG_PAX_ASLR=y
+
CONFIG_PAX_RANDKSTACK=y
+
CONFIG_PAX_RANDUSTACK=y
+
CONFIG_PAX_RANDMMAP=y
+
#
+
# Miscellaneous hardening features
+
#
+
CONFIG_PAX_MEMORY_SANITIZE=y
+
CONFIG_PAX_MEMORY_UDEREF=y
+
CONFIG_KEYS=y
+
# CONFIG_KEYS_DEBUG_PROC_KEYS is not set
+
CONFIG_SECURITY=y
+
CONFIG_SECURITY_NETWORK=y
+
CONFIG_SECURITY_NETWORK_XFRM=y
+
CONFIG_SECURITY_CAPABILITIES=m
+
CONFIG_SECURITY_ROOTPLUG=m
+
+
If you are running a non-x86 system you will observe that there is no CONFIG_GRKERNSEC_PAX_NOEXEC. You should select  CONFIG_GRKERNSEC_PAX_PAGEEXEC instead as it is the only non-exec implementation around.
+
 
+
=== Controlling PaX ===
+
 
+
Not all Linux applications are happy with the PaX security restrictions. These tools include xorg-x11, java, mplayer, xmms and others. If you plan on using them you can elevate the protections for these applications using chpax and paxctl. You can find they on AUR.
+
 
+
You can also use pax-utils, which is a small toolbox which contains useful applications to administrate a PaX aware server. Find it on AUR.
+
 
+
Interesting tools include scanelf and pspax:
+
 
+
* With scanelf you can scan over library and binary directories and list the various permissions and ELF types that pertain to running an ideal pax/grsec setup
+
* With pspax you can display PaX flags/capabilities/xattr from the kernel's perspective
+
 
+
=== Verifying the PaX Settings ===
+
 
+
Peter Busser has written a regression test suite called paxtest. This tool will check various cases of possible attack vectors and inform you of the result. When you run it, it will leave a logfile called paxtest.log in the current working directory.
+
 
+
# paxtest
+
Executable anonymous mapping            : Killed
+
Executable bss                          : Killed
+
Executable data                          : Killed
+
Executable heap                          : Killed
+
Executable stack                        : Killed
+
Executable anonymous mapping (mprotect)  : Killed
+
Executable bss (mprotect)                : Killed
+
Executable data (mprotect)              : Killed
+
Executable heap (mprotect)              : Killed
+
Executable stack (mprotect)              : Killed
+
Executable shared library bss (mprotect) : Killed
+
Executable shared library data (mprotect): Killed
+
Writable text segments                  : Killed
+
Anonymous mapping randomisation test    : 16 bits (guessed)
+
Heap randomisation test (ET_EXEC)        : 13 bits (guessed)
+
Heap randomisation test (ET_DYN)        : 25 bits (guessed)
+
Main executable randomisation (ET_EXEC)  : 16 bits (guessed)
+
Main executable randomisation (ET_DYN)  : 17 bits (guessed)
+
Shared library randomisation test        : 16 bits (guessed)
+
Stack randomisation test (SEGMEXEC)      : 23 bits (guessed)
+
Stack randomisation test (PAGEEXEC)      : No randomisation
+
Return to function (strcpy)              : Vulnerable
+
Return to function (memcpy)              : Vulnerable
+
Return to function (strcpy, RANDEXEC)    : Killed
+
Return to function (memcpy, RANDEXEC)    : Killed
+
Executable shared library bss            : Killed
+
Executable shared library data          : Killed
+
 
+
In the above example run you notice that:
+
 
+
* strcpy and memcpy are listed as Vulnerable. This is expected and normal - it is simply showing the need for a technology such as ProPolice/SSP
+
* there is no randomization for PAGEEXEC. This is normal since our recommended x86 kernel configuration did not activate the PAGEEXEC setting. However, on arches that support a true NX (non-executable) bit (most of them do, including x86_64), PAGEEXEC is the only method available for NOEXEC and has no performance hit.
+
 
+
== Other features ==
+
=== Filesystem Protection ===
+
 
+
==== Fighting Chroot and Filesystem Abuse ====
+
 
+
Grsecurity includes many patches that prohibits users from gaining unnecessary knowledge about the system. This includes restrictions on /proc usage, chrooting, linking, etc.
+
 
+
===== Kernel Configuration =====
+
 
+
We recommend the following grsecurity kernel configuration for filesystem protection:
+
 
+
#
+
# Filesystem Protections
+
#
+
CONFIG_GRKERNSEC_PROC=y
+
# CONFIG_GRKERNSEC_PROC_USER is not set
+
CONFIG_GRKERNSEC_PROC_USERGROUP=y
+
CONFIG_GRKERNSEC_PROC_GID=3
+
CONFIG_GRKERNSEC_PROC_ADD=y
+
CONFIG_GRKERNSEC_LINK=y
+
CONFIG_GRKERNSEC_FIFO=y
+
CONFIG_GRKERNSEC_CHROOT=y
+
CONFIG_GRKERNSEC_CHROOT_MOUNT=y
+
CONFIG_GRKERNSEC_CHROOT_DOUBLE=y
+
CONFIG_GRKERNSEC_CHROOT_PIVOT=y
+
CONFIG_GRKERNSEC_CHROOT_CHDIR=y
+
CONFIG_GRKERNSEC_CHROOT_CHMOD=y
+
CONFIG_GRKERNSEC_CHROOT_FCHDIR=y
+
CONFIG_GRKERNSEC_CHROOT_MKNOD=y
+
CONFIG_GRKERNSEC_CHROOT_SHMAT=y
+
CONFIG_GRKERNSEC_CHROOT_UNIX=y
+
CONFIG_GRKERNSEC_CHROOT_FINDTASK=y
+
CONFIG_GRKERNSEC_CHROOT_NICE=y
+
CONFIG_GRKERNSEC_CHROOT_SYSCTL=y
+
CONFIG_GRKERNSEC_CHROOT_CAPS=y
+
 
+
===== Triggering the Security Mechanism =====
+
 
+
When you are using a kernel compiled with the above (or similar) settings, you will get the option to enable/disable many of the options through the /proc filesystem or via sysctl.
+
 
+
The example below shows an excerpt of a typical {{ic|/etc/sysctl.d/10-grsecurity.conf}}.
+
 
+
kernel.grsecurity.chroot_deny_sysctl = 1
+
kernel.grsecurity.chroot_caps = 1
+
kernel.grsecurity.chroot_execlog = 0
+
kernel.grsecurity.chroot_restrict_nice = 1
+
kernel.grsecurity.chroot_deny_mknod = 1
+
kernel.grsecurity.chroot_deny_chmod = 1
+
kernel.grsecurity.chroot_enforce_chdir = 1
+
kernel.grsecurity.chroot_deny_pivot = 1
+
kernel.grsecurity.chroot_deny_chroot = 1
+
kernel.grsecurity.chroot_deny_fchdir = 1
+
kernel.grsecurity.chroot_deny_mount = 1
+
kernel.grsecurity.chroot_deny_unix = 1
+
kernel.grsecurity.chroot_deny_shmat = 1
+
 
+
You can enable or disable settings at will using the sysctl command:
+
 
+
(Toggling the exec_logging feature ON)
+
# sysctl -w kernel.grsecurity.exec_logging = 1
+
(Toggling the exec_logging feature OFF)
+
# sysctl -w kernel.grsecurity.exec_logging = 0
+
 
+
There is a very important sysctl setting pertaining to grsecurity, namely kernel.grsecurity.grsec_lock. When set, you are not able to change any setting anymore.
+
 
+
# sysctl -w kernel.grsecurity.grsec_lock = 1
+
 
+
=== Kernel Auditing ===
+
 
+
==== Extend your System's Logging Facilities ====
+
 
+
grsecurity adds extra functionality to the kernel pertaining the logging. With grsecurity's Kernel Auditing the kernel informs you when applications are started, devices (un)mounted, etc.
+
 
+
==== The various Kernel Audit Settings ====
+
 
+
The following kernel configuration section can be used to enable grsecurity's Kernel Audit Settings:
+
 
+
  #
+
# Kernel Auditing
+
#
+
# CONFIG_GRKERNSEC_AUDIT_GROUP is not set
+
CONFIG_GRKERNSEC_EXECLOG=y
+
CONFIG_GRKERNSEC_RESLOG=y
+
CONFIG_GRKERNSEC_CHROOT_EXECLOG=y
+
CONFIG_GRKERNSEC_AUDIT_CHDIR=y
+
CONFIG_GRKERNSEC_AUDIT_MOUNT=y
+
CONFIG_GRKERNSEC_AUDIT_IPC=y
+
CONFIG_GRKERNSEC_SIGNAL=y
+
CONFIG_GRKERNSEC_FORKFAIL=y
+
CONFIG_GRKERNSEC_TIME=y
+
CONFIG_GRKERNSEC_PROC_IPADDR=y
+
CONFIG_GRKERNSEC_AUDIT_TEXTREL=y
+
 
+
==== Process Restrictions ====
+
 
+
===== Executable Protection =====
+
 
+
With grsecurity you can restrict executables. Since most exploits work through one or more running processes this protection can save your system's health.
+
 
+
===== Network Protection =====
+
 
+
Linux' TCP/IP stack is vulnerable to prediction-based attacks. grsecurity includes randomization patches to counter these attacks. Apart from these you can also enable socket restrictions, disallowing certain groups network access altogether.
+
 
+
===== Kernel Settings =====
+
 
+
The following kernel settings enable various executable and network protections:
+
 
+
  #
+
# Executable Protections
+
#
+
CONFIG_GRKERNSEC_EXECVE=y
+
CONFIG_GRKERNSEC_DMESG=y
+
CONFIG_GRKERNSEC_RANDPID=y
+
CONFIG_GRKERNSEC_TPE=y
+
CONFIG_GRKERNSEC_TPE_ALL=y
+
CONFIG_GRKERNSEC_TPE_GID=100
+
+
#
+
# Network Protections
+
#
+
CONFIG_GRKERNSEC_RANDNET=y
+
CONFIG_GRKERNSEC_RANDISN=y
+
CONFIG_GRKERNSEC_RANDID=y
+
CONFIG_GRKERNSEC_RANDSRC=y
+
CONFIG_GRKERNSEC_RANDRPC=y
+
# CONFIG_GRKERNSEC_SOCKET is not set
+
 
+
== Using linux-pax-flags AUR Package ==
+
 
+
The linux-pax-flags program is what makes using PaX on Arch Linux easy as pie. When you run this program it will set the PaX flags for all the problematic programs for you. However, if you use some uncommon program it may have problems forcing you to set the paxctl flags yourself. You will most likely see something like {{ic|Denied RWX}} in journalctl. That means you will need to disable MPROTECT for the program {{ic|paxctl -cPEmRXS /usr/bin/bla}}
+
 
+
After you find what PaX flags need to be set post a comment on the linux-pax-flags AUR package so it can be added.
+
  
More extensive documentation of the linux-pax-flags utility is to be found on its man page.
+
"O" is one of a number of flags you might append to the Subject mode. Others include:
 +
A Protect the shared memory of this subject. No other processes but processes contained within this subject may access the shared memory of this subject.
 +
C Auto-kill all processes belonging to the attacker's IP address upon violation of security policy.
 +
K When processes belonging to this subject generate an alert, kill the process.
 +
O Allow loading of writable libraries.
 +
T Deny execution of binaries or scripts that are writable by any other subject in the policy. This flag is evaluated at policy enable time. All binaries with execute permission that are writable by another subject (ignoring special roles) will be reported and the RBAC system will not allow itself to be enabled until the changes are made.
  
== Tips and Tricks ==
+
See [http://en.wikibooks.org/wiki/Grsecurity/Appendix/Subject_Modes this link.]
  
Because you will not be able to change the PaX flags for a running program, and that the vast majority of programs which would need them are graphical, it is strongly advisable to not use a Graphical Login like GDM or KDM. Instead simply have the system drop you to a console to log in and use {{ic|startx}}. Then you will have a chance to set the PaX flags before anything starts. For the same reasons it is strongly advisable to update your system and run {{ic|linux-pax-flags}} right after boot, before running {{ic|startx}}.
+
== Troubleshooting ==
 +
=== Out-of-tree kernel module compilation failure ===
  
Grsecurity will harden /proc and /sys so your normal user will no longer be able to see the network status, because of this none of your desktop network monitors will work. Instead just install terminal based monitoring programs, such as {{Pkg|nmon}} or {{Pkg|nload}} and run them as root, or as a user in the proc-trusted group.
+
PaX and grsecurity implement some hardening features via GCC plugins. The compiler configuration / version used to build the plugins provided in the package needs to be the same when building a kernel module. For example, the compiler provided in the {{pkg|gcc-multilib}} package will not work - one should use the same compiler toolchain that was used to build the kernel. This also means {{pkg|linux-grsec}} needs to be rebuilt after even minor GCC upgrades before modules built with the new compiler can work with it. Rebuilding a kernel can be accomplished with the [[Kernels/Arch_Build_System|Arch Build System]]. See bug {{bug|43057}}.

Latest revision as of 12:01, 29 September 2016

Related articles

Grsecurity is an extensive security enhancement to the Linux kernel that defends against a wide range of security threats. The PaX project is included, hardening both userspace applications and the kernel against memory corruption-based exploits. Grsecurity includes a powerful Mandatory Access Control system with an effortless automatic learning mode and a host of other miscellaneous hardening features.

Installation

The linux-grsec package provides the grsecurity hardened kernel. In most cases, this package is a drop-in replacement for the vanilla kernel and will not cause any issues. By default, many of the user-facing features are disabled, but there is significant hardening of the kernel itself against exploitation.

Note: Upstream no longer provides a long-term support version of grsecurity, which it calls the "stable" series. The package linux-grsec is known at upstream as the "test" series.

After installing the linux-grsec package, edit your bootloader settings to load vmlinuz-linux-grsec and initramfs-linux-grsec.img.

Installing the optional paxd package causes the PaX exploit mitigations to be enabled, protecting userspace processes. It automatically applies the necessary exceptions for packages in the repositories. See PaX#PaX exceptions for more details.

Also included are checksec, pax-utils and paxtest packages providing useful tooling for working with PaX and verifying that the exploit mitigation techniques are active.

The optional gradm package provides the userspace tooling for managing RBAC policies. RBAC is disabled by default, and the sample policy is not usable without significant configuration (likely via heavy use of the learning mode).

Custom kernel

Compiling a custom kernel based on the official package with ABS is worth considering. There are several important compromises to make between performance and security, so while the official configuration is solid it is not perfect for every use case. See PaX#Performance for coverage of the PaX options with a significant performance impact. The official package prioritizes security over performance.

The /proc and /sys restrictions are unacceptable for a general purpose package due to breaking too much software, but can be worth enabling to plug potential information leaks.

Some features like the RANDSTRUCT plugin and hiding symbol addresses are only truly useful with a custom kernel, since the pre-built kernel is available for analysis by any attacker. The linux-grsec package enables CONFIG_RANDOMIZE_BASE, but a custom build can provide unique symbol offsets in addition to the randomized base, making CONFIG_GRKERNSEC_HIDESYM valuable.

linux-libre-grsecAUR and linux-zen-grsecAUR are also available.

Compatibility

Note: An incompatibility between linux-grsec and another package should not be reported as a bug in that package. It should be filed against the linux-grsec package and will either be fixed or documented as a compatibility issue here.

The following incompatibilities require building a custom kernel with fewer features enabled:

  • hibernation is not supported (conflicts with CONFIG_GRKERNSEC_KMEM, CONFIG_PAX_MEMORY_SANITIZE and CONFIG_RANDOMIZE_BASE)
  • Xen and virtualbox are not supported (conflicts with CONFIG_PAX_KERNEXEC and CONFIG_PAX_MEMORY_UDEREF)
  • The code reuse attacks protection (RAP), enabled with CONFIG_PAX_RAP, is not compatible with out-of-tree binary code, as, for example, the patched proprietary nvidia driver nvidia-grsecAUR in the AUR.

Known incompatibilities with other packages:

Out-of-tree modules may require patches for compatibility with kernel hardening features like CONFIG_PAX_SIZE_OVERFLOW:

  • the nvidia-grsecAUR package in the AUR patches the proprietary NVIDIA driver for compatibility with the CONFIG_PAX_USERCOPY and CONFIG_PAX_CONSTIFY_PLUGIN features

PaX

The PaX project provides many of the exploit mitigations offered by grsecurity. See the documentation on PaX for more information.

Configuration

The user-facing features are configurable at runtime via sysctl settings. Sane defaults are set in the /etc/sysctl.d/05-grsecurity.conf configuration file and it can be modified as desired.

Trusted path execution

Trusted path execution (TPE) is an opt-in feature restricting file execution. It can be enabled by setting the kernel.grsecurity.tpe sysctl switch to 1. TPE prevents users from executing any file writeable by a non-root user. By tightening up the rules for executing files, some exploits (such as upload + CGI exploits on a web server) and persistent backdoors will be prevented.

Using the tpe group as a whitelist or blacklist

By default, kernel.grsecurity.tpe_invert is set to 1, causing TPE to operate with a whitelist-based model. It will be applied to every user that is not a member of the tpe group. If kernel.grsecurity.tpe_invert is set to 0, the tpe group will instead function as a blacklist of users with the restriction, with users not in the group unaffected.

The whitelist model is recommended, and adding non-system users to the whitelist is usually enough. It will slightly improve the isolation of services running as non-root while not getting in anyone's way.

Compatibility

Containers or plain chroots can throw a wrench into the ease of using TPE, as each one has a local /etc/group. A group with the same id in the container will still work as a whitelist, but this will be broken if the container makes use of user namespaces (not yet supported by Arch kernels).

Partially restrict all non-root users

Setting the kernel.grsecurity.tpe_restrict_all sysctl switch to 1 will prevent non-root users from executing files writeable by a user other than themselves or root. This feature is enabled by the default /etc/sysctl.d/05-grsecurity.conf.

chroot hardening

A chroot is a common isolation mechanism for services. Grsecurity includes features for eliminating many common escape routes from chroots and can lock them down to the point where the confinement is equivalent to a container. These features can all be toggled on and off via sysctl switches. For a detailed explanantion of these features, see the configuration documentation.

The following features are enabled in /etc/sysctl.d/05-grsecurity.conf by default and are unlikely to cause any compatibility issues:

kernel.grsecurity.chroot_deny_fchdir = 1
kernel.grsecurity.chroot_deny_shmat = 1
kernel.grsecurity.chroot_deny_sysctl = 1
kernel.grsecurity.chroot_deny_unix = 1
kernel.grsecurity.chroot_enforce_chdir = 1
kernel.grsecurity.chroot_findtask = 1

The remaining features are left off by default, to remain compatible with containers:

#kernel.grsecurity.chroot_caps = 1
#kernel.grsecurity.chroot_deny_chmod = 1
#kernel.grsecurity.chroot_deny_chroot = 1
#kernel.grsecurity.chroot_deny_mknod = 1
#kernel.grsecurity.chroot_deny_mount = 1
#kernel.grsecurity.chroot_deny_pivot = 1
#kernel.grsecurity.chroot_restrict_nice = 1

Socket restrictions

There are 3 groups for restricting access to sockets. Users in the socket-deny-client group are forbidden from connecting to other hosts. Users in the socket-deny-server group are unable to listen on a port. The socket-deny-all group includes both of the restrictions.

Auditing

There are a few security-related logging features added to the kernel.

By default, only kernel.grsecurity.rwxmap_logging is enabled. It logs an error whenever an application has an mprotect or mmap system call rejected due to the PaX MPROTECT feature along with some other edge cases. In most cases, the application is intentionally doing dynamic machine code generation and just needs an exception. However, it may indicate a compiler / linker bug or a bug in application / library code and the errors will also be logged when an exploit attempt is prevented by the MPROTECT feature. See PaX for more information about exceptions.

The remaining audit features are currently disabled by default due to the high number of false positives, but can be enabled via sysctl. The kernel.grsecurity.audit_group switch can be set to 1 to limit kernel.grsecurity.audit_chdir and kernel.grsecurity.exec_logging to users in the audit group as they will generate a LOT of log messages.

Hide information from /proc

The linux-grsec package does not enable the strict /proc restrictions (CONFIG_GRKERNSEC_PROC). Instead, the hidepid=2 mount option can be set on /proc to hide processes of other users and the gid option can be used to make a group with an exception from the restrictions. The hidepid mount option is less invasive because it's local to each process namespace so it can be set per container. However, it's missing the additional miscellaneous information hiding so compiling a custom kernel may be desired.

The hidepid package can be installed to set up the necessary systemd-logind exception and enable hidepid=2. It will also work with CONFIG_GRKERNSEC_PROC in a custom kernel configured to use the correct proc group gid.

RBAC

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: This section needs an overhaul, including fixing some inaccuracies. (Discuss in Talk:Grsecurity#)

Role Based Access Control

There are two basic types of access control mechanisms used to prevent unauthorized access to files (or information in general): DAC (Discretionary Access Control) and MAC (Mandatory Access Control). By default, Linux uses a DAC mechanism: the creator of the file can define who has access to the file. A MAC system however forces everyone to follow rules set by the administrator.

The MAC implementation grsecurity supports is called Role Based Access Control. RBAC associates roles with each user. Each role defines what operations can be performed on certain objects. Given a well-written collection of roles and operations your users will be restricted to perform only those tasks that you tell them they can do. The default "deny-all" ensures you that a user cannot perform an action you have not thought of.

Working with gradm

gradm is a tool which allows you to administer and maintain a policy for your system. With it, you can enable or disable the RBAC system, reload the RBAC roles, change your role, set a password for admin mode, etc.

When you install gradm a default policy will be installed in /etc/grsec/policy.

By default, the RBAC policies are not activated. It is the sysadmin's job to determine when the system should have an RBAC policy enforced. Before activating the RBAC system you should set an admin password.

# gradm -P admin
Setting up grsecurity RBAC password
Password: (Enter a well-chosen password)
Re-enter Password: (Enter the same password for confirmation)
Password written in /etc/grsec/pw
# gradm -E

To disable the RBAC system, run gradm -D. If you are not allowed to, you first need to switch to the admin role:

# gradm -a admin
Password: (Enter your admin role password)
# gradm -D

If you want to leave the admin role, run gradm -u admin:

# gradm -u admin

Generating a policy

The RBAC system comes with a great feature called "learning mode". The learning mode can generate an anticipatory least privilege policy for your system. This allows for time and money savings by being able to rapidly deploy multiple secure servers.

To use the learning mode, activate it using gradm:

# gradm -F -L /etc/grsec/learning.log

Now use your system, do the things you would normally do. Try to avoid rsyncing, running locate or any other heavy file i/o operation as this can really slow down the processing time.

When you believe you have used your system sufficiently to obtain a good policy, let gradm process them and propose roles under /etc/grsec/learning.roles:

# gradm -D
# gradm -F -L /etc/grsec/learning.log -O /etc/grsec/learning.roles

Audit the /etc/grsec/learning.roles and save it as /etc/grsec/policy (mode 0600) when you are finished.

# mv /etc/grsec/learning.roles /etc/grsec/policy
# chmod 0600 /etc/grsec/policy

You will now be able to enable the RBAC system with your new learned policy.

# gradm -E
Tip: If you receive the error Viewing access is allowed by role <insert user> to /etc/grsec, the directory which stores RBAC policies and RBAC password information., add the following to your subject / under # Role: <insert user>:
/etc/grsec h

Example:

# Role: root
subject /  {
       /                               h
       /etc                            rx
       /etc/grsec                      h

The reasoning for this can be found here

Tweaking your policy

An interesting feature of grsecurity 2.x is Set Operation Support for the configuration file. Currently it supports unions, intersections and differences of sets (of objects in this case).

define objset1 {
/root/blah rw
/root/blah2 r
/root/blah3 x
}

define somename2 {
/root/test1 rw
/root/blah2 rw
/root/test3 h
}

Here is an example of its use, and the resulting objects that will be added to your subject:

subject /somebinary o
$objset1 & $somename2

The above would expand to:

subject /somebinary o
/root/blah2 r

This is the result of the & operator which takes both sets and returns the files that exist in both sets and the permission for those files that exist in both sets.

subject /somebinary o
$objset1 | $somename2

This example would expand to:

subject /somebinary o
/root/blah rw
/root/blah2 rw
/root/blah3 x
/root/test1 rw
/root/test3 h

This is the result of the | operator which takes both sets and returns the files that exist in either set. If a file exists in both sets, it is returned as well and the mode contains the flags that exist in either set.

subject /somebinary o
$objset1 - $somename2

This example would expand to:

subject /somebinary o
/root/blah rw
/root/blah2 h
/root/blah3 x

This is the result of the - operator which takes both sets and returns the files that exist in the set on the left but not in the match of the file in set on the right. If a file exists on the left and a match is found on the right (either the filenames are the same, or a parent directory exists in the right set), the file is returned and the mode of the second set is removed from the first set, and that file is returned.

In some obscure pseudo-language you could see this as:

if ( ($objset1 contained /tmp/blah rw) and
     ($objset2 contained /tmp/blah r) )
then
  $objset1 - $objset2 would contain /tmp/blah w

if ( ($objset1 contained /tmp/blah rw) and
     ($objset2 contained / rwx) )
then 
  $objset1 - $objset2 would contain /tmp/blah h

As for order of precedence (from highest to lowest): "-, & |".

If you do not want to bother remembering precedence, parenthesis support is also included, so you can do things like:

(($set1 - $set2) | $set3) & $set4

Tweaking /etc/grsec/policy directly

Sometimes, full learning mode doesnt work for a particular program and direct revisions to the policy file will need to be made. One might simply want to tweak the policy file to add or remove access to directories without requiring one to reinitiate learning mode or recreating a policy file. The file itself is composed of Roles and Subjects. A Role determines what user the ruleset applies to, while the Subject could be seen as what process/program the ruleset applies to.

Consider a situation where the role is "username", while the subject is /usr/lib/firefox/firefox. Within the curly braces of this role/subject rule, directories will be listed, along with flags that dictate what capacities (read, write, execute, etc) you wish to give that subject (firefox for example) under that role (username, when firefox is ran under the user "username" for example). Here is a list of flags and what they do:

  a 	This object can be opened for appending.
  c 	Allow creation of the file/directory.
  d 	Allow deletion of the file/directory.
  f 	Needed to mark the pipe used for communication with init to transfer the privilege of the 		persistent role; only valid within a persistent role. Transfer only occurs when the file is opened for writing.
  h 	This object is hidden.
  i 	This mode only applies to binaries. When the object is executed, it inherits the ACL of the     subject in which it was contained.
  l 	Lowercase L. Allow a hardlink at this path. Hardlinking requires a minimum of c and l modes, and the target link cannot have any greater permission than the source file.
  m 	Allow creation of setuid/setgid files/directories and modification of files/directories to be setuid/setgid.
  p 	Reject all ptraces to this object.
  r 	This object can be opened for reading.
  t 	This object can be ptraced, but cannot modify the running task. This is referred to as a 'read-only ptrace'.
  w 	This object can be opened for writing or appending.
  x 	This object can be executed (or mmap'd with PROT_EXEC into a task).

So for example, if you want firefox to have read access to the home folder of the user username, be able to do everything (read, write, create and destroy files, execute) in /home/username/Downloads, but not be able to see /home/username/secretstuff or anything in /, your ruleset might look like this:

  # Role: username
  subject /usr/lib/firefox/firefox o {
      /                                               h
      /home/username                       r
      /home/username/Downloads     rwxcd
      /home/username/secretstuff      h
  }

Of course, a Firefox ruleset will need more than just the above (like access to directories it needs to run in /usr for example); compare the above with what is generated by full-learning-mode and you quickly see the pattern. The idea is that you want to limit each process as much as possible to limit the changes it can make to the filesystem in the event it is compromised. Much more info is available on the GRsecurity RBAC wiki page.

Using Wine; Changes needed to /etc/grsec/policy

In the event you use wine, your executables for wine apps are on an NTFS partition, and you want it to work while RBAC is enabled, you will need to append "O" to the Subject mode of /usr/bin/wine-preloader for the Role (user) using this subject. I am unsure if this applies to executables in .wine as I do not have the free space to test it. I put my system into full-learning mode and ran wine, and after generating a /etc/grsec/policy from this session RBAC still prevented my wine program from running with:

grsec: (username:U:/usr/bin/wine-preloader) denied load of writable library /mnt/winblows/Program Files (x86)/Diablo II/Game.exe by /usr/bin/wine-preloader[Game.exe:7518] uid...

Appending "O" to the end of the Subject mode will fix this problem. An example of a working ruleset (notice the capital O after subject /usr/bin/wine-preloader):

# Role: username
subject /usr/bin/wine-preloader O {
 /					r
 <other listed files generated by full-learning mode>   rwcdx
}

"O" is one of a number of flags you might append to the Subject mode. Others include:

A 	Protect the shared memory of this subject. No other processes but processes contained within this subject may access the shared memory of this subject.
C 	Auto-kill all processes belonging to the attacker's IP address upon violation of security policy.
K 	When processes belonging to this subject generate an alert, kill the process.
O 	Allow loading of writable libraries.
T 	Deny execution of binaries or scripts that are writable by any other subject in the policy. This flag is evaluated at policy enable time. All binaries with execute permission that are writable by another subject (ignoring special roles) will be reported and the RBAC system will not allow itself to be enabled until the changes are made.

See this link.

Troubleshooting

Out-of-tree kernel module compilation failure

PaX and grsecurity implement some hardening features via GCC plugins. The compiler configuration / version used to build the plugins provided in the package needs to be the same when building a kernel module. For example, the compiler provided in the gcc-multilib package will not work - one should use the same compiler toolchain that was used to build the kernel. This also means linux-grsec needs to be rebuilt after even minor GCC upgrades before modules built with the new compiler can work with it. Rebuilding a kernel can be accomplished with the Arch Build System. See bug FS#43057.