Demystifying SELinux Part II: Who’s Policy Is It Anyway Dave Quigley SELinux Ninja/Linux Kernel Developer dpquigl@davequigley.com www.davequigley.com/dquigley www.davequigley.com/selinux
Outline The Basics SELinux Fundamentals Identifying Problems Policy Basics ftransferd Policy Development Basics Extras Questions
The Basics
Access Controls determine who/what can access system resources What is Access Control? Access Controls determine who/what can access system resources
What You're Use To Web Content Home Directory Files Sensitive Credit Card Data Dave (Apache) Dave (Firefox)
A “New” Type of Access Controls Web Content TCP Port 80 Sensitive Credit Card Data Database Socket Apache Logs Dave (Apache) Dave (PostgreSQL) Database Files
DEMO: Who’s File is it Anyway? Two services both running as the same user httpd Mysqld A bug in either may allow access to the shared files How do we keep access separate? Assign the services some sort of identifier Create access rules based on these identifiers
What is SELinux? SELinux is a label based security system Every process has a label, every object on the system has a label Files, Directories, network ports … The SELinux policy controls how process labels interact with other labels on the system The kernel enforces the policy rules
apt-get install selinux How do I get SELinux? SELinux isn't a distribution by itself but a security enhancement to Linux that can be enabled by your distribution or vendor (or yourself if you are very motivated) Distribution How to get it RHEL 4+ Default Fedora 2+ Ubuntu apt-get install selinux Debian http://wiki.debian.org/SELinux/Setup Gentoo Hardened Gentoo OpenSUSE 13.1 Basic support
How Do I know if SELinux is on? /usr/sbin/sestatus [user@localhost ~]# sestatus SELinux status: enabled SELinuxfs mount: /selinux Current mode: enforcing Mode from config file: enforcing Policy version: 24 Policy from config file: targeted /usr/sbin/getenforce [user@localhost ~]# getenforce Enforcing
Enforcing vs Permissive Perform access checks and enforce failures Reports each failure in audit logs Permissive Perform access checks but does not enforce denials Reports access failures in audit logs only once per type of failure Does not provide real protection
Setting Enforcing Mode Two ways to set at boot-time: enforcing=0 or enforcing=1 on kernel command line (grub.conf) SELINUX=permissive or SELINUX=enforcing in /etc/selinux/config To set at runtime: /usr/sbin/setenforce 0 | 1 | Enforcing | Permissive echo 0 > /selinux/enforce
LAB: Set Enforcing Mode Check the current mode of your machine What does it say? Set the current mode to permissive Check the status again Set the mode back to enforcing This is important to ensure later labs work
All information needed for SELinux to make an access control decision What is a Label? -rw-r--r-- root root system_u:object_r:etc_t:s0 /etc/passwd DAC Components Security Label system_u:object_r:etc_t:s0 User Role Type MLS All information needed for SELinux to make an access control decision
How do I see Labels? Files ls -Z Processes ps -Z, pstree -Z Ports netstat -Z, semanage ports -l
LAB: Viewing Contexts Use ls -Z to look around common system directories. Use ps -Z to look at the contexts of running processes. Look at network socket labeling with netstat -Z
Setting File Contexts Determining Labels matchpathcon Setting Labels chcon semanage fcontext Restoring Labels restorecon fixfiles
LAB: Setting File Contexts Try using some of the commands we just saw. Try setting labels with chcon and then restoring the label with restorecon Identify the context for a path with matchpathcon Look at network socket labeling with netstat -Z
SELinux Fundamentals
SELinux Security Models The SELinux security server implements 3 security models. Type Enforcement(TE) Role-Based Access Control (RBAC) Multi-Level Security (MLS).
Type Enforcement (TE) Core security model of SELinux. Supports binding permissions to specific programs/code. Supports least privilege, integrity, and assured invocation. No rigid model - driven by customizable policy configuration.
TE: Domains Each subject (e.g. process, applet) is labeled with a “domain”. Simple string tag identifying the subject from a security point of view. Subjects that should have the same permissions to the same objects can share same domain. Examples: user_t (unprivileged user shell), passwd_t (passwd process)
TE: Types Each object (e.g. file, socket) is labeled with a “type”. Simple string tag identifying the object from a security point of view. Objects that should be accessible in the same way by the same subjects can share the same type. Examples: passwd_exec_t (/bin/passwd), shadow_t (/etc/shadow).
TE: Domains vs. Types Domains and types are both equivalence classes. A domain might be used as an object, e.g. recipient of a signal or IPC /proc/pid files A domain is just a kind of type, one that can be applied to processes. SELinux uses “type” for both.
Object Classes Identify the kind of object being accessed. Class name Description process A process file A regular file dir A directory chr_file A character device blk_file A block device tcp_socket A TCP socket rawip_socket A raw IP socket capability A Linux capability
Permissions Identify the operation being performed. Defined on a per-class basis. File permissions Socket permissions create read write rename bind unlink connect execute accept
Access Vectors A set of permissions. Represented as a bitmap. Computed by the security server. Cached by the Access Vector Cache (AVC). Used to represent: What is allowed What is to be audited
Running /bin/passwd passwd process passwd_t transition user shell user_t entrypoint read write execute /bin/passwd passwd_exec_t /etc/shadow shadow_t
Domain Transition Example Only authorized domains (e.g. passwd_t) can write to shadow_t. passwd_t can only be entered by running a program labeled with passwd_exec_t. passwd_t cannot execute any other programs. Only authorized domains (e.g. user_t) can transition to passwd_t. passwd_t can only read and write authorized types (e.g. shadow_t).
LAB: Observe Domain Transition (passwd) Start two terminals and view their contexts (id -Z) What is the terminals domain? Run passwd in one terminal In the second terminal ps -AZ | grep passwd What domain is passwd running in? Then run pstree -Z | less and find passwd What domain is passwd's parent running in?
Role Based Access Control (RBAC) Each process is labeled with a role. Object security contexts just use “object_r”. Organizes TE domains into roles. Each role authorized for certain domain types. role staff_r types { staff_t passwd_t }; Each SELinux user authorized for certain roles. user staff_u roles { staff_r system_r };
Multi-Level Security Each process and object is labeled with a single level or a range (low-high). A level consists of a sensitivity and category set. Configurable constraints define how different levels may interact, using the dominance relation. Red Hat uses it for “Multi-Category Security” (MCS), leveraged by sandbox and SVirt. Traditional MLS via separate -mls policy.
Identifying Problems
How to tell if something is wrong? Logged to /var/log/messages if no auditd or during early boot before auditd. grep avc /var/log/messages Logged to /var/log/audit/audit.log if running auditd. /sbin/ausearch -mAVC,SELINUX_ERR -i Notification via setroubleshoot if running. /var/log/audit/audit.log, desktop pop-up
Example Permission Denial type=AVC msg=audit(09/07/2010 14:06:38.240:54981) : avc: denied { read } for pid=4866 comm=bash name=.bash_history dev=dm-0 ino=138 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:admin_home_t:s0 tclass=file An attempt by a bash process to read a .bash_history file was denied, where the bash process was running in the httpd_t domain and the .bash_history file was labeled with admin_home_t (i.e. under /root).
Silent Denials Permission denials may be silenced by dontaudit rules in the policy. Used to avoid filling audit logs with noise from harmless application probing. May hide the cause of a denial when developing policy. Use semodule -DB to strip dontaudit rules. Use semodule -B to restore them.
Getting Full Paths in AVC Denials Problem: AVC denials only list the last path component. This is a problem in the case of directories like public_html. Solution: Adding an audit rule will turn on full path resolution Set once at runtime: $ auditctl -w /etc/shadow -p wa Set Persistently $ echo "-w /etc/shadow -p w" >> /etc/audit/audit.rules $ service auditd restart
Augmented Denial type=PATH msg=audit(09/07/2010 14:06:38.240:54981) : item=0 name=/root/.bash_history inode=138 dev=fd:00 mode=file,600 ouid=root ogid=root rdev=00:00 obj=unconfined_u:object_r:admin_home_t:s0 type=CWD msg=audit(09/07/2010 14:06:38.240:54981) : cwd=/home/sds Now we get to see the current working directory (CWD) of the process and the full pathname (PATH) that was passed to the system call.
Most Common SELinux Problems Incorrect Labeling Non-Default Configuration of a Confined Program Bug in Policy or an Application Your machine may have been compromised
Labeling Problems Every process and object on the system is labeled If labels are not correct access may be denied Causes Alternative paths (semanage fcontext) Files created in wrong context (restorecon) Processes started in wrong context
Usecase: Move instead of copy Administrator uploads and extracts a tarball of static web content to his home directory Administrator moves the files into the document root for www.example-labels.com Administrator tries to access site Access fails, why?
Lab: Move instead of copy Create A file in your home directory Observe its label Move it to the document root for www.example- labels.com Observe is label, did it change? Use chcon or restorecon to fix the label
Non-Default Configuration SELinux needs to know how a confined daemon is configured Non-default directories Need to ensure files are labeled properly Booleans Allow optional functionality to be enabled Non-default ports Need to ensure ports labeled properly
Usecase: Non Default Location Administrator decides to setup a website www.example-opt.com with the location of /opt/www Administrator creates the directory and copies files into it. Administrator tries to access site Page access fails, why?
Lab: Non Default Locaton Copy the original docroot files over to a new location Modify the apache config to read from this new location Try to access Fails why? Set up equivalence mapping with semanage fcontext
Usecase: Web content in user home directories Administrator decides to setup a website www.example-userhome.com to allow users to host personal webpages. Administrator enables Userdirs to public_html. Administrator tries to access site www.example- userhome.com/~sedemo Page access fails, why?
Lab: Web content in user home directories Create a public_html directory in your home directory and ensure its labeled properly Create a file under it Try to access the file at http://www.example- userhome.com/~username/filename Why does it fail Enable httpd to read home directories using getsebool/setsebool
Usecase: Apache on a non-standard port Administrator decides to change the port his apache server at www.example-port.com to 10321 to heighten security. Administrator changes the listening port in the config. Administrator tries start httpd. Server fails to start, why?
Lab: Apache on a non-standard port Change port in Apache config to read on port 10321 Attempt to restart Apache Why does this fail? Identify the port label for Apache Use semanage port or sepolicy network if on a new enough system Create new mapping for port 10321 to the appropriate context using semanage port
Bugs in Policy/Apps SELinux policy bugs Incomplete policy (unusual code path) Unknown application configuration Application bugs Leaked File Descriptors Executable Memory (execmem) Badly built libraries (execmem and others)
Bugs in Policy/Apps (2) Options Report bugs in bugzilla (Best long term solution) Create a policy module (Temporary fix) Labeling is correct? No appropriate booleans? Use audit2allow to create a policy module Examine resulting policy Make sure it's safe Ask for help (#fedora-selinux and mailing lists)
Your machine may have been compromised Current tools not good at differentiating Warning signs: a confined domain tries to: Load a kernel module Turn off SELinux enforcing mode Write to etc_t or shadow_t Modify iptables rules Sendmail others You may be compromised
Policy Basics
Policy What is it? Rules governing interactions on the system Information about initial label states Mappings of roles and users Where is it? /etc/selinux/<policy_name>
Dissecting a Policy Directory Contains compiled policy loaded into the kernel modules/ Policy store containing all modules and local modifications Manipulate only using semodule and semanage contexts/ Initial labeling information for security aware user space applications
TE: Allow Rules Everything not explicitly allowed is denied. Syntax: allow source-type target-type : class { permissions }; Examples: allow user_t passwd_exec_t:file execute; allow passwd_t passwd_exec_t:file entrypoint; allow user_t passwd_t:process transition;
TE: Transition Rules Default assignment of types on program execution and object creation. Syntax: type_transition source-type target-type:class default_type; Examples: type_transition user_t passwd_exec_t:process passwd_t; type_transition passwd_t etc_t:file shadow_t;
ftransferd
What is ftransferd? Simple file transfer daemon Uses file in the user’s home directory to host files Can access the directory for any user Has a small vulnerability in it for fun!
What does it do? Reads from a directory in the user’s home directory Writes output to syslog Binds and communicates through TCP ports
Policy Development Basics
Writing New Policy: Dependencies Need policy headers (/usr/share/selinux/devel). selinux-policy-devel in RHEL5. Folded into selinux-policy in modern Fedora. Need checkpolicy. May want a copy of the policy sources for reference. selinux-policy.src.rpm oss.tresys.com/projects/refpolicy
Writing New Policy: Understanding Interfaces Existing policy makes extensive use of interfaces/macros. The interface files (*.if) are installed under /usr/share/selinux/devel/include. Documentation for the interfaces can be viewed using /usr/share/selinux/devel/policyhelp.
Policy Writing Tools SELinux Policy IDE (SLIDE), Eclipse plugin. http://oss.tresys.com/projects/slide eclipse-slide in Fedora >= 9, RHEL 6. Policy generation tools /usr/share/selinux/devel/policygentool (old) system-config-selinux new module wizard /usr/bin/sepolgen vi/emacs for the rest of us!
Writing new policy Typically generate an initial stub domain using your favorite tool (or by hand) Load the policy module, label the relevant files Run the program in permissive mode (or use a permissive domain) Collect denials Augment policy Rinse and repeat
SEPolgen CLI and GUI program to generate a simple policy module Questions asked to include common policy sections Creates a script for generating more policy rules using audit2allow
Lab: Create Initial Policy Use sepolgen or eclipse-slide to create a new policy module Select items for what we currently know about ftransferd Inspect created polcy
Permissive Domains Fedora >= 10, RHEL 6 Allows a single domain to be placed in permissive mode instead of the entire system In policy permissive myapp_t; At runtime $ semanage permissive -a myapp_t $ semanage permissive -d myapp_t
Lab: Make new domain permissive Identify the domain type for ftransferd Decide whether you want long or shor term permissive policy semanage permissive Make the appropriate change
Audit2allow Tool for generating policy rules based on AVC messages (Use with caution!) Can inspect rules in generated te file Never run with the same -M name twice (will override old module) # audit2allow -l -a -M local ******************** IMPORTANT *********************** To make this policy package active, execute: semodule -i local.pp
Audit2allow Examples Create and insert a local policy module that allows all logged denials since the last reload. audit2allow -l -a -M mypolicy semodule -i mypolicy.pp Create and insert a local policy module that allows all denials logged on the httpd program. ausearch -m avc -c httpd | audit2allow -M myhttpd semodule -i myhttpd
Audit2allow -R By default, audit2allow emits raw policy rules. Existing policy is written using macros (interfaces). Audit2allow -R will try to find the right interface and use it. audit2allow -l -a -R -M mypolicy Imperfect, but can be helpful.
Lab: Generate Denials & Policy Clear your audit logs Restart auditd Run ftransferd Transfer a few files with the client Look for generated AVC denials Run them through audit2allow Don't forge to use a different module name each time Merge the policy modules
Extras
Tools Auditing ausearch, aureport, auditctl, audit2why Policy Management tools semodule, semanage, {get,set}sebool Policy Querying Tools sesearch, sediff, apol Policy Generation Tools audit2allow, sepolgen GUI Tools setroubleshoot, system-config-selinux, apol
External Resources Fedora Docs, http://docs.fedoraproject.org SELinux FAQ Security-Enhanced Linux User Guide Managing Confined Services SELinux wiki, http://selinuxproject.org Tresys OSS site, http://oss.tresys.com SELinux By Example: Using Security Enhanced Linux
Resources SELinux Project Wiki http://www.selinuxproject.org Dan Walsh's Blog http://danwalsh.livejournal.com/ Fedora SELinux Mailing List https://www.redhat.com/mailman/listinfo/fedora-selinux-list NSA SELinux Mailing List http://www.nsa.gov/research/selinux/list.shtml
Questions?
Survey Thank you for listening to me talk. Please help improve the talk by filling out a quick survey at http://goo.gl/Of4H4z