SlideShare une entreprise Scribd logo
1  sur  88
Igor Sikorsky KPI
Basic usage
Composed by: As. Prof. Dmytro Minochkin
Presented at: University of Luxembourg
on 27.04.2017
What is Security Enhanced Linux?
 Security Enhanced Linux or SELinux is an
advanced access control mechanism built into
most modern Linux distributions.
 It was initially developed by the US National
Security Agency to protect computer systems
from malicious intrusion and tampering.
 Over time, SELinux was released in the
public domain and various distributions have
since incorporated it in their code.
2
What is Security Enhanced Linux?
 A properly configured SELinux system can greatly reduce security risks, and knowledge
about it can help you troubleshoot access-related error messages.
 We will learn about the concepts behind SELinux: packages, commands, and configuration
files and the error messages it logs when access is denied.
 We will also see a few practical instances of putting SELinux in action.
3
Who Uses SELinux?
 Available in almost all popular Linux distributions (Debian/Ubuntu, RHEL/Centos, etc.)
 Starting with Android 4.3, SELinux is used for tightening the boundaries of the Android
application sandbox.
 Android 4.3 – Permissive Mode
 Android 4.4 – Partial Enforcement Mode
 Android 5.0+ - Full Enforcement Mode
(More on modes later)
4
Basic Concepts 1/2
 SELinux implements what's known as MAC (Mandatory Access Control). This is implemented
on top of what's already present in every Linux distribution, the DAC (Discretionary Access
Control).
 In a traditional security model, we have three entities: User, Group, and Other (u,g,o) who
can have a combination of Read, Write, and Execute (r,w,x) permissions on a file or
directory.
 If a user test creates a file in his/her home directory, that user will have read/write access to
it, and so will the test group. The "other" entity will possibly have no access to it.
# Run as normal user
# List contents of home directory of current user
# with help of USER environment variable
ls -lah /home/$USER
5
Basic Concepts 2/2
 test can grant (and restrict) access to these files to other users
and groups or change the owner of the files.
 These actions can leave critical files exposed to accounts who
don't need this access.
 test can also restrict to be more secure, but that's
DISCRETIONARY: there's no way for the system administrator to
enforce it for every single file in the system.
total 16K
drwx------. 3 vagrant vagrant 95 кві 16 11:42 .
drwxr-xr-x. 7 root root 83 кві 16 11:40 ..
-rw-------. 1 vagrant vagrant 5 кві 16 11:42 .bash_history
-rw-r--r--. 1 vagrant vagrant 18 гру 6 23:19 .bash_logout
-rw-r--r--. 1 vagrant vagrant 193 гру 6 23:19 .bash_profile
-rw-r--r--. 1 vagrant vagrant 231 гру 6 23:19 .bashrc
drwx------. 2 vagrant vagrant 29 кві 16 11:38 .ssh
6
Another Example
 When a Linux process runs, it may run as
the root user or another account with
superuser privileges.
 If a hacker takes control of the application,
they can use that application to get access
to whatever resource the user account has
access to.
 For processes running as the root user,
basically this means EVERYTHING in the
Linux server.
7
SELinux
 SELinux is a way to fine-tune access
control requirements.
 With SELinux, you can define what a user
or process can do.
 It confines every process to its own
domain so the process can interact with
only certain types of files and other
processes from allowed domains.
 This prevents a hacker from hijacking any
process to gain system-wide access.
8
SELinux Intro 1/2
 SELinux was originally a development project from the National Security Agency (NSA ).
 The NSA integrated SELinux into the Linux kernel using the Linux Security Modules
(LSM) framework. SELinux motivated the creation of LSM
 Originally, the SELinux implementation used persistent security IDs (PSIDs) stored in an
unused field of the ext2 inode.
 These numerical representations (non-human-readable) were mapped by SELinux to a
security context label.
 This required modifying each file system type to support PSIDs.
9
SELinux Intro 2/2
 The next evolution of SELinux was as a loadable
kernel module.
 This module stored PSIDs in a normal file, and
SELinux was able to support more file systems.
 This solution was not optimal for performance, and
was inconsistent across platforms.
 Finally, the SELinux code was integrated to the 2.6.x
kernel, which had full support for LSM and had
extended attributes (xattrs) in the ext3 file system.
 SELinux was moved to using xattrs to store security
context information. The xattr namespace provides
useful separation for multiple security modules
existing on the same system.
10
Test System
 The commands, packages, and files that we are
going to see today will be shown on CentOS 7.
 The concepts remain the same for other
distributions.
 We will be running the commands as the root user
unless otherwise stated.
 If you don't have access to the root account and
use another account with sudo privileges, you need
to precede the commands with the sudo keyword.
11
Test System
 We will start with a bare installation of CentOS 7
with minimal packages installed and install
additional software on the VM with default
configurations.
 We will also create a few test user accounts for
training purpose.
 Finaly, we will install needed SELinux-related
packages. This is to ensure we can work with the
latest SELinux commands.
 To speed up the process we will use a combination
of Vagrant VM provisioner and Virtualbox VM
provider.
 We will also require GIT version control system
12
Additional Software
 git version control system (https://git-scm.com/downloads)
 ssh client: We can use either git-bash (for windows) or native ssh client for linux/mac
 Virtualbox (https://www.virtualbox.org/) for all supported platforms
 Vagrant (https://www.vagrantup.com/downloads.html)
# Run as normal user
git clone https://github.com/DmyMi/lux-selinux-demo.git
cd lux-selinux-demo
vagrant up # start provisioning, will take 5-15 minutes
vagrant ssh # when provisioning is successful
13
Overview of scripts and SELinux
Packages
 policycoreutils (provides utilities for managing SELinux)
 policycoreutils-python (provides utilities for managing SELinux)
 selinux-policy (provides SELinux reference policy)
 selinux-policy-targeted (provides SELinux targeted policy)
 libselinux-utils (provides some tools for managing SELinux)
 setroubleshoot-server (provides tools for deciphering audit log messages)
 setools (provides tools for audit log monitoring, querying policy, and file context
management)
 setools-console (provides tools for audit log monitoring, querying policy, and file context
management)
 mcstrans (tools to translate different levels to easy-to-understand format)
# To see all installed SELinux Packages run as root
rpm -qa | grep selinux
14
SELinux Modes
At any one time, SELinux can be in any of three possible modes:
 ENFORCING - SELinux will enforce its policy on the Linux
system and make sure any unauthorized access attempts by
users and processes are denied
 PERMISSIVE - is a semi-enabled state. SELinux doesn't apply
its policy in permissive mode, so no access is denied.
 DISABLED is self-explanatory 
15
Checking SELinux Modes and
Status
# We can run the getenforce command to check the current SELinux mode.
# Run as either normal or super user
getenforce
# We can also run the sestatus command:
# Run as either normal or super user
sestatus
# The later should also give additional info regarding SELinux status,
# if it is enabled in either Enforcing or Permissive mode.
16
 The main configuration file for SELinux is /etc/selinux/config
 There are two directives in this file. The SELINUX directive dictates the SELinux mode
and it can have three possible values as we discussed before.
 The SELINUXTYPE directive determines the policy that will be used.
SELinux Configuration File
# We can run the following command to view its contents:
cat /etc/selinux/config
17
 Enabling SELinux is fairly simple, but unlike disabling it, should be done in a two-step
process.
 As a first step, we need to edit the /etc/selinux/config file to change the SELINUX
directive to permissive mode. After that we need to issue a system reboot
 In the second phase, we need to edit the config file to change the SELINUX directive
from permissive to enforcing in the /etc/selinux/config file. Next, reboot the server
again.
Enable and Disable SELinux
# In permissive mode Log in to your VM again and search
# for the string "SELinux is preventing" from the contents of the /var/log/messages file.
cat /var/log/messages | grep "SELinux is preventing“
# If there are no errors reported, we can safely move to the next step. However, it would
# still be a good idea to search for text containing "SELinux" in /var/log/messages file
cat /var/log/messages | grep "SELinux“
# We can also temporarily switch between enforcing and permissive modes with setenforce:
setenforce permissive
18
 At the heart of SELinux' security engine is its policy.
 A policy is a set of rules that define the security and
access rights for everything in the system.
 When we say everything, we mean users, roles,
processes, and files.
 The policy defines how each of these entities are
related to one another.
SELinux Policy: Terminology
19
 SELinux has a set of pre-built users. Every regular
Linux user account is mapped to one or more
SELinux users.
 In Linux, a user runs a process. This can be as simple
as the user test opening a document in the text editor
(it will be test's account running the editor process) or
a service account running the httpd daemon.
 In the SELinux world, a process (a daemon or a
running program) is called a subject.
Users
20
 A role is like a gateway that sits between a user and a
process.
 A role defines which users can access that process.
 Roles are not like groups, but more like filters: a user
may enter or assume a role at any time provided the
role grants it.
 The definition of a role in SELinux policy defines which
users have access to that role. It also defines what
process domains the role itself has access to.
 Roles come into play because part of SELinux
implements what's known as Role Based Access
Control (RBAC).
Roles
21
 A subject is a process and can potentially affect an
object.
 An object in SELinux is anything that can be acted
upon.
 This can be a file, a directory, a port, a tcp socket, the
cursor, or even an X server.
 The actions that a subject can perform on an object
are the subject's permissions.
Subjects and Objects
22
 A domain is the context within which an SELinux
subject (process) can run.
 That context is like a wrapper around the subject. It
tells the process what it can and can't do.
 For example, the domain will define what files,
directories, links, devices, or ports are accessible to
the subject.
Domains for Subjects
23
 A type is the context for a file that stipulates the file's
purpose.
 For example, the context of a file may dictate that it's a
web page, or that the file belongs to the /etc directory,
or that the file's owner is a specific SELinux user.
Types for Objects
24
 SELinux policy defines user access to roles, role access to domains, and
domain access to types.
 First the user has to be authorized to enter a role, and then the role has to be
authorized to access the domain. The domain in turn is restricted to access only
certain types of files.
 The last bit, where a process running within a particular domain can perform only
certain operations on certain types of objects, is called Type Enforcement (TE).
What is SELinux policy?
25
 SELinux policy is not something that
replaces traditional DAC security.
 If a DAC rule prohibits a user access to a
file, SELinux policy rules won't be evaluated
because the first line of defense has
already blocked access.
 SELinux security decisions come into play
after DAC security has been evaluated.
SELinux Policy Behavior 1/2
26
 When an SELinux-enabled system starts, the policy is
loaded into memory.
 SELinux policy comes in modular format, much like the
kernel modules loaded at boot time.
 And just like the kernel modules, they can be
dynamically added and removed from memory at run
time.
 The policy store used by SELinux keeps track of the
modules that have been loaded.
SELinux Policy Behavior 2/2
# The sestatus command shows the policy store #
name.
# The semodule -l command lists the SELinux
# policy
# modules currently loaded into memory.
semodule -l | less
# semodule can be used for a number other
# tasks like installing, removing, reloading,
# upgrading, enabling and disabling SELinux
# policy modules.
27
 Most modern distributions include binary versions of the modules as part of the
SELinux packages. The policy files have a .pp extension.
 The .pp files are not human readable though.
 The way SELinux modularization works is that when the system boots, policy
modules are combined into what's known as the active policy.
 This policy is then loaded into memory.
SELinux Policy Location
# If there are any modules available – you can check them with
ls -l /etc/selinux/targeted/modules/active/modules/
# The combined binary version of this loaded policy can be found under the
# /etc/selinux/targeted/policy directory
ls -l /etc/selinux/targeted/policy/
28
 Although you can't read the policy module files, there's a simple way to tweak their
settings.
 That's done through SELinux booleans.
 Changed booleans are not permanent. They revert to their old values after a reboot.
 To make things permanent, we can use the -P switch with the setsebool command.
Changing SELinux Boolean Settings
# Show the different switches that can be turned on or off,
# what they do, and their current statuses.
semanage boolean -l | less
# To change any of the settings, we can use the setsebool command
# check
getsebool ftpd_anon_write
# set
setsebool ftpd_anon_write on
# check again
getsebool ftpd_anon_write
29
 The SELinux policy for the application will determine what types of
files it needs access to and what processes it can transition to.
 The first part of security puts a label on each entity in the Linux
system.
 A label is like any other file or process attribute (owner, group, date
created etc.) it shows the context of the resource.
 Context is a collection of security related information that helps
SELinux make access control decisions.
SELinux for Processes and Files
30
Before we go any further, here is a note about SELinux naming
convention:
SELinux Users are suffixed by "_u”
SELinux Roles are suffixed by “_r”
SELinux Types (for files) or SELinux Domains (for processes) are
suffixed by "_t".
Naming Conventions
31
 Let's start by understanding SELinux file contexts.
 We now have an extra column of information after the user and group ownership.
 This column shows the security contexts of the files.
 A file is said to have been labelled with its security context when you have this
information available for it
SELinux File Contexts 1/2
# regular ls -l command against the /etc directory
ls –l /etc
# now add the -Z flag
ls –Z /etc
32
 Let's take a closer look at one of the security contexts.
 The first part is the SELinux user context for the file. We will discuss SELinux users
later, but for now, we can see that it's system_u.
 The second part specifies the SELinux role, which is object_r.
 What's most important here is the third part, the type of the file that's listed here as
etc_t. This is the part that defines what type the file or directory belongs to.
 The fourth part of the security context, s0, has to do with multilevel security or MLS.
SELinux File Contexts 2/2
ls –Z /etc | grep yum.conf
ls –Z /etc | grep locale.conf
33
 Let's now talk about process security contexts.
 The security context has four parts: user, role, domain, and sensitivity.
 The user, role, and sensitivity work just like the same contexts for files.
 The domain is unique to processes.
SELinux Process Contexts
# Restart the Apache and SFTP services
systemctl restart httpd && systemctl restart vsftpd
# We can run the ps command with a few flags to show the Apache and SFTP processes running
ps -efZ | grep 'httpd|vsftpd'
34
 So far we have seen that files and processes can have different contexts, and that
they are restricted to their own types or domains.
 To run, a process needs to access its files and perform some actions on them (open,
read, modify, or execute).
 We have also learned that each process can have access to only certain types of
resources (files, directories, ports, etc.).
 SELinux stipulates these access rules in a policy. The access rules follow a standard
allow statement structure
 Class defines what the resource actually represents (file, directory, symbolic link,
device, ports, etc.)
How Processes Access Resources
allow <domain> <type>:<class> { <permissions> };
35
 Let's consider the security contexts of the httpd daemon running on our system
Ex. #1: Apache httpd 1/3
# The default home directory for the web server is /var/www/html.
# Let's create a file within that directory and check its context
touch /var/www/html/index.html
ls -Z /var/www/html/*
# We can use the sesearch command to check the type of access allowed for the httpd daemon
sesearch --allow --source httpd_t --target httpd_sys_content_t --class file
# The flags used with the command are fairly self-explanatory:
-the source domain is httpd_t (the domain Apache is running in)
-We are interested about target resources that are classified as files
-and have a type context of httpd_sys_content_t.
# Notice the line
allow httpd_t httpd_sys_content_t : file { ioctl read getattr lock open } ;
# This says that the httpd daemon (the Apache web server) has I/O control, read, get attribute,
# lock, and open access to files of the httpd_sys_content_t type.
# In this case our index.html file has the same type.
36
 Let's first modify the web page /var/www/html/index.html
 Lets try to access it in our browser: http://127.0.0.1:8080
 The httpd daemon is authorized to access a particular type of file and we can see it
when accessing via the browser.
Ex. #1: Apache httpd 2/3
nano /var/www/html/index.html
# Place the following content into the file:
<html>
<title>
This is a test web page
</title>
<body>
<h1>Hello Luxembourg Security :)</h1>
</body>
</html>
# Next, we will change the permission of the
# /var/www/ folder and its contents, followed by
# a restart of the httpd daemon
chmod -R 755 /var/www
systemctl restart httpd
37
 Let's make things a little different by changing the context of the file.
 We will use the chcon command for it.
 When we try to access the web page (i.e. the httpd daemon tries to read the file),
you may get a Forbidden error, or you may see the generic CentOS "Testing 123"
page.
 To make things work again, let's change the file type with the restorecon command.
Ex. #1: Apache httpd 3/3
# The --type flag for the command allows us to specify a new type for the target resource.
# We are changing the file type to var_t
chcon --type var_t /var/www/html/index.html
# Confirm the change
ls -Z /var/www/html/
# The -v switch shows the change of context labels
restorecon -v /var/www/html/index.html
38
 SELinux enforces something we can term as "context inheritance". What this
means is that unless specified by the policy, processes and files are created with the
contexts of their parents.
 So if we have a process called "proc_a" spawning another process called "proc_b",
the spawned process will run in the same domain as "proc_a" unless specified
otherwise by the SELinux policy.
 Similarly, if we have a directory with a type of "some_context_t", any file or directory
created under it will have the same type context unless the policy says otherwise.
Context Inheritance for Files and
Directories
# Check directory
ls -Z /var/www
# Copy to another directory
cp /var/www/html/index.html /var/
# Check file
ls -Z /var/index.html
# This change of context can be overridden by the --preserver=context clause
# in the cp command.
# Now move and check
mv /var/index.html /etc/
ls -Z /etc/index.html
39
Ex. #2: File Context Error
# Create new directory and check its context (should be default_t)
mkdir -p /www/html && ls -Z /www/
# Copy our website . It should get the default_t type
cp /var/www/html/index.html /www/html/
# Edit Apache config
nano /etc/httpd/conf/httpd.conf
# Find the following section and change it (starts at line 119)
# to look like right snippet
# then restart Apache using command: systemctl restart httpd
DocumentRoot "/var/www/html"
#
# Relax access to content within /var/www.
#
<Directory "/var/www">
AllowOverride None
# Allow open access:
Require all granted
</Directory>
DocumentRoot "www/html"
#
# Relax access to content within /var/www.
#
<Directory "/www">
AllowOverride None
# Allow open access:
Require all granted
</Directory>
40
 We saw two commands for changing file contents: chcon and restorecon. Running
chcon is a temporary measure.
 Running chcon requires you to know the correct context for the file, as the --type
flag specifies the context for the target.
 restorecon doesn't need this specified. If you run restorecon, the file will have the
correct context re-applied and the changes will be made permanent.
 But if you don't know the file's correct context, how does the system know which
context to apply when it runs restorecon?
Changing and Restoring SELinux
File Contexts 1/2
# extract from one of the files
cat /etc/selinux/targeted/contexts/files/file_contexts | less41
 To permanently change the context of our test file (index.html) file under /www/html,
we have to follow a two-step process
 First, we create our context binding using semanage command
 Second, we will use restorecon to apply all the required contexts
 Now we know a few more useful commands 
Changing and Restoring SELinux
File Contexts 2/2
# Step 1: Set file contexts for both directories
semanage fcontext --add --type httpd_sys_content_t "/www(/.*)?"
semanage fcontext --add --type httpd_sys_content_t "/www/html(/.*)?"
# Check if contexts are added
cat /etc/selinux/targeted/contexts/files/file_contexts.local
# Step 2: restorecon with recursive(-R) flag
restorecon -Rv /www
# Verify the correct context before and after restorecon
matchpathcon -V /www/html/index.html
42
 So far we have seen how processes access file system resources.
 Domain transition is the method where a process changes its context from one domain to
another.
 The case of domain transition is fairly common in SELinux.
Domain Transition
43
 Let’s consider the systemd process. This is the ancestor of all processes and runs
within a context of init_t
Domain Transition Example
# Check system context
ps -eZ | grep init
# Check vsftpd binary context
ls -Z /usr/sbin/vsftpd
# Check vsftpd process
ps -eZ | grep vsftpd
44
Domain transition is subject to three strict rules:
The parent process of the source domain must have the execute permission for the application
sitting between both the domains (this is the entrypoint).
The file context for the application must be identified as an entrypoint for the target domain.
The original domain must be allowed to transition to the target domain.
Domain Transition Rules
45
 Taking the vsftpd daemon example, let's run the sesearch command with different
switches to see if the daemon conforms to these three rules.
Domain Transition Rule Example
# See if source domain has execute permission on entry point
# flags: -s – source, -t – target, -c – class, -p – permission,
# -A – allow rules, -d – direct name match
sesearch -s init_t -t ftpd_exec_t -c file -p execute –Ad
# Check if binary is entry point for target domain
sesearch -s ftpd_t -t ftpd_exec_t -c file -p entrypoint –Ad
# Check if there is a transition permission
sesearch -s init_t -t ftpd_t -c process -p transition -Ad
46
 We compared domain to a hypothetical bubble around the process: something that stipulates what
the process can and can't do.
 This is what confines the process.
 SELinux also has processes that run within unconfined domains.
 Example of an unconfined process domain would be unconfined_t.
Unconfined Domains
47
 SELinux users are different entities from normal Linux user accounts, including the root
account.
 The user names end with _u, just like types or domain names end with _t and roles end
with _r.
 Different SELinux users have different rights in the system and that's what makes them
useful.
 When SELinux is enforced, each regular Linux user account is mapped to an SELinux user
account.
SELinux Users 1/4
48
 There are only three listed here, though we've created a few more during VM
provisioning?!
 New users are represented by the entry shown as default.
SELinux Users 2/4
# To view user mapping
semanage login –l
Login Name SELinux User MLS/MCS Range Service
__default__ unconfined_u s0-s0:c0.c1023 *
root unconfined_u s0-s0:c0.c1023 *
system_u system_u s0-s0:c0.c1023 *
49
 What does this bigger table mean?
SELinux Users 3/4
# See what SELinux users are available in the system
semanage user –l
Labeling MLS/ MLS/
SELinux User Prefix MCS Level MCS Range SELinux Roles
guest_u user s0 s0 guest_r
root user s0 s0-s0:c0.c1023 staff_r sysadm_r system_r unconfined_r
staff_u user s0 s0-s0:c0.c1023 staff_r sysadm_r system_r unconfined_r
sysadm_u user s0 s0-s0:c0.c1023 sysadm_r
system_u user s0 s0-s0:c0.c1023 system_r unconfined_r
unconfined_u user s0 s0-s0:c0.c1023 system_r unconfined_r
user_u user s0 s0 user_r
xguest_u user s0 s0 xguest_r
50
 Demonstration of unconfined access by regular users
We had seen the list of a number of SELinux users before:
 guest_u: This user doesn't have access to X-Window system (GUI) or networking and can't
execute su / sudo command.
 xguest_u: This user has access to GUI tools and networking is available via Firefox browser.
 user_u: This user has more access than the guest accounts (GUI and networking), but can't switch
users by running su or sudo.
 staff_u: Same rights as user_u, except it can execute sudo command to have root privileges.
 system_u: This user is meant for running system services and not to be mapped to regular user
accounts.
Let’s change the default behavior 
SELinux Users 4/4
# run as root user
id -Z
# Go to GUI and log in as regular user (login: reguser & password: regpass)
# run same command
id -Z
51
 Mind you though, it still doesn't stop people from logging in directly as the high-
privileged user with login & password
 But if you set up a passwordless SSH connection with RSA keypair for every user –
it can help protect your server even if the password for regular user is known to a
hacker.
Restricting User Access
# Use Vbox GUI
# The regular user switches to the switched user account.
# We assume he knows the password for switched user (it’s swpass )
su – swuser
# Go to root user terminal
# (-a – add a record of specified type, -s SEUSER – SELinux user type)
semanage login -a -s user_u reguser
# update contexts
restorecon -RFv /home/reguser/
52
Restricting Access to Services
# As root user stop Apache
systemctl stop httpd
# Go to GUI and log in as restricted user (login: restuser & password: respass)
# assume he doesn’t know root password
systemctl start httpd
# Go to GUI after adding to sudoers
sudo systemctl start httpd
# in root terminal
semanage login -a -s user_u restuser
# verify user_u access to roles and user_r role access to domains (root terminal)
# There are a number of httpd related domains, but httpd_t is not one of them.
seinfo -uuser_u –x
seinfo -ruser_r -x | grep httpd
# as restricted user try to start httpd again
sudo systemctl start httpd
nano /etc/sudoers
# in the file, add the
# following line,
# save and exit
restuser ALL=(ALL) ALL
53
 You can set all new users to be mapped to user_u by default
 Restricting is boring. What if we want to permit a user to do something?
 We have to use a more permissive role or …
 We have to write our own role with all the required permissions, which requires deep
understanding of available permission checks, reference policy macros and more.
 It is out of the scope of this intro 
Changing the Default Mapping
# -m – modify a record of specified object
# -r – security range for MLS/MCS
semanage login -m -S targeted -s "user_u" -r s0 __default__
# verify with
semanage login -l
# more permissive role
semanage login -a -s "sysadm_u" guestuser
# update contexts
restorecon -RFv /home/guestuser/
54
New Role Example
policy_module(pgsql_admin, 1.0)
# Define the pgsql_admin_r role
role pgsql_admin_r;
# Create a pgsql_admin_t type that has minimal rights a regular
# user domain would need in order to work
# on a Linux system
userdom_base_user_template(pgsql_admin)
# Allow the pgsql_admin_t type to execute regular binaries (f.i. id)
corecmd_exec_bin(pgsql_admin_t)
# Allow the user domain to read its own selinux context
selinux_getattr_fs(pgsql_admin_t)
# Allow the user to administer postgresql, but do not fail
# if no postgresql SELinux module is loaded yet
optional_policy('
postgresql_admin(pgsql_admin_t, pgsql_admin_r)
')
# To allow transition from staff_r to pgsql_admin_r
gen_require('
role staff_r;
')
allow staff_r pgsql_admin_r;
55
 While administering your system, you would be interested to look at the error
messages logged by SELinux.
 These messages are logged in specific files and they can provide detailed
information about access denials.
 In a CentOS 7 system you can look at two files
SELinux Audit Logs 1/3
/var/log/audit/audit.log
/var/log/messages
# The first command is ausearch. We can make use of this command if the auditd daemon is running.
# For example, let’s check our Apache server, -m – message, -c – command (process) name
ausearch -m avc -c httpd
56
 In our system a number of entries might be listed, but we will concentrate on the next
one
 To understand it, let's take apart each of the fields
SELinux Audit Logs 2/3
type=SYSCALL msg=audit(1489938539.297:155): arch=c000003e syscall=4 success=no exit=-13 a0=7ffb8aab4130 a1=7ffe02c56fb0 a2=7ffe02c56fb0
a3=ffffff00 items=0 ppid=22187 pid=22189 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295
comm="httpd" exe="/usr/sbin/httpd" subj=system_u:system_r:httpd_t:s0 key=(null)
type=AVC msg=audit(1489938539.297:155): avc: denied { getattr } for pid=22189 comm="httpd" path="/var/www/html/index.html"
dev="dm-0" ino=67359616 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file
57
 type=AVC and avc: AVC stands for Access Vector Cache.
 denied { getattr }: The permission that was attempted and the result it got. In this case the get
attribute operation was denied.
 pid=22189. This is the process id of the process that attempted the access.
 comm: The process id by itself doesn't mean much. The comm attribute shows the process
command. In this case it's httpd. Immediately we know the error is coming from the web server.
 path: The location of the resource that was accessed. In this case it's a file under
/var/www/html/index.html.
 dev and ino: The device where the target resource resides and its inode address.
 scontext: The security context of the process. We can see the source is running under the httpd_t
domain.
 tcontext: The security context of the target resource. In this case the file type is var_t.
 tclass: The class of the target resource. In this case it's a file.
SELinux Audit Logs 3/3
type=AVC msg=audit(1489938539.297:155): avc: denied { getattr } for pid=22189 comm="httpd"
path="/var/www/html/index.html" dev="dm-0" ino=67359616 scontext=system_u:system_r:httpd_t:s0
tcontext=unconfined_u:object_r:var_t:s0 tclass=file
58
An SELinux denial can be corrected in different ways
Correct a wrong label on the source domain or the target resource. If not using the
defaults, you will probably need to do this
Change an SELinux Boolean. Many applications behaviour can be modified this way
Use the application as it was intended 
Add a new rule that allows the denial. Only if all of the above are not applicable!
Usual Ways to Fix the Errors?
59
 We can also use the sealert tool.
 This command can be used with the id value of the error message logged in the
/var/log/messages file
Understanding the Error
# Check if there are any errors in the logs
cat /var/log/messages | grep "SELinux is preventing"
# Check detailed info about the error
sealert -l <your-error-id>
# Or we can use audit2why that parses the logs and shows the reason in readable form
# first lets search the logs for today’s errors with ausearch and pipe it to audit2why
# -ts – time stamp to start the search
ausearch -m avc -ts today | audit2why
60
Exercise #1. SELinux Administration
61
 Edit SFTP config file and uncomment anon_upload_enable=YES
Step #1
# Open SFTP Config file
nano /etc/vsftpd/vsftpd.conf
# find and uncomment the line anon_upload_enable=YES
# Restart SFTP
systemctl restart vsftpd
# Run the lftp cli
lftp
# open the connection to localhost
lftp> open 127.0.0.1
# try to upload a file
lftp> put .bashrc -o pub/.bashrc
# try to figure why we encounter an error
# hint use ls command
lftp> ls -lah pub/
62
 Wrong DAC settings. No write permission
 To solve it – exit the lftp client and change permission
Step #1: Solved
drwxr-xr-x 2 0 0 6 Nov 05 19:43 .
drwxr-xr-x 3 0 0 17 Apr 16 11:39 ..
chmod 777 /var/ftp/pub/
63
 Try uploading again
Step #2
# Run the lftp cli
lftp
# open the connection to localhost
lftp> open 127.0.0.1
# try to upload a file
lftp> put .bashrc -o pub/.bashrc
# try to figure why we encounter ANOTHER error 
# hint use ausearch command
ausearch -m avc -c vsftpd
# or sealert on the latest entry in logfile
tail /var/log/messages -n 4 | grep "SELinux is preventing"
sealert -l <error-id>
# or audit2why
ausearch -m avc -c vsftpd | audit2why
64
 MAC error ftpd_t domain cannot write to public_content_t type. Confirm it by
running
 sealert proposes two fixes:
Step #2: Solved
# Proposed Fix no. 1
# If you want to allow vsftpd to be able to write to shared public content
# Then you need to change the label on pub to public_content_rw_t, and potentially turn
on # the allow_httpd_sys_script_anon_write boolean.
# Do
semanage fcontext -a -t public_content_rw_t pub
restorecon -R -v pub
setsebool -P allow_ftpd_anon_write 1
# Proposed Fix no. 2
#You can generate a local policy module to allow this access.
#Do
#allow this access for now by executing:
ausearch -c 'vsftpd' --raw | audit2allow -M my-vsftpd
semodule -i my-vsftpd.pp
sesearch --allow --source ftpd_t --target public_content_t -d
65
 It can generate SELinux policy allow/dontaudit rules from logs of denied operations
 Usually this generated policy is very unsecure
Mostly used flags are:
 -M – generate compiled and loadable SELinux module,
 -a – get all from raw input,
 -m – generate uncompiled module (type enforcement file)
 Then we can view and compile this module with checkmodule
 Finally we can package the compiled policy using semodule_package and installed
audit2allow
ausearch -c 'vsftpd' --raw | audit2allow -a -m my-vsftpd > my-vsftpd.te
# -M – MLS enabled, -m – non-base policy (can be added to existing policy), -o - output
checkmodule -M -m -o my-vsftpd.mod my-vsftpd.te
semodule_package -o my-vsftpd.pp -m my-vsftpd.mod
semodule -i my-vsftpd.pp
66
 Set up a test environment and enable SELinux in Permissive mode
 Launch an application that needs a policy
 Extensively use the application and most of it’s features for a long period of time
(hours, days)
 Use audit2allow to generate a policy from security log
 Review the policy and remove/modify unnecessary permissions
 Use the policy in production 
audit2allow General Workflow
67
SELinux policy consists of six components:
Type enforcement (TE) attributes
TE type declarations
TE transition rules
TE change rules (not used much)
TE access vector rules
File context specifications
These components are stored in type enforcement file (.te).
Creating Custom Policy
68
 Identify sets of types with similar properties.
 SELinux does not interpret these attributes.
Attributes
# Their format is
attribute <name>
# For example
attribute logfile;
attribute privuser;
69
 Define type names, with optional aliases and attributes.
TE Type Declarations
# Their format is
type <name> [alias <aliases>] [attributes]
# For example
type mailman_log_t, file_type, sysadmfile, logfile;
type man_t alias catman_t;
70
 Specify allowed type transitions.
That can be read as:
 When a process running in the mysqld_t domain accesses a socket labeled with the
mysql_db_t type, transition to the mysqld_var_run_t domain.
TE Transition Rules
# Their format is
type_transition <source> <action> <target>
# For example
type_transition mysqld_t mysql_db_t:sock_file mysqld_var_run_t;
71
 Specify the new type to use when relabeling, based on process domain, object type,
and object class
That can be read as:
 When running in the rssh_t domain, relabel the associated terminal device as a user
terminal
TE Change Rules (Optional)
# Their format is
type_change <source> <action> <target>
# For example
type_change rssh_t server_ptynode:chr_file rssh_devpts_t;
72
 Specify the set of permissions based on a type pair and an object security class
Where <kind> can be one of:
 allow – allow requested access
 auditallow – allow requested access and log the access
 dontaudit – don’t allow and don’t log
 neverallow – stop compilation of policy
TE Access Vector Rules 1/3
# Their format is
<kind> <source> <target>:<securityclass> <permissions>
73
Can be read as:
Processes running in the initrc_t domain have get-attribute, read, and execute access
to files of type account_exec_t
Can be read as:
Processes running in the traceroute_t domain do not log the denial of a request for
name_bind permission on a tcp_socket for all types associated to the port_type
attribute (except port_t)
TE Access Vector Rules 2/3
# example
allow initrc_t acct_exec_t:file { getattr read execute };
# example
dontaudit traceroute_t { port_type -port_t }:tcp_socket name_bind;
74
Can be read as:
Processes running in the ada_t domain log the granting of a request to execute code
located on the process stack.
Can be read as:
No subsequent allow rule can permit the shadow password file to be read, except for
those rules associated with the can_read_shadow_passwords attribute.
This rule is intended to be used during the compilation of policy files, not to protect a
running system.
TE Access Vector Rules 3/3
# example
auditallow ada_t self:process { execstack execmem };
# example
neverallow ~can_read_shadow_passwords shadow_t:file read;
75
 Define default contexts for files.
 These components are stored in file context file (.fc)
 Type is optional and can be left blank.
 When it is filled, it is similar to the mode field for the ls command. The -d means to
match only directories, the -- means to match only files.
File Context Specifications
# Their format is
<name-reg-exp> [file-type][security-context]
# For example
/bin/login -- system_u:object_r:login_exec_t:s0
/var/tmp/logcheck -d system_u:object_r:logrotate_tmp_t
/etc/tripwire(/.*)? system_u:object_r:tripwire_etc_t
76
Exercise # 2. Custom Policy
77
 For this practical example we will use a simple java application Jnode
This simle application represents a typical aplication we can have on a server:
 it uses network,
 connects to the database,
 reads config files,
 writes data to tmp files,
 monitors its state (cpu, memory and disk)
Creating a Policy for Test
Application
78
Why do we need so many types?
Because all of them represent different categories of system access
Type Enforcement File: jnode.te
policy_module(jnode, 1.0.0)
# process domain
type jnode_t;
# type for executable file
type jnode_exec_t;
# type for config files
type jnode_conf_t;
# type for caching (i.e. /var/cache/)
type jnode_cache_t;
# type for log file
type jnode_log_t;
# type for temporary files
type jnode_tmp_t;
# type for the port that the application listens to (using binkp protocol)
type binkp_port_t;
79
Easy way:
audit2allow
Hard way:
Manual configuration of all permissions
Can use predefined macros to help (still doesn’t make it easy )
What’s Next?
# Macros location
/usr/share/selinux/devel/include/
# contains quite a few *.if` files with default macros‘
# for SELinux base policy and their description
# Example
cat /usr/share/selinux/devel/include/system/userdomain.if
80
 If you remember the attribute concept - some kind of container for types, that can
has special access rules too.
 It means that if we add our new type to some kind of attribute we automaticaly will
have default rights for that attribute.
 There are some predefined macros to allocate types to attribute, so you don't have
to memorize them all
Attribute Macros
# For config files
files_config_file(jnode_conf_t)
# For misc files
files_type(jnode_cache_t)
# For log files
logging_log_file(jnode_log_t)
# For temp files
files_tmp_file(jnode_tmp_t)
# For ports
corenet_port(binkp_port_t)81
 When we have all the types defined, we can set the default behaviour to our
application.
 You can find them in the *.if files easily using keywords
Default Permission Macros 1/2
# Application macros: adds jnode_t type to the list of applications
# and allows it to be launched by jnode_exec_t type
application_domain(jnode_t, jnode_exec_t)
# Daemon macros: adds jnode_t type to the list of daemons,
# allowing it to be launched by systemd and sets the transition:
# if systemd launches the file with jnode_exec_t type, then the process
# receives the jnode_t type
init_daemon_domain(jnode_t, jnode_exec_t)
# Allows the jnode_t type execute standard binary files ( /bin, /usr/bin )
corecmd_exec_bin(jnode_t)
# Allows the jnode_t type to use libraries
libs_use_ld_so(jnode_t)
# Allows the jnode_t type to read the system status ( cpu, memory )
kernel_read_system_state(jnode_t)
# Allows the jnode_t type to write to /tmp
files_rw_generic_tmp_dir(jnode_t)
# Allows the jnode_t type to read the network config files (i.e., /etc/resolv.conf)
sysnet_read_config(jnode_t)82
Default Permission Macros 2/2
# Allows the jnode_t type to read random numbers from /dev/(u)random
dev_read_rand(jnode_t)
# Allows the jnode_t type to read file ssystem attributes ( free disk space )
fs_getattr_xattr_fs(jnode_t)
# Allows the jnode_t type to do dns resolve
sysnet_dns_name_resolve(jnode_t)
# Allows the jnode_t type to read /var/log ( read_only )
logging_search_logs(jnode_t)
# Sets the rule: log files created by jnode_t process
# will have the jnode_log_t type
logging_log_filetrans(jnode_t, jnode_log_t, file)
# Sets the rule: tmp-files created by jnode_t process
# will have the jnode_tmp_t type
files_poly_member_tmp(jnode_t, jnode_tmp_t)
# Allows jnode_t to execute bind() to any address
corenet_tcp_bind_generic_node(jnode_t)
# Allows jnode_t to communicate with postgresql over unix-socket
postgresql_stream_connect(jnode_t)
# Allows jnode_t to communicate with postgresql over network
corenet_tcp_connect_postgresql_port(jnode_t)
83
 Now it is time to bind the new types to file system.
 Lets create the File Contexts file jnode.fc
File Contexts
# Executable File
/opt/jnode/jnode.run -- gen_context(system_u:object_r:jnode_exec_t)
# Everything that needs to be read_only for the service
# we can move to the "config"
/opt/jnode(/.*)? gen_context(system_u:object_r:jnode_conf_t)
/opt/jnode/jar(/.*) gen_context(system_u:object_r:jnode_conf_t)
# And the configs them self
/opt/jnode/point/.*.cfg gen_context(system_u:object_r:jnode_conf_t)
# The service will have permission to write files here,
# but will no be able to not remove them
/opt/jnode/fileechoes(/.*)? gen_context(system_u:object_r:jnode_cache_t)
/opt/jnode/point(/.*)? gen_context(system_u:object_r:jnode_cache_t)
# Here is the folder for any temporary files and folders our service generates
/opt/jnode/(inbound|temp)(/.*)? gen_context(system_u:object_r:jnode_tmp_t)
# And here we will store the log files
/var/log/jnode(/.*)? gen_context(system_u:object_r:jnode_log_t)
84
 Now we are ready to compile our module.
Compilation and installation
# Switch to the folder containing jnode.te and jnode.fc
sudo make -f /usr/share/selinux/devel/Makefile
To install the module we can use
sudo semodule -i jnode.pp
# to enable it
sudo semodule -e jnode
# Now we can set any port for our binkp_port_t type, for example
sudo semanage port -a -t binkp_port_t -p tcp 24554
# finaly change the file contexts according to contexts file
sudo restorecon -Rv /opt/jnode
# Check if rules applied
sesearch --allow -s jnode_t -d
85
 Now we are ready to compile our module.
Final audit2allow
# Now we can start the service
cd /opt/jnode/bin/ && sudo bash /opt/jnode/bin/run.sh &
# Application should be accessible at: http://127.0.0.1:8082/index.html
# After app activity
audit2allow -b -r -t jnode_t
86
87
Useful Links
SELinux Wiki - https://selinuxproject.org
RHEL SELinux Manual -
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/
SELinux in Android -
https://source.android.com/security/selinux/
88

Contenu connexe

Tendances (20)

Linux User Management
Linux User ManagementLinux User Management
Linux User Management
 
Linux
LinuxLinux
Linux
 
Linux
LinuxLinux
Linux
 
Intro to linux
Intro to linuxIntro to linux
Intro to linux
 
Presentacion debian
Presentacion debianPresentacion debian
Presentacion debian
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Linux kernel
Linux kernelLinux kernel
Linux kernel
 
Linux file system
Linux file systemLinux file system
Linux file system
 
what is LINUX ? presentation.
what is LINUX ? presentation.what is LINUX ? presentation.
what is LINUX ? presentation.
 
Linux basics
Linux basicsLinux basics
Linux basics
 
Ubuntu
UbuntuUbuntu
Ubuntu
 
Nagios
NagiosNagios
Nagios
 
Linux security introduction
Linux security introduction Linux security introduction
Linux security introduction
 
Debian Linux Overview
Debian Linux OverviewDebian Linux Overview
Debian Linux Overview
 
MR201406 A Re-introduction to SELinux
MR201406 A Re-introduction to SELinuxMR201406 A Re-introduction to SELinux
MR201406 A Re-introduction to SELinux
 
Linux kernel Architecture and Properties
Linux kernel Architecture and PropertiesLinux kernel Architecture and Properties
Linux kernel Architecture and Properties
 
Operating systems linux
Operating systems linuxOperating systems linux
Operating systems linux
 
Linux
Linux Linux
Linux
 
Operating Systems: Linux in Detail
Operating Systems: Linux in DetailOperating Systems: Linux in Detail
Operating Systems: Linux in Detail
 
Présentation ubuntu 12.10 PDF
Présentation ubuntu  12.10 PDFPrésentation ubuntu  12.10 PDF
Présentation ubuntu 12.10 PDF
 

Similaire à SELinux Basic Usage

selinuxbasicusage.pptx
selinuxbasicusage.pptxselinuxbasicusage.pptx
selinuxbasicusage.pptxPandiya Rajan
 
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security OverviewShawn Wells
 
SELinux_@gnu_group_meetup
SELinux_@gnu_group_meetupSELinux_@gnu_group_meetup
SELinux_@gnu_group_meetupJayant Chutke
 
SELinux workshop
SELinux workshopSELinux workshop
SELinux workshopjohseg
 
Unix Security
Unix SecurityUnix Security
Unix Securityreplay21
 
SELinux concept in rhel_Linux_today.pptx
SELinux concept in rhel_Linux_today.pptxSELinux concept in rhel_Linux_today.pptx
SELinux concept in rhel_Linux_today.pptxAbhradipChatterjee2
 
2008-10-15 Red Hat Deep Dive Sessions: SELinux
2008-10-15 Red Hat Deep Dive Sessions: SELinux2008-10-15 Red Hat Deep Dive Sessions: SELinux
2008-10-15 Red Hat Deep Dive Sessions: SELinuxShawn Wells
 
Linux Operating System
Linux Operating SystemLinux Operating System
Linux Operating SystemKunalKewat1
 
chroot and SELinux
chroot and SELinuxchroot and SELinux
chroot and SELinuxShay Cohen
 
Chapter 10
Chapter 10Chapter 10
Chapter 10cclay3
 
Hardening Linux, introducing Securix GNU/Linux
Hardening Linux, introducing Securix GNU/LinuxHardening Linux, introducing Securix GNU/Linux
Hardening Linux, introducing Securix GNU/LinuxMartin Holovský
 
2008 08-12 SELinux: A Key Component in Secure Infrastructures
2008 08-12 SELinux: A Key Component in Secure Infrastructures2008 08-12 SELinux: A Key Component in Secure Infrastructures
2008 08-12 SELinux: A Key Component in Secure InfrastructuresShawn Wells
 
unit 4 Se linux.docx
unit 4 Se linux.docxunit 4 Se linux.docx
unit 4 Se linux.docxthdc
 
Red Hat Linux 5 Hardening Tips - National Security Agency
Red Hat Linux 5 Hardening Tips - National Security AgencyRed Hat Linux 5 Hardening Tips - National Security Agency
Red Hat Linux 5 Hardening Tips - National Security Agencysanchetanparmar
 
Exploitation and distribution of setuid and setgid binaries on Linux systems
Exploitation and distribution of setuid and setgid binaries on Linux systemsExploitation and distribution of setuid and setgid binaries on Linux systems
Exploitation and distribution of setuid and setgid binaries on Linux systemsZero Science Lab
 
4 effective methods to disable se linux temporarily or permanently
4 effective methods to disable se linux temporarily or permanently4 effective methods to disable se linux temporarily or permanently
4 effective methods to disable se linux temporarily or permanentlychinkshady
 

Similaire à SELinux Basic Usage (20)

selinuxbasicusage.pptx
selinuxbasicusage.pptxselinuxbasicusage.pptx
selinuxbasicusage.pptx
 
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview
2009-08-11 IBM Teach the Teachers (IBM T3), Linux Security Overview
 
SELinux_@gnu_group_meetup
SELinux_@gnu_group_meetupSELinux_@gnu_group_meetup
SELinux_@gnu_group_meetup
 
SELinux workshop
SELinux workshopSELinux workshop
SELinux workshop
 
کارگاه امنیت با عنوان Stop Disabling SElinux
کارگاه امنیت با عنوان Stop Disabling SElinuxکارگاه امنیت با عنوان Stop Disabling SElinux
کارگاه امنیت با عنوان Stop Disabling SElinux
 
Unix Security
Unix SecurityUnix Security
Unix Security
 
SELinux concept in rhel_Linux_today.pptx
SELinux concept in rhel_Linux_today.pptxSELinux concept in rhel_Linux_today.pptx
SELinux concept in rhel_Linux_today.pptx
 
Linux security
Linux securityLinux security
Linux security
 
Se linux course1
Se linux course1Se linux course1
Se linux course1
 
2008-10-15 Red Hat Deep Dive Sessions: SELinux
2008-10-15 Red Hat Deep Dive Sessions: SELinux2008-10-15 Red Hat Deep Dive Sessions: SELinux
2008-10-15 Red Hat Deep Dive Sessions: SELinux
 
Linux Operating System
Linux Operating SystemLinux Operating System
Linux Operating System
 
chroot and SELinux
chroot and SELinuxchroot and SELinux
chroot and SELinux
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
Hardening Linux, introducing Securix GNU/Linux
Hardening Linux, introducing Securix GNU/LinuxHardening Linux, introducing Securix GNU/Linux
Hardening Linux, introducing Securix GNU/Linux
 
2008 08-12 SELinux: A Key Component in Secure Infrastructures
2008 08-12 SELinux: A Key Component in Secure Infrastructures2008 08-12 SELinux: A Key Component in Secure Infrastructures
2008 08-12 SELinux: A Key Component in Secure Infrastructures
 
unit 4 Se linux.docx
unit 4 Se linux.docxunit 4 Se linux.docx
unit 4 Se linux.docx
 
Linux remote
Linux remoteLinux remote
Linux remote
 
Red Hat Linux 5 Hardening Tips - National Security Agency
Red Hat Linux 5 Hardening Tips - National Security AgencyRed Hat Linux 5 Hardening Tips - National Security Agency
Red Hat Linux 5 Hardening Tips - National Security Agency
 
Exploitation and distribution of setuid and setgid binaries on Linux systems
Exploitation and distribution of setuid and setgid binaries on Linux systemsExploitation and distribution of setuid and setgid binaries on Linux systems
Exploitation and distribution of setuid and setgid binaries on Linux systems
 
4 effective methods to disable se linux temporarily or permanently
4 effective methods to disable se linux temporarily or permanently4 effective methods to disable se linux temporarily or permanently
4 effective methods to disable se linux temporarily or permanently
 

Dernier

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Dernier (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

SELinux Basic Usage

  • 1. Igor Sikorsky KPI Basic usage Composed by: As. Prof. Dmytro Minochkin Presented at: University of Luxembourg on 27.04.2017
  • 2. What is Security Enhanced Linux?  Security Enhanced Linux or SELinux is an advanced access control mechanism built into most modern Linux distributions.  It was initially developed by the US National Security Agency to protect computer systems from malicious intrusion and tampering.  Over time, SELinux was released in the public domain and various distributions have since incorporated it in their code. 2
  • 3. What is Security Enhanced Linux?  A properly configured SELinux system can greatly reduce security risks, and knowledge about it can help you troubleshoot access-related error messages.  We will learn about the concepts behind SELinux: packages, commands, and configuration files and the error messages it logs when access is denied.  We will also see a few practical instances of putting SELinux in action. 3
  • 4. Who Uses SELinux?  Available in almost all popular Linux distributions (Debian/Ubuntu, RHEL/Centos, etc.)  Starting with Android 4.3, SELinux is used for tightening the boundaries of the Android application sandbox.  Android 4.3 – Permissive Mode  Android 4.4 – Partial Enforcement Mode  Android 5.0+ - Full Enforcement Mode (More on modes later) 4
  • 5. Basic Concepts 1/2  SELinux implements what's known as MAC (Mandatory Access Control). This is implemented on top of what's already present in every Linux distribution, the DAC (Discretionary Access Control).  In a traditional security model, we have three entities: User, Group, and Other (u,g,o) who can have a combination of Read, Write, and Execute (r,w,x) permissions on a file or directory.  If a user test creates a file in his/her home directory, that user will have read/write access to it, and so will the test group. The "other" entity will possibly have no access to it. # Run as normal user # List contents of home directory of current user # with help of USER environment variable ls -lah /home/$USER 5
  • 6. Basic Concepts 2/2  test can grant (and restrict) access to these files to other users and groups or change the owner of the files.  These actions can leave critical files exposed to accounts who don't need this access.  test can also restrict to be more secure, but that's DISCRETIONARY: there's no way for the system administrator to enforce it for every single file in the system. total 16K drwx------. 3 vagrant vagrant 95 кві 16 11:42 . drwxr-xr-x. 7 root root 83 кві 16 11:40 .. -rw-------. 1 vagrant vagrant 5 кві 16 11:42 .bash_history -rw-r--r--. 1 vagrant vagrant 18 гру 6 23:19 .bash_logout -rw-r--r--. 1 vagrant vagrant 193 гру 6 23:19 .bash_profile -rw-r--r--. 1 vagrant vagrant 231 гру 6 23:19 .bashrc drwx------. 2 vagrant vagrant 29 кві 16 11:38 .ssh 6
  • 7. Another Example  When a Linux process runs, it may run as the root user or another account with superuser privileges.  If a hacker takes control of the application, they can use that application to get access to whatever resource the user account has access to.  For processes running as the root user, basically this means EVERYTHING in the Linux server. 7
  • 8. SELinux  SELinux is a way to fine-tune access control requirements.  With SELinux, you can define what a user or process can do.  It confines every process to its own domain so the process can interact with only certain types of files and other processes from allowed domains.  This prevents a hacker from hijacking any process to gain system-wide access. 8
  • 9. SELinux Intro 1/2  SELinux was originally a development project from the National Security Agency (NSA ).  The NSA integrated SELinux into the Linux kernel using the Linux Security Modules (LSM) framework. SELinux motivated the creation of LSM  Originally, the SELinux implementation used persistent security IDs (PSIDs) stored in an unused field of the ext2 inode.  These numerical representations (non-human-readable) were mapped by SELinux to a security context label.  This required modifying each file system type to support PSIDs. 9
  • 10. SELinux Intro 2/2  The next evolution of SELinux was as a loadable kernel module.  This module stored PSIDs in a normal file, and SELinux was able to support more file systems.  This solution was not optimal for performance, and was inconsistent across platforms.  Finally, the SELinux code was integrated to the 2.6.x kernel, which had full support for LSM and had extended attributes (xattrs) in the ext3 file system.  SELinux was moved to using xattrs to store security context information. The xattr namespace provides useful separation for multiple security modules existing on the same system. 10
  • 11. Test System  The commands, packages, and files that we are going to see today will be shown on CentOS 7.  The concepts remain the same for other distributions.  We will be running the commands as the root user unless otherwise stated.  If you don't have access to the root account and use another account with sudo privileges, you need to precede the commands with the sudo keyword. 11
  • 12. Test System  We will start with a bare installation of CentOS 7 with minimal packages installed and install additional software on the VM with default configurations.  We will also create a few test user accounts for training purpose.  Finaly, we will install needed SELinux-related packages. This is to ensure we can work with the latest SELinux commands.  To speed up the process we will use a combination of Vagrant VM provisioner and Virtualbox VM provider.  We will also require GIT version control system 12
  • 13. Additional Software  git version control system (https://git-scm.com/downloads)  ssh client: We can use either git-bash (for windows) or native ssh client for linux/mac  Virtualbox (https://www.virtualbox.org/) for all supported platforms  Vagrant (https://www.vagrantup.com/downloads.html) # Run as normal user git clone https://github.com/DmyMi/lux-selinux-demo.git cd lux-selinux-demo vagrant up # start provisioning, will take 5-15 minutes vagrant ssh # when provisioning is successful 13
  • 14. Overview of scripts and SELinux Packages  policycoreutils (provides utilities for managing SELinux)  policycoreutils-python (provides utilities for managing SELinux)  selinux-policy (provides SELinux reference policy)  selinux-policy-targeted (provides SELinux targeted policy)  libselinux-utils (provides some tools for managing SELinux)  setroubleshoot-server (provides tools for deciphering audit log messages)  setools (provides tools for audit log monitoring, querying policy, and file context management)  setools-console (provides tools for audit log monitoring, querying policy, and file context management)  mcstrans (tools to translate different levels to easy-to-understand format) # To see all installed SELinux Packages run as root rpm -qa | grep selinux 14
  • 15. SELinux Modes At any one time, SELinux can be in any of three possible modes:  ENFORCING - SELinux will enforce its policy on the Linux system and make sure any unauthorized access attempts by users and processes are denied  PERMISSIVE - is a semi-enabled state. SELinux doesn't apply its policy in permissive mode, so no access is denied.  DISABLED is self-explanatory  15
  • 16. Checking SELinux Modes and Status # We can run the getenforce command to check the current SELinux mode. # Run as either normal or super user getenforce # We can also run the sestatus command: # Run as either normal or super user sestatus # The later should also give additional info regarding SELinux status, # if it is enabled in either Enforcing or Permissive mode. 16
  • 17.  The main configuration file for SELinux is /etc/selinux/config  There are two directives in this file. The SELINUX directive dictates the SELinux mode and it can have three possible values as we discussed before.  The SELINUXTYPE directive determines the policy that will be used. SELinux Configuration File # We can run the following command to view its contents: cat /etc/selinux/config 17
  • 18.  Enabling SELinux is fairly simple, but unlike disabling it, should be done in a two-step process.  As a first step, we need to edit the /etc/selinux/config file to change the SELINUX directive to permissive mode. After that we need to issue a system reboot  In the second phase, we need to edit the config file to change the SELINUX directive from permissive to enforcing in the /etc/selinux/config file. Next, reboot the server again. Enable and Disable SELinux # In permissive mode Log in to your VM again and search # for the string "SELinux is preventing" from the contents of the /var/log/messages file. cat /var/log/messages | grep "SELinux is preventing“ # If there are no errors reported, we can safely move to the next step. However, it would # still be a good idea to search for text containing "SELinux" in /var/log/messages file cat /var/log/messages | grep "SELinux“ # We can also temporarily switch between enforcing and permissive modes with setenforce: setenforce permissive 18
  • 19.  At the heart of SELinux' security engine is its policy.  A policy is a set of rules that define the security and access rights for everything in the system.  When we say everything, we mean users, roles, processes, and files.  The policy defines how each of these entities are related to one another. SELinux Policy: Terminology 19
  • 20.  SELinux has a set of pre-built users. Every regular Linux user account is mapped to one or more SELinux users.  In Linux, a user runs a process. This can be as simple as the user test opening a document in the text editor (it will be test's account running the editor process) or a service account running the httpd daemon.  In the SELinux world, a process (a daemon or a running program) is called a subject. Users 20
  • 21.  A role is like a gateway that sits between a user and a process.  A role defines which users can access that process.  Roles are not like groups, but more like filters: a user may enter or assume a role at any time provided the role grants it.  The definition of a role in SELinux policy defines which users have access to that role. It also defines what process domains the role itself has access to.  Roles come into play because part of SELinux implements what's known as Role Based Access Control (RBAC). Roles 21
  • 22.  A subject is a process and can potentially affect an object.  An object in SELinux is anything that can be acted upon.  This can be a file, a directory, a port, a tcp socket, the cursor, or even an X server.  The actions that a subject can perform on an object are the subject's permissions. Subjects and Objects 22
  • 23.  A domain is the context within which an SELinux subject (process) can run.  That context is like a wrapper around the subject. It tells the process what it can and can't do.  For example, the domain will define what files, directories, links, devices, or ports are accessible to the subject. Domains for Subjects 23
  • 24.  A type is the context for a file that stipulates the file's purpose.  For example, the context of a file may dictate that it's a web page, or that the file belongs to the /etc directory, or that the file's owner is a specific SELinux user. Types for Objects 24
  • 25.  SELinux policy defines user access to roles, role access to domains, and domain access to types.  First the user has to be authorized to enter a role, and then the role has to be authorized to access the domain. The domain in turn is restricted to access only certain types of files.  The last bit, where a process running within a particular domain can perform only certain operations on certain types of objects, is called Type Enforcement (TE). What is SELinux policy? 25
  • 26.  SELinux policy is not something that replaces traditional DAC security.  If a DAC rule prohibits a user access to a file, SELinux policy rules won't be evaluated because the first line of defense has already blocked access.  SELinux security decisions come into play after DAC security has been evaluated. SELinux Policy Behavior 1/2 26
  • 27.  When an SELinux-enabled system starts, the policy is loaded into memory.  SELinux policy comes in modular format, much like the kernel modules loaded at boot time.  And just like the kernel modules, they can be dynamically added and removed from memory at run time.  The policy store used by SELinux keeps track of the modules that have been loaded. SELinux Policy Behavior 2/2 # The sestatus command shows the policy store # name. # The semodule -l command lists the SELinux # policy # modules currently loaded into memory. semodule -l | less # semodule can be used for a number other # tasks like installing, removing, reloading, # upgrading, enabling and disabling SELinux # policy modules. 27
  • 28.  Most modern distributions include binary versions of the modules as part of the SELinux packages. The policy files have a .pp extension.  The .pp files are not human readable though.  The way SELinux modularization works is that when the system boots, policy modules are combined into what's known as the active policy.  This policy is then loaded into memory. SELinux Policy Location # If there are any modules available – you can check them with ls -l /etc/selinux/targeted/modules/active/modules/ # The combined binary version of this loaded policy can be found under the # /etc/selinux/targeted/policy directory ls -l /etc/selinux/targeted/policy/ 28
  • 29.  Although you can't read the policy module files, there's a simple way to tweak their settings.  That's done through SELinux booleans.  Changed booleans are not permanent. They revert to their old values after a reboot.  To make things permanent, we can use the -P switch with the setsebool command. Changing SELinux Boolean Settings # Show the different switches that can be turned on or off, # what they do, and their current statuses. semanage boolean -l | less # To change any of the settings, we can use the setsebool command # check getsebool ftpd_anon_write # set setsebool ftpd_anon_write on # check again getsebool ftpd_anon_write 29
  • 30.  The SELinux policy for the application will determine what types of files it needs access to and what processes it can transition to.  The first part of security puts a label on each entity in the Linux system.  A label is like any other file or process attribute (owner, group, date created etc.) it shows the context of the resource.  Context is a collection of security related information that helps SELinux make access control decisions. SELinux for Processes and Files 30
  • 31. Before we go any further, here is a note about SELinux naming convention: SELinux Users are suffixed by "_u” SELinux Roles are suffixed by “_r” SELinux Types (for files) or SELinux Domains (for processes) are suffixed by "_t". Naming Conventions 31
  • 32.  Let's start by understanding SELinux file contexts.  We now have an extra column of information after the user and group ownership.  This column shows the security contexts of the files.  A file is said to have been labelled with its security context when you have this information available for it SELinux File Contexts 1/2 # regular ls -l command against the /etc directory ls –l /etc # now add the -Z flag ls –Z /etc 32
  • 33.  Let's take a closer look at one of the security contexts.  The first part is the SELinux user context for the file. We will discuss SELinux users later, but for now, we can see that it's system_u.  The second part specifies the SELinux role, which is object_r.  What's most important here is the third part, the type of the file that's listed here as etc_t. This is the part that defines what type the file or directory belongs to.  The fourth part of the security context, s0, has to do with multilevel security or MLS. SELinux File Contexts 2/2 ls –Z /etc | grep yum.conf ls –Z /etc | grep locale.conf 33
  • 34.  Let's now talk about process security contexts.  The security context has four parts: user, role, domain, and sensitivity.  The user, role, and sensitivity work just like the same contexts for files.  The domain is unique to processes. SELinux Process Contexts # Restart the Apache and SFTP services systemctl restart httpd && systemctl restart vsftpd # We can run the ps command with a few flags to show the Apache and SFTP processes running ps -efZ | grep 'httpd|vsftpd' 34
  • 35.  So far we have seen that files and processes can have different contexts, and that they are restricted to their own types or domains.  To run, a process needs to access its files and perform some actions on them (open, read, modify, or execute).  We have also learned that each process can have access to only certain types of resources (files, directories, ports, etc.).  SELinux stipulates these access rules in a policy. The access rules follow a standard allow statement structure  Class defines what the resource actually represents (file, directory, symbolic link, device, ports, etc.) How Processes Access Resources allow <domain> <type>:<class> { <permissions> }; 35
  • 36.  Let's consider the security contexts of the httpd daemon running on our system Ex. #1: Apache httpd 1/3 # The default home directory for the web server is /var/www/html. # Let's create a file within that directory and check its context touch /var/www/html/index.html ls -Z /var/www/html/* # We can use the sesearch command to check the type of access allowed for the httpd daemon sesearch --allow --source httpd_t --target httpd_sys_content_t --class file # The flags used with the command are fairly self-explanatory: -the source domain is httpd_t (the domain Apache is running in) -We are interested about target resources that are classified as files -and have a type context of httpd_sys_content_t. # Notice the line allow httpd_t httpd_sys_content_t : file { ioctl read getattr lock open } ; # This says that the httpd daemon (the Apache web server) has I/O control, read, get attribute, # lock, and open access to files of the httpd_sys_content_t type. # In this case our index.html file has the same type. 36
  • 37.  Let's first modify the web page /var/www/html/index.html  Lets try to access it in our browser: http://127.0.0.1:8080  The httpd daemon is authorized to access a particular type of file and we can see it when accessing via the browser. Ex. #1: Apache httpd 2/3 nano /var/www/html/index.html # Place the following content into the file: <html> <title> This is a test web page </title> <body> <h1>Hello Luxembourg Security :)</h1> </body> </html> # Next, we will change the permission of the # /var/www/ folder and its contents, followed by # a restart of the httpd daemon chmod -R 755 /var/www systemctl restart httpd 37
  • 38.  Let's make things a little different by changing the context of the file.  We will use the chcon command for it.  When we try to access the web page (i.e. the httpd daemon tries to read the file), you may get a Forbidden error, or you may see the generic CentOS "Testing 123" page.  To make things work again, let's change the file type with the restorecon command. Ex. #1: Apache httpd 3/3 # The --type flag for the command allows us to specify a new type for the target resource. # We are changing the file type to var_t chcon --type var_t /var/www/html/index.html # Confirm the change ls -Z /var/www/html/ # The -v switch shows the change of context labels restorecon -v /var/www/html/index.html 38
  • 39.  SELinux enforces something we can term as "context inheritance". What this means is that unless specified by the policy, processes and files are created with the contexts of their parents.  So if we have a process called "proc_a" spawning another process called "proc_b", the spawned process will run in the same domain as "proc_a" unless specified otherwise by the SELinux policy.  Similarly, if we have a directory with a type of "some_context_t", any file or directory created under it will have the same type context unless the policy says otherwise. Context Inheritance for Files and Directories # Check directory ls -Z /var/www # Copy to another directory cp /var/www/html/index.html /var/ # Check file ls -Z /var/index.html # This change of context can be overridden by the --preserver=context clause # in the cp command. # Now move and check mv /var/index.html /etc/ ls -Z /etc/index.html 39
  • 40. Ex. #2: File Context Error # Create new directory and check its context (should be default_t) mkdir -p /www/html && ls -Z /www/ # Copy our website . It should get the default_t type cp /var/www/html/index.html /www/html/ # Edit Apache config nano /etc/httpd/conf/httpd.conf # Find the following section and change it (starts at line 119) # to look like right snippet # then restart Apache using command: systemctl restart httpd DocumentRoot "/var/www/html" # # Relax access to content within /var/www. # <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> DocumentRoot "www/html" # # Relax access to content within /var/www. # <Directory "/www"> AllowOverride None # Allow open access: Require all granted </Directory> 40
  • 41.  We saw two commands for changing file contents: chcon and restorecon. Running chcon is a temporary measure.  Running chcon requires you to know the correct context for the file, as the --type flag specifies the context for the target.  restorecon doesn't need this specified. If you run restorecon, the file will have the correct context re-applied and the changes will be made permanent.  But if you don't know the file's correct context, how does the system know which context to apply when it runs restorecon? Changing and Restoring SELinux File Contexts 1/2 # extract from one of the files cat /etc/selinux/targeted/contexts/files/file_contexts | less41
  • 42.  To permanently change the context of our test file (index.html) file under /www/html, we have to follow a two-step process  First, we create our context binding using semanage command  Second, we will use restorecon to apply all the required contexts  Now we know a few more useful commands  Changing and Restoring SELinux File Contexts 2/2 # Step 1: Set file contexts for both directories semanage fcontext --add --type httpd_sys_content_t "/www(/.*)?" semanage fcontext --add --type httpd_sys_content_t "/www/html(/.*)?" # Check if contexts are added cat /etc/selinux/targeted/contexts/files/file_contexts.local # Step 2: restorecon with recursive(-R) flag restorecon -Rv /www # Verify the correct context before and after restorecon matchpathcon -V /www/html/index.html 42
  • 43.  So far we have seen how processes access file system resources.  Domain transition is the method where a process changes its context from one domain to another.  The case of domain transition is fairly common in SELinux. Domain Transition 43
  • 44.  Let’s consider the systemd process. This is the ancestor of all processes and runs within a context of init_t Domain Transition Example # Check system context ps -eZ | grep init # Check vsftpd binary context ls -Z /usr/sbin/vsftpd # Check vsftpd process ps -eZ | grep vsftpd 44
  • 45. Domain transition is subject to three strict rules: The parent process of the source domain must have the execute permission for the application sitting between both the domains (this is the entrypoint). The file context for the application must be identified as an entrypoint for the target domain. The original domain must be allowed to transition to the target domain. Domain Transition Rules 45
  • 46.  Taking the vsftpd daemon example, let's run the sesearch command with different switches to see if the daemon conforms to these three rules. Domain Transition Rule Example # See if source domain has execute permission on entry point # flags: -s – source, -t – target, -c – class, -p – permission, # -A – allow rules, -d – direct name match sesearch -s init_t -t ftpd_exec_t -c file -p execute –Ad # Check if binary is entry point for target domain sesearch -s ftpd_t -t ftpd_exec_t -c file -p entrypoint –Ad # Check if there is a transition permission sesearch -s init_t -t ftpd_t -c process -p transition -Ad 46
  • 47.  We compared domain to a hypothetical bubble around the process: something that stipulates what the process can and can't do.  This is what confines the process.  SELinux also has processes that run within unconfined domains.  Example of an unconfined process domain would be unconfined_t. Unconfined Domains 47
  • 48.  SELinux users are different entities from normal Linux user accounts, including the root account.  The user names end with _u, just like types or domain names end with _t and roles end with _r.  Different SELinux users have different rights in the system and that's what makes them useful.  When SELinux is enforced, each regular Linux user account is mapped to an SELinux user account. SELinux Users 1/4 48
  • 49.  There are only three listed here, though we've created a few more during VM provisioning?!  New users are represented by the entry shown as default. SELinux Users 2/4 # To view user mapping semanage login –l Login Name SELinux User MLS/MCS Range Service __default__ unconfined_u s0-s0:c0.c1023 * root unconfined_u s0-s0:c0.c1023 * system_u system_u s0-s0:c0.c1023 * 49
  • 50.  What does this bigger table mean? SELinux Users 3/4 # See what SELinux users are available in the system semanage user –l Labeling MLS/ MLS/ SELinux User Prefix MCS Level MCS Range SELinux Roles guest_u user s0 s0 guest_r root user s0 s0-s0:c0.c1023 staff_r sysadm_r system_r unconfined_r staff_u user s0 s0-s0:c0.c1023 staff_r sysadm_r system_r unconfined_r sysadm_u user s0 s0-s0:c0.c1023 sysadm_r system_u user s0 s0-s0:c0.c1023 system_r unconfined_r unconfined_u user s0 s0-s0:c0.c1023 system_r unconfined_r user_u user s0 s0 user_r xguest_u user s0 s0 xguest_r 50
  • 51.  Demonstration of unconfined access by regular users We had seen the list of a number of SELinux users before:  guest_u: This user doesn't have access to X-Window system (GUI) or networking and can't execute su / sudo command.  xguest_u: This user has access to GUI tools and networking is available via Firefox browser.  user_u: This user has more access than the guest accounts (GUI and networking), but can't switch users by running su or sudo.  staff_u: Same rights as user_u, except it can execute sudo command to have root privileges.  system_u: This user is meant for running system services and not to be mapped to regular user accounts. Let’s change the default behavior  SELinux Users 4/4 # run as root user id -Z # Go to GUI and log in as regular user (login: reguser & password: regpass) # run same command id -Z 51
  • 52.  Mind you though, it still doesn't stop people from logging in directly as the high- privileged user with login & password  But if you set up a passwordless SSH connection with RSA keypair for every user – it can help protect your server even if the password for regular user is known to a hacker. Restricting User Access # Use Vbox GUI # The regular user switches to the switched user account. # We assume he knows the password for switched user (it’s swpass ) su – swuser # Go to root user terminal # (-a – add a record of specified type, -s SEUSER – SELinux user type) semanage login -a -s user_u reguser # update contexts restorecon -RFv /home/reguser/ 52
  • 53. Restricting Access to Services # As root user stop Apache systemctl stop httpd # Go to GUI and log in as restricted user (login: restuser & password: respass) # assume he doesn’t know root password systemctl start httpd # Go to GUI after adding to sudoers sudo systemctl start httpd # in root terminal semanage login -a -s user_u restuser # verify user_u access to roles and user_r role access to domains (root terminal) # There are a number of httpd related domains, but httpd_t is not one of them. seinfo -uuser_u –x seinfo -ruser_r -x | grep httpd # as restricted user try to start httpd again sudo systemctl start httpd nano /etc/sudoers # in the file, add the # following line, # save and exit restuser ALL=(ALL) ALL 53
  • 54.  You can set all new users to be mapped to user_u by default  Restricting is boring. What if we want to permit a user to do something?  We have to use a more permissive role or …  We have to write our own role with all the required permissions, which requires deep understanding of available permission checks, reference policy macros and more.  It is out of the scope of this intro  Changing the Default Mapping # -m – modify a record of specified object # -r – security range for MLS/MCS semanage login -m -S targeted -s "user_u" -r s0 __default__ # verify with semanage login -l # more permissive role semanage login -a -s "sysadm_u" guestuser # update contexts restorecon -RFv /home/guestuser/ 54
  • 55. New Role Example policy_module(pgsql_admin, 1.0) # Define the pgsql_admin_r role role pgsql_admin_r; # Create a pgsql_admin_t type that has minimal rights a regular # user domain would need in order to work # on a Linux system userdom_base_user_template(pgsql_admin) # Allow the pgsql_admin_t type to execute regular binaries (f.i. id) corecmd_exec_bin(pgsql_admin_t) # Allow the user domain to read its own selinux context selinux_getattr_fs(pgsql_admin_t) # Allow the user to administer postgresql, but do not fail # if no postgresql SELinux module is loaded yet optional_policy(' postgresql_admin(pgsql_admin_t, pgsql_admin_r) ') # To allow transition from staff_r to pgsql_admin_r gen_require(' role staff_r; ') allow staff_r pgsql_admin_r; 55
  • 56.  While administering your system, you would be interested to look at the error messages logged by SELinux.  These messages are logged in specific files and they can provide detailed information about access denials.  In a CentOS 7 system you can look at two files SELinux Audit Logs 1/3 /var/log/audit/audit.log /var/log/messages # The first command is ausearch. We can make use of this command if the auditd daemon is running. # For example, let’s check our Apache server, -m – message, -c – command (process) name ausearch -m avc -c httpd 56
  • 57.  In our system a number of entries might be listed, but we will concentrate on the next one  To understand it, let's take apart each of the fields SELinux Audit Logs 2/3 type=SYSCALL msg=audit(1489938539.297:155): arch=c000003e syscall=4 success=no exit=-13 a0=7ffb8aab4130 a1=7ffe02c56fb0 a2=7ffe02c56fb0 a3=ffffff00 items=0 ppid=22187 pid=22189 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="httpd" exe="/usr/sbin/httpd" subj=system_u:system_r:httpd_t:s0 key=(null) type=AVC msg=audit(1489938539.297:155): avc: denied { getattr } for pid=22189 comm="httpd" path="/var/www/html/index.html" dev="dm-0" ino=67359616 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file 57
  • 58.  type=AVC and avc: AVC stands for Access Vector Cache.  denied { getattr }: The permission that was attempted and the result it got. In this case the get attribute operation was denied.  pid=22189. This is the process id of the process that attempted the access.  comm: The process id by itself doesn't mean much. The comm attribute shows the process command. In this case it's httpd. Immediately we know the error is coming from the web server.  path: The location of the resource that was accessed. In this case it's a file under /var/www/html/index.html.  dev and ino: The device where the target resource resides and its inode address.  scontext: The security context of the process. We can see the source is running under the httpd_t domain.  tcontext: The security context of the target resource. In this case the file type is var_t.  tclass: The class of the target resource. In this case it's a file. SELinux Audit Logs 3/3 type=AVC msg=audit(1489938539.297:155): avc: denied { getattr } for pid=22189 comm="httpd" path="/var/www/html/index.html" dev="dm-0" ino=67359616 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:var_t:s0 tclass=file 58
  • 59. An SELinux denial can be corrected in different ways Correct a wrong label on the source domain or the target resource. If not using the defaults, you will probably need to do this Change an SELinux Boolean. Many applications behaviour can be modified this way Use the application as it was intended  Add a new rule that allows the denial. Only if all of the above are not applicable! Usual Ways to Fix the Errors? 59
  • 60.  We can also use the sealert tool.  This command can be used with the id value of the error message logged in the /var/log/messages file Understanding the Error # Check if there are any errors in the logs cat /var/log/messages | grep "SELinux is preventing" # Check detailed info about the error sealert -l <your-error-id> # Or we can use audit2why that parses the logs and shows the reason in readable form # first lets search the logs for today’s errors with ausearch and pipe it to audit2why # -ts – time stamp to start the search ausearch -m avc -ts today | audit2why 60
  • 61. Exercise #1. SELinux Administration 61
  • 62.  Edit SFTP config file and uncomment anon_upload_enable=YES Step #1 # Open SFTP Config file nano /etc/vsftpd/vsftpd.conf # find and uncomment the line anon_upload_enable=YES # Restart SFTP systemctl restart vsftpd # Run the lftp cli lftp # open the connection to localhost lftp> open 127.0.0.1 # try to upload a file lftp> put .bashrc -o pub/.bashrc # try to figure why we encounter an error # hint use ls command lftp> ls -lah pub/ 62
  • 63.  Wrong DAC settings. No write permission  To solve it – exit the lftp client and change permission Step #1: Solved drwxr-xr-x 2 0 0 6 Nov 05 19:43 . drwxr-xr-x 3 0 0 17 Apr 16 11:39 .. chmod 777 /var/ftp/pub/ 63
  • 64.  Try uploading again Step #2 # Run the lftp cli lftp # open the connection to localhost lftp> open 127.0.0.1 # try to upload a file lftp> put .bashrc -o pub/.bashrc # try to figure why we encounter ANOTHER error  # hint use ausearch command ausearch -m avc -c vsftpd # or sealert on the latest entry in logfile tail /var/log/messages -n 4 | grep "SELinux is preventing" sealert -l <error-id> # or audit2why ausearch -m avc -c vsftpd | audit2why 64
  • 65.  MAC error ftpd_t domain cannot write to public_content_t type. Confirm it by running  sealert proposes two fixes: Step #2: Solved # Proposed Fix no. 1 # If you want to allow vsftpd to be able to write to shared public content # Then you need to change the label on pub to public_content_rw_t, and potentially turn on # the allow_httpd_sys_script_anon_write boolean. # Do semanage fcontext -a -t public_content_rw_t pub restorecon -R -v pub setsebool -P allow_ftpd_anon_write 1 # Proposed Fix no. 2 #You can generate a local policy module to allow this access. #Do #allow this access for now by executing: ausearch -c 'vsftpd' --raw | audit2allow -M my-vsftpd semodule -i my-vsftpd.pp sesearch --allow --source ftpd_t --target public_content_t -d 65
  • 66.  It can generate SELinux policy allow/dontaudit rules from logs of denied operations  Usually this generated policy is very unsecure Mostly used flags are:  -M – generate compiled and loadable SELinux module,  -a – get all from raw input,  -m – generate uncompiled module (type enforcement file)  Then we can view and compile this module with checkmodule  Finally we can package the compiled policy using semodule_package and installed audit2allow ausearch -c 'vsftpd' --raw | audit2allow -a -m my-vsftpd > my-vsftpd.te # -M – MLS enabled, -m – non-base policy (can be added to existing policy), -o - output checkmodule -M -m -o my-vsftpd.mod my-vsftpd.te semodule_package -o my-vsftpd.pp -m my-vsftpd.mod semodule -i my-vsftpd.pp 66
  • 67.  Set up a test environment and enable SELinux in Permissive mode  Launch an application that needs a policy  Extensively use the application and most of it’s features for a long period of time (hours, days)  Use audit2allow to generate a policy from security log  Review the policy and remove/modify unnecessary permissions  Use the policy in production  audit2allow General Workflow 67
  • 68. SELinux policy consists of six components: Type enforcement (TE) attributes TE type declarations TE transition rules TE change rules (not used much) TE access vector rules File context specifications These components are stored in type enforcement file (.te). Creating Custom Policy 68
  • 69.  Identify sets of types with similar properties.  SELinux does not interpret these attributes. Attributes # Their format is attribute <name> # For example attribute logfile; attribute privuser; 69
  • 70.  Define type names, with optional aliases and attributes. TE Type Declarations # Their format is type <name> [alias <aliases>] [attributes] # For example type mailman_log_t, file_type, sysadmfile, logfile; type man_t alias catman_t; 70
  • 71.  Specify allowed type transitions. That can be read as:  When a process running in the mysqld_t domain accesses a socket labeled with the mysql_db_t type, transition to the mysqld_var_run_t domain. TE Transition Rules # Their format is type_transition <source> <action> <target> # For example type_transition mysqld_t mysql_db_t:sock_file mysqld_var_run_t; 71
  • 72.  Specify the new type to use when relabeling, based on process domain, object type, and object class That can be read as:  When running in the rssh_t domain, relabel the associated terminal device as a user terminal TE Change Rules (Optional) # Their format is type_change <source> <action> <target> # For example type_change rssh_t server_ptynode:chr_file rssh_devpts_t; 72
  • 73.  Specify the set of permissions based on a type pair and an object security class Where <kind> can be one of:  allow – allow requested access  auditallow – allow requested access and log the access  dontaudit – don’t allow and don’t log  neverallow – stop compilation of policy TE Access Vector Rules 1/3 # Their format is <kind> <source> <target>:<securityclass> <permissions> 73
  • 74. Can be read as: Processes running in the initrc_t domain have get-attribute, read, and execute access to files of type account_exec_t Can be read as: Processes running in the traceroute_t domain do not log the denial of a request for name_bind permission on a tcp_socket for all types associated to the port_type attribute (except port_t) TE Access Vector Rules 2/3 # example allow initrc_t acct_exec_t:file { getattr read execute }; # example dontaudit traceroute_t { port_type -port_t }:tcp_socket name_bind; 74
  • 75. Can be read as: Processes running in the ada_t domain log the granting of a request to execute code located on the process stack. Can be read as: No subsequent allow rule can permit the shadow password file to be read, except for those rules associated with the can_read_shadow_passwords attribute. This rule is intended to be used during the compilation of policy files, not to protect a running system. TE Access Vector Rules 3/3 # example auditallow ada_t self:process { execstack execmem }; # example neverallow ~can_read_shadow_passwords shadow_t:file read; 75
  • 76.  Define default contexts for files.  These components are stored in file context file (.fc)  Type is optional and can be left blank.  When it is filled, it is similar to the mode field for the ls command. The -d means to match only directories, the -- means to match only files. File Context Specifications # Their format is <name-reg-exp> [file-type][security-context] # For example /bin/login -- system_u:object_r:login_exec_t:s0 /var/tmp/logcheck -d system_u:object_r:logrotate_tmp_t /etc/tripwire(/.*)? system_u:object_r:tripwire_etc_t 76
  • 77. Exercise # 2. Custom Policy 77
  • 78.  For this practical example we will use a simple java application Jnode This simle application represents a typical aplication we can have on a server:  it uses network,  connects to the database,  reads config files,  writes data to tmp files,  monitors its state (cpu, memory and disk) Creating a Policy for Test Application 78
  • 79. Why do we need so many types? Because all of them represent different categories of system access Type Enforcement File: jnode.te policy_module(jnode, 1.0.0) # process domain type jnode_t; # type for executable file type jnode_exec_t; # type for config files type jnode_conf_t; # type for caching (i.e. /var/cache/) type jnode_cache_t; # type for log file type jnode_log_t; # type for temporary files type jnode_tmp_t; # type for the port that the application listens to (using binkp protocol) type binkp_port_t; 79
  • 80. Easy way: audit2allow Hard way: Manual configuration of all permissions Can use predefined macros to help (still doesn’t make it easy ) What’s Next? # Macros location /usr/share/selinux/devel/include/ # contains quite a few *.if` files with default macros‘ # for SELinux base policy and their description # Example cat /usr/share/selinux/devel/include/system/userdomain.if 80
  • 81.  If you remember the attribute concept - some kind of container for types, that can has special access rules too.  It means that if we add our new type to some kind of attribute we automaticaly will have default rights for that attribute.  There are some predefined macros to allocate types to attribute, so you don't have to memorize them all Attribute Macros # For config files files_config_file(jnode_conf_t) # For misc files files_type(jnode_cache_t) # For log files logging_log_file(jnode_log_t) # For temp files files_tmp_file(jnode_tmp_t) # For ports corenet_port(binkp_port_t)81
  • 82.  When we have all the types defined, we can set the default behaviour to our application.  You can find them in the *.if files easily using keywords Default Permission Macros 1/2 # Application macros: adds jnode_t type to the list of applications # and allows it to be launched by jnode_exec_t type application_domain(jnode_t, jnode_exec_t) # Daemon macros: adds jnode_t type to the list of daemons, # allowing it to be launched by systemd and sets the transition: # if systemd launches the file with jnode_exec_t type, then the process # receives the jnode_t type init_daemon_domain(jnode_t, jnode_exec_t) # Allows the jnode_t type execute standard binary files ( /bin, /usr/bin ) corecmd_exec_bin(jnode_t) # Allows the jnode_t type to use libraries libs_use_ld_so(jnode_t) # Allows the jnode_t type to read the system status ( cpu, memory ) kernel_read_system_state(jnode_t) # Allows the jnode_t type to write to /tmp files_rw_generic_tmp_dir(jnode_t) # Allows the jnode_t type to read the network config files (i.e., /etc/resolv.conf) sysnet_read_config(jnode_t)82
  • 83. Default Permission Macros 2/2 # Allows the jnode_t type to read random numbers from /dev/(u)random dev_read_rand(jnode_t) # Allows the jnode_t type to read file ssystem attributes ( free disk space ) fs_getattr_xattr_fs(jnode_t) # Allows the jnode_t type to do dns resolve sysnet_dns_name_resolve(jnode_t) # Allows the jnode_t type to read /var/log ( read_only ) logging_search_logs(jnode_t) # Sets the rule: log files created by jnode_t process # will have the jnode_log_t type logging_log_filetrans(jnode_t, jnode_log_t, file) # Sets the rule: tmp-files created by jnode_t process # will have the jnode_tmp_t type files_poly_member_tmp(jnode_t, jnode_tmp_t) # Allows jnode_t to execute bind() to any address corenet_tcp_bind_generic_node(jnode_t) # Allows jnode_t to communicate with postgresql over unix-socket postgresql_stream_connect(jnode_t) # Allows jnode_t to communicate with postgresql over network corenet_tcp_connect_postgresql_port(jnode_t) 83
  • 84.  Now it is time to bind the new types to file system.  Lets create the File Contexts file jnode.fc File Contexts # Executable File /opt/jnode/jnode.run -- gen_context(system_u:object_r:jnode_exec_t) # Everything that needs to be read_only for the service # we can move to the "config" /opt/jnode(/.*)? gen_context(system_u:object_r:jnode_conf_t) /opt/jnode/jar(/.*) gen_context(system_u:object_r:jnode_conf_t) # And the configs them self /opt/jnode/point/.*.cfg gen_context(system_u:object_r:jnode_conf_t) # The service will have permission to write files here, # but will no be able to not remove them /opt/jnode/fileechoes(/.*)? gen_context(system_u:object_r:jnode_cache_t) /opt/jnode/point(/.*)? gen_context(system_u:object_r:jnode_cache_t) # Here is the folder for any temporary files and folders our service generates /opt/jnode/(inbound|temp)(/.*)? gen_context(system_u:object_r:jnode_tmp_t) # And here we will store the log files /var/log/jnode(/.*)? gen_context(system_u:object_r:jnode_log_t) 84
  • 85.  Now we are ready to compile our module. Compilation and installation # Switch to the folder containing jnode.te and jnode.fc sudo make -f /usr/share/selinux/devel/Makefile To install the module we can use sudo semodule -i jnode.pp # to enable it sudo semodule -e jnode # Now we can set any port for our binkp_port_t type, for example sudo semanage port -a -t binkp_port_t -p tcp 24554 # finaly change the file contexts according to contexts file sudo restorecon -Rv /opt/jnode # Check if rules applied sesearch --allow -s jnode_t -d 85
  • 86.  Now we are ready to compile our module. Final audit2allow # Now we can start the service cd /opt/jnode/bin/ && sudo bash /opt/jnode/bin/run.sh & # Application should be accessible at: http://127.0.0.1:8082/index.html # After app activity audit2allow -b -r -t jnode_t 86
  • 87. 87
  • 88. Useful Links SELinux Wiki - https://selinuxproject.org RHEL SELinux Manual - https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/ SELinux in Android - https://source.android.com/security/selinux/ 88

Notes de l'éditeur

  1. To understand DAC, let&amp;apos;s first consider how traditional Linux file security works.
  2. Now test can change this access.
  3. The inode is a data structure in a Unix-style file system that describes a filesystem object such as a file or a directory. Each inode stores the attributes and disk block location(s) of the object&amp;apos;s data.
  4. ENFORCING - SELinux will enforce its policy on the Linux system and make sure any unauthorized access attempts by users and processes are denied. The access denials are also written to relevant log files. We will talk about SELinux policies and logs later. PERMISSIVE - is a semi-enabled state. SELinux doesn&amp;apos;t apply its policy in permissive mode, so no access is denied. However any policy violation is still logged in the audit logs. It&amp;apos;s a great way to test SELinux before enforcing it. DISABLED is self-explanatory  (the system won&amp;apos;t be running with enhanced security).
  5. The default value is targeted. With a targeted policy, SELinux allows you to customize and fine tune access control permissions. The other possible value is &amp;quot;MLS&amp;quot; (multilevel security), an advanced mode of protection. Also for MLS, you need to install additional packages.
  6. 1. We assume that SELinux is currently disabled (if it is not - lets disable it). 2. Setting the status to permissive first is necessary because every file in the system needs to have its context labelled before SELinux can be enforced. Unless all files are properly labelled, processes running in confined domains may fail because they can&amp;apos;t access files with the correct contexts. This can cause the boot process to fail or start with errors. I will introduce contexts and domains later in the workshop. 3. The reboot process will see all the files in the server labelled with an SELinux context. Since the system is running in permissive mode, SELinux errors and access denials will be reported but it won&amp;apos;t stop anything. 4. cat /var/log/messages | grep &amp;quot;SELinux“ - It might show some errors that were happening when SELInux was either disabled or in permissive mode. These types of errors are fine. 5. We can&amp;apos;t run setenforce when SELinux is disabled.
  7. https://en.wikipedia.org/wiki/Role-based_access_control
  8. The policy itself is a number of rules that say that so-and-so users can assume only so-and-so roles, and those roles will be authorized to access only so-and-so domains. The domains in turn can access only so-and-so file types. SELinux policy implementations are also typically targeted by default. If you remember, SELINUXTYPE directive is set to be targeted in the SELinux config file that we saw before. What this means is that, by default, SELinux will restrict only certain processes in the system (i.e. only certain processes are targeted). The ones that are not targeted will run in unconfined domains. The alternative is a deny-by-default model where every access is denied unless approved by the policy. It would be a very secure implementation, but this also means that developers have to anticipate every single possible permission every single process may need on every single possible object. The default behaviour sees SELinux concerned with only certain processes.
  9. The purpose of SELinux is to secure how processes access files in a Linux environment. Without SELinux, a process or application like the Apache daemon will run under the context of the user that started it. If your system is compromised by a rogue application that&amp;apos;s running under the root user, the app can do whatever it wants because root has all-encompassing rights on every file. SELinux tries to go one step further and eliminate this risk. With SELinux, a process or application will have only the rights it needs to function and NOTHING more. Everything in a Linux system can have a security context: a user account, a file, a directory, a daemon, or a port can all have their security contexts. However, security context will mean different things for different types of objects.
  10. Each Linux user account maps to an SELinux user, and in this case, the root user that owns the file is mapped to the system_u SELinux user. This mapping is done by the SELinux policy. _ Most files belong to the etc_t type in the /etc directory. Hypothetically, you can think of type as a sort of &amp;quot;group&amp;quot; or *attribute* for the file: it&amp;apos;s a way of classifying the file. We can also see some files may belong to other types, like locale.conf which has a locale_t type. Even when all the files listed here have the same user and group owners, their types could be different. Basically this is another way of enforcing SELinux security policy, and this part shows the sensitivity of the resource (s0). We will briefly talk about sensitivity and categories later. For most setups of SELinux, the first three security contexts are more important.
  11. So what&amp;apos;s the domain doing for processes? It gives the process a context to run within. It&amp;apos;s like a bubble around the process that confines it. It tells the process what it can do and what it can&amp;apos;t do. This confinement makes sure each process domain can act on only certain types of files and nothing more. Using this model, even if a process is hijacked by another malicious process or user, the worst it can do is to damage the files it has access to. For example, the vsftp daemon will not have access to files used by say, sendmail or samba. This restriction is implemented from the kernel level: it&amp;apos;s enforced as the SELinux policy loads into memory, and thus the access control becomes mandatory.
  12. Here&amp;apos;s what this generic allow statement means: 1. If a process is of certain domain 2. And the resource object it&amp;apos;s trying to access is of certain class and type 3. Then allow the access 4. Else deny access
  13. The file context for our web content will be httpd_sys_content_t.
  14. So what&amp;apos;s happening here? Obviously some access is now being denied, but whose access is it? As far as SELinux is concerned, the web server is authorized to access only certain types of files and var_t is not one of those contexts. Since we changed the context of the index.html file to var_t, Apache can no longer read it and we get an error. If we try to access the page after restoration, it will show our test page again. This is an important concept to understand: making sure files and directories have the correct context is pivotal to making sure SELinux is behaving as it should.
  15. To illustrate this, let&amp;apos;s check the contexts of the /var/www/ directory The html directory within /var/www/ has the httpd_sys_content_t type context. As we saw before, the index.html file within it has the same context (i.e., the context of the parent). This inheritance is not preserved when files are copied to another location. In a copy operation, the copied file or directory will assume the type context of the target location. Lets copy the index.html file (with &amp;quot;httpd_sys_content_t&amp;quot; type context) to the /var/ directory. If we check the copied file&amp;apos;s context, we will see it has changed to var_t, the context of its current parent directory When files or directories are moved, original contexts are preserved. When we check the moved file&amp;apos;s context, we see that the var_t context has been preserved under the /etc/ directory
  16. We are not getting into detailed Apache configuration here; we just want our site to work for SELinux purposes. Once the server has been restarted, accessing the web page will give us the same &amp;quot;403 Forbidden&amp;quot; error (or default &amp;quot;Testing 123&amp;quot; page) we saw before.
  17. You can use chcon to temporarily change file or directory contexts for troubleshooting access denial errors. However, this method is only temporary: a file system relabel or running the restorecon command will revert the file back to its original context. Conveniently, SELinux &amp;quot;remembers&amp;quot; the context of every file or directory in the server. In CentOS 7, contexts of files already existing in the system are listed in the /etc/selinux/targeted/contexts/files/file_contexts file. It&amp;apos;s a large file and it lists every file type associated with every application supported by the Linux distribution. Contexts of new directories and files are recorded in the /etc/selinux/targeted/contexts/files/file_contexts.local file. So when we run the restorecon command, SELinux will look up the correct context from one of these two files and apply it to the target. There is also a file for listing of contexts for home directories of users.
  18. Step 1: First we run the semanage fcontext command. This will write the new context to the /etc/selinux/targeted/contexts/files/file_contexts.local file. But it won&amp;apos;t relabel the file itself. We&amp;apos;ll do this for both directories. Step 2: Next, we run the restorecon command. This will relabel the file or directory with what&amp;apos;s been recorded in the previous step This should reset the context in three levels: the top level /www directory, the /www/html directory under it and the `index.html` file under /www/html. If we now try to access the web page, it should work. There is an useful tool called matchpathcon that can help troubleshoot context-related problems. This command will look at the current context of a resource and compare it with what&amp;apos;s listed under the SELinux context database. If different, it will suggest the change required. Let’s try to check our file with the `-V` flag that verifies the context: The matchpathcon output should show that the context is verified.
  19. We will now see how processes access other processes. To understand it, let&amp;apos;s say you have a process called proc_a running within a context of context_a_t. With domain transition, proc_a can run an application (a program or an executable script) called app_x that would spawn another process. This new process could be called proc_b and it could be running within the context_b_t domain. So, context_a_t is transitioning to context_b_t through app_x. The app_x executable is working as an entrypoint to context_b_t.
  20. Let&amp;apos;s consider the vsftpd process running on our machine. If it is not running, we can run the systemctl start vsftpd command to start the daemon. The process running within the init_t domain is a short-lived one: it will invoke the binary executable /usr/sbin/vsftpd, which has a type context of ftpd_exec_t. When the binary executable starts, it becomes the vsftpd daemon itself and runs within the ftpd_t domain. So here the process running in the init_t domain is executing a binary file with the ftpd_exec_t type. That file starts a daemon within the ftpd_t domain. This transition is not something the application or the user can control. This has been stipulated in the SELinux policy that loads into memory as the system boots. In a non-SELinux server a user can start a process by switching to a more powerful account (provided she or he has the right to do so). In SELinux, such access is controlled by pre-written policies. And that&amp;apos;s another reason SELinux is said to implement Mandatory Access Control.
  21. We will now see how processes access other processes. To understand it, let&amp;apos;s say you have a process called proc_a running within a context of context_a_t. With domain transition, proc_a can run an application (a program or an executable script) called app_x that would spawn another process. This new process could be called proc_b and it could be running within the context_b_t domain. So, context_a_t is transitioning to context_b_t through app_x. The app_x executable is working as an entrypoint to context_b_t.
  22. First, the source domain init_t needs to have execute permission on the entrypoint application with the ftpd_exec_t context. The result should show that processes within init_t domain can read, get attribute, execute, and open files of ftpd_exec_t context. Next, we check if the binary file is the entrypoint for the target domain ftpd_t. And indeed it is so. Finally, the source domain init_t needs to have permission to transition to the target domain ftpd_t. As we can see, the source domain has that permission.
  23. As you can imagine, unconfined processes would have all types of access in the system. Even then, this full access is not arbitrary: full access is also specified in the SELinux policy. unconfined_t - this is the same domain logged in users run their processes by default. We will talk about users and their accesses to process domains next.
  24. An SELinux user is not something you create with a special command, nor does it have its own login access to the server. Instead, SELinux users are defined in the policy that&amp;apos;s loaded into memory at boot time, and there are only a few of these users. The SELinux user listed in the first part of a file&amp;apos;s security context is the user that owns that file. This is just like you would see a file&amp;apos;s owner from a regular ls -l command output. A user label in a process context shows the SELinux user&amp;apos;s privilege the process is running with. There can be multiple user accounts mapped to the same SELinux user. This mapping enables a regular account to inherit the permission of its SELinux counterpart.
  25. The first column in this table, &amp;quot;Login Name&amp;quot;, represents the local Linux user accounts. Any regular Linux user account is first mapped to the default login. This is then mapped to the SELinux user called unconfined_u. In our case, this is the second column of the first row. The third column shows the multilevel security / Multi Category Security (MLS / MCS) class for the user. For now, let&amp;apos;s ignore that part and also the column after that (Service). Next, we have the root user. It has been given its own entry. Once again, root is also mapped to the unconfined_u SELinux user. system_u is a different class of user, meant for running processes or daemons.
  26. First of all, it shows the different SELinux users defined by the policy. We had seen users like unconfined_u and system_u before, but we are now seeing other types of users like guest_u, staff_u, sysadm_u, user_u and so on. The names are somewhat indicative of the rights associated with them. For example, we can perhaps assume that the sysadm_u user would have more access rights than guest_u. To verify our guess, let&amp;apos;s look at the fifth column, SELinux Roles. If you remember, SELinux roles are like gateways between a user and a process. We also compared them to filters: a user may enter a role, provided the role grants it. If a role is authorized to access a process domain, the users associated with that role will be able to enter that process domain. Now from this table we can see the unconfined_u user is mapped to the system_r and unconfined_r roles. Although not evident here, SELinux policy actually allows these roles to run processes in the unconfined_t domain. Similarly, user sysadm_u is authorized for the sysadm_r role, but guest_u is mapped to guest_r role. Each of these roles will have different domains authorized for them. Now if we take a step back, we also saw from the first code snippet that the default login maps to the unconfined_u user, just like the root user. Since the __default__ login represents any regular Linux user account, those accounts will be authorized for system_r and unconfined_r roles as well. So what this really means is that any Linux user that maps to the unconfined_u user will have the privileges to run any app that runs within the unconfined_t domain.
  27. So the root account is mapped to the unconfined_u SELinux user, and unconfined_u is authorized for the unconfined_r role, which in turn is authorized to run processes in the unconfined_t domain. Go to regular user, if we execute the same id -Z command from there, the output will look the same. In this case, regulauser account is mapped to the unconfined_u SELinux user account and it can assume the unconfined_r role. The role can run processes in an unconfined domain. This is the same SELinux user/role/domain the root account also maps to. That&amp;apos;s because SELinux targeted policy allows logged in users to run in unconfined domains.
  28. To see how SELinux can enforce security for user accounts, let&amp;apos;s think about the regularuser account. As a system administrator, you now know the user has the same unrestricted SELinux privileges as the root account and you would like to change that. Specifically, you don&amp;apos;t want the user to be able to switch to other accounts, including the root account. Let&amp;apos;s first check the user&amp;apos;s ability to switch to another account. Lets go back to the root user and change regularuser&amp;apos;s SELinux user mapping. We will map regularuser to user_u. So what are we doing here? We are adding `-a` the regular user account to the SELinux `-s` user account user_u. The change won&amp;apos;t take effect until regular user logs out and logs back in. When we connect as regularuser, and try to change to switcheduser again, we receive an &amp;quot;Authentication failure&amp;quot; error. If we now run the `id -Z` command again to see the SELinux context for regular user, we will see the output is quite different from what we saw before: regular user is now mapped to user_u.
  29. Let&amp;apos;s now see how roles also play a part in restricting user access. As was said before, a role in SELinux sits between the user and the process domain and controls what domains the user&amp;apos;s process can get into. Roles are not that important when we see them in file security contexts. For files, it&amp;apos;s listed with a generic value of object_r. Roles become important when dealing with users and processes. Let&amp;apos;s first make sure that the httpd daemon is not running in the system. So the account has the default behaviour of running as unconfined_u user and having access to unconfined_r role. However, this account does not have the right to start any processes within the system. If restricted user is trying to start the httpd daemon he will get an access denied error. Next we move back to the root user terminal window and make sure the restricted user account has been added to the /etc/sudoers file. This action will enable the restricted user account to use root privileges. If we now log out of the restricted user terminal window and log back in again, we can start and stop the httpd service with sudo privileges. Now that restricteduser has been restricted to user_u (and that means to role user_r and domain user_t), we can verify its access using the `seinfo` command from our root user&amp;apos;s window The user can also stop the service now too. That&amp;apos;s all very normal: system administrators give sudo access to user accounts they trust. But what if you want to stop this particular user from starting the httpd service even when the user&amp;apos;s account is listed in the sudoers file? To see how this can be achieved, let&amp;apos;s switch back to the root user terminal window and map the restricted user to the SELinux user_u account. This is what we did for the regular user account.
  30. These files are populated by the auditd daemon and the rsyslogd daemon respectively. So what do these daemons do? The man pages say the auditd daemon is the userspace component of the Linux auditing system and rsyslogd is the system utility providing support for message logging. The /var/log/audit/audit.log file will be used if the auditd daemon is running. The /var/log/messages file is used if auditd is stopped and rsyslogd is running. If both the daemons are running, both the files are used: /var/log/audit/audit.log records detailed information while an easy-to-read version is kept in /var/log/messages. You can use the grep command to sift through /var/log/messages file. But finding something there might still be an issue. Fortunately SELinux comes with a few tools to make life a bit easier than that. These tools are not installed by default and require installing a few packages, which you should have installed by the script at the beginning.
  31. Even experienced system administrators can get confused by messages like this unless they know what they are looking for. The first part (small text) tells us detailed info about the process who encountered the error. The second part describes the actual error. Detailed description on next slide
  32. Even experienced system administrators can get confused by messages like this unless they know what they are looking for. The first part (small text) tells us detailed info about the process who encountered the error. The second part describes the actual error. SELinux caches access control decisions for resource and processes. This cache is known as the Access Vector Cache (AVC). That&amp;apos;s why SELinux access denial messages are also known as &amp;quot;AVC denials&amp;quot;. These two fields of information are saying the entry is coming from an AVC log and it&amp;apos;s an AVC event. If you look closely, the process domain is httpd_t and the file&amp;apos;s type context is var_t. Since the httpd daemon runs within a confined domain and SELinux policy stipulates this domain doesn&amp;apos;t have any access to files with var_t type, the access was denied.
  33. The first few lines of the output of sealert tell us about the remediation steps. However, if we now look near the end of the output stream, we can see the &amp;quot;Raw Audit Messages&amp;quot; section. The entry here is coming from the audit.log file, which we discussed earlier, so you can use that section to help you interpret the output.
  34. We already know the commands from Fix no. 1. What is this magic audit2allow ?!
  35. The regular expression is anchored on both ends, meaning the expression search only considers matches that start with the first character and end with the last character. This means that it ignores an expression that appears in the middle of a sentence
  36. First we need to create a type enforcement file, i.e. jnode.te, and describe the base types. jnode_exec_t will be executable by everyone and it will have type transition rules jnode_t will be the process domain and it will have all the required permissions jnode_conf_t will be read_only for the application and read_write for the administrator jnode_cache_t will be append_only for the application and read_write for the administrator jnode_log_t will be append_only for the application and read_write for syslog/logrotate/journald jnode_tmp_t will be read-write for the application and denied for everyone else binkp_port_t is needed for managing the application ports
  37. Technicaly, here we can finish the module by adding type transition rules. Afterwards, we need to compile it and install to the system, finaly we can use chcon to mark the SELinux context of the filesystem. After reading the logs with audit2allow we can get hundreds of weird lines of required permissions that can be used to make a complete module and it may even work. But we will go the hard way to better under the process. The hard way is to analyze the SELinux header files and select the required macros&amp;apos;. The /usr/share/selinux/devel/include/ folder contains quite a few `*.if` files with default macros&amp;apos; for SELinux base policy and their description. Alas, you will need to use a combination of grep and cat to find something. We will discuss only some useful, in my opinion
  38. After some time, depending on the application activity (hours, days...) we can issue the audit2allow -b -r -t jnode_t command and see any extra permissions our application needs, except the ones we already gave it. The list should be short. Then you will have to decide what should be allowed and what permissions should be left out. When audit2allow will show empty list - we can set the enforcing policy for our first application :) - sudo setenforce 1