Grsecurity/Print version
| This is the print version of Grsecurity You won't see this message or any elements not part of the book's content when you print or preview this page. |
Introduction
grsecurity is a set of patches for the Linux kernel with an emphasis on enhancing security. Its typical application is in web servers and systems that accept remote connections from untrusted locations, such as systems offering shell access to its users.
Released under the GNU General Public License, grsecurity is free software.
History
Work on grsecurity began in February 2001 as a port of Openwall Project's security-enhancing patches for Linux 2.4. The first release of grsecurity was for Linux 2.4.1.
PaX
A major component bundled with grsecurity is PaX, which is a patch that, amongst other things, flags data memory, such as that on the stack, as non-executable, and program memory as non-writable. The aim is to prevent executable memory pages from being overwritten with injected machine code, which prevents exploitation of many types of security vulnerabilities, such as buffer overflows. PaX also provides address space layout randomization (ASLR), which randomizes important memory addresses to hinder attacks that rely on such addresses being easily known. PaX is not itself developed by the grsecurity developers, and is also available independently from grsecurity [1].
Role-based Access Control
Another notable component of grsecurity is that it provides a full Role-based access control (RBAC) system. RBAC is intended to restrict access to the system further than what is normally provided by Unix access control lists, with the aim of creating a fully least-privilege system, where users and processes have the absolute minimum privileges to work correctly and nothing more. This way, if the system is compromised, the ability by the attacker to damage or gain sensitive information on the system can be drastically reduced. RBAC works through a collection of "roles". Each role can have individual restrictions on what they can or cannot do, and these roles and restrictions form a "policy" which can be amended as needed.
A list of RBAC features:
- Domain support for users and groups
- Role transition tables
- IP-based roles
- Non-root access to special roles
- Special roles that require no authentication
- Nested subjects
- Variable support in configuration
- And, or, and difference set operations on variables in configuration
- Object mode that controls the creation of setuid and setgid files
- Create and delete object modes
- Kernel interpretation of inheritance
- Real-time regular-expression resolution
- Ability to deny ptraces to specific processes
- User and group transition checking and enforcement on an inclusive or exclusive basis
- /dev/grsec special device for kernel authentication and learning logs
- Next-generation code that produces least-privilege policies for the entire system with no configuration
- Policy statistics for gradm
- Inheritance-based learning
- Learning configuration file that allows the administrator to enable inheritance-based learning or disable learning on specific paths
- Full pathnames for offending process and parent process
- RBAC status function for gradm
- /proc/<pid>/ipaddr gives the remote address of the person who started a given process
- Secure policy enforcement
- Supports read, write, append, execute, view, and read-only ptrace object permissions
- Supports hide, protect, and override subject flags
- Supports the PaX flags
- Shared memory protection feature
- Integrated local attack response on all alerts
- Subject flag that ensures a process can never execute trojaned code
- Full-featured fine-grained auditing
- Resource, socket, and capability support
- Protection against exploit bruteforcing
- /proc/pid filedescriptor/memory protection
- Rules can be placed on non-existent files/processes
- Policy regeneration on subjects and objects
- Configurable log suppression
- Configurable process accounting
- Human-readable configuration
- Not filesystem or architecture dependent
- Scales well: supports as many policies as memory can handle with the same performance hit
- No runtime memory allocation
- SMP safe
- O(1) time efficiency for most operations
- Include directive for specifying additional policies
- Enable, disable, reload capabilities
- Option to hide kernel processes
Chroot Restrictions
grsecurity restricts chroot in a variety of ways to prevent a variety of vulnerabilities, privilege escalation attacks, and to add additional checks and balances.
Chroot Modifications:
- No attaching shared memory outside of chroot
- No kill outside of chroot
- No ptrace outside of chroot (architecture independent)
- No capget outside of chroot
- No setpgid outside of chroot
- No getpgid outside of chroot
- No getsid outside of chroot
- No sending of signals by fcntl outside of chroot
- No viewing of any process outside of chroot, even if /proc is mounted
- No mounting or remounting
- No pivot_root
- No double chroot
- No fchdir out of chroot
- Enforced chdir("/") upon chroot
- No (f)chmod +s
- No mknod
- No sysctl writes
- No raising of scheduler priority
- No connecting to abstract Unix domain sockets outside of chroot
- Removal of harmful privileges via capabilities
Miscellaneous Features
grsecurity also adds enhanced auditing to the Linux kernel. It can be configured to audit a specific group of users, audit mounts/unmounts of devices, changes to the system time and date, chdir logging, amongst other things. Some of these other things allow the admin to also log denied resource attempts, failed fork attempts, and exec logging with arguments.
Trusted path execution is another optional feature that can be used to prevent users from executing binaries that are not owned by the root user, or are world-writable. This is useful to prevent users from executing their own malicious binaries or accidentally executing system binaries that could have been modified by a malicious user (being world-writable).
grsecurity also hardens the way chroot "jails" work. A chroot jail can be used to isolate a particular process from the rest of the system, which can be used to minimise the potential for damage should the service be compromised. However, there are ways to "break out" of a chroot jail. grsecurity attempts to prevent this.
There are also other features that increase security and prevent users from gaining unnecessary knowledge about the system, such as restricting the dmesg and netstat commands to the root user [2].
List of additional features and security improvements:
- /proc restrictions that don't leak information about process owners
- Symlink/hardlink restrictions to prevent /tmp races
- Hardlink restrictions to prevent users from hardlinking to files they do not own
- FIFO/Named pipe restrictions
- dmesg(8) restriction
- Enhanced implementation of Trusted Path Execution
- Group-based socket restrictions
- Nearly all options are sysctl-tunable, with a locking mechanism
- All alerts and audits support a feature that logs the IP address of the attacker with the log
- Stream connections across unix domain sockets carry the attacker's IP address with them (on 2.4 kernels only)
- Detection of local connections: copies attacker's IP address to the other task
- Automatic deterrence of exploit bruteforcing
- Pre-defined Low, Medium, High, and Custom security levels
- Tunable flood-time and burst for logging
This book uses many different terms, some of which have the same meaning. We have listed some of these terms and their definitions here. The book also contains inline links to relevant Wikipedia articles.
- policy
- The policy is a system-wide set of rules enforced by grsecurity. A very good description is offered in the mandatory access control article: "Any operation by any subject on any object will be tested against the set of authorization rules (aka policy) to determine if the operation is allowed."
- access control list
- From a related Wikipedia article: "An access control list (ACL) is a list of permissions attached to an object. The list specifies who or what is allowed to access the object and what operations are allowed to be performed on the object." In the context of this book, an ACL is used to mean a single role or subject definition, or the whole policy file.
- ruleset
- Ruleset is used much in the same way as "access control list". It is perhaps more often used to refer to role or subject definitions than the whole policy file.
- object
- An object is a part of the system that is used by the programs running on the system. It can be an absolute path to a file or a directory; a capability; a system resource; a PaX flag; network access (IP ACLs).
- subject
- A subject uses and accesses objects and the ruleset of the subject enforces what objects it may use and in what way. In practice a subject is most often a program running on the system. In grsecurity, a subject is defined as an absolute path to the actual program executable (e.g. /sbin/init) or a directory (e.g. /lib/hal/scripts).
- role
- A role is an abstraction that encompasses traditional users and groups that exist in Linux distributions and special roles, that are specific to grsecurity. Roles can be used to split the responsibility of system administration into smaller logical sets of responsibilities, such as "database administrator" or "DNS administrator". Compare this approach to having a single superuser (e.g. root) that is used to do every administrative task on the system.
- domain
- With domains you can combine users that do not belong in the same group as well as groups so that they share a single policy. Domains work just like roles.
Grsecurity/Typographic Conventions
Installation
The following instructions will lead you through the process of downloading all the components necessary for using grsecurity on your system. Download each component to the same directory on your computer.
You need:
- The latest stable version of grsecurity.
- A matching version of gradm, the administration utility for grsecurity.
- Full source code of the Linux kernel.
You also need to have necessary programs for building, configuring and installing a custom kernel for your system. The preferred way, and required tools, to do the installation depend on the Linux distribution you are using. If you encounter problems with configuring or installing the kernel, please consult your distribution’s documentation.
Downloading grsecurity
Point your browser to http://grsecurity.net/. Click on the “Download” link and then “Stable”. For the purposes of this document, we will be installing the latest stable grsecurity for kernel 3.2.21. Therefore the patch file will be called ‘’grsecurity-2.9.1-3.2.21-201206201812.patch'’.
| All grsecurity packages have a version string in their names. It contains both the version of the release itself and the kernel version it is meant for. For example, the version string 2.9.1-3.2.21-201206201812 tells us that the version of this grsecurity release is 2.9.1 and it is meant for kernel version 3.2.21. The last section of the version is a timestamp. |
In our case we downloaded the following files
- ‘’grsecurity-2.9.1-3.2.21-201206201812.patch
- ‘’grsecurity-2.9.1-3.2.21-201206201812.patch.sig'’ - This is the digital signature of this release.
Downloading gradm
When downloading gradm, the administration utility for grsecurity’s role-based access control system, you must download the version that matches the version of the grsecurity patch you downloaded. Gradm is located on the same download page as grsecurity.
In our case we downloaded the following files
- ‘’gradm-2.9.1-201206091838.tar.gz
- ‘’gradm-2.9.1-201206091838.tar.gz.sig'’ - This is the digital signature of this release.
Downloading the Linux Kernel
The grsecurity patches can only be applied to a vanilla kernel. Many distributions modify the official kernel with additional patches, which means that any kernel source packages acquired through their package manager is very likely incompatible with grsecurity.
For this reason we will download the official unmodified kernel from http://www.kernel.org/. Download the full kernel source package and its signature (the ‘’.sign'’ file), and make sure its version matches the version of the grsecurity patch you downloaded. In this document the version is 3.2.21. The required version is most likely not the latest, so you need to get it from the kernel archives.
If you’ve got a terminal open, you can use the below commands to download both the kernel source and the signature to the current working directory:
$ wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3.2.21.tar.bz2 $ wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3.2.21.tar.sign
‘’‘NOTE: The versions of the grsecurity patch and the kernel must match exactly.
Verifying the Downloads
The grsecurity and gradm packages have been cryptographically signed so that users can verify that the source code has not been modified since it was packaged. You can find the public key used to sign them from the same download page as grsecurity. Scroll down the page until you see a heading that says “Verify these downloads with GPG”. Below the heading is a link to the public key. Download the key to the directory where you placed grsecurity.
Before you can verify the downloads, you need to import the grsecurity key to your public keyring using Gnu Privacy Guard (GPG). If you are unfamiliar with GPG and wish to know more, please refer to The GNU Privacy Handbook.
To import the key, run the following command in the directory where your grsecurity and its key were downloaded.
$ gpg --import spender-gpg-key.asc gpg: key 4245D46A: public key “Bradley Spengler (spender) <spender@grsecurity.net>” imported gpg: Total number processed: 1 gpg: imported: 1
After importing the key, verify the downloaded grsecurity and gradm packages by running the below commands in your grsecurity directory:
$ gpg --verify grsecurity-2.9.1-3.2.21-201206201812.patch.sig gpg: Signature made Wed 20 Jun 2012 03:14:19 PM PDT using DSA key ID 4245D46A gpg: Good signature from “Bradley Spengler (spender) <spender@grsecurity.net>" gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 9F74 393D 7E7F FF3C 6500 E778 9879 B649 4245 D46A $ gpg --verify gradm-2.9.1-201206091838.tar.gz.sig gpg: Signature made Sat 09 Jun 2012 03:39:23 PM PDT using DSA key ID 4245D46A gpg: Good signature from “Bradley Spengler (spender) <spender@grsecurity.net>" gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 9F74 393D 7E7F FF3C 6500 E778 9879 B649 4245 D46A
As long as GPG reports the signature is good, you do not need to worry about the warning. If you signed the grsecurity key with your own key, you will not get the warning. If the verification of either file failed, re-download the file in question and try again.
The Linux kernel source packages have been signed as well. The latest public key used to sign all kernel packages and revocation certificates can be found at http://www.kernel.org/signature.html. You can import the public key directly from a key server (the servers use port 11371):
$ gpg --recv-keys 6092693E gpg: requesting key 6092693E from hkp server keys.gnupg.net gpg: key 6092693E: public key “Greg Kroah-Hartman (Linux kernel stable release signing key) <greg@kroah.com>” imported gpg: no ultimately trusted keys found gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1)
‘’‘NOTE:’ Before you download the key, visit http://www.kernel.org/signature.html and make sure the key ID (in this example “6092693E”) is the latest valid key.
There are many public key servers to choose from for key verification (eg ‘’--keyserver wwwkeys.pgp.net’‘ can be placed in between the ‘’gpg’‘ and ‘’--recv-keys’‘ terminals without quotes) if the key ID does not have a default one set by the signer. Some of them are listed on Wikipedia.
Before you verify the Linux kernel you will have to untar it because kernel.org now signs their kernels against the .tar file to reduce the amount of .sig files they need to maintain, run:
# bzip2 -d linux-3.2.21.tar.bz2
Now to verify the kernel package, run:
$ gpg --verify linux-3.2.21.tar.sign gpg: Signature made Tue 19 Jun 2012 05:40:25 PM PDT using RSA key ID 6092693E gpg: Good signature from “Greg Kroah-Hartman (Linux kernel stable release signing key) <greg@kroah.com>" gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 647F 2865 4894 E3BD 4571 99BE 38DB BDC8 6092 693E
If GPG reports that the signature is good, you are good to go. If the verification failed, re-download the kernel source and its signature, and try again. Although not shown in this example, you will get the same warning from GPG as with the other packages, unless you signed the kernel archive key with your own key.
When you have successfully verified the downloaded files, you are ready to configure grsecurity.
The following instructions will lead you through the process of patching the Linux kernel with grsecurity, configuring its features and compiling, and installing the patched kernel.
Patching Your Kernel with grsecurity
In this document the compressed kernel source package is called ‘’linux-3.2.21.tar‘’ and the matching grsecurity patch ‘’grsecurity-2.9.1-3.2.21-201206201812.patch'’. Both files are in the same directory.
Change to the root user and run the following commands in the directory you downloaded the files to. The first command decompresses the Linux source package, and the second one applies the patch to the kernel.
# tar -xf linux-3.2.21.tar # cd linux-3.2.21 # patch -p1 < ../grsecurity-2.9.1-3.2.21-201206201812.patch
Configuring the Kernel
The kernel source package contains a generic configuration file that should work without any significant modifications. Your distribution may have its own process and tools for configuring and building the kernel, in which case you should consult their documentation. Nonetheless you should go through the options and make sure they match your hardware and current setup.
To configure the kernel using the default configuration as a base, change into the kernel source directory (e.g. ‘’/usr/src/linux-3.2.21‘’), and execute the below command.
$ make menuconfig
In the 2.6 kernels, the grsecurity options are under Security options » Grsecurity. In the 2.4 kernels there is a top-level menu item called Grsecurity. Use the built-in help of the kernel configuration system, and make sure you understand each option before you enable or disable them.
There are three basic security levels—low, medium and high—and a custom level for advanced users. You should choose one of the basic the security levels that best suits your situation. See the Appendix for a list of all grsecurity and PaX kernel configuration options and their descriptions. You can use it to plan ahead what features to enable.
Suggestions
- Enable the sysctl interface (Grsecurity » Sysctl support). It will enable you to change the options that grsecurity runs with without recompiling the kernel. This is a very helpful feature especially when you are using grsecurity for the first time.
- Some auditing options produce a lot of log messages, most notably exec and chdir logging (GRKERNSEC_EXECLOG and GRKERNSEC_AUDIT_CHDIR, respectively). If you enable either of them, make sure your logging system is properly configured to prevent the logs from flooding.
Compiling and Installing the Kernel
On Debian and Ubuntu
To compile the kernel and build a Debian package (deb), execute the below commands in the kernel source directory. Ubuntu users should reference the Ubuntu Community Page and decide whether they wish to use the ubuntu-package overlay directory in building. For building on Maverick from a git checkout, see How to compile a Ubuntu 10.10 kernel
# fakeroot make deb-pkg
To install the newly created Debian package, run:
# cd .. # dpkg -i *.deb
For more information about building kernels in Debian, please refer to the Debian Linux Kernel Handbook.
Other Distributions
- Gentoo Linux: Gentoo Linux (x86) Handbook and Hardened Gentoo
- CentOS: http://wiki.centos.org/HowTos/Custom_Kernel
- Fedora (release 8 and later): http://fedoraproject.org/wiki/Docs/CustomKernel
Compilation Differences
As you are compiling a kernel patched with grsecurity, you will notice some differences. One of these differences appears towards the end of compilation, and may look similar to:
WARNING: modpost: Found 2820 section mismatch(es). To see full details build your kernel with: ‘make CONFIG_DEBUG_SECTION_MISMATCH=y'
This warning is harmless. As described by the PaX Team on the grsecurity mailing list:
the extra section mismatches are due to my changes, i explicitly added detection for writeable function pointers which are potential exploit targets, just to know how many of them there are. we’ve been eliminating some of them already but this work will never finish. as for what they are in general, a mismatch means an unwanted reference from one section to another. say, accessing init code or data from normal code/data is not good since init sections are freed up on boot, so any reference to them must not exist from permanent sections.
You will also notice additional warnings emitted by the compiler when compiling a kernel patched with grsecurity. This is due to additional warning flags that have been added to the build process to help spot specific kinds of bugs. You can ignore these additional warnings.
Administration
Gradm, the administration utility for the role-based access control system, is a powerful tool that parses your ACLs (Access Control Lists), performs the enforcement of a secure base policy, optimizes the ACLs, as well as handles parsing of the learning logs, merges them with your ACL set and outputs the final ACLs.
Before you install gradm, boot into your patched grsecurity kernel. You can compile gradm in any kernel you wish, but the installation will fail if the kernel does not support grsecurity.
Installation
If your Linux distribution provides ready-made grsecurity kernel packages, they will very likely provide a package for gradm too. If that is the case you should consider using it before compiling gradm yourself.
Before compiling and installing gradm, make sure you have the following applications installed in your system: lex or flex and byacc or bison. If you need Pluggable Authentication Modules (PAM) support, install the header files for your system; The package containing them will very likely be called libpam-dev or similar.
Change to the directory you downloaded gradm and grsecurity to earlier. In this document the name of the compressed package is gradm-2.2.2-201108142019.tar.gz. Decompress the package and change to the gradm2 directory by executing the following commands:
$ tar xzf gradm-2.2.2-201108142019.tar.gz $ cd gradm2
To install gradm with PAM support, run:
$ make # make install
To install gradm without PAM support, run:
$ make nopam # make install
A note should be added to say that if you are compiling gradm on your default linux kernel without grsecurity support the compile will fail and that you will only be able to compile after you reboot into your new grsecurity enabled kernel.
The installation process does the following:
- Installs the gradm and grlearn programs to /sbin.
- Creates a directory /etc/grsec and two files in it (if they are not already present): learn_config and policy.
- Installs gradm's man pages to /usr/share/man8.
- (grlearn does not come with a man page. It is used internally by gradm.)
- Finally, and most importantly, you will be asked to provide the administrative password for the RBAC system. Choose a long password, but one that you will remember (especially if you start gradm from an initscript). Do not use the same password as your root password.
If you need to change any of the binary or man page locations, modify the Makefile.
Usage
To display all available command-line switches, run gradm --help.
# gradm --help
gradm 2.2.2
grsecurity administration program
Usage: gradm [option] ...
Examples:
gradm -P
gradm -F -L /etc/grsec/learning.logs -O /etc/grsec/policy
Options:
-E, --enable Enable the grsecurity RBAC system
-D, --disable Disable the grsecurity RBAC system
-C, --check Check RBAC policy for errors
-S, --status Check status of RBAC system
-F, --fulllearn Enable full system learning
-P [rolename], --passwd
Create password for RBAC administration
or a special role
-R, --reload Reload the RBAC system while in admin mode
-L <filename>, --learn
Specify the pathname for learning logs
-O <filename>, --output
Specify where to place policies generated from learning mode
-M <filename|uid>, --modsegv
Remove a ban on a specific file or UID
-a <rolename> , --auth
Authenticates to a special role that requires auth
-u, --unauth Remove yourself from your current special role
-n <rolename> , --noauth
Transitions to a special role that doesn't require authentication
-p <rolename> , --pamauth
Authenticates to a special role through PAM
-V, --verbose Display verbose policy statistics when enabling system
-h, --help Display this help
-v, --version Display version information
Learning Mode
The learning mode is different than anything found in other security systems. Grsecurity's learning mode can be used on a per-subject or per-role basis, as well as system-wide. When using the learning mode on a single process or role, the rest of the system remains protected as defined by the policy. The learning mode can learn all things that the RBAC system supports: files, capabilities, resources, what IP addresses make use of each role, and socket usage. The learning system performs intelligent reduction of filesystem and network access to reduce policy size, increase readability, and reduce the amount of manual tweaking needed later. Furthermore, the learning system enforces a secure base that is configurable. The /etc/grsec/learn_config file gives the administrator the ability to specify files/directories that should be considered protected resources by the learning system. The learning system will ensure that regardless of any rule reduction done, only the processes that access those protected resources through normal usage will be granted access through the generated policy. Furthermore, it will create new subjects for the processes that access the protected resources, creating privilege boundaries that grant those processes additional protection.
Full System Learning
To enable full system learning, run gradm as root with the following options:
# gradm -F -L /etc/grsec/learning.logs
This will enable the Role-based Access Control (RBAC) system and initiate full system learning. That is, gradm will monitor and log what your system does. The log can then be used to build a least privilege policy for your system.
Run and use the application(s) that you normally do, several times. This is important, since the learning mode uses a threshold–based system to determine when access should be given to a file or whether it should be given to a directory. If four or more similar accesses are made in a single directory (such as writing to several files in /tmp), access is granted to that directory instead of the individual files. This reduces the amount of rules you have and ensures that the application will work correctly after the final ACLs are compiled.
| Do not perform any administrative tasks outside of the admin role while full system learning is enabled. |
To perform administrative tasks while full system learning is enabled, authenticate to the admin role with:
# gradm -a admin
Remember to exit your shell or unauthenticate from the admin role with gradm -u when you are done performing administrative tasks.
Once you feel you've given the system the normal usage it would see in real life, disable the RBAC system with gradm -D, and execute:
# gradm -F -L /etc/grsec/learning.logs -O /etc/grsec/policy
This will place the new learned ACLs at the end of your ruleset. You can test the policy by enabling grsecurity (run gradm -E), and making sure all applications are functioning the way they're supposed to.
Process and Role-Based Learning
Using this learning mode is very simple. All you have to do is add "l" (the small letter L, not the number 1) to the subject mode of the process, you want to enable learning for. To learn on a given role, add "l" to the role mode. For both of these, to enable learning, enable the system by executing:
# gradm -L /etc/grsec/learning.logs -E
When you are done, disable the ACL system with gradm -D (or alternatively, go into admin mode with gradm -a), and use:
# gradm -L /etc/grsec/learning.logs -O /etc/grsec/policy
This will place the new learned ACLs at the end of your ruleset. Simply remove the old ACLs and you are ready to go.
/etc/grsec/learn_config
This configuration file aids the learning process by tweaking the learning algorithm for specific files and directories. It accepts lines in the form of:
<command> <pathname>
Where <command> can be inherit-learn, no-learn, inherit-no-learn, high-reduce-path, dont-reduce-path, protected-path, high-protected-path, and always-reduce-path. inherit-learn, no-learn, and inherit-no-learn only affect full system learning, while the others work on all modes of learning.
inherit-learn changes the learning process for the specified path by throwing all learned accesses for every binary executed by the processes contained in the pathname into the subject specified by the pathname. This is useful for cron in the case of full system learning, so that scripts that eventually end up executing mv or rm with privilege don't cause the root policy to grant that privilege to mv or rm in all cases.
no-learn allows processes within the path to perform any operation that normal system usage would allow without restriction. If a process is generating a huge number of learning logs, it may be best to use this command on that process and configure its policy manually.
inherit-no-learn combines the above two cases, such that processes within the specified path will be able to perform any normal system operation without restriction as will any binaries executed by these processes.
high-reduce-path modifies the heuristics of the learning process to weigh in favor of reducing accesses for this path.
dont-reduce-path modifies the heuristics of the learning process so that it will never reduce accesses for this path.
always-reduce-path modifies the heuristics of the learning process so that the path specified will always have all files and directories within it reduced to the path specified.
protected-path specifies a path on your system that is considered an important resource. Any process that modifies one of these paths is given its own subject in the learning process, facilitating a secure policy.
high-protected-path specifies a path that should be hidden from all processes but those that access it directly. It is recommended to use highly sensitive files for this command.
Note that regular expressions are not supported for pathnames in this configuration file.
This page will introduce you to some additional utilities. They are not required to use a grsecurity-enabled system, but are very useful and thus recommended.
Controlling PaX Flags (paxctl)
Paxctl is a user-space utility for controlling PaX flags of executables (see Appendix/PaX Flags for a list of these flags).
Installation
Download the latest version from the PaX website at http://pax.grsecurity.net/. In our case we downloaded paxctl-0.5.tar.gz. Paxctl packages are not signed. Change into the directory you downloaded the package to and run the below commands.
$ tar xzf paxctl-0.5.tar.gz $ cd paxctl-0.5 $ make $ su # make install
The installation process does the following:
- Installs the paxctl program to /sbin.
- Installs paxctl's man pages to /usr/share/man1.
If you need to change either of these locations, modify the Makefile.
Usage
To display all available command-line switches, run paxctl --help. Read the man page for more detailed information.
$ paxctl --help
PaX control v0.5
Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu>
usage: paxctl <options> <files>
options:
-p: disable PAGEEXEC -P: enable PAGEEXEC
-e: disable EMUTRMAP -E: enable EMUTRMAP
-m: disable MPROTECT -M: enable MPROTECT
-r: disable RANDMMAP -R: enable RANDMMAP
-x: disable RANDEXEC -X: enable RANDEXEC
-s: disable SEGMEXEC -S: enable SEGMEXEC
-v: view flags -z: restore default flags
-q: suppress error messages -Q: report flags in short format
-c: convert PT_GNU_STACK into PT_PAX_FLAGS (see manpage!)
-C: create PT_PAX_FLAGS (see manpage!)
Examples
Lets query what, if any, PaX flags have been enabled for /usr/bin/vi:
# paxctl -v /usr/bin/vi PaX control v0.5 Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu> file /usr/bin/vi does not have a PT_PAX_FLAGS program header, try conversion
As you can see, paxctl could not display the flags because vi does not have the appropriate program header. We need to convert the header and query the flags again.
| Note that paxctl does not make backup copies of the files it modifies. It is recommended that you make backups of the binaries you want to modify. |
# paxctl -c /usr/bin/vi
file /usr/bin/vi had a PT_GNU_STACK program header, converted
# paxctl -v /usr/bin/vi
PaX control v0.5
Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu>
- PaX flags: -------x-e-- [/usr/bin/vi]
RANDEXEC is disabled
EMUTRAMP is disabled
With the appropriate program header in place, we can query and modify the PaX flags of vi.
Displaying Program Capabilities (pspax)
The pspax program displays the run-time capabilities of all programs you have permission for. It is part of the pax-utils package. Pax-utils can be found at http://dev.gentoo.org/~vapier/dist/. It contains many useful tools for PaX but is not as critical as paxctl. The pax-utils package is maintained by the Hardened Gentoo Project.
Programs that the pax-utils package provides:
- pspax - Displays the run-time capabilities of all programs you have permission for.
- scanelf - Prints out information specific to the ELF structure of a binary.
- dumpelf - Converts a ELF file into human readable C code that defines a structure with the same image as the original ELF file.
For more information, see the Gentoo Linux guide to pax-utils at http://dev.gentoo.org/~solar/pax-utils/.
Installation
Gentoo Linux and Debian GNU/Linux users (and possibly others) can install the pax-utils package the same way they install any other application in their system. Below are instructions on how to compile and install it from the source.
Download the latest version from http://dev.gentoo.org/~vapier/dist/. In our case we downloaded pax-utils-0.2.tar.bz2. Change into the directory you downloaded the package to and run the below commands.
$ tar xjf pax-utils-0.2.tar.bz2 $ cd pax-utils-0.2 $ make $ su # make install
The installation process does the following:
- Installs the pspax, scanelf, dumpelf and scanmacho programs to /usr/bin.
- Installs man pages of pspax, scanelf and dumpelf to /usr/share/man1.
If you need to change either of these locations, modify the Makefile.
Usage
To display all available command-line switches, run pspax --help. Read the man page for more detailed information.
$ pspax --help * List ELF/PaX information about running processes Usage: pspax [options] Options: -a, --all * Show all processes -e, --header * Print GNU_STACK/PT_LOAD markings -p, --pid * Process ID/pid # -u, --user * Process user/uid # -g, --group * Process group/gid # -n, --nx * Only display w^x processes -w, --wx * Only display w|x processes -v, --verbose * Be verbose about executable mappings -B, --nobanner * Don't display the header -h, --help * Print this help and exit -V, --version * Print version and exit
Pspax shows the PaX flags of a single program as a string of characters (e.g. "peMRS"). Lowercase character means the flag is disabled, uppercase means it is enabled. Below is a table that shows these characters and their corresponding PaX flags used by grsecurity. The "Details" column contains a link to a detailed explanation of each flag.
| pspax flag | grsecurity's PaX flag | Details |
|---|---|---|
| S | PAX_SEGMEXEC | segmexec.txt |
| P | PAX_PAGEEXEC | pageexec.txt |
| M | PAX_MPROTECT | mprotect.txt |
| R | PAX_RANDMMAP | randmmap.txt |
| E | PAX_EMUTRAMP | emutramp.txt |
Examples
The command pspax -p <process_id> displays information about a specific process, identified by its PID. It is unlikely that you happen to know or remember the PID of a process, so it is easier to refer to them by name. The below example uses the pidof command to find the PID of a process which it then passes on to pspax:
# pidof inetd | xargs pspax -p USER PID PAX MAPS ETYPE NAME CAPS_ATTR root 1741 peMRS w^x ET_EXEC inetd =ep cap_setpcap-ep
Managing the Executable Stack of Binaries (execstack)
Execstack is a tool to set, clear or query executable stack flag of ELF binaries and shared libraries. It is part of the prelink program.
Installation
You are very likely to find the prelink program using your distribution's package management system. At least Gentoo, Debian, Red Hat and distributions based on them provide a prelink package.
Usage
To display all available command-line switches, run execstack --help. Read the man page for more detailed information. Online version of the man page can be found at http://linux.die.net/man/8/execstack.
# execstack --help
Usage: execstack [OPTION...]
execstack -- program to query or set executable stack flag
-c, --clear-execstack Clear executable stack flag bit
-q, --query Query executable stack flag bit
-s, --set-execstack Set executable stack flag bit
-?, --help Give this help list
--usage Give a short usage message
-V, --version Print program version
Report bugs to <jakub@redhat.com>.
Examples
To check if a library has executable stack enabled, run:
# execstack -q /usr/lib/libcrypto.so.0.9.8 - /usr/lib/libcrypto.so.0.9.8
The dash means libcrypto does not require an executable stack. If it did, the line would start with a capital "X" instead of a dash.
To query the status of all libraries in your system, run:
# find /lib /usr/lib -name '*.so.*.*.*' | xargs execstack
The sysctl Interface
The sysctl command provides an interface for modifying kernel parameters at runtime. There is an option in the grsecurity kernel configuration to enable support for this interface (see Configuring grsecurity). In Linux, sysctl is simply a wrapper around filesystem routines that read and write contents of files in the /proc directory. This means that you can also set parameters by echoing values to files in /proc. See the Appendix for a list of all available sysctl options for grsecurity.
Usage
The sysctl command takes a list of variables or variable=value pairs and sets or reads their value. Variable is a path to a file in /proc/sys separated by periods or forward slashes. The value depends on the parameter in question. Most of grsecurity's options are either 1 (enabled) or 0 (disabled).
Sysctl's man page is available online at http://linux.die.net/man/8/sysctl.
Examples
If you want to know every available runtime option for grsecurity, list the contents of /proc/sys/kernel/grsecurity.
To enable mount auditing and disable chdir auditing in a single sysctl command, run:
# sysctl kernel.grsecurity.audit_mount=1 kernel.grsecurity.audit_chdir=0 kernel.grsecurity.audit_mount = 1 kernel.grsecurity.audit_chdir = 0
You can achieve the same result by echoing:
# echo 1 > /proc/sys/kernel/grsecurity/audit_mount # echo 0 > /proc/sys/kernel/grsecurity/audit_chdir
Grsecurity/Auditing
Policy Configuration
What Is an RBAC System?
A role-based access control (RBAC) system is an approach to restricting system access to authorized users. You need an RBAC system if you want to restrict access to files, capabilities, resources, or sockets to all users, including root. This is similar to a Mandatory Access Control (MAC) model. The other features of grsecurity are only effective at fending of attackers trying to gain root, so the RBAC system is used to fill in this gap. Least privilege can be granted to processes, which, in turn, forces attackers to reevaluate their methods of attack, since gaining access to the root account no longer means that they have full access to the system. Access can be explicitly granted to processes that need it, in such a way that root acts as any other user. Though grsecurity and its RBAC system are in no means perfect security, they greatly increase the difficulty of successfully compromising the system.
In grsecurity, the RBAC system is managed through a policy file which is essentially a system-wide set of rules. When the RBAC system is activated with gradm, the policy file is parsed and checked for security holes, such as granting the default role access to certain sensitive devices and files like the policy file itself. If a security hole is found, gradm will refuse to enable the RBAC system, and will give the user a list of things that need to be fixed. The policy file is protected when the RBAC system is active, and only the admin role may access it during that time. To make it easier to create a secure policy, gradm has the ability to learn how the system functions, and build a least-privilege policy based on the collected data (see Learning Mode).
Limitations of Any Access Control System
So as not to contribute further to the false sense of security many have regarding access control systems (whether they be grsecurity's RBAC, SELinux, RSBAC, SMACK, TOMOYO, AppArmor, etc.) it's important first to describe the limitations of any access control system.
There is a fundamental architectural limitation to the kind of guarantees an access control system can provide when the policy decision-making code resides alongside the Operating System's kernel. A compromise of the Operating System can easily result in compromise of the access control system, and it is common practice for exploits which compromise the kernel to disable any active security systems.
Grsecurity is in no ways immune to this fundamental limitation, though it does contain several features to help prevent exploitation of the kernel in the first place and furthermore to make the kernel a more hostile environment to an attacker if they do manage to exploit certain types of bugs. The project will continue to make adding similar protections one of its main goals.
Specifically, the following features are involved in kernel self-protection and increasing the difficulty of kernel exploitation:
GRKERNSEC_MODHARDEN GRKERNSEC_HIDESYM PAX_MEMORY_SANITIZE PAX_UDEREF PAX_KERNEXEC PAX_RANDKSTACK PAX_USERCOPY PAX_REFCOUNT
There also exist some features of grsecurity which are always active (and thus have no configure-time option) which aid in the above goals. These include the read-only and non-executable vsyscall page (and its shadow page) on amd64, prevention of integer wraparound vulnerabilities from addition/multiplication done in allocator arguments, const-ifying hundreds of function table pointers, etc.
Though these features have been successful at preventing previous vulnerabilities from being exploited (and surely will continue to do so) there have still been many vulnerabilities it did nothing to prevent exploitation of, and there are entire classes of vulnerabilities (such as missing capability checks, some race conditions, etc.) that it can likely never do anything to prevent exploitation of.
It's partially due to this fundamental limitation of any access control system that grsecurity's RBAC system was designed as it was: to be as automated as possible, to provide a sufficient level of access control, to have easily editable human-readable configurations, and to enforce secure base policies to eliminate some administrator error.
Neither grsecurity's RBAC system nor any other access control system should be used to separate classified information from unclassified information on the same machine. There is no virtual replacement for a physical air-gap.
Policy Structure
The policy is made up of roles, subjects and objects. Role is an abstraction that encompasses traditional users and groups that exist in Linux distributions and special roles, that are specific to grsecurity. Subjects are processes or directories, and objects are files, capabilities, resources, PaX flags, and IP ACLs. The location of the main policy file is /etc/grsec/policy.
Policy Structure in a Nutshell
To see a small example policy, look at the default /etc/grsec/policy file that is installed with gradm. In a nutshell, RBAC policies have the following structure:
role <role1> <rolemode>
<role attributes>
subject / <subject mode>
<subject attributes>
/ <object mode>
<extra objects>
<capability rules>
<IP ACLs>
<resource restrictions>
subject <extra subject> <subject mode>
<subject attributes>
/ <object mode>
<extra objects>
...
role <role2> <rolemode>
...
Using the default policy as an example:
role admin sA
subject / rvka
/ rwcdmlxi
role default G
role_transitions admin
subject /
/ r
/opt rx
/home rwxcd
/mnt rw
/dev
/dev/grsec h
...
Policy Structure in Detail
Below is the complete formal definition of the policy, presented in a custom variant of Extended Backus–Naur Form (EBNF). You do not need to understand it to use grsecurity; It is likely to be more useful when you want to generate a syntactically correct policy with a script or program.
EBNF is used to describe the grammar of a language, such as those of different programming languages. Each EBNF definition is made up of production rules, which often reference other production rules. Production rules are made up of a symbol and its definition, and are terminated with a semicolon.
- Literal strings are enclosed in single quotes (e.g. 'role_allow_ip').
- Single space or line break is used to concatenate symbols and literal strings. Literal whitespace and line break are explicitly expressed—using their symbols—in every definition where they are allowed or required.
- Exceptional cases may be expressed with a hyphen (-).
Example: Vowel = Alphabets - Consonant ;. - Parentheses may be used to group symbols and literal strings.
Example: Subject-Path = ('/' Character* [':/' Character*])+ ; - Alternatives are expressed by separating options with a vertical bar (|).
Example: Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; - Curly braces are not used to signify repetition. Use quantifiers and square brackets instead.
- Square brackets ([]) are used to express an optional element. That is, the element or a group of elements may appear once or not at all.
- The following quantifiers may be used:
- * Means that the preceding symbol or symbols may appear zero or more times.
- + Means that the preceding symbol or symbols may appear one or more times.
Example:
Subject-Path = ('/' Character* [':/' Character*])+ ;
In this example, "Subject-Path" is a symbol and its definition is "('/' Character* [':/' Character*])+ ;". Let's break down the definition from inside out:
- '/' is a literal forward slash.
- Character* is a reference to another symbol named Character. The quantifier (*) means this symbol may appear zero or more times.
- After the first set of Characters there is an optional string ':/' followed by zero or more Characters.
- The literal forward slash and the Character symbol are inside parentheses and thus form a group. The group has got a quantifier (+), which means the whole group may appear once or more.
A Subject-Path thus defines the rules for an absolute path and an absolute nested path (i.e. /bin/prog:/sbin/prog2).
Below are a few examples of syntactically correct Subject-Paths:
- /
- /:/
- /usr
- /usr/sbin/lighttpd:/usr/bin/python2.5
- /usr/bin
Complete Formal Definition
Policy = (Role-Definition line-break+)+ Role-Definition = 'role' whitespace Name whitespace Role-Mode+ line-break+ ('role_allow_ip' whitespace Ip-Address ['/' Cidr-Netmask] line-break)* ('role_transitions' (whitespace Name)+ line-break)* (Subject-Definition line-break+)+ ; Domain-Definition = 'domain' whitespace Name whitespace ('u' (whitespace User)+ | 'g' (whitespace Group)+) ['G'] ['T'] line-break+ ('role_allow_ip' whitespace Ip-Address ['/' Cidr-Netmask] line-break)* ('role_transitions' (whitespace Name)+ line-break)* (Subject-Definition line-break+)+ ; Subject-Definition = 'subject' whitespace Subject-Path whitespace Subject-Mode* whitespace ['{'] line-break+ (User-Transition line-break+)* (Group-Transition line-break+)* (Ip-Override line-break+)* (File-Definition line-break+)+ (Capability-Definition line-break+)* (Resource-Definition line-break+)* (Pax-Flag-Definition line-break+)* (Ip-Acl-Definition line-break+)* ['}'] ; User-Transition = ('user_transition_allow' | 'user_transition_deny') (whitespace User)+ ; Group-Transition = ('group_transition_allow' | 'group_transition_deny') (whitespace Group)+ ; Ip-Override = 'ip_override' whitespace Ip-Address File-Definition = ('/' (['*' | '?'] Character*)*)+ whitespace Object-Mode* ; Capability-Definition = ('+' | '-') Capability-Name ; Resource-Definition = Resource-Name whitespace Limit whitespace Limit ; Pax-Flag-Definition = ('+' | '-') Pax-Flag ; Ip-Acl-Definition = ('connect' | 'bind') whitespace 'disabled' | ('connect' | 'bind') whitespace ['{'] Ip-Address ['/' Cidr-Netmask] ':' [Port | Port '-' Port] whitespace Socket-Type whitespace Protocol ['}'] ; Replace-Rule = 'replace' whitespace Character* whitespace Character* line-break+ ; Variable = '$(' Character+ ')' ; Name = ? A string of 1-64 characters within the range a-zA-Z0-9-._ ? ; Subject-Path = ('/' Character* [':/' Character*])+ | (Subject-Path* Character* Variable+ Character* Subject-Path*)+ ; User = ? A valid username that exists in the system. ? ; Group = ? A valid group name that exists in the system. ? ; Ip-Address = ? A valid IPv4 address, including 0.0.0.0 (meaning any address). ? ; Cidr-Netmask = ? A numeric value within the range 0-32. See CIDR notation. ? ; Port = ? A valid port number (i.e. 1-65535). ? ; Socket-Type = 'sock' | 'dgram' | 'raw_sock' | 'any_sock' ; Protocol = 'raw_proto' | 'any_proto' | ? Any protocol name listed in /etc/protocols. ? ; Limit = ? A numeric value optionally followed by a unit. See Resource Restrictions for details. ? ; Character = ? All accepted characters. ? ; whitespace = ? Whitespace characters (excluding line breaks). ? ; line-break = ? Line break characters. ? ;
Rules for Policies
Policy generalization
There exist some features of the RBAC system to aid in simplification and generalization of policies. One of these is the recently added "replace" rule. The replace rule allows you to assign a string to a variable, and then use that variable within any subject or object pathname to have it replaced with the string. The syntax of replace rules are:
replace <variable name> <replace string>
So for example:
replace CVSROOT /home/cvs
The defined variable can then be used as follows:
replace CVSROOT /home/cvs
replace PUBHTML public_html
subject $(CVSROOT)/bin/test o
$(CVSROOT)/grsecurity r
/home/spender/$(PUBHTML) r
...
The variables defined with replace rules can be reassigned at any location in the policy. All rules in the policy until another redefinition of the variable will use that new assigned value for the variable. For example:
replace CVSROOT /home/cvs $(CVSROOT)/grsecurity r replace CVSROOT /var/cvs $(CVSROOT)/test r
would cause the following object rules to be created:
/home/cvs/grsecurity r /var/cvs/test r
Special Cases
There are some special cases you should know about when writing policies for the RBAC system.
There exist some unique accesses to filesystem objects that require specific object modes. For instance, a process that connects to a unix domain socket (/dev/log for example) will need "rw" set as the object mode for that socket.
Adding the setgid or setuid flag to a path requires the "m" object mode.
Creating a hard-link requires at minimum a "cl" object mode. The remaining object flags must match on the target and the source. So for instance, if a process is creating a hard-link from /bin/bash to /bin/bash2, example rules would be:
/bin/bash rx /bin/bash2 rxcl
Creating a symlink requires the "wc" object mode.
Wildcarded Objects
One very useful feature of the RBAC system is the support of wildcards in objects. The "*" character matches zero or more characters, "?" matches exactly one character, and "[]" can be used to specify an inclusive or exclusive list or range of characters to match. Depending on how these wildcard characters are used, they have different effects. Here are four examples of the use of wildcards:
/dev/tty* rw /home/*/bin rwx /dev/tty[0-9] rw /dev/tty? rw
The first example would match /dev/ttya, /dev/tty0, /dev/ttyS0, etc. Since a '*' at the end of a path can match the '/' character as well, if a '/dev/tty/somefile' path existed, the first example would match it also.
The second example would match /home/user1/bin, /home/user2/bin, etc. Note that this rule would not match the path /home/user1/test/bin as the wildcard characters will not match '/' unless it appears at the end of a path. To use the particular wildcarded object for this example, a /home object must exist as an "anchor" for the wildcarded object. If you forget to add one, gradm will remind you.
The third example would match /dev/tty0, /dev/tty1, ... , /dev/tty9 and nothing else.
The fourth example would match /dev/ttya and /dev/tty0 just like the first example, but would not match /dev/ttyS0 since only one character can match the '?' wildcard.
Wildcards are evaluated at run-time, providing a powerful way of specifying and simplifying policy. Since wildcard matching is based off pathnames and not inode/device pairs though, they aren't intended to be used for objects which are known to be hardlinked at policy enable time.
Roles
Roles exist essentially as a container for a set of subjects, put to use in specific scenarios. There exist user roles, group roles, a default role, and special roles. See Flow of Matches to see how a role gets matched with a particular process.
User Roles
In a simplified form, user roles are roles that are automatically applied when a process either is executed by a user of a particular UID or the process changes to that particular UID. In the RBAC system, the name of a user role must match up with the name of an actual user on the system.
A user role looks like:
role user1 u
Group Roles
As with user roles, group roles pertain to a particular GID. The name of the group role must match up with the name of an actual group on the system. Note that this is tied only to the GID of a process, not to any supplemental groups a process may have. Group roles are applied for a given process only if a user role does not match the process' UID.
A group role looks like:
role group1 g
Default Role
If neither a user or group role match a given process, then it is assigned the default role. The default role should ideally be a role with nearly no access to the system. It is configured in such a way if full system learning is used.
A default role looks like:
role default
Special Roles
Special roles are to be used for granting extra privilege to normal user accounts. Some example uses of special roles are to provide an "admin" role that can restart services and edit system configuration files. Special roles can also be provided for regular users to keep their accounts more secure. If they have their own public_html directory, the user role for the user could keep this directory read-only, while a special role to which the user is allowed to transition could allow modification of the files in the directory.
Special roles come in two flavors, ones that require authentication, and ones that do not. On the side of special roles that require authentication, the RBAC system supports a flag that allows PAM authentication to be used for the special role. See Role Modes for a list of all these flags.
Special roles by themselves won't do anything unless there exist non-special (user, group, or default) roles that can transition to them. This transitioning is defined by the role_transitions rule, described in the Role Attributes page.
To authenticate to a special role, use gradm -a <rolename>. To authenticate with PAM to a special role, use gradm -p <rolename>. To transition to a special role that requires no authentication, use gradm -n <rolename>.
Special roles look like:
role specialauth s role specialnoauth sN role specialpamauth sP
Domains
With domains you can combine users that don't share a common group ID as well as groups so that they share a single policy. Domains work just like roles, with the only exception being that the line starting with "role" is replaced with one of the following:
domain somedomainname u user1 user2 user3 user4 ... usern domain somedomainname g group1 group2 group3 group4 ... groupn
Example:
domain somedomain u daemon bin www-data
subject /
/ h
As it is with user and group roles, all domain members must exist, and if they're not, and error is raised.
Capability Restrictions
When no capability restriction rules are used for a given subject, all capabilities that the system grants normally to processes within that subject are allowed to be used. An exception to this is if the subject involved uses policy inheritance. In that case, the capability restrictions would come from the subject(s) being inherited from. Capability rules have the form +CAP_NAME or -CAP_NAME. CAP_ALL is a pseudo-capability meant to describe the entire list of capabilities. It's mainly used to remove all capability usage for a subject, or in conjunction with a small number of rules granting the ability to use individual capabilities. Provided below are some example scenarios of capability restriction usage, along with an explanation of how the policy is interpreted.
Scenario #1: In this scenario, we're removing all capabilities from su but CAP_SETUID and CAP_SETGID.
...
subject /bin/su o
...
-CAP_ALL
+CAP_SETUID
+CAP_SETGID
Scenario #2: In this scenario, we're making use of policy inheritance. Note that the default subject allows CAP_NET_BIND_SERVICE and CAP_NET_RAW. In our ping subject, we're removing CAP_NET_BIND_SERVICE, but since we're inheriting from the default subject (note the lack of the o subject mode on the ping subject), we are still allowed CAP_NET_RAW. Granting important capabilities to default subjects is not something allowed by the RBAC system, so this is just an example.
...
subject /
...
-CAP_ALL
+CAP_NET_RAW
+CAP_NET_BIND_SERVICE
subject /bin/ping
...
-CAP_NET_BIND_SERVICE
Auditing and Suppression: Auditing of attempted capability use and suppression of denied capability usage is possible as well. Capability auditing and suppression supports the same policy inheritance rules as normal capability rules. The below example demonstrates auditing the use of CAP_NET_RAW and the suppression of CAP_NET_BIND_SERVICE denials:
...
subject /
...
-CAP_ALL
-CAP_NET_BIND_SERVICE suppress
+CAP_NET_RAW audit
For a full listing of the capabilities available, see: Capability Names and Descriptions. Note that not all of the capabilities listed may be supported by your particular version of the Linux kernel.
Resource Restrictions
One of the features of grsecurity's ACL system is process–based resource restrictions. Using this feature allows you to restrict things like how much memory a process can take up, how much CPU time, how many files it can open, and how many processes it can execute. Also in this section, we will discuss a "fake" resource implemented in grsecurity's ACL system called "RES_CRASH" that helps guard against bruteforce exploit attempts, which is necessary if you're using PaX.
A single resource rule follows the following syntax:
<resource name> <soft limit> <hard limit>
An example of this syntax would be:
RES_NOFILE 3 3
This would allow the process to open a maximum of 3 files (all processes have 3 open file descriptors at some point: stdin (standard input), stdout (standard output), and stderr (standard error output)).
To clarify what the soft limit and hard limit are, the soft limit is the limit assigned to the process when it is run. The hard limit is the maximum point to which a process can raise the limit via setrlimit(2), unless they have CAP_SYS_RESOURCE. In the case of RES_CPU, when the soft limit is overstepped, a special signal is sent to the process continuously. When the hard limit is overstepped, the process is killed.
A person who is less familiar with Linux should stick to setting limits on the number of files, the address space limit, and number of processes. Of course, you can always use the learning mode of grsecurity to set the resource limits for you. The RES_CPU resource is the only one that accepts time as limits. The time defaults to units of milliseconds. You can also append a case sensitive unit to your limit.
Some examples would be:
- 100s – 100 seconds
- 25m – 25 minutes
- 65h – 65 hours
- 2d – 2 days
The other resources either operate on a number itself or on a size, in bytes. For these you can use the following units: K, M, and G, like:
- 2G – 2 billion
- 25M – 25 million
- 100K – 100 thousand
If you don't want any restriction for the soft or hard limit for a resource, you can use "unlimited" as the limit. Here are some more examples to help you understand how this works:
subject /bin/bash
/ r
/opt rx
/home rwxcd
/mnt rw
/dev
/dev/grsec h
RES_CPU 25m 30m
RLIMIT_AS 5M 5M
RLIMIT_NPROC 2 2
RLIMIT_FSIZE 5K 10K
...
For a list of accepted resource names and units, see System Resources.
RES_CRASH
This "fake" resource limit is expressed by using the name "RES_CRASH" and has the following syntax:
RES_CRASH <number of crashes> <amt. of time>
For example, if you wanted to allow the program to crash once every 30 minutes, you would use the following:
RES_CRASH 1 30m
What happens when this threshold is reached? Well, the only way to ensure that the process won't crash again is to keep it from being executed. If the process is a suid/sgid binary run by a regular user, we kill all processes of that regular user and keep them from logging in for the amount of time, specified as the second parameter to the RES_CRASH resource. So for the above example, the user would be locked out of the system for 30 minutes. If the process is not a suid/sguid binary, we simply keep the binary from being run again for the amount of time specified as the second parameter to the RES_CRASH resource, after killing all processes of that binary.
Socket Policies
The RBAC system supports policies on what local IP addresses and ports can be reserved on the machine, as well as what remote hosts and ports can be communicated with. These two different accesses are abstracted to bind and connect rules, respectively. The syntax for the rules is:
connect <IP/host>/<netmask>:<port/portrange> <socket type 1> ... <socket type n> <proto 1> ... <proto n> bind <IP/host>/<netmask>:<port/portrange> <socket type 1> ... <socket type n> <proto 1> ... <proto n> or: connect disabled bind disabled
"proto" can be any of the protocol names listed in /etc/protocol or "any_proto" to denote any protocol. "socket type" is most commonly "ip", "dgram", or "stream", but can also be "raw_sock", "rdm", or "any_sock" to denote any socket type. Most of the parameters for these rules are optional, particularly the netmask and port or port range. If a port is supplied, then at least an IP address of 0.0.0.0/0 needs to be supplied.
As with capability restrictions, resource restrictions, and many other RBAC features, if the socket policies are omitted for a given subject, then the subject is allowed to bind or connect to anything normally allowed by the system. Note though that if a connect rule is given, then at least one bind rule must also be specified. Older versions of gradm (before the 9/16/09 2.1.14 release) will treat the unspecified rule as a "disabled" rule, whereas new versions will generate an error on such policies.
Here are some example rules:
subject /usr/bin/ssh o ... connect 192.168.0.0/24:22 stream tcp connect ourdnsserver.com:53 dgram udp
In this example, ssh is allowed to connect to ssh servers anywhere on the class C 192.168.0.X network. It is also allowed to do DNS lookups through the host specified. The hostname is resolved at the time the RBAC system is enabled.
subject /usr/bin/nc o ... bind 0.0.0.0/0:1024-65535 stream tcp connect 22.22.22.22:5190 stream tcp
In this example, netcat is allowed to listen on ports 1024 through 65535 on any local interface for TCP connections. It is also able to connect to TCP port 5190 of the 22.22.22.22 host.
subject /bin/strange o ... bind disabled connect 192.168.1.5:6000-6006 stream tcp
This example illustrates how you can have bind disabled but still specify connect rules, or conversely, have connect disabled and only specify bind rules.
As you can see from the examples above, you can have as many socket policies as you wish for a given subject, and as you'll read below there are some powerful extensions to the socket policies.
Per-interface Socket Policies
Rules such as:
bind eth1:80 stream tcp bind eth0#1:22 stream tcp
are allowed, giving you the ability to tie specific socket rules to a single interface (or by using the inverted rules mentioned below, all but one interface). Virtual interfaces are specified by the <ifname>#<vindex> syntax. If an interface is specified, no IP/netmask or host may be specified for the rule.
Inverted Socket Policies
Rules such as:
connect ! www.google.com:80 stream tcp
are allowed, which allows you to specify that a process can connect to anything except to port 80 of www.google.com with a stream TCP socket. The inverted socket matching also works on bind rules.
PaX Flags
In more recent versions of the RBAC system, PaX flags have been changed from single-letter subject modes to more closely resemble how capabilities are handled within the policy. Therefore, PaX flags can now be fully controlled on or off for any given subject by adding +PAX_<feature> or -PAX_<feature> within the scope of a subject. For a full listing of the PaX flags available, see: PaX Flags.
Flow of Matches
Each process on the system has a role and a subject attached to it. This section describes how a process is matched to a role and subject, and how matches are calculated against the objects and capabilities they use. Understanding the flow of matches is necessary for manually creating policies.
Role Hierarchy
When determining a role for a process, the RBAC system matches based on the following role hierarchy, from most specific to least specific:
user -> group -> default
Both user and group roles are permitted to have the role_allow_ip attributes. When checking the UID or GID against the user or group role, respectively, the role_allow_ip attributes come into play. Imagine the following policy:
role user1 u role_allow_ip 192.168.1.5 ...
If someone attempted to log in to the machine as user1 from any IP address other than 192.168.1.5, they would not be assigned the user1 role. The matching system would then fall back on trying to find an acceptable group role, or if one could not be found, fall back to the default role.
Subject/Object Hierarchy
Hierarchy for subjects and objects involves matching a most specific pathname over a less specific pathname. So, if a /bin object exists, and a /bin/ping object exists, and a process is attempting to read /bin/ping, the /bin/ping object would be the one matching. If /bin/su were being accessed instead, then /bin would match.
The path from most specific to least specific pathname isn't linear however, particularly in the case of subjects using policy inheritance. Imagine the following policy:
role user1 u
subject /
/ r
/tmp rwcd
/usr/bin rx
/root r
/root/test/blah r
...
subject /usr/bin/specialbin
/root/test rw
...
If /root/test/blah was being accessed by /usr/bin/specialbin, it would not be able to write to it. The reason for this is that when going from most specific to least specific for a given path (which involves stripping off each trailing path component and attempting a match for the resulting pathname), the matching algorithm will look (in order from most specific to least specific) in each of the subjects the current subject inherits from. In this case, the algorithm saw that no object existed for /root/test/blah in the /usr/bin/specialbin subject, so upon checking the subject for / it found a /root/test/blah object, thus resulting in the read-only permission.
When going from most specific to least specific, a globbed object such as /home/* is treated as less specific than /home/blah (if the requested access is for /home/blah). Globbed objects are matched in the order in which they're listed in the RBAC policy. So in the following example:
role user1 u
subject /
/ r
/home r
/home/* r
/home/test* rw
...
If a process were accessing /home/testing/somefile it would only be allowed to read it, since the /home/* rule was listed first. It was likely that the policy writer didn't intend this behavior (because the /home/test* rule would never match) so the /home/test* object should be swapped to the line the /home/* object is on.
Capability Hierarchy
When determining whether a capability is granted or not, the RBAC system works from most specific subject to least specific (in the case of policy inheritance). The first subject along that path that mentions the capability in question is the one that matches. To illustrate:
role user1 u
subject /
...
-CAP_ALL
+CAP_NET_BIND_SERVICE
subject /bin
...
-CAP_NET_BIND_SERVICE
subject /bin/su
...
+CAP_SETUID
+CAP_SETGID
In this example, /bin/su is able to use only CAP_SETUID and CAP_SETGID. A lookup on CAP_NET_BIND_SERVICE would fall back to the /bin subject, since /bin/su inherits from it and did not explicitly list a rule for CAP_NET_BIND_SERVICE. The /bin subject specifies that CAP_NET_BIND_SERVICE be disallowed. Matching against another capability, CAP_SYS_ADMIN for instance, would end up falling back to the / subject, where it would match -CAP_ALL and be denied.
Policy Recommendations
Try to remove as many capabilities from default subjects as possible. The more you remove, the closer root comes to acting as a regular user. The more capabilities you remove, however, the more subjects you will have to create for programs that need those capabilities. The RBAC system will enforce that a minimum level of capabilities be removed from all default subjects.
Use full system learning. It will generate a better policy than you would have generated by hand. Make sure you're making full use of the /etc/grsec/learn_config file to specify the files and directories particular to your system that you want protected. gradm will do all the heavy lifting of creating privilege boundaries for processes that access or modify important data.
Administrative programs, such as shutdown or reboot, should require authentication instead of giving everyone the capabilities to run them.
Always inspect your kernel logs. The RBAC system provides a great amount of human-readable information in every kernel log. Of particular importance is what role and subject were assigned to the process causing an alert. If you think that the alert doesn't match up with what you expect from your policy, make sure that the role and subject actually match. If they don't, then you may have issues with a role_allow_ip rule that's preventing the proper role from being applied.
Familiarize yourself with Linux’s capabilities and what they cover. A full listing of them is available here: Capability Names and Descriptions.
Avoid using policy inheritance until you understand fully how it forms the policy for a given subject. Even then, use it sparingly, reserving it generally for cases where a default subject is configured least privilege, with no readable/writable/executable objects and no capabilities.
Wherever possible, avoid granting both write and execute permission to objects. This gives a potential attacker the ability to execute arbitrary code. Similar to how PaX prevents arbitrary code execution within a given process' address space, one of your goals in creating policies is to prevent this on the file system as well.
Be careful using the suppression ('s') object flag, especially when applying it to / to ignore accesses a program does not really need to operate correctly. A change in glibc or another library the subject uses could cause the application to fail in a way that will be difficult to debug (unless your first step is to remove the suppression flag).
Sample Policies
Below is the sample policy provided with a gradm installation:
role admin sA
subject / rvka
/ rwcdmlxi
role default G
role_transitions admin
subject /
/ r
/opt rx
/home rwxcd
/mnt rw
/dev
/dev/grsec h
/dev/urandom r
/dev/random r
/dev/zero rw
/dev/input rw
/dev/psaux rw
/dev/null rw
/dev/tty? rw
/dev/console rw
/dev/tty rw
/dev/pts rw
/dev/ptmx rw
/dev/dsp rw
/dev/mixer rw
/dev/initctl rw
/dev/fd0 r
/dev/cdrom r
/dev/mem h
/dev/kmem h
/dev/port h
/bin rx
/sbin rx
/lib rx
/usr rx
# compilation of kernel code should be done within the admin role
/usr/src h
/etc rx
/proc rwx
/proc/slabinfo h
/proc/kcore h
/proc/modules h
/proc/sys r
/root r
/tmp rwcd
/var rwxcd
/var/tmp rwcd
/var/log r
# hide the kernel images and modules
/boot h
/lib/modules h
/etc/grsec h
/etc/ssh h
# if sshd needs to be restarted, it can be done through the admin role
# restarting sshd should be followed immediately by a gradm -u
/usr/sbin/sshd
-CAP_KILL
-CAP_SYS_TTY_CONFIG
-CAP_LINUX_IMMUTABLE
-CAP_NET_RAW
-CAP_MKNOD
-CAP_SYS_ADMIN
-CAP_SYS_RAWIO
-CAP_SYS_MODULE
-CAP_SYS_PTRACE
-CAP_NET_ADMIN
-CAP_NET_BIND_SERVICE
-CAP_NET_RAW
-CAP_SYS_CHROOT
-CAP_SYS_BOOT
# RES_AS 100M 100M
# connect 192.168.1.0/24:22 stream tcp
# bind 0.0.0.0 stream dgram tcp udp
# the d flag protects /proc fd and mem entries for sshd
# all daemons should have 'p' in their subject mode to prevent
# an attacker from killing the service (and restarting it with trojaned
# config file or taking the port it reserved to run a trojaned service)
subject /usr/sbin/sshd dpo
/ h
/bin/bash x
/dev h
/dev/log rw
/dev/random r
/dev/urandom r
/dev/null rw
/dev/ptmx rw
/dev/pts rw
/dev/tty rw
/dev/tty? rw
/etc r
/etc/grsec h
/home
/lib rx
/root
/proc r
/proc/kcore h
/proc/sys h
/usr/lib rx
/usr/share/zoneinfo r
/var/log
/var/mail
/var/log/lastlog rw
/var/log/wtmp w
/var/run/sshd
/var/run/utmp rw
-CAP_ALL
+CAP_CHOWN
+CAP_SETGID
+CAP_SETUID
+CAP_SYS_CHROOT
+CAP_SYS_RESOURCE
+CAP_SYS_TTY_CONFIG
subject /usr/X11R6/bin/XFree86
/dev/mem rw
+CAP_SYS_ADMIN
+CAP_SYS_TTY_CONFIG
+CAP_SYS_RAWIO
-PAX_SEGMEXEC
-PAX_PAGEEXEC
-PAX_MPROTECT
subject /usr/bin/ssh
/etc/ssh/ssh_config r
subject /sbin/klogd
+CAP_SYS_ADMIN
subject /sbin/syslog-ng
+CAP_SYS_ADMIN
subject /usr/sbin/cron
/dev/log rw
subject /bin/login
/dev/log rw
/var/log/wtmp w
/var/log/faillog rwcd
subject /sbin/getty
/var/log/wtmp w
subject /sbin/init
/var/log/wtmp w
Below is a full user role policy that covers the behavior of cvs-pserver when run as the non-root cvs user, providing anonymous read-only CVS repository access.
role cvs u
subject /
/ h
-CAP_ALL
connect disabled
bind disabled
subject /usr/bin/cvs
/
/etc/fstab r
/etc/mtab r
/etc/passwd r
/proc/meminfo r
/dev/urandom r
/dev/log rw
/dev/null rw
/home/cvs r
/home/cvs/CVSROOT/val-tags rw
/home/cvs/CVSROOT/history ra
/tmp rwcd
/var/lock/cvs rwcd
/var/run/.nscd_socket rw
/proc/sys/kernel r
/var/run
Here's all that's needed for an unprivileged sshd account:
role sshd u
subject /
/ h
/var/run/sshd r
-CAP_ALL
bind disabled
connect disabled
Application-specific Settings
This page lists applications that need specific settings to work with grsecurity and PaX. If you wish to add an application to the list, you are most welcome to do so. Please keep the list in alphabetical order and remember to update the table of contents on the front page.
ATI Catalyst (fglrx) graphics driver
When using Xorg and the proprietary ATI Catalyst graphics driver, CONFIG_PAX_USERCOPY must not be set as PAX_USERCOPY prevents a real overflow from occurring in the ATI driver that is still unfixed. This is in addition to what's shown in the section on Xorg below.
As of 11.8, CONFIG_PAX_MEMORY_UDEREF must also be disabled.
Firefox (or Iceweasel in Debian)
Mozilla Firefox and possibly all, if not some(?) of, the lib.so files in the folder (/usr/lib/firefox) with the Firefox binary (called /usr/lib/firefox/firefox) need mprotect disabled for flash to function. Without the Firefox binary having disabled mprotect Firefox will enter an infinite loop at startup or take minutes to load. Without the lib.so files having mprotect disabled any page encountered with Flash will surely run an infinite loop and the Firefox process will have to be killed.
The option must be disabled for just-in-time compilation of certain scripts for both xulrunner-stub and xulrunner-bin. See Grsecurity forums for more details. [3] The safest option would of course be denying mprotect and boycot sites that use just-in-time (JIT) flash scripts. You may disable JIT compilation in the browser by initiating the address about:config, search for "jit" in the page's integrated search bar, and double-click the options "javascript.options.methodjit.chrome" and "javascript.options.methodjit.content" to set them to "false".
Firefox >= 3.5 may need RANDMMAP to be disabled (), if not it will enter in an infinite loop during startup. To disable, execute paxctl -r /firefox_binary. Usually the binary is somewhere in /usr/lib64/*firefox*. See http://bugs.gentoo.org/show_bug.cgi?id=278698 for more details. As of at least Firefox 13 on Ubuntu-based distros you can enable RANDMMAP.
Google Chrome 15.0.874.106
On Google Chrome:
$ paxctl -v /opt/google/chrome/chrome
PaX control v0.5
Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu>
- PaX flags: P----m-x-eR- [/opt/google/chrome/chrome]
PAGEEXEC is enabled
MPROTECT is disabled
RANDEXEC is disabled
EMUTRAMP is disabled
RANDMMAP is enabled
$ paxctl -v /opt/google/chrome/nacl_helper
PaX control v0.5
Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu>
- PaX flags: -p---m-x-e-- [/opt/google/chrome/nacl_helper]
PAGEEXEC is disabled
MPROTECT is disabled
RANDEXEC is disabled
EMUTRAMP is disabled
$ paxctl -v /opt/google/chrome/chrome-sandbox
PaX control v0.5
Copyright 2004,2005,2006,2007 PaX Team <pageexec@freemail.hu>
- PaX flags: -----m-x-e-- [/opt/google/chrome/chrome-sandbox]
MPROTECT is disabled
RANDEXEC is disabled
EMUTRAMP is disabled
These PaX flags work well on my system with flash. Chrome's nacl does throw this however:
[1:1:14105440733:ERROR:nacl_fork_delegate_linux.cc(78)] Bad NaCl helper startup ack (0 bytes)
GUFW/UFW firewalls or Update Manager
GUFW is an optional graphical application interface for the Ubuntu firewall (UFW), both of which use Python. Update Manager is a Gnome application for updating packages that also depends on Python. Really, any application that uses Python try enabling EMUTRAMP for the version of Python that is the dependency of your affected program (GUFW or Update Manager). (Example: # paxctl -E /usr/bin/Python2.7).
PHP and other applications that set their own resource limits
While Apache/PHP run very well with a grsec/PaX enabled kernel, you could feel like there are possible memory leaks or strange OOM (out of memory) errors with PHP using a PaX enabled kernel with the SEGMEXEC flag enabled. There's no memory leak, and the OOM errors are normal, particularly if you didn't set high enough resource limits.
Concerning "abnormal" memory usage with PHP and SEGMEXEC flag enabled, see spender's answers on http://bugs.php.net/bug.php?id=49501 comments:
"Due to VMA mirroring, the SEGMEXEC option causes accounted vm usage to double. So you weren't experiencing a memory leak -- you were just being accounted for twice as much memory as you thought you were using. The solution would be to double the resource limit or, if your system is NX-capable and PAE is enabled, use PAGEEXEC."
Java
With problems with an epoll stack trace lookup [4]. Also there is a problem with just-in-time compilation. Disable mprotect for /usr/lib/jvm/java-6-sun-1.6.0.10/jre/bin/java and /usr/lib/jvm/java-6-sun-1.6.0.10/jre/bin/javaws.
Openoffice.org
Openoffice.org uses two binaries which need custom settings to work. Both /usr/lib/openoffice/program/soffice.bin and /usr/lib/openoffice/program/unopkg.bin need to have unrestricted mprotect. [5]
X.org
X.org might need some specific kernel settings during configuration (depending on the hardware and the drivers used X won't run with non-executable pages (PAX_NOEXEC)). The problem manifested especially in XFree4. Although, recent versions of X.org are known to work with non-executable pages enabled. If you run into problems with X watch your non-executeble settings.
Some users experience mouse freezes when the system load is high. Typically the mouse pointer is reset, but stays in the upper left corner of the screen. This behaviour was found to occur with certain pre-emption settings [6][7]. It seems to be an interaction between forced-preemption and KERNEXEC. You should be able to re-enable KERNEXEC as long as you disable preemption or use voluntary preemption.
According to the Pax-Team KERNEXEC should work as is, since the changes should be only basic functions like open/close functions. If you should experience problems switch to voluntary or none pre-emption.
Reporting Bugs
Contacts
Submitting bug reports to the proper developer will help get your bug resolved quicker. Though the developers of PaX and grsecurity will forward bug reports to each other, doing so may delay the resolution of your problem.
For bugs within grsecurity features, submit bug reports to: spender@grsecurity.net. For bugs within PaX, submit bug reports to pageexec@freemail.hu.
Bug reports can also be submitted to the gsecurity forums. (this is the preferred method). The developers monitor RSS feeds of the forums to be able to respond to bug reports quickly.
If possible, avoid submitting bug reports to the grsecurity mailing list, as it is mainly intended for announcements or other important topics.
Requirements
To be able to reproduce the problem you're experiencing or properly debug it, information will be requested of you depending on the type of bug you are reporting. For any large files that are requested, such as the kernel's vmlinux file, please attempt to make these available via a website (you can use a free file uploading service) as they will likely be rejected by the developers' mail servers. Additional information may be requested for debugging purposes (particularly if the problem cannot be reproduced by the developers), but below is specified the minimum requested information.
For any bug you report, please specify the name of the patch you have applied to the kernel. Please also note that the developers only support the latest test patches, as a bug reported in an older patch may have already been fixed in the latest test patch.
A properly submitted bug report that includes the requested information below up-front greatly improves turnaround time for getting your problem solved.
Compilation Errors
- A copy of your kernel .config
Build/Linking Errors
- A copy of your kernel .config
- Your binutils version (ld --version)
RBAC Problems
- A copy of your kernel .config
- A copy of your policy file
- A listing of the steps performed to produce the problem
Kernel Crashes/Hangs
- A copy of your kernel .config
- Your binutils version (ld --version)
- A copy of your vmlinux file (from the kernel source tree)
- A copy of your bzImage file (from the /boot directory)
- A copy of your System.map file (from the /boot directory)
- The OOPS report, if one exists (take a photo of the screen if you are unable to capture it on disk). Note: we previously required that GRKERNSEC_HIDESYM be disabled for bug reports. This is no longer the case. Any recent grsecurity patch doesn't require GRKERNSEC_HIDESYM to be disabled for symbols to be displayed in OOPs messages.
- A description of the machine's hardware (particularly any non-standard hardware)
- Information about your Virtual Machine setup (if applicable): preferred execution mode and kernel paravirtualization
- Steps required to reproduce the crash (if not before init starts)
Appendix
Introduction
This is a list of all grsecurity and PaX configuration options in the kernel. You can access this same information using the kernel configuration's built-in help. This page contains only the configuration options present in the latest stable grsecurity release. The grsecurity options are available under Security options » Grsecurity. Please note that this listing is out of date. The most up to date information is available in the kernel configuration help. Please edit this page to reflect the current configuration help information if you'd like to assist.
Grsecurity Kernel Configuration Options
Configuration option: CONFIG_GRKERNSEC
Security Level
Configuration option: CONFIG_GRKERNSEC_LOW | CONFIG_GRKERNSEC_MEDIUM | CONFIG_GRKERNSEC_HIGH | CONFIG_GRKERNSEC_CUSTOM
This menu lets you choose between four security levels
Low
If you choose this option, several of the grsecurity options will be enabled that will give you greater protection against a number of attacks, while assuring that none of your software will have any conflicts with the additional security measures. If you run a lot of unusual software, or you are having problems with the higher security levels, you should say Y here. With this option, the following features are enabled:
- Linking restrictions
- FIFO restrictions
- Enforcing RLMIT_NPROC on execve()
- Restricted dmesg
- Enforced chdir("/") on chroot
- Runtime module disabling
Medium
If you say Y here, several features in addition to those included in the low additional security level will be enabled. These features provide even more security to your system, though in rare cases they may be incompatible with very old or poorly written software. If you enable this option, make sure that your auth service (identd) is running as gid 1001. With this option the following features (in addition to those provided in the low additional security level) will be enabled:
- Failed fork logging
- Time change logging
- Signal logging
- Deny mounts in chroot
- Deny double chrooting
- Deny sysctl writes in chroot
- Deny mknod in chroot
- Deny access to abstract AF_UNIX sockets out of chroot
- Deny pivot_root in chroot
- Denied writes of /dev/kmem, /dev/mem, and /dev/port
- /proc restrictions with special GID set to 10 (usually wheel)
- Address Space Layout Randomization (ASLR)
- Prevent exploitation of most refcount overflows
- Bounds checking of copying between the kernel and userland
High
If you say Y here, many of the features of grsecurity will be enabled, that will protect you against many kinds of attacks against your system. The heightened security comes at a cost of an increased chance of incompatibilities with rare software on your machine. Since this security level enables PaX, you should view <http://pax.grsecurity.net> and read about the PaX project. While you are there, download chpax and run it on binaries that cause problems with PaX. Also remember that since the /proc restrictions are enabled, you must run your identd as gid 1001. This security level enables the following features in addition to those listed in the low and medium security levels:
- Additional /proc restrictions
- Chmod restrictions in chroot
- No signals, ptrace, or viewing or processes outside of chroot
- Capability restrictions in chroot
- Deny fchdir out of chroot
- Priority restrictions in chroot
- Segmentation-based implementation of PaX
- Mprotect restrictions
- Removal of addresses from /proc/<pid>/[smaps|maps|stat]
- Kernel stack randomization
- Mount/unmount/remount logging
- Kernel symbol hiding
- Preventation of memory exhaustion based exploits
- Hardening of module auto-loading
- Ptrace restrictions
- Restricted vm86 mode
- Restricted sysfs/debugfs
- Active kernel exploit response
Custom
If you say Y here, you will be able to configure every grsecurity option, which allows you to enable many more features that aren't covered in the basic security levels. These additional features include TPE, socket restrictions, and the sysctl system for grsecurity. It is advised that you read through the help for each option to determine its usefulness in your situation.
Address Space Protection
This menu lets you choose options that affect the Address Space Protection
Deny writing to /dev/kmem, /dev/mem, and /dev/port
Configuration option: CONFIG_GRKERNSEC_KMEM
If you say Y here, /dev/kmem and /dev/mem< won't be allowed to be written to via mmap or otherwise to modify the running kernel. /dev/port will also not be allowed to be opened. If you have module support disabled, enabling this will close up four ways that are currently used to insert malicious code into the running kernel. Even with all these features enable, we still highly recommend that you use the RBAC system, as it is still possible for an attacker to modify the running kernel through privileged I/O granted by ioperm/iopl. If you are not using XFree86, you may be able to stop this additional case by enabling the "Disable privileged I/O" option. Though nothing legitimately writes to /dev/kmem, XFree86 does need to write to /dev/mem but only to video memory, which is the only writing we allow in this case. If /dev/kmem or /dev/mem are mmaped without PROT_WRITE, they will not be allowed to mprotect it with PROT_WRITE later. It is highly recommended that you say Y here if you meet all the conditions above.
Disable privileged I/O
Configuration option: CONFIG_GRKERNSEC_IO
If you say Y here, all ioperm and iopl calls will return an error. Ioperm and iopl can be used to modify the running kernel. Unfortunately, some programs need this access to operate properly, the most notable of which are XFree86 and hwclock. Hwclock can be remedied by having RTC support in the kernel, so CONFIG_RTC is enabled if this option is enabled, to ensure that hwclock operated correctly. XFree86 still will not operate correctly with this option enabled, so DO NOT CHOOSE Y IF YOU USE XFree86. If you use XFree86 and you still want to protect the kernel against modification, use the RBAC system.
Remove addresses from /proc/<pid>/[smaps|maps|stat]
Configuration option: CONFIG_GRKERNSEC_PROC_MEMMAP
If you say Y here, the /proc/<pid>/maps and /proc/<pid>/stat files will give no information about the addresses of its mappings if PaX features that rely on random addresses are enabled on the task. If you use PaX it is greatly recommended that you say Y here as it closes up a hole that makes the full ALSR useless for suid binaries.
Deter exploit bruteforcing
Configuration option: CONFIG_GRKERNSEC_BRUTE
If you say Y here, attempts to bruteforce exploits against forking daemons such as apache or sshd, as well as against suid/sgid binaries will be deterred. When a child of a forking daemon is killed by PaX or crashed due to an illegal instruction or other suspicious signal, the parent process will be delayed 30 seconds upon every subsequent fork until the administrator is able to assess the situation and restart the daemon.
In the suid/sgid case, the attempt is logged, the user has all their processes terminated, and they are prevented from executing any further processes for 15 minutes.
It is recommended that you also enable signal logging in the auditing section so that logs are generated when a process triggers a suspicious signal.
If the sysctl option is enabled, a sysctl option with name deter_bruteforce is created.
Harden module auto-loading
Configuration option: CONFIG_GRKERNSEC_MODHARDEN
If you say Y here, module auto-loading in response to use of some feature implemented by an unloaded module will be restricted to root users. Enabling this option helps defend against attacks by unprivileged users who abuse the auto-loading behavior to cause a vulnerable module to load that is then exploited.
If this option prevents a legitimate use of auto-loading for a non-root user, the administrator can execute modprobe manually with the exact name of the module mentioned in the alert log. Alternatively, the administrator can add the module to the list of modules loaded at boot time by modifying init scripts.
Modification of init scripts will most likely be needed on Ubuntu servers with encrypted home directory support enabled, as the first non-root users logging in will cause the ecb(aes), ecb(aes)-all, cbc(aes), and cbc(aes)-all modules to be loaded.
Hide kernel symbols
Configuration option: CONFIG_GRKERNSEC_HIDESYM
If you say Y here, getting information on loaded modules, and displaying all kernel symbols through a syscall will be restricted to users with CAP_SYS_MODULE. For software compatibility reasons, /proc/kallsyms will be restricted to the root user. The RBAC system can hide that entry even from root.
This option also prevents leaking of kernel addresses through several /proc entries.
Note that this option is only effective provided the following conditions are met:
- The kernel using grsecurity is not precompiled by some distribution
- You have also enabled GRKERNSEC_DMESG
- You are using the RBAC system and hiding other files such as your kernel image and System.map. Alternatively, enabling this option
causes the permissions on /boot, /lib/modules, and the kernel source directory to change at compile time to prevent reading by non-root users. If the above conditions are met, this option will aid to provide a useful protection against local and remote kernel exploitation of overflows and arbitrary read/write vulnerabilities.
Active kernel exploit response
Configuration option: CONFIG_GRKERNSEC_KERN_LOCKOUT
If you say Y here, when a PaX alert is triggered due to suspicious activity in the kernel (from KERNEXEC/UDEREF/USERCOPY) or an OOPs occurs due to bad memory accesses, instead of just terminating the offending process (and potentially allowing a subsequent exploit from the same user), we will take one of two actions:
- If the user was root, we will panic the system
- If the user was non-root, we will log the attempt, terminate all processes owned by the user, then prevent them from creating any new processes until the system is restarted
This deters repeated kernel exploitation/bruteforcing attempts and is useful for later forensics.
Role Based Access Control Options
This menu lets you choose options that affect the RBAC system
Disable RBAC system
Configuration option: CONFIG_GRKERNSEC_NO_RBAC
If you say Y here, the /dev/grsec device will be removed from the kernel, preventing the RBAC system from being enabled. You should only say Y here if you have no intention of using the RBAC system, so as to prevent an attacker with root access from misusing the RBAC system to hide files and processes when loadable module support and /dev/[k]mem have been locked down.
Hide kernel processes
Configuration option: CONFIG_GRKERNSEC_ACL_HIDEKERN
If you say Y here, all kernel threads will be hidden to all processes but those whose subject has the "view hidden processes" flag.
Maximum tries before password lockout
Configuration option: CONFIG_GRKERNSEC_ACL_MAXTRIES
This options enforces the maximum number of times a user can attempt to authorize themselves with the grsecurity RBAC system before being denied the ability to attempt authorization again for a specified time. The lower the number, the harder it will be to brute-force a password.
Time to wait after max password tries, in seconds
Configuration option: CONFIG_GRKERNSEC_ACL_TIMEOUT
This options specified the time the user must wait after attempting to authorize to the RBAC system with the maximum number of invalid passwords. The higher the number, the harder it will be to brute-force a password.
Filesystem Protections
This menu lets you choose options that affect filesystem security
Proc restrictions
Configuration option: CONFIG_GRKERNSEC_PROC
If you say Y here, the permissions of the /proc filesystem will be altered to enhance system security and privacy. You MUST choose either a user only restriction or a user and group restriction. Depending upon the option you choose, you can either restrict users to see only the processes they themselves run, or choose a group that can view all processes and files normally restricted to root if you choose the "restrict to user only" option. NOTE: If you're running identd as a non-root user, you will have to run it as the group you specify here.
Restrict /proc to user only
Configuration option: CONFIG_GRKERNSEC_PROC_USER
If you say Y here, non-root users will only be able to view their own processes, and restricts them from viewing network-related information, and viewing kernel symbol and module information.
Allow special group
Configuration option: CONFIG_GRKERNSEC_PROC_USERGROUP
If you say Y here you will be able to select a group that will be able to view all processes, network-related information, and kernel and symbol information. This option is useful if you want to run identd as a non-root user.
- GID for special group (CONFIG_GRKERNSEC_PROC_GID) - Specifies the group id of the special group
Additional restrictions
Configuration option: CONFIG_GRKERNSEC_PROC_ADD
If you say Y here, additional restrictions will be placed on /proc that keep normal users from viewing device information and slabinfo information that could be useful for exploits.
Linking restrictions
Configuration option: CONFIG_GRKERNSEC_LINK
If you say Y here, /tmp race exploits will be prevented, since users will no longer be able to follow symlinks owned by other users in world-writable "+t" directories (i.e. /tmp), unless the owner of the symlink is the owner of the directory. Users will also not be able to hardlink to files they do not own. If the sysctl option is enabled, a sysctl option with name linking_restrictions is created.
FIFO restrictions
Configuration option: CONFIG_GRKERNSEC_FIFO
If you say Y here, users will not be able to write to FIFOs they don't own in world-writable "+t" directories (i.e. /tmp), unless the owner of the FIFO is the same owner of the directory it's held in. If the sysctl options is enabled, a sysctl option with the name "fifo_restrictions" is created.
Sysfs/debugfs restriction
Configuration option: CONFIG_GRKERNSEC_SYSFS_RESTRICT
If you say Y here, sysfs (the pseudo-filesystem mounted at /sys) and any filesystem normally mounted under it (e.g. debugfs) will only be accessible by root. These filesystems generally provide access to hardware and debug information that isn't appropriate for unprivileged users of the system. Sysfs and debugfs have also become a large source of new vulnerabilities, ranging from infoleaks to local compromise.
There has been very little oversight with an eye toward security involved in adding new exporters of information to these filesystems, so their use is discouraged.
This option is equivalent to a chmod 0700 of the mount paths.
Runtime read-only mount protection
Configuration option: CONFIG_GRKERNSEC_ROFS
If you say Y here, a sysctl option with name romount_protect will be created. By setting this option to 1 at runtime, filesystems will be protected in the following ways:
- No new writable mounts will be allowed
- Existing read-only mounts won't be able to be remounted read/write
- Write operations will be denied on all block devices
This option acts independently of grsec_lock: once it is set to 1, it cannot be turned off. Therefore, please be mindful of the resulting behavior if this option is enabled in an init script on a read-only filesystem. This feature is mainly intended for secure embedded systems.
Chroot jail restrictions
Configuration option: CONFIG_GRKERNSEC_CHROOT
If you say Y here, you will be able to choose several options that will make breaking out of a chrooted jail much more difficult. If you encounter no software incompatibilities with the following options, it is recommended that you enable each one.
Deny mounts
Configuration option: CONFIG_GRKERNSEC_CHROOT_MOUNT
If you say Y here, processes inside a chroot will not be able to mount or remount filesystems. If the sysctl option is enabled, a sysctl option with name chroot_deny_mount is created.
Deny double-chroots
Configuration option: CONFIG_GRKERNSEC_CHROOT_DOUBLE
If you say Y here, processes inside a chroot will not be able to chroot again outside the chroot. This is a widely used method of breaking out of a chroot jail and should not be allowed. If the sysctl option is enabled, a sysctl option with name chroot_deny_chroot is created.
Deny pivot_root in chroot
Configuration option: CONFIG_GRKERNSEC_CHROOT_PIVOT
If you say Y here, processes inside a chroot will not be able to use a function called pivot_root() that was introduced in Linux 2.3.41. It works similar to chroot in that it changes the root filesystem. This function could be misused in a chrooted process to attempt to break out of the chroot, and there should not be allowed. If the sysctl option is enabled, a sysctl option with name chroot_deny_pivot is created.
Enforce chdir("/") on all chroots
Configuration option: CONFIG_GRKERNSEC_CHROOT_CHDIR
If you say Y here, the current working directory of all newly-chrooted applications will be set to the root directory of the chroot.
The man page on chroot(2) states:
Note that this call does not change the current working directory, so that '.' can be outside the tree rooted at "/". In particular, the super-user can escape from a "chroot jail" by doing mkdir foo; chroot foo; cd ...
It is recommended that you say Y here, since it's not known to break any software. If the sysctl option is enabled, a sysctl option with name chroot_enforce_chdir is created.
Deny (f)chmod +s
Configuration option: CONFIG_GRKERNSEC_CHROOT_CHMOD
If you say Y here, processes inside a chroot will not be able to chmod or fchmod files to make them have suid or sgid bits. This protects against another published method of breaking a chroot. If the sysctl option is enabled, a sysctl option with name chroot_deny_chmod is created.
Deny fchdir out of chroot
Configuration option: CONFIG_GRKERNSEC_CHROOT_FCHDIR
If you say Y here, a well-known method of breaking chroots by fchdir'ing to a file descriptor of the chrooting process that points to a directory outside the filesystem will be stopped. If the sysctl option is enabled, a sysctl option with name chroot_deny_fchdir is created.
Deny mknod
Configuration option: CONFIG_GRKERNSEC_CHROOT_MKNOD
If you say Y here, processes inside a chroot will not be allowed to mknod. The problem with using mknod inside a chroot is that it would allow an attacker to create a device entry that is the same as one on the physical root of your system, which could range from anything from the console device to a device for your harddrive (which they could then use to wipe the drive or steal data). It is recommended that you say Y here, unless you run into software incompatibilities. If the sysctl option is enabled, a sysctl option with name chroot_deny_mknod is created.
Deny shmat() out of chroot
Configuration option: CONFIG_GRKERNSEC_CHROOT_SHMAT
If you say Y here, processes inside a chroot will not be able to attach to shared memory segments that were created outside of the chroot jail. It is recommended that you say Y here. If the sysctl option is enabled, a sysctl option with name chroot_deny_shmat is created.
Deny access to abstract AF_UNIX sockets out of chroot
Configuration option: CONFIG_GRKERNSEC_CHROOT_UNIX
If you say Y here, processes inside a chroot will not be able to connect to abstract (meaning not belonging to a filesystem) Unix domain sockets that were bound outside of a chroot. It is recommended that you say Y here. If the sysctl option is enabled, a sysctl option with name chroot_deny_unix is created.
Protect outside processes
Configuration option: CONFIG_GRKERNSEC_CHROOT_FINDTASK
If you say Y here, processes inside a chroot will not be able to kill, send signals with fcntl, ptrace, capget, getpgid, getsid, or view any process outside of the chroot. If the sysctl option is enabled, a sysctl option with name chroot_findtask is created.
Restrict priority changes
Configuration option: CONFIG_GRKERNSEC_CHROOT_NICE
If you say Y here, processes inside a chroot will not be able to raise the priority of processes in the chroot, or alter the priority of processes outside the chroot. This provides more security than simply removing CAP_SYS_NICE from the process' capability set. If the sysctl option is enabled, a sysctl option with name chroot_restrict_nice is created.
Deny sysctl writes
Configuration option: CONFIG_GRKERNSEC_CHROOT_SYSCTL
If you say Y here, an attacker in a chroot will not be able to write sysctl entries, either by sysctl(2) or through a /proc interface. It is strongly recommended that you say Y here. If the sysctl option is enabled, a sysctl option with name chroot_deny_sysctl is created.
Capability restrictions
Configuration option: CONFIG_GRKERNSEC_CHROOT_CAPS
If you say Y here, the capabilities on all root processes within a chroot jail will be lowered to stop module insertion, raw i/o, system and net admin tasks, rebooting the system, modifying immutable files, modifying IPC owned by another, and changing the system time. This is left an option because it can break some apps. Disable this if your chrooted apps are having problems performing those kinds of tasks. If the sysctl option is enabled, a sysctl option with name chroot_caps is created.
Kernel auditing
This menu lets you choose options that affect the kernel auditing
Single group for auditing
Configuration option: CONFIG_GRKERNSEC_AUDIT_GROUP
If you say Y here, the exec, chdir, (un)mount and ipc logging features will only operate on a group you specify. This options is recommended if you only want to watch certain users instead of having a large amount of logs from the entire system. If the sysctl option is enabled, a sysctl option with name audit_group is created.
- GID for auditing (CONFIG_GRKERNSEC_AUDIT_GID) - The id of the group being audited
Exec logging
Configuration option: CONFIG_GRKERNSEC_EXECLOG
If you say Y here, all execve() calls will be logged (since the other exec*() calls are frontends to execve(), all execution will be logged). Useful for shell-servers that like to keep track of their users. If the sysctl option is enabled, a sysctl option with name "exec_logging" is created.
==WARNING:== This option when enabled will produce a LOT of logs, especially on an active system.
Resource logging
Configuration option: CONFIG_GRKERNSEC_RESLOG
If you say Y here, all attempts to overstep resource limits will be logged with the resource name, the requested size, and the current limit. It is highly recommended that you say Y here. If the sysctl option is enabled, a sysctl option with name resource_logging is created. If the RBAC system is enabled the sysctl value is ignored.
Log execs within chroot
Configuration option: CONFIG_GRKERNSEC_CHROOT_EXECLOG
If you say Y here, all executions inside a chroot jail will be logged to syslog. This can cause a large amount of logs if certain applications (e.g. djb's daemontools) are installed on the system, and is therefore left as an option. If the sysctl option is enabled, a sysctl option with name chroot_execlog is created.
Ptrace logging
Configuration option: CONFIG_GRKERNSEC_AUDIT_PTRACE
If you say Y here, all attempts to attach to a process via ptrace will be logged. If the sysctl option is enabled, a sysctl option with name audit_ptrace" is created.
Chdir logging
Configuration option: CONFIG_GRKERNSEC_AUDIT_CHDIR
If you say Y here, all chdir() calls will be logged. If the sysctl option is enabled, a sysctl option with name audit_chdir is created.
(Un)mount logging
Configuration option: CONFIG_GRKERNSEC_AUDIT_MOUNT
If you say Y here, all mounts and unmounts will be logged. If the sysctl option is enabled, a sysctl option with name audit_mount is created.
Signal logging
Configuration option: CONFIG_GRKERNSEC_SIGNAL
If you say Y here, certain important signals will be logged, such as SIGSEV, which will as a result inform you of when an error in a program occurred, which in some cases could mean a possible exploit attempt. If the sysctl option is enabled, a sysctl option with name signal_logging is created.
Fork failure logging
Configuration option: CONFIG_GRKERNSEC_FORKFAIL
If you say Y here, all failed fork() attempts will be logged. This could suggest a fork bomb, or someone attempting to overstep their process limit. If the sysctl option is enabled, a sysctl option with name forkfail_logging is created.
Time change logging
Configuration option: CONFIG_GRKERNSEC_TIME
If you say Y here, any changes of the system clock will be logged. If the sysctl option is enabled, a sysctl option with name timechange_logging is created.
/proc/<pid>/ipaddr support
Configuration option: CONFIG_GRKERNSEC_PROC_IPADDR
If you say Y here, a new entry will be added to each /proc/<pid> directory that contains the IP address of the person using the task. The IP is carried across local TCP and AF_UNIX stream sockets. This information can be useful for IDS/IPSes to perform remote response to a local attack. The entry is readable by only the owner of the process (and root if he has CAP_DAC_OVERRIDE, which can be removed via the RBAC system), and thus does not create privacy concerns.
Denied RWX mmap/mprotect logging
Configuration option: CONFIG_GRKERNSEC_RWXMAP_LOG
If you say Y here, calls to mmap() and mprotect() with explicit usage of PROT_WRITE and PROT_EXEC together will be logged when denied by the PAX_MPROTECT feature. If the sysctl option is enabled, a sysctl option with name rwxmap_logging is created.
ELF text relocations logging (READ HELP)
Configuration option: CONFIG_GRKERNSEC_AUDIT_TEXTREL
If you say Y here, text relocations will be logged with the filename of the offending library or binary. The purpose of the feature is to help Linux distribution developers get rid of libraries and binaries that need text relocations which hinder the future progress of PaX. Only Linux distribution developers should say Y here, and never on a production machine, as this option creates an information leak that could aid an attacker in defeating the randomization of a single memory region. If the sysctl option is enabled, a sysctl option with name audit_textrel is created.
Executable Protections
This menu lets you choose options that affect executable protections
Enforce RLMIT_NPROC on execs
Configuration option: CONFIG_GRKERNSEC_??? (is this option deprecated?)
If you say Y here, users with a resource limit on processes will have the value checked during execve() calls. The current system only checks the system limit during fork() calls. If the sysctl option is enabled, a sysctl option with name execve_limiting is created.
Dmesg(8) restriction
Configuration option: CONFIG_GRKERNSEC_DMESG
If you say Y here, non-root users will not be able to use dmesg(8) to view up to the last 4kb of messages in the kernel's log buffer. If the sysctl option is enabled, a sysctl option with name dmesg is created.
Deter ptrace-based process snooping
Configuration option: CONFIG_GRKERNSEC_HARDEN_PTRACE
If you say Y here, TTY sniffers and other malicious monitoring programs implemented through ptrace will be defeated. If you have been using the RBAC system, this option has already been enabled for several years for all users, with the ability to make fine-grained exceptions.
This option only affects the ability of non-root users to ptrace processes that are not a descendent of the ptracing process. This means that strace ./binary and gdb ./binary will still work, but attaching to arbitrary processes will not. If the sysctl option is enabled, a sysctl option with name harden_ptrace is created.
Require read access to ptrace sensitive binaries
Configuration option: CONFIG_GRKERNSEC_PTRACE_READEXEC
If you say Y here, unprivileged users will not be able to ptrace unreadable binaries. This option is useful in environments that remove the read bits (e.g. file mode 4711) from suid binaries to prevent infoleaking of their contents. This option adds consistency to the use of that file mode, as the binary could normally be read out when run without privileges while ptracing. If the sysctl option is enabled, a sysctl option with name ptrace_readexec is created.
Enforce consistent multithreaded privileges
Configuration option: CONFIG_GRKERNSEC_SETXID
If you say Y here, a change from a root uid to a non-root uid in a multithreaded application will cause the resulting uids, gids, supplementary groups, and capabilities in that thread to be propagated to the other threads of the process. In most cases this is unnecessary, as glibc will emulate this behavior on behalf of the application. Other libcs do not act in the same way, allowing the other threads of the process to continue running with root privileges. If the sysctl option is enabled, a sysctl option with name consistent_setxid is created.
Trusted Path Execution (TPE)
Configuration option: CONFIG_GRKERNSEC_TPE
If you say Y here, you will be able to choose a gid to add to the supplementary groups of users you want to mark as "untrusted". These users will not be able to execute any files that are not in root-owned directories writable only by root. If the sysctl option is enabled, a sysctl option with name tpe is created.
Partially restrict non-root users
Configuration option: CONFIG_GRKERNSEC_TPE_ALL
If you say Y here, all non-root users other than the ones in the group specified in the main TPE option will only be allowed to execute files in directories they own that are not group or world-writable, or in directories owned by root and writable only by root. If the sysctl option is enabled, a sysctl option with name tpe_restrict_all is created.
Invert GID options
Configuration option: CONFIG_GRKERNSEC_TPE_INVERT
If you say Y here, the group you specify in the TPE configuration will decide what group TPE restrictions will be ==disabled== for. This option is useful if you want TPE restrictions to be applied to most users on the system. If the sysctl option is enabled, a sysctl option with name tpe_invert is created. Unlike other sysctl options, this entry will default to no for backward-compatibility.
- GID for trusted/untrusted users (CONFIG_GRKERNSEC_TPE_GID) - If you have selected the "Invert GID option" above, setting this GID determines what group TPE restrictions will be ==disabled== for. If you have not selected the "Invert GID option" above, setting this GID determines what group TPE restrictions will be ==enabled== for. If the sysctl option is enabled, a sysctl option with name tpe_gid is created.
Network Protections
This menu lets you choose options that affect network protections
Larger entropy pools
Configuration option: CONFIG_GRKERNSEC_RANDNET
If you say Y here, the entropy pools used for many features of Linux and grsecurity will be doubled in size. Since several grsecurity features use additional randomness, it is recommended that you say Y here. Saying Y here has a similar effect as modifying /proc/sys/kernel/random/poolsize.
TCP/UDP blackhole
Configuration option: CONFIG_GRKERNSEC_BLACKHOLE
If you say Y here, neither TCP nor ICMP destination-unreachable packets will be sent in response to packets sent to ports for which no associated listening process exists. This feature supports both IPv4 and IPv6 and exempts the loopback interface from blackholing. Enabling this feature makes a host more resilient to DoS attacks and reduces network visibility against scanners.
The blackhole feature as-implemented is equivalent to the FreeBSD blackhole feature, as it prevents RST responses to all packets, not just SYNs. Under most application behavior this causes no problems, but applications (like haproxy) may not close certain connections in a way that cleanly terminates them on the remote end, leaving the remote host in LAST_ACK state. Because of this side-effect and to prevent intentional LAST_ACK DoSes, this feature also adds automatic mitigation against such attacks. The mitigation drastically reduces the amount of time a socket can spend in LAST_ACK state. If you're using haproxy and not all servers it connects to have this option enabled, consider disabling this feature on the haproxy host.
If the sysctl option is enabled, two sysctl options with names ip_blackhole and lastack_retries will be created. While ip_blackhole takes the standard zero/non-zero on/off toggle, lastack_retries uses the same kinds of values as tcp_retries1 and tcp_retries2. The default value of 4 prevents a socket from lasting more than 45 seconds in LAST_ACK state.
Disable TCP Simultaneous Connect
Configuration option: CONFIG_GRKERNSEC_NO_SIMULT_CONNECT
If you say Y here, a feature by Willy Tarreau will be enabled that removes a weakness in Linux's strict implementation of TCP that allows two clients to connect to each other without either entering a listening state. The weakness allows an attacker to easily prevent a client from connecting to a known server provided the source port for the connection is guessed correctly. As the weakness could be used to prevent an antivirus or IPS from fetching updates, or prevent an SSL gateway from fetching a CRL, it should be eliminated by enabling this option. Though Linux is one of few operating systems supporting simultaneous connect, it has no legitimate use in practice and is rarely supported by firewalls.
Socket restrictions
Configuration option: CONFIG_GRKERNSEC_SOCKET
If you say Y here, you will be able to choose from several options. If you assign a GID on your system and add it to the supplementary groups of users you want to restrict socket access to, this patch will perform up to three things, based on the option(s) you choose.
Deny any sockets to group
Configuration option: CONFIG_GRKERNSEC_SOCKET_ALL
If you say Y here, you will be able to choose a GID of whose users will be unable to connect to other hosts from your machine or run server applications from your machine. If the sysctl option is enabled, a sysctl option with name socket_all is created.
- GID to deny all sockets for (CONFIG_GRKERNSEC_SOCKET_ALL_GID) - Here you can choose the GID to disable socket access for. Remember to add the users you want socket access disabled for to the GID specified here. If the sysctl option is enabled, a sysctl option with name socket_all_gid is created.
Deny client sockets to group
Configuration option: CONFIG_GRKERNSEC_SOCKET_CLIENT
If you say Y here, you will be able to choose a GID of whose users will be unable to connect to other hosts from your machine, but will be able to run servers. If this option is enabled, all users in the group you specify will have to use passive mode when initiating ftp transfers from the shell on your machine. If the sysctl option is enabled, a sysctl option with name socket_client is created.
- GID to deny client sockets for (CONFIG_GRKERNSEC_SOCKET_CLIENT_GID) - Here you can choose the GID to disable client socket access for. Remember to add the users you want client socket access disabled for to the GID specified here. If the sysctl option is enabled, a sysctl option with name socket_client_gid is created.
Deny server sockets to group
Configuration option: CONFIG_GRKERNSEC_SOCKET_SERVER
If you say Y here, you will be able to choose a GID of whose users will be unable to run server applications from your machine. If the sysctl option is enabled, a sysctl option with name socket_server is created.
- GID to deny server sockets for (CONFIG_GRKERNSEC_SOCKET_SERVER_GID) - Here you can choose the GID to disable socket access for. Remember to add the users you want server socket access disabled for to the GID specified here. If the sysctl option is enabled, a sysctl option with name socket_server_gid is created.
Sysctl support
This menu lets you choose whether to enable or disable the sysctl support of grsecurity
Sysctl support
Configuration option: CONFIG_GRKERNSEC_SYSCTL
If you say Y here, you will be able to change the options that grsecurity runs with at bootup, without having to recompile your kernel. You can echo values to files in /proc/sys/kernel/grsecurity to enable (1) or disable (0) various features. All the sysctl entries are mutable until the grsec_lock entry is set to a non-zero value. All features enabled in the kernel configuration are disabled at boot if you do not say Y to the "Turn on features by default" option. All options should be set at startup, and the grsec_lock entry should be set to a non-zero value after all the options are set. ==THIS IS EXTREMELY IMPORTANT.==
Extra sysctl support for distro makers
Configuration option: CONFIG_GRKERNSEC_SYSCTL_DISTRO
If you say Y here, additional sysctl options will be created for features that affect processes running as root. Therefore, it is critical when using this option that the grsec_lock entry be enabled after boot. Only distros with prebuilt kernel packages with this option enabled that can ensure grsec_lock is enabled after boot should use this option. ==Failure to set grsec_lock after boot makes all grsec features this option covers useless==
Currently this option creates the following sysctl entries: "Disable Privileged I/O": disable_priv_io
Turn on features by default
Configuration option: CONFIG_GRKERNSEC_SYSCTL_ON
If you say Y here, instead of having all features enabled in the kernel configuration disabled at boot time, the features will be enabled at boot time. It is recommended you say Y here unless there is some reason you would want all sysctl-tunable features to be disabled by default. As mentioned elsewhere, it is important to enable the grsec_lock entry once you have finished modifying the sysctl entries.
Logging Options
This menu lets you choose logging options
Seconds in between log messages (minimum)
Configuration option: CONFIG_GRKERNSEC_FLOODTIME
This options allows you to enforce the number of seconds between grsecurity log messages. The default should be suitable for most people, however, if you choose to change it, choose a value small enough to allow informative logs to be produced, but large enough to prevent flooding.
Number of messages in a burst (maximum)
Configuration option: CONFIG_GRKERNSEC_FLOODBURST
This option allows you to choose the maximum number of messages allowed within the flood time interval you chose in a separate option, The default should be suitable for most people, however if you find that many of your logs are being interpreted as flooding, you may want to raise this value.
PaX Kernel Configuration Options
Configuration option: CONFIG_PAX
PaX Control
This menu lets you choose core PaX features
Support soft mode
Configuration option: CONFIG_PAX_SOFTMODE
Enabling this option will allow you to run PaX in soft mode, that is, PaX features will not be enforced by default, only on executables marked explicitly. You must also enable PT_PAX_FLAGS support as it is the only way to mark executables for soft mode use. Soft mode can be activated by using the "pax_softmode=1" kernel command line option on boot. Furthermore you can control various PaX features at runtime via the entries in /proc/sys/kernel/pax.
Use legacy ELF header marking
Configuration option: CONFIG_PAX_EI_PAX
Enabling this option will allow you to control PaX features on a per executable basis via the "chpax" utility available at http://pax.grsecurity.net/. The control flags will be read from an otherwise reserved part of the ELF header. This marking has numerous drawbacks (no support for soft-mode, toolchain does not know about the non-standard use of the ELF header) therefore it has been deprecated in favour of PT_PAX_FLAGS.
If you have applications not marked by the PT_PAX_FLAGS ELF program header then you ==MUST== enable this option. Othwerwise they will not get any protection.
Note that if you enable PT_PAX_FLAGS marking support as well, the PT_PAX_FLAG marks will override the legacy EI_PAX marks.
Use ELF program header marking
Configuration option: CONFIG_PAX_PT_PAX_FLAGS
Enabling this option will alllow you to control PaX features on a per executable basis via the "paxctl" utility available at http://pax.grsecurity.net/. The control flags will be read from a PaX specific ELF program header (PT_PAX_FLAGS). This marking has the benefits of supporting both soft mode and being fully integrated into the toolchain (the binutils patch is available from [8]).
If you have applications not marked by the PT_PAX_FLAGS ELF program header then you MUST enable the EI_PAX marking support. Othwerwise they will not get any protection.
Note that if you enable the legacy EI_PAX marking support as well, the EI_PAX marks will overridden by the PT_PAX_FLAG marks.
Use filesystem extended attributes marking
Configuration option: CONFIG_PAX_XATTR_PAX_FLAGS
Enabling this option will allow you to control PaX features on a per executable basis via the "setfattr" utility. The control flags will be read from the user.pax.flags extended attribute of the file. This marking has the benefit of supporting binary-only applications that self-check themselves (e.g., skype) and would not tolerate chpax/paxctl changes. The main drawback is that extended attributes are not supported by some filesystems (e.g., isofs, udf, vfat) so copying files through such filesystems will lose the extended attributes and these PaX markings. Note that if you enable the legacy EI_PAX marking support as well, the EI_PAX marks will be overridden by the XATTR_PAX_FLAGS marks. If you enable both PT_PAX_FLAGS and XATTR_PAX_FLAGS support then you must make sure that the marks are the same if a binary has both marks. If you enable none of the marking options then all applications will run with PaX enabled on them by default.
MAC system integration
Configuration option: CONFIG_PAX_NO_ACL_FLAGS | CONFIG_PAX_HAVE_ACL_FLAGS | CONFIG_PAX_HOOK_ACL_FLAGS
Mandatory Access Control systems have the option of controlling PaX flags on a per executable basis, choose the method supported by your particular system.
- none: if your MAC system does not interact with PaX,
- direct: if your MAC system defines pax_set_flags() itself,
- hook: if your MAC system uses the pax_set_flags_func callback.
NOTE: this option is for developers/integrators only
Non-executable pages
This menu lets you choose PaX settings that enforce non-executable memory pages
Enforce non-executable pages
Configuration option: CONFIG_PAX_NOEXEC
By design some architectures do not allow for protecting memory pages against execution or even if they do, Linux does not make use of this feature. In practice this means that if a page is readable (such as the stack or heap) it is also executable.
There is a well known exploit technique that makes use of this fact and a common programming mistake where an attacker can introduce code of his choice somewhere in the attacked program's memory (typically the stack or heap) and then execute it.
If the attacked program was running with different (typically higher) privileges that of the attacker, then he can elevate his own privilege level (e.g. get a root shell, write to files for which he does not have write access to, etc.).
Paging based non-executable pages
Configuration option: CONFIG_PAX_PAGEEXEC
This implementation is based on the paging feature of the CPU. On i386 without hardware non-executable bit support there is a variable but usually low performance impact, however on Intel's P4 core based CPUs it is very high so you should not enable this for kernels meant to be used on such CPUs.
On alpha, avr32, ia64, parisc, sparc, sparc64, x86_64 and i386 with hardware non-executable bit support there is no performance impact, on ppc the impact is negligible.
Note that several architectures require various emulations due to badly designed userland ABIs, this will cause a performance impact but will disappear as soon as userland is fixed (e.g., ppc users can make use of the secure-plt feature found in binutils).
Segmentation based non-executable pages
Configuration option: CONFIG_PAX_SEGMEXEC (is this option deprecated?)
This implementation is based on the segmentation feature of the CPU and has a very small performance impact, however applications will be limited to a 1.5 GB address space instead of the normal 3 GB.
Emulate trampolines
Configuration option: CONFIG_PAX_EMUTRAMP
There are some programs and libraries that for one reason or another attempt to execute special small code snippets from the non-executable pages. Most notably examples are the signal handler return code generated by the kernel itself and the GCC trampolines.
If you enabled CONFIG_PAX_PAGEEXEC or CONFIG_PAX_SEGMEXEC then such programs will no longer work under your kernel.
As a remedy you can say Y here and use thr chpax or paxctl utilities to enable trampoline emulation for the affected programs yet still have the protection provided by the non-executable pages.
On parisc and ppc you MUST enable this options and EMUSIGRT as well, otherwise you system will not even boot.
NOTE: Enabling this feature may open up a loophole in the protection provided by non-executable pages that an attacker could abuse. Therefore the best solutions is to not have any files on your system that would require this option. This can be achieved by not using libc5 (which relies on the kernel signal handler return code) and not using or rewriting programs that make use of the nested function implementation of GCC. Skilled users can just fix GCC itself so that it implements nested function calls in a way that does not interfere with PaX.
Restrict mprotect()
Configuration option: CONFIG_PAX_MPROTECT
Enabling this option will prevent programs from:
- changing the executable status of memory pages that were not originally created as executable
- making read-only executable pages writable again
- creating executable pages from anonymous memory
- making read-only-after-relocations (RELRO) data pages writable again.
You should say Y here to complete the protection provided by the enforcement of non-executable pages.
NOTE: You can use the chpax or paxctl utilities to control this feature on a per file basis.
Use legacy/compat protection demoting
Configuration option: CONFIG_PAX_MPROTECT_COMPAT
The current implementation of PAX_MPROTECT denies RWX allocations/mprotects by sending the proper error code to the application. For some broken userland, this can cause problems with Python or other applications. The current implementation however allows for applications like clamav to detect if JIT compilation/execution is allowed and to fall back gracefully to an interpreter-based mode if it does not. While we encourage everyone to use the current implementation as-is and push upstream to fix broken userland (note that the RWX logging option can assist with this), in some environments this may not be possible. Having to disable MPROTECT completely on certain binaries reduces the security benefit of PaX, so this option is provided for those environments to revert to the old behavior.
Allow ELF text relocations
Configuration option: CONFIG_PAX_ELFRELOCS
Non-executable pages and mprotect() restrictions are effective in preventing the introduction of new executable code into an attacked task's address space. There remain only two venues for this kind of attack: if the attacker can execute already existing code in the attacked task then he can either have it create and mmap() a file containing his code or have it mmap() an already existing ELF library that does not have position independent code in it and use mprotect() on it to make it writable and copy his code there. While protecting against the former approach is beyond PaX, the latter can be prevented by having only PIC ELF libraries on one's system (which do not need to relocate their code). If you are sure this is your case, as is the case with all modern Linux distributions, then leave this option disabled. You should say 'n' here.
Enforce non-executable kernel pages
Configuration option: CONFIG_PAX_KERNEXEC
This is the kernel land equivalent of PAGEEXEC and MPROTECT, that is, enabling this option will make it harder to inject and execute "foreign" code in kernel memory itself.
Address Space Layout Randomization
This menu lets you choose features that affect the ASLR
Address Space Layout Randomization
Configuration option: CONFIG_PAX_ASLR
Many if not most exploit techniques rely on the knowledge of certain addresses in the attacked program. The following options will allow the kernel to apply a certain amount of randomization to specific parts of the program thereby forcing an attacker to guess them in most cases. Any failed guess will most likely crash the attacked program which allow the kernel to detect such attempts and react on them. PaX itself provides no reaction mechanism, instead it is strongly encouraged that you make use of Nergal's segvguard (ftp://ftp.pl.openwall.com/misc/segvguard/) or grsecurity's (http://grsecurity.net/) built-in crash-detection features or develop one yourself.
By saying Y here you can choose to randomize the following areas:
- top of the task's kernel stack
- top if the task's userland stack
- base address for mmap() requests that do not specify one (this includes all libraries)
- base address of the main executable
It is strongly recommended to say Y here as address space layout randomization has negligible impact on performance yet it provides a very effective protection.
NOTE: You can use the chpax or paxctl utilities to control this feature on a per file basis.
Randomize kernel stack base
Configuration option: CONFIG_PAX_RANDKSTACK
By saying Y here the kernel will randomize every task's kernel stack on every system call. This will not only force an attacker to guess it but also prevent him from making use of possible leaked information about it.
Since the kernel stack is a rather scarce resource, randomization may cause unexpected overflows, therefore you should very carefully test your system. Note that once enabled in the kernel configuration, this feature cannot be disabled on a per file basis.
Randomize user stack base
Configuration option: CONFIG_PAX_RANDUSTACK
By saying Y here the kernel will randomize every task's userland stack. The randomization is done in two steps where the second one may apply a big amount of shift to the top of the stack and cause problems for programs that want to use lots of memory (more than 2.5 GB if SEGMEXEC is not active, or 1.25 GB when it is). For this reason the second step can be controlled by chapx or paxctl on a per file basis.
Randomize mmap() base
Configuration option: CONFIG_PAX_RANDMMAP
By saying Y here the kernel will use a randomized base address for mmap() requests that do not specify one themselves. As a result all dynamically loaded libraries will appear at random addresses and therefore be harder to exploit by a technique where an attacker attempts to execute library code for his purposes (e.g. spawn a shell from an exploited program that is running at an elevated privilege level).
Furthermore, if a program is relinked as a dynamic ELF file, its base address will be randomized as well, completing the fill randomization of the address space layout. Attacking such programs becomes a guess game. You can find an example of doing this at http://pax.grsecurity.net/et_dyn.tar.gz and practical samples at http://grsecurity.net/grsec-gcc-specs.tar.gz.
NOTE: You can use the chpax or paxctl utilities to control this feature on a per file basis.
Miscellaneous hardening features
This menu lets you choose miscellaneous hardening features of PaX
Sanitize all freed memory
Configuration option: CONFIG_PAX_MEMORY_SANITIZE
By saying Y here the kernel will erase memory pages as soon as they are freed. This is turn reduces the lifetime of data stored in the pages, making it less likely that sensitive information such as passwords, cryptographic secrets, etc. stay in memory for too long.
This is especially useful for programs whose runtime is short, long lived processes and the kernel itself benefit from this as long as they operate on whole memory pages and ensure time freeing of pages that may hold sensitive information.
The tradeoff is performance impact, on a single CPU system kernel compilation sees a 3% slowdown, other systems and workloads may vary and you are advised to test this feature on your expected workload before deploying it.
Note that this feature does not protect data stored in live pages, e.g., process memory swapped to disk may there for a long time.
Sanitize kernel stack
Configuration option: CONFIG_PAX_MEMORY_STACKLEAK
By saying Y here the kernel will erase the kernel stack before it returns from a system call. This in turn reduces the information that a kernel stack leak bug can reveal.
Note that such a bug can still leak information that was put on the stack by the current system call (the one eventually triggering the bug) but traces of earlier system calls on the kernel stack cannot leak anymore.
The tradeoff is performance impact, on a single CPU system kernel compilation sees a 1% slowdown, other systems and workloads may vary and you are advised to test this feature on your expected workload before deploying it.
Note: full support for this feature requires gcc with plugin support so make sure your compiler is at least gcc 4.5.0 (cross compilation is not supported). Using older gcc versions means that functions with large enough stack frames may leave uninitialized memory behind that may be exposed to a later syscall leaking the stack.
Prevent invalid userland pointer dereferences
Configuration option: CONFIG_PAX_MEMORY_UDEREF
By saying Y here the kernel will be prevented from dereferencing userland pointers in contexts where the kernel expects only kernel pointers. This is both a useful runtime debugging feature and a security measure that prevents exploiting a class of kernel bugs.
The tradeoff is that some virtualization solutions may experience a huge slowdown and therefore you should not enable this feature for kernels meant to run in such environments. Whether a given VM solutions is affected or not is best determined by simply trying it out, the performance impact will be obvious right on boot as this mechanism engages from very early on. A good rule of thumb is that VMs running on CPUs without hardware virtualization support (i.e., the majority of IA-32 CPUs) will likely experience the slowdown.
Prevent various kernel object reference counter overflows
Configuration option: CONFIG_PAX_REFCOUNT
By saying Y here the kernel will detect and prevent overflowing various (but not all) kinds of object reference counters. Such overflows can normally occur due to bugs only and are often, if not always, exploitable.
The tradeoff is that data structures protected by an overflowed refcount will never be freed and therefore will leak memory. Note that this leak also happens even without this protection but in that case the overflow can eventually trigger the freeing of the data structure while it is still being used elsewhere, resulting in the exploitable situation that this feature prevents.
Since this has a negligible performance impact, you should enable this feature.
Automatically constify eligible structures
Configuration option: CONFIG_PAX_CONSTIFY_PLUGIN
By saying Y here the compiler will automatically constify a class of types that contain only function pointers. This reduces the kernel's attack surface and also produces a better memory layout.
Note that the implementation requires a gcc with plugin support, i.e., gcc 4.5 or newer. You may need to install the supporting headers explicitly in addition to the normal gcc package.
Note that if some code really has to modify constified variables then the source code will have to be patched to allow it. Examples can be found in PaX itself (the no_const attribute) and for some out-of-tree modules at http://www.grsecurity.net/~paxguy1/ .
Harden heap object copies between kernel and userland
Configuration option: CONFIG_PAX_USERCOPY
By saying Y here the kernel will enforce the size of heap objects when they are copied in either direction between the kernel and userland, even if only a part of the heap object is copied.
Specifically, this checking prevents information leaking from the kernel heap during kernel to userland copies (if the kernel heap object is otherwise fully initialized) and prevents kernel heap overflows during userland to kernel copies.
Note that the current implementation provides the strictest checks for the SLUB allocator.
Prevent various integer overflows in function size parameters
Configuration option: CONFIG_PAX_SIZE_OVERFLOW
By saying Y here the kernel recomputes expressions of function arguments marked by a size_overflow attribute with double integer precision (DImode/TImode for 32/64 bit integer types).
The recomputed argument is checked against TYPE_MAX and an event is logged on overflow and the triggering process is killed.
Homepage: http://www.grsecurity.net/~ephox/overflow_plugin/
Note that the implementation requires a gcc with plugin support, i.e., gcc 4.5 or newer. You may need to install the supporting headers explicitly in addition to the normal gcc package.
Generate some entropy during boot
Configuration option: CONFIG_PAX_LATENT_ENTROPY
By saying Y here the kernel will instrument early boot code to extract some entropy from both original and artificially created program state. This will help especially embedded systems where there is little 'natural' source of entropy normally. The cost is some slowdown of the boot process.
When pax_extra_latent_entropy is passed on the kernel command line, entropy will be extracted from up to the first 4GB of RAM while the runtime memory allocator is being initialized. This costs even more slowdown of the boot process.
Note that the implementation requires a gcc with plugin support, i.e., gcc 4.5 or newer. You may need to install the supporting headers explicitly in addition to the normal gcc package.
Note that entropy extracted this way is not cryptographically secure!
Appendix Tables
| Mode | Meaning |
|---|---|
| u | This role is a user role. That is, the role name must be an existing user on the system. |
| g | This role is a group role. That is, the role name must be an existing group on the system. |
| s | This role is a special role, meaning it does not belong to a user or group and does not require an enforced secure policy base to be included in the ruleset. |
| A | This role is an administrative role, thus it has special privileges that normal roles do not have. In particular, this role bypasses the additional ptrace and library loading restrictions. |
| G | This role can use gradm to authenticate to the kernel. A policy for gradm will automatically be added to the role. |
| l | This role has learning enabled. |
| N | This role does not require authentication. To access this role, use 'gradm -n <rolename>'. |
| P | This role uses Pluggable Authentication Modules (PAM) for authentication. |
| T | This role has Trusted Path Execution (TPE) enabled. |
| R | The role is persistence. When shell/session in which authorization was done is terminated, spawned processes won't be dropped to non-special role. Do NOT use this flag with any role that does anything but shut the system down. |
role_transitions
Role transitions specify which special roles a given role is allowed to authenticate to. This applies to special roles that do not require password authentication as well. If a user tries to authenticate to a role that is not within his transition table, he will receive a permission denied error. A common mistake when creating a new special role is forgetting to create a role_transitions rule for the role that will transition to the special role, which a user confuses with having entered an incorrect password. The role_transitions rule is added below the declaration of a role, but before any subject declaration.
Usage:
role_transitions <special role 1> <special role 2> ... <special role n>
Example:
role person u role_transitions www_admin dns_admin subject / ...
role_allow_ip
This rule restricts the use of a role to a list of IPs. If a user is on the system who would normally get the rule does not belong to the specified list of IPs, the system falls back through its method of determining a role for the user (checking for an applicable group role then falling back to the default role). This rule can be specified multiple times for a role. Like role_transitions, it should be added below the declaration of a role, but before any subject declaration.
Usage:
role_allow_ip <IP>/<optional netmask>
Example:
role person u role_allow_ip 192.168.1.0/24 subject / ...
role_umask
This rule ensures that a user cannot accidentally create a file that others can read (a confidentiality issue). Like previous role attributes, it should be added below the declaration of a role, but before any subject declaration.
Usage:
role_umask <mask>
Example:
role person u role_umask 077 subject / ...
| Mode | Meaning |
|---|---|
| a | Allow this process to talk to the /dev/grsec device. |
| b | Enable process accounting for processes in this subject. |
| d | Protect the /proc/<pid>/fd, /proc/<pid>/mem, /proc/<pid>/cmdline, and /proc/<pid>/environ entries for processes in this subject, |
| h | This process is hidden and only viewable by processes with the v mode. |
| i | Enable inheritance-based learning, causing all accesses of this subject and anything it executes to be logged as originating from this subject. The policy generated from this learning will have the inheritance flag added to every file executed from this subject. |
| k | This process can kill protected processes. |
| l | Enables learning mode for this process. |
| o | Override ACL inheritance for this process. |
| p | This process is protected; it can only be killed by processes with the k mode, or by processes within the same subject. |
| r | Relax ptrace restrictions (allows ptracing of processes other than one's own children). |
| s | (In v2.2.1 and above): Enable AT_SECURE when entering this subject. This enables the same environment sanitization that occurs in glibc upon execution of a suid binary. |
| t | Allow ptracing of any process (do not use unless necessary, allows ptrace to cross subject boundaries). This flag also allows a process to use CLONE_FS and execute a binary that causes a subject change. |
| v | This process can view hidden processes. |
| 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. |
user/group transitions
You may specify what users and groups a given subject can transition to. This can be done on an inclusive or exclusive basis. Omitting these rules allows a subject with proper privilege granted by capabilities to transition to any user/group.
Usage:
user_transition_allow <user 1> <user 2> ... <user n> user_transition_deny <protected user 1> <protected user 2> ... <protected user n> group_transition_allow <group 1> <group 2> ... <group n> group_transition_deny <protected group 1> <protected group 2> ... <protected group n>
Example:
role person u subject /bin/su user_transition_allow root spender group_transition_allow root spender ... role person u subject /bin/su user_transition_deny specialuser user_transition_deny specialgroup ...
ip_override
It is possible to force a given subject to bind to a particular IP address on the machine. This can be useful for some sandboxed environments, to ensure the source IP used from the sandbox is one determined by RBAC policy. To restrict what other source IP addresses a subject can bind to, use the normal IP ACL support of the RBAC system. This option is solely used to override an application's use of INADDR_ANY when connecting out or binding to a local port.
Usage:
ip_override <IP>
Example:
role person u subject / ip_override 192.168.0.1 ...
| Mode | Meaning |
|---|---|
| r | This object can be opened for reading. |
| w | This object can be opened for writing or appending. |
| a | This object can be opened for appending. |
| c | Allow creation of the file/directory. |
| x | This object can be executed (or mmap’d with PROT_EXEC into a task). |
| d | Allow deletion of the file/directory. |
| h | This object is hidden. |
| t | This object can be ptraced, but cannot modify the running task. This is referred to as a 'read-only ptrace'. |
| p | Reject all ptraces to this object. |
| i | This mode only applies to binaries. When the object is executed, it inherits the ACL of the subject in which it was contained. |
| m | Allow creation of setuid/setgid files/directories and modification of files/directories to be setuid/setgid. |
| 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. |
| none | Lack of any of the above modes implies "find" access to the object. The object can be listed and have its ownership, size, etc. information obtained, but cannot be read or modified. |
| Mode | Meaning |
|---|---|
| M | Audit the setuid/setgid creation/modification. |
| C | Audit the creation. |
| D | Audit the deletion. |
| L | Audit link creation. |
| R | Audit successful reads to this object. |
| W | Audit successful writes to this object. |
| X | Audit successful execs of this object. |
| A | Audit successful appends to this object. |
| F | Audit successful finds of this object. |
| I | Audit successful ACL inherits of this object. |
| Mode | Meaning |
|---|---|
| s | Logs will be suppressed for denied access to this object. |
This table lists all PaX flags that can be forced on or off in the policy, regardless of the flags on the binary, by using + or - before the flag name.
| Flag | Description | Details |
|---|---|---|
| PAX_SEGMEXEC | PaX SEGMEXEC | http://pax.grsecurity.net/docs/segmexec.txt |
| PAX_PAGEEXEC | PaX PAGEEXEC | http://pax.grsecurity.net/docs/pageexec.txt |
| PAX_MPROTECT | PaX MPROTECT | http://pax.grsecurity.net/docs/mprotect.txt |
| PAX_RANDMMAP | PaX ASLR | http://pax.grsecurity.net/docs/randmmap.txt |
| PAX_EMUTRAMP | PaX Trampoline emulation | http://pax.grsecurity.net/docs/emutramp.txt |
This table lists all standard Linux capabilities and one special capability related to grsecurity. With capabilities, the system is divided into logical groups that may be individually granted to, or removed from, different processes. See [[../../The RBAC System#Capability Restrictions|Capability Restrictions]] for more information.
| Capability Name | Meaning |
|---|---|
| CAP_ALL | CAP_ALL is not a real capability, but was coded into gradm to represent all capabilities. Therefore to denote dropping of all capabilities, but CAP_SETUID, -CAP_ALL and +CAP_SETUID would be used. |
| CAP_CHOWN | In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this overrides the restriction of changing file ownership and group ownership. |
| CAP_DAC_OVERRIDE | Override all DAC access, including ACL execute access if [_POSIX_ACL] is defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. |
| CAP_DAC_READ_SEARCH | Overrides all DAC restrictions, regarding read and search on files and directories, including ACL restrictions, if [_POSIX_ACL] is defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. |
| CAP_FOWNER | Overrides all restrictions about allowed operations on files, where file owner ID must be equal to the user ID, except where CAP_FSETID is applicable. It doesn't override MAC and DAC restrictions. |
| CAP_FSETID | Overrides the following restrictions, that the effective user ID shall match the file owner ID, when setting the S_ISUID and S_ISGID bits on that file; that the effective group ID (or one of the supplementary group IDs) shall match the file owner ID when setting the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are cleared on successful return from chown(2) (not implemented). |
| CAP_KILL | Overrides the restriction, that the real or effective user ID of a process, sending a signal, must match the real or effective user ID of the process receiving the signal. |
| CAP_SETGID |
|
| CAP_SETUID |
|
| CAP_SETPCAP | Without VFS support for capabilities:
|
| CAP_LINUX_IMMUTABLE | Allow modification of S_IMMUTABLE and S_APPEND file attributes. |
| CAP_NET_BIND_SERVICE |
|
| CAP_NET_BROADCAST | Allow broadcasting, listen to multicast. |
| CAP_NET_ADMIN |
|
| CAP_NET_RAW |
|
| CAP_IPC_LOCK |
|
| CAP_IPC_OWNER | Override IPC ownership checks. |
| CAP_SYS_MODULE | Insert and remove kernel modules – modify kernel without limit. |
| CAP_SYS_RAWIO |
|
| CAP_SYS_CHROOT | Allow use of chroot(). |
| CAP_SYS_PTRACE | Allow ptrace() of any process. |
| CAP_SYS_PACCT | Allow configuration of process accounting. |
| CAP_SYS_ADMIN |
|
| CAP_SYS_BOOT |
|
| CAP_SYS_NICE |
|
| CAP_SYS_RESOURCE |
|
| CAP_SYS_TIME |
|
| CAP_SYS_TTY_CONFIG |
|
| CAP_MKNOD | Allow the privileged aspects of mknod(). |
| CAP_LEASE | Allow taking of leases on files. |
| CAP_AUDIT_WRITE | Allow emitting auditing messages. |
| CAP_AUDIT_CONTROL | Allow administration of the kernel's auditing system. |
| CAP_SETFCAP | Allow the setting of file capabilities. |
| CAP_MAC_OVERRIDE | Override MAC access. The base kernel enforces no MAC policy. An LSM may enforce a MAC policy and if it does and it chooses to implement capability based overrides of that policy, this is the capability it should use to do so. |
| CAP_MAC_ADMIN | Allow MAC configuration or state changes. The base kernel requires no MAC configuration. An LSM may enforce a MAC policy, and if it does and it chooses to implement capability based checks on modifications to that policy or the data required to maintain it, this is the capability it should use to do so. |
Introduction
This table lists all system resources that can be restricted by grsecurity. Grsecurity supports all the resources Linux supports, but uses slightly different names for them: The RLIMIT prefix has been replaced with RES. For example, the Linux resource RLIMIT_CPU is called RES_CPU in grsecurity.
For detailed information about resources in Linux, see the man page of getrlimit.
Syntax and Examples
A single resource rule follows the following syntax:
<resource name> <soft limit> <hard limit>
An example of this syntax would be:
RES_FSIZE 5K 5K
This would prevent the process from creating files that are bigger than 5 Kilobytes.
Using unlimited is valid for both the soft limit and the hard limit, to denote an unlimited resource. Note that by omitting a resource restriction, the system's default limits are used (as set by PAM or the application itself). If a resource is specified within the policy, the specific limits override the system's default limits for the given subject.
A number of suffixes are allowed when specifying resource limits. They are described below.
| Suffix | Meaning |
|---|---|
| s | Amount of time in seconds. |
| m | Amount of time in minutes. |
| h | Amount of time in hours. |
| d | Amount of time in days. |
| K | Size in kilobytes. |
| M | Size in megabytes. |
| G | Size in gigabytes. |
A full list of supported resources is supplied below.
| Resource Name | Meaning |
|---|---|
| RES_AS | The maximum size of the process's virtual memory (address space) in bytes. |
| RES_CORE | Maximum size of core file, in bytes. When 0 no core dump files are created. When non-zero, larger dumps are truncated to this size. |
| RES_CPU | CPU time limit in seconds. |
| RES_DATA | The maximum size of the process's data segment, in bytes (initialized data, uninitialized data, and heap). |
| RES_FSIZE | The maximum size of files, in bytes, that the process may create. |
| RES_LOCKS | A limit on the combined number of flock() locks and fcntl() leases that this process may establish. |
| RES_MEMLOCK | The maximum number of bytes of memory that may be locked into RAM. In effect this limit is rounded down to the nearest multiple of the system page size. |
| RES_MSGQUEUE | Specifies the limit on the number of bytes that can be allocated for POSIX message queues for the real user ID of the calling process |
| RES_NICE | Specifies a ceiling to which the process's nice value can be raised using setpriority(2) or nice(2). |
| RES_NOFILE | Specifies a value one greater than the maximum file descriptor number that can be opened by this process. |
| RES_NPROC | The maximum number of threads that can be created for the real user ID of the calling process. |
| RES_RSS | Specifies the limit (in pages) of the process's resident set (the number of virtual pages resident in RAM). This limit only has effect in Linux 2.4.x, x < 30. |
| RES_RTPRIO | Specifies a ceiling on the real-time priority that may be set for this process using sched_setscheduler(2) and sched_setparam(2). |
| RES_SIGPENDING | Specifies the limit on the number of signals that may be queued for the real user ID of the calling process. Both standard and real-time signals are counted for the purpose of checking this limit. |
| RES_STACK | The maximum size of the process stack, in bytes. |
| RES_RTTIME | Specifies a limit on the amount of CPU time that a process scheduled under a real-time scheduling policy may consume without making a blocking system call. for the purpose of this limit, each time a process makes a blocking system call, the count of its consumed CPU time is reset to zero. The CPU time count is not reset if the process continues trying to use the CPU but is preempted, if its time slice expires, or if it calls sched_yield(2). Upon reaching the soft limit, the process is sent a SIGXCPU signal. If the process catches or ignores this signal and continues consuming CPU time, then SIGXCPU will be generated once each second until the hard limit is reached, at which point the process is sent a SIGKILL signal. The intended use of this limit is to stop a runaway real-time process from locking up the system. |
| RES_CRASH | This is a pseudo-resource interpreted only by the RBAC system. The meaning of soft and hard limits are overridden for this resource. The intent of the resource is to be able to rate-limit bruteforced exploit attempts for a given subject. The soft limit for this resource is the number of times the subject is allowed to crash in ways that suggest an exploitation attempt. The hard limit specifies the amount of time those crashes are allowed to occur in. With a rule like RES_CRASH 3 30m one can limit a privileged binary to three exploit attempts every 10 minutes, deterring bruteforcing attempts. The RBAC system actively responds to bruteforcing attempts that overstep this limit. If the target is a setuid binary, the attacker has all of his/her processes killed and will be unable to log in for the remainder of the configured time. If the target is a forking network daemon, that daemon will be unable to fork additional copies of itself for the remainder of the configured time. |
These tables describe every available option in grsecurity that can be changed at runtime. They are changed using the sysctl interface, or by echoing values to files in /proc/sys/kernel/grsecurity/. The available options vary depending on how grsecurity was configured. See Configuring and Installing grsecurity and Runtime configuration for more information.
To find out what options are available in your system, list the contents of /proc/sys/kernel/grsecurity. If you use the sysctl interface, all of grsecurity's option are prefixed with kernel.grsecurity (e.g. kernel.grsecurity.audit_chdir).
| Option | Description |
|---|---|
| audit_chdir | Log all chdir() calls.
WARNING: This option when enabled may produce a lot of logs. |
| audit_group | Specifies a single group (GID) for auditing. The exec, chdir, (un)mount and ipc logging features will only operate on this group. |
| audit_mount | Log all mounts and unmounts. |
| audit_textrel | Log text relocations with the filename of the offending library or binary. The purpose of the feature is to help Linux distribution developers get rid of libraries and binaries that need text relocations which hinder the future progress of PaX.
WARNING: Only Linux distribution developers should enable this option, and never on a production machine, as this option creates an information leak that could aid an attacker in defeating the randomization of a single memory region. |
| chroot_execlog | Log all executions inside a chroot jail to syslog. This can cause a large amount of logs if certain applications (e.g. djb's daemontools) are installed on the system. |
| exec_logging | Log all execve() calls (since the other exec*() calls are frontends to execve(), all execution will be logged).
WARNING: This option when enabled will produce a LOT of logs, especially on an active system. |
| forkfail_logging | Log all failed fork() attempts. This could suggest a fork bomb, or someone attempting to overstep their process limit. |
| resource_logging | Log all attempts to overstep resource limits with the resource name, the requested size, and the current limit. If the RBAC system is enabled the sysctl value is ignored. |
| signal_logging | Log certain important signals, such as SIGSEGV, which will as a result inform you of when an error in a program occurred, which in some cases could mean a possible exploit attempt. |
| timechange_logging | Log any changes of the system clock. |
| Option | Description |
|---|---|
| chroot_caps | If enabled, the capabilities on all root processes within a chroot jail will be lowered to stop module insertion, raw i/o, system and net admin tasks, rebooting the system, modifying immutable files, modifying IPC owned by another, and changing the system time. This is left an option because it can break some apps. Disable this if your chrooted apps are having problems performing those kinds of tasks. |
| chroot_deny_chmod | If enabled, processes inside a chroot will not be able to chmod or fchmod files to make them have suid or sgid bits. This protects against another published method of breaking a chroot. |
| chroot_deny_chroot | If enabled, processes inside a chroot will not be able to chroot again outside the chroot. This is a widely used method of breaking out of a chroot jail and should not be allowed. |
| chroot_deny_fchdir | If enabled, a well-known method of breaking chroots by fchdir'ing to a file descriptor of the chrooting process that points to a directory outside the filesystem will be stopped. |
| chroot_deny_mknod | If enabled, processes inside a chroot will not be allowed to mknod. The problem with using mknod inside a chroot is that it would allow an attacker to create a device entry that is the same as one on the physical root of your system, which could range from anything from the console device to a device for your harddrive (which they could then use to wipe the drive or steal data). It is recommended that you enable this option, unless you run into software incompatibilities. |
| chroot_deny_mount | If enabled, processes inside a chroot will not be able to mount or remount filesystems. |
| chroot_deny_pivot | If enabled, processes inside a chroot will not be able to use a function called pivot_root() that was introduced in Linux 2.3.41. It works similar to chroot in that it changes the root filesystem. This function could be misused in a chrooted process to attempt to break out of the chroot, and there should not be allowed. |
| chroot_deny_shmat | If enabled, processes inside a chroot will not be able to attach to shared memory segments that were created outside of the chroot jail. It is recommended that you enable this option. |
| chroot_deny_sysctl | If enabled, an attacker in a chroot will not be able to write sysctl entries, either by sysctl(2) or through a /proc interface. It is strongly recommended that you enable this option. |
| chroot_deny_unix | If enabled, processes inside a chroot will not be able to connect to abstract (meaning not belonging to a filesystem) Unix domain sockets that were bound outside of a chroot. It is recommended that you enable this option. |
| chroot_enforce_chdir | If enabled, the current working directory of all newly-chrooted applications will be set to the root directory of the chroot. The man page on chroot(2) states: Note that this call does not change the current working directory, so that '.' can be outside the tree rooted at "/". In particular, the super-user can escape from a "chroot jail" by doing mkdir foo; chroot foo; cd ... It is recommended that you enable this option, since it's not known to break any software. |
| chroot_findtask | If enabled, processes inside a chroot will not be able to kill, send signals with fcntl, ptrace, capget, getpgid, getsid, or view any process outside of the chroot. |
| chroot_restrict_nice | If enabled, processes inside a chroot will not be able to raise the priority of processes in the chroot, or alter the priority of processes outside the chroot. This provides more security than simply removing CAP_SYS_NICE from the process' capability set. |
| Option | Description |
|---|---|
| socket_all | If enabled, the option "socket_all_gid" specifies a GID of whose users will be unable to connect to other hosts from your machine or run server applications from your machine. |
| socket_all_gid | The GID to disable socket access for. Remember to add the users you want socket access disabled for to the GID specified here. |
| socket_client | If enabled, the option "socket_client_gid" specifies a GID of whose users will be unable to connect to other hosts from your machine, but will be able to run servers. If this option is enabled, all users in the group you specify will have to use passive mode when initiating ftp transfers from the shell on your machine. |
| socket_client_gid | The GID to disable client socket access for. Remember to add the users you want client socket access disabled for to the GID specified here. |
| socket_server | If enabled, the option "socket_server_gid" specifies a GID of whose users will be unable to run server applications from your machine. |
| socket_server_gid | The GID to disable socket access for. Remember to add the users you want server socket access disabled for to the GID specified here. |
| ip_blackhole | If enabled, the option "ip_blackhole" turns on the TCP/UDP blackhole feature, preventing RST or ICMP packets from being sent in response to packets sent to ports not being listened on. |
| Option | Description |
|---|---|
| disable_modules | Setting this option to "1" disables module loading. After this option is set, no further writes to it are allowed until the system is rebooted.
This feature is useful if you need the ability to load kernel modules at boot time, but do not want to allow an attacker to load a rootkit kernel module into the system, or remove a loaded kernel module important to system functioning. You should enable the /dev/mem protection feature as well, since rootkits can be inserted into the kernel via other methods than kernel modules. Since an untrusted module could still be loaded by modifying init scripts and rebooting the system, it is also recommended that you enable the RBAC system. |
| dmesg | If enabled, non-root users will not be able to use dmesg(8) to view up to the last 4kb of messages in the kernel's log buffer. |
| execve_limiting | If enabled, users with a resource limit on processes will have the value checked during execve() calls. The current system only checks the system limit during fork() calls. |
| fifo_restrictions | If enabled, users will not be able to write to FIFOs they don't own in world-writable "+t" directories (i.e. /tmp), unless the owner of the FIFO is the same owner of the directory it's held in. |
| grsec_lock | All the sysctl entries are mutable until this option is set to a non-zero value. All options should be set at startup, and this option should be set to a non-zero value after all the options are set. THIS IS EXTREMELY IMPORTANT. |
| harden_ptrace | If enabled, TTY sniffers and other malicious monitoring programs implemented through ptrace will be defeated. If you have been using the RBAC system, this option has already been enabled for several years for all users, with the ability to make fine-grained exceptions. This option only affects the ability of non-root users to ptrace processes that are not a descendent of the ptracing process. This means strace ./binary and gdb ./binary will still work, but attaching to arbitrary processes will not. |
| linking_restrictions | If enabled, /tmp race exploits will be prevented, since users will no longer be able to follow symlinks owned by other users in world-writable "+t" directories (i.e. /tmp), unless the owner of the symlink is the owner of the directory. User will also not be able to hardlink to files they do not own. |
| romount_protect | If enabled, filesystems will be protected in the following ways:
This option acts independently of grsec_lock: once it is set to 1, it cannot be turned off. Therefore, please be mindful of the resulting behavior if this option is enabled in an init script on a read-only filesystem. This feature is mainly intended for secure embedded systems. |
| tpe | Enforce Trusted Patch Execution (TPE). A trusted path/directory is one that is owned by root and writable only by root. See also option "tpe_gid". |
| tpe_invert | If enabled, the group you specify in the TPE configuration will decide what group TPE restrictions will be disabled for. This option is useful if you want TPE restrictions to be applied to most users on the system. Unlike other sysctl options, this entry will default to on for backward-compatibility. |
| tpe_gid | If you have selected the "Invert GID option", setting this GID determines what group TPE restrictions will be disabled for. If you have not selected the "Invert GID option", setting this GID determines what group TPE restrictions will be enabled for. |
| tpe_restrict_all | If enabled, all non-root users will be covered under a weaker TPE restriction. This is separate from, and in addition to, the main TPE options that you have selected elsewhere. Thus, if a "trusted" GID is chosen, this restriction applies to even that GID. Under this restriction, all non-root users will only be allowed to execute files in directories they own that are not group or world-writable, or in directories owned by root and writable only by root. |
Credits and Permissions
Introduction
On this page you will find documentation regarding permissions to use material written by others before this Wikibook was started.
The Original grsecurity Documentation
The original documentation for grsecurity was written by Brad Spengler, the author of grsecurity. This includes the ACL documentation and the grsecurity Quick-Start Guide (PDF).
Permission to Use the Official Documentation
Below is the correspondence between myself (Meev0 (talk)) and Brad Spengler regarding the use of his works in this Wikibook.
Sent at: Mon Apr 20, 2009 5:56 pm
You may publish my answer to the original request (and this request too). You may copy/republish any and all parts of the grsecurity documentation. I don't think I put an explicit license on the documentation, but I consider it to be essentially public domain.
-BradSent at: Mon Apr 20, 2009 5:27 pm
Thanks!I'm making a separate page for the book that will include credits, links to the original documents and a copy of your message where you grant this permission.
Just so that there is no misunderstanding
1) May I publish your answer to my original request?
2) In my request I mentioned wanting to copy "parts" which is very vague. Basically what's needed (IMO) is you clearly stating what parts of the grsecurity documentation can be published under the GNU Free Documentation License. I'm not a copyright lawyer, but I think the clearer the situation the better.I'll try to limit the amount of text I need to copy, as I like writing documentation, but most of technical notes are better left as they are.
- Ville
Sent at: Sat Apr 18, 2009 7:59 pm
Of course, that's fine with me. Thanks again for your work, and hope things get better for you personally.-Brad
Sent at: Sat Apr 18, 2009 5:41 pm
Hi Brad,I wanted to ask about using the Grsecurity QuickStart guides (the quickstart.pdf and the newGradmDoc.pdf) in the Wikibook. As you are the copyright holder of both documents, I need your permission to copy parts from those files. Mainly I would like to copy the ACL documentation, as it would be silly for me to start writing it from scratch. Naturally I would credit you and include a link to the original documents.
Below is a link to the copyright policy of Wikibooks. http://en.wikibooks.org/wiki/Wikibooks:Copyrights
You can reach me by replying to this PM or by email at ***.
- Ville