Chapter 22. Managing SELinux

Image

The following topics are covered in this chapter:

The following RHCSA exam objectives are covered in this chapter:

  • Set enforcing and permissive modes for SELinux

  • List and identify SELinux file and process context

  • Restore default file contexts

  • Use boolean settings to modify system SELinux settings

  • Diagnose and address routine SELinux policy violations

Since the earliest days of Linux, file permissions have been the standard method of securing Linux systems. In some cases, file permissions are just not enough to secure a server fully. Let’s take a look at an example:

One morning I found out that my server was hacked. An intruder had broken through a bad script on my web server and had obtained shell access as the httpd user—this was possible due to a bug in the shell code that I was using. Using this file access, he managed to create thousands of little PHP scripts that were involved in a massive DDoS attack.

From a security perspective, it is interesting that nothing really was wrong with the security settings on this server. All permissions were set in a decent way, and the httpd user, like any other user on a Linux server, does have permissions to create files in /var/tmp, as in /tmp. So, what would have been a good solution to prevent this kind of problem?

You could, of course, argue that the administrator of the web server should have been doing a better job and should have been watching what the scripts on the server were doing. But that is not how Linux servers are normally used. The Linux server administrator does not necessarily have in-depth knowledge of the internals of all the applications running on the Linux server, and the application administrator does not understand enough about Linux to ensure that something like this can never happen.

Another solution is to apply further security measures. For instance, this specific situation would have been prevented if the permission to run program files from the /tmp and /var/tmp directory had been taken away by using the noexec mount option. But even if that would have worked for this specific situation, it is not a good overall security solution that prevents applications from doing things they are not supposed to be doing. Basically, Linux just needs a default security solution that covers all settings.

That is why SELinux was invented. SELinux provides mandatory access control to a Linux server, where every system call is denied unless it has been specifically allowed. This chapter explains how to use SELinux to make sure that serious security incidents will never happen on your server.

Tip

By any means, make sure that at the end of the exam SELinux is working on your server. If it is not, it will cost you many points!

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz allows you to assess whether you should read this entire chapter thoroughly or jump to the “Exam Preparation Tasks” section. If you are in doubt about your answers to these questions or your own assessment of your knowledge of the topics, read the entire chapter. Table 22-1 lists the major headings in this chapter and their corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes and ‘Review Questions.’

Table 22-1 “Do I Know This Already?” Section-to-Question Mapping

Foundation Topics Section

Questions

Understanding SELinux Working Modes

1–2

Understanding Context Settings and Policy

3–6

Restoring Default File Contexts

7

Using Boolean Settings to Modify SELinux Settings

8

Diagnosing and Addressing SELinux Policy Violations

9–10

1. Which of the following is not a valid SELinux mode?

a. Enforcing

b. Permissive

c. Disabled

d. Enabled

2. Which of the following commands enable you to see the current SELinux mode? (Choose two.)

a. sestatus

b. lsmode

c. semode

d. getenforce

3. Which of the following items in the context label is the most significant for SELinux system administration tasks?

a. Type

b. User

c. Role

d. Mission

4. To which of the following can SELinux security not be applied?

a. Users.

b. Files.

c. Ports.

d. It can be applied to all of the above.

5. Which command-line switch is used with many commands to display SELinux-related information?

a. -S

b. -X

c. -Z

d. -D

6. Which of the following commands should be used to set the context type of the directory /web to httpd_sys_content_t?

a. chcon -t httpd_sys_content_t /web

b. semanage -t httpd_sys_content_t "/web(/.*)?"

c. semanage fcontext -t httpd_sys_content_t "/web(/.*)?"

d. semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"

7. Which command must you run to ensure that a file has the appropriate SELinux context after moving the file to another location?

a. reboot

b. restorecon /new/filename

c. chcon

d. restorecon -R /etc/selinux -v

8. Which command enables you to change a Boolean in a way that it survives a reboot?

a. chcon boolean -P

b. setsebool -P

c. setsebool

d. semanage boolean

9. Which file contains all information you need to troubleshoot SELinux messages?

a. /var/log/audit/audit.log

b. /var/log/selinux/selinux.log

c. /var/log/messages

d. /var/log/selinux.log

10. You want to grep the log file for SELinux log messages. Which of the following strings should you use grep on?

a. selinux

b. deny

c. violation

d. avc

Foundation Topics

Understanding SELinux Working and Modes

If SELinux is enabled and nothing else has been configured, all system calls are denied. To specify what exactly is allowed, a policy is used. In this policy, rules define which source domain is allowed to access which target domain. The source domain is the object that is trying to access something. Typically, this is a process or a user. The target domain is the object that is accessed. Typically, that is a file, a directory, or a network port. To define exactly what is allowed, context labels are used. Using these labels is the essence of SELinux because these labels are used to define access rules. Table 22-2 summarizes the most important SELinux building blocks.

Key topic

Table 22-2 SELinux Core Elements

Element

Use

Policy

A collection of rules that define which source has access to which target.

Source domain

The object that is trying to access a target. Typically a user or a process.

Target domain

The thing that a source domain is trying to access. Typically a file or a port.

Context

A security label that is used to categorize objects in SELinux.

Rule

A specific part of the policy that determines which source domain has which access permissions to which target domain.

Labels

Same as a context label, defined to determine which source domain has access to which target domain.

On a Linux system, you can choose to enable or disable SELinux. When SELinux is enabled, kernel support for SELinux is loaded, and some applications that are SELinux aware change their behavior, because specific libraries are used on a system that has SELinux enabled. If SELinux is disabled, no SELinux activity happens at all. Changing between SELinux enabled mode and SELinux disabled mode requires a reboot of your system. This is because SELinux is a feature that is deeply interwoven with the Linux kernel.

If on a system SELinux is enabled, you can select to put SELinux in enforcing mode or in permissive mode. In enforcing mode, SELinux is fully operational and enforcing all SELinux rules in the policy. If SELinux is in permissive mode, all SELinux-related activity is logged, but no access is blocked. This makes SELinux permissive mode an excellent mode to do troubleshooting. Permissive mode is also a great way to do something and see the result from an SELinux perspective by analyzing the messages that are written to /var/log/audit/audit/log. That can help in building new and more efficient policies.

To set the default SELinux mode while booting, use the file /etc/sysconfig/selinux. Example 22-1 shows the content of this file.

Example 22-1 Content of the /etc/sysconfig/selinux File

[root@server1 ~]# cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#      enforcing - SELinux security policy is enforced.
#      permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these two values:
#      targeted - Targeted processes are protected,
#      minimum - Modification of targeted policy. Only selected
         processes are protected.
#      mls - Multi Level Security protection.
SELINUXTYPE=targeted

As you can see, in this file, which is read while booting, you can choose to put SELinux in enforcing, permissive, or disabled mode.

On a server that currently has SELinux enabled, you can use the getenforce command to see whether SELinux currently is in enforcing mode or in permissive mode. To switch between permissive mode and enforcing mode, you can use setenforce. The command setenforce 0 temporarily puts SELinux in permissive mode, and setenforce 1 puts SELinux temporarily in enforcing mode. To change the default mode persistently, you need to write it to /etc/sysconfig/selinux.

Another useful command is sestatus. If used with the option -v, this command shows detailed information about the current status of SELinux on a server. Example 22-2 shows the output of the sestatus -v command. It not only shows you which parts of SELinux are enabled but also shows the current version of the policy that is loaded and the context labels for some critical parts of the system.

Example 22-2 Using sestatus -v to Get Detailed Information About the Current Protection Status

[root@server1 ~]# sestatus -v
SELinux status:               enabled
SELinuxfs mount:              /sys/fs/selinux
SELinux root directory:       /etc/selinux
Loaded policy name:           targeted
Current mode:                 enforcing
Mode from config file:        enforcing
Policy MLS status:            enabled
Policy deny_unknown status:   allowed
Memory protection checking:   actual (secure)
Max kernel policy version:    31

Process contexts:
Current context:              unconfined_u:unconfined_r:unconfined_
                                t:s0-s0:c0.c1023
Init context:                 system_u:system_r:init_t:s0
/usr/sbin/sshd                system_u:system_r:sshd_t:s0-s0:c0.c1023

File contexts:
Controlling terminal:         unconfined_u:object_r:user_devpts_t:s0
/etc/passwd                   system_u:object_r:passwd_file_t:s0
/etc/shadow                   system_u:object_r:shadow_t:s0
/bin/bash                     system_u:object_r:shell_exec_t:s0
/bin/login                    system_u:object_r:login_exec_t:s0
/bin/sh                       system_u:object_r:bin_t:s0 ->
                                system_u:object_r:shell_exec_t:s0
/sbin/agetty                  system_u:object_r:getty_exec_t:s0
/sbin/init                    system_u:object_r:bin_t:s0 ->
                                system_u:object_r:init_exec_t:s0
/usr/sbin/sshd                system_u:object_r:sshd_exec_t:s0

In Exercise 22-1, you practice working with these different modes.

Exercise 22-1 Manipulating SELinux Modes

  1. Open a root console on your server and type getenforce. You’ll normally see that SELinux is in enforcing mode. If the output of getenforce shows SELINUX=disabled, edit the /etc/sysconfig/selinux file and change SELINUX= to enforcing (that is, SELINUX=enforcing). Then save the file and reboot the system before you continue.

  2. Type setenforce 0 and type getenforce again. SELinux now switches to permissive mode.

  3. Open the file /etc/sysconfig/selinux with an editor and change the line SELINUX= so that it reads SELINUX=disabled. Reboot your server.

  4. After rebooting, log in to a root shell again and type getenforce. You’ll see that SELinux is now in disabled mode.

  5. Try using the command setenforce 1. You’ll see the message “setenforce: SELinux is disabled.” You cannot switch between disabled and enforcing mode without rebooting your server.

  6. Open the file /etc/sysconfig/selinux again and change the line SELINUX=disabled back to SELINUX=enforcing. Reboot your system again.

  7. After rebooting, type sestatus -v and read current status information about SELinux.

Tip

Whatever you do, do not change the contents of the /etc/sysconfig/selinux file on the exam. Your exam system must be configured with SELinux in enforcing mode. To troubleshoot SELinux, you can put it temporarily in permissive mode by using setenforce 0. In this mode, you can troubleshoot any SELinux problem, but at least you’ll be sure that after a reboot your server is started in a mode where SELinux is enabled, which is an essential requirement if you want to pass the exam.

Note that on real Red Hat servers, SELinux on occasion is set to be disabled. Putting SELinux in disabled mode certainly makes it easier for administrators to run their applications. However, it also makes the server much less secure. Often, ignorance of the system administrator is the only reason SELinux is put in disabled mode. If an application vendor tells you that the application is supported only if SELinux is disabled, that simply means the application vendor has no knowledge about SELinux.

A fully enforcing system is especially important if your server is accessed directly by users from the Internet. If your server cannot be reached directly from the Internet and is in a safe internal network, having SELinux enabled is not strictly necessary (but I recommend always keeping it in enforcing mode anyway). On the RHCSA exam, however, you must make sure that SELinux is enabled and fully protecting your server.

Note

SELinux is often disabled on servers either because of administrator laziness or because an application vendor who doesn’t know how to deal with it has instructed the administrator to disable it. On many occasions, even applications that do not know how to work with SELinux can be fully functional on a server with SELinux. It just takes a bit more work to figure out the additional rules in the policy that need to be created to use the application on an SELinux-enabled system.

Understanding Context Settings and the Policy

Context settings are an important part of SELinux operations. The context is a label that can be applied to different objects:

Key topic
  • Files and directories

  • Ports

  • Processes

  • Users

Context labels define the nature of the object, and SELinux rules are created to match context labels of source objects to the context labels of target objects. So, setting correct context labels is a very important skill for system administrators. You learn how to do that later in this chapter.

Note

Managing SELinux context labels is a key skill for securing systems with SELinux. It is not listed in the RHCSA exam objectives though. Nevertheless, I’ll give you a decent explanation of how context labels work, because a mismatch of context labels can create lots of SELinux-related problems.

Monitoring Current Context Labels

To see current context settings on the objects in the previous bulleted list, many commands offer support for the -Z option. In Example 22-3, you see how ls -Z shows context settings for some directories in the / file system. Other commands also support the -Z option to show current context label settings. Some examples are ps Zaux, which shows a list of all processes, including their context label, or ss -Ztul, which shows all network ports and the current context label associated with each port.

Example 22-3 Displaying Context Labels on Files with ls –Z

[root@server1 /]# ls -Z
        system_u:object_r:bin_t:s0 bin    unconfined_u:object_r:
                                            default_t:s0 repo
        system_u:object_r:boot_t:s0 boot  system_u:object_r:admin_
                                            home_t:s0 root
      system_u:object_r:device_t:s0 dev   system_u:object_r:var_
                                            run_t:s0 run
        system_u:object_r:etc_t:s0 etc    system_u:object_r:bin_t:
                                            s0 sbin
  system_u:object_r:unlabeled_t:s0 files  system_u:object_r:var_t:
                                            s0 srv
  system_u:object_r:home_root_t:s0 home   system_u:object_r:root_t:
                                            s0 stratis
       system_u:object_r:lib_t:s0 lib     system_u:object_r:unlabeled_
                                            t:s0 stratis1
       system_u:object_r:lib_t:s0 lib64   system_u:object_r:sysfs_t:
                                            s0 sys
       system_u:object_r:mnt_t:s0 media   system_u:object_r:tmp_t:
                                            s0 tmp
       system_u:object_r:mnt_t:s0 mnt     system_u:object_r:usr_t:
                                            s0 usr
       system_u:object_r:usr_t:s0 opt     system_u:object_r:var_t:
                                            s0 var
      system_u:object_r:proc_t:s0 proc    system_u:object_r:
                                            unlabeled_t:s0 vdo1

Every context label always consists of three different parts:

Key topic
  • User: The user can be recognized by _u in the context label; it is set to system_u on most directories in Example 22-3. SELinux users are not the same as Linux users, and they are not important on the RHCSA exam.

  • Role: The role can be recognized by _r in the context label. In Example 22-3, most objects are labeled with the object_r role. In advanced SELinux management, specific SELinux users can be assigned permissions to specific SELinux roles. For the RHCSA exam, you do not have to know how to configure roles.

  • Type: The type context can be recognized by _t in the context label. In Example 22-3, you can see that a wide variety of context types are applied to the directories in the / file system. Make sure that you know how to work with context types, because they are what the RHCSA exam expects you to know.

Tip

Just to make sure that you are focusing on the parts that really matter on the RHCSA exam, you need to work with context types only. You can safely ignore the user and role parts of the context label.

Setting Context Types

As an administrator, it is important that you know how to set context types. You can set these context types on files and directories and other objects such as network ports. Let’s focus on that task first.

You can use two commands to set context type:

  • semanage: This is the command you want to use. The semanage command writes the new context to the SELinux policy, from which it is applied to the file system.

  • chcon: This command is for use in specific cases only and normally should be avoided. The chcon command writes the new context to the file system and not to the policy. Everything that is applied with chcon is overwritten when the file system is relabeled, or the original context is restored from the policy to the file system. Do not use this command!

Note

You might want to know why I bother mentioning chcon if you should not use it. Well, you’ll often see the chcon command still being referred to in the documentation, which might give the impression that it is a useful command. It is not, because if your file system is relabeled, all changes applied with chcon are lost. File system relabeling actions can take you by surprise if you are new to SELinux, and you will fail your exam if by accident a file system relabeling happens on a file system where you have applied SELinux context with chcon. So, I repeat: Do not use it.

Tip

The semanage command may not be installed by default. Fortunately, you can type yum whatprovides */semanage to find the RPM containing semanage and then install it. Do not learn the names of all relevant RPMs by heart; just remember yum whatprovides. It will find any RPM you need. See Chapter 9, “Managing Software,” for more information about the use of the yum command and package management in general.

To set context using semanage, you first need to find the appropriate context (a topic covered in more depth in the next section, “Finding the Context Type You Need”). An easy way to find the appropriate context is by looking at the default context settings on already-existing items. If you want to change the context for a web server, for example, type ls -Z /var/www to see the context settings:

[root@server1 /]# ls -Z /var/www
drwxr-xr-x. root root system_u:object_r:httpd_sys_script_exec_t:s0
  cgi-bin
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 html

As you can see, the context settings on /var/www/html are set to httpd_sys_content_t. (As a reminder, we’re looking only at the context type because the user and role are for advanced use only.) To set this context type to any new directory that you want to be accessible by the Apache web server, use the following command:

semanage fcontext -a -t httpd_sys_content_t "/mydir(/.*)?"

In this command, the option -a is used to add a context type. This is what you need to do for all directories that you have created manually yourself. Then you use -t to change the context type (as opposed to user and role). The last part of the command is a regular expression, which is used to refer to the directory /mydir and anything that might exist below this directory.

Setting the context in this way is not enough, though, because you’ll write it only to the policy and not to the file system. To complete the command, you need to apply the policy setting to the file system, as follows:

restorecon -R -v /mydir

You’ll see that the new context is now applied, which allows the httpd process to access the directory.

Tip

The semanage command is not the easiest command to remember. Fortunately, it has some excellent man pages. Type man semanage and use G to go all the way down to the bottom of the man page. You’ll now see the “See Also” section, which mentions semanage-fcontext, which is about managing file context with semanage. Open this man page using man semanage-fcontext, type /examples, and you’ll see some pretty examples that mention exactly what you need to know (see Example 22-4).

Example 22-4 semanage fcontext Usage Example from the man Page

EXAMPLE
      remember to run restorecon after you set the file context
      Add file-context for everything under /web
      # semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
      # restorecon -R -v /web

      Substitute /home1 with /home when setting file context
      # semanage fcontext -a -e /home /home1
      # restorecon -R -v /home1

      For home directories under top level directory, for example
        /disk6/home,
      execute the following commands.
      # semanage fcontext -a -t home_root_t "/disk6"
      # semanage fcontext -a -e /home /disk6/home
      # restorecon -R -v /disk6

SEE ALSO
      selinux (8), semanage (8)

AUTHOR
      This man page was written by Daniel Walsh <[email protected]>

                                  20130617      semanage-fcontext(8)

Now it is time for an exercise. In Exercise 22-2, you learn how to change the document root for the Apache web server and label the new document root in the right way.

Exercise 22-2 Setting a Context Label on a Nondefault Apache Document Root

  1. Open a root shell and type yum install httpd curl -y.

  2. Still from the root shell, type mkdir /web.

  3. Type vim /web/index.html and put the following contents in the file: welcome to my web server.

  4. Type vim /etc/httpd/conf/httpd.conf to open the Apache configuration file and find the DocumentRoot parameter. Change it so that it reads DocumentRoot "/web".

  5. In the same httpd.conf configuration file, add the following section, as without this section it will be Apache and not SELinux blocking access to the new DocumentRoot:

    <Directory "/web">
        AllowOverride None
        Require all granted
    </Directory>
  6. Type systemctl enable --now httpd to start and enable the httpd service. Note that if the httpd service was already running, you’ll need to use systemctl restart httpd to restart it so that it can pick up the changes you’ve made to the httpd.conf configuration file.

  7. Type curl http://localhost. You’ll see the default Red Hat web page and not the contents of the index.html file you have just created.

  8. Type setenforce 0 to switch SELinux to permissive mode.

  9. Repeat step 7. You’ll now get access to your custom web page, which proves that SELinux was doing something to block access.

  10. Type semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?" to apply the new context label to /web.

  11. Type restorecon -R -v /web. The -v (verbose) option ensures that you see what is happening and that you will see the new context being applied to /web.

  12. Set SELinux back in enforcing mode, using setenforce 1.

  13. Type elinks http://localhost. You’ll now get access to your custom web page because SELinux now allows access to it.

Finding the Context Type You Need

One of the challenging parts of setting SELinux contexts is finding the context you need. Roughly, there are three approaches:

  • Look at the default environment.

  • Read the configuration files.

  • Use man -k _selinux to find SELinux-specific man pages for your service.

The most powerful way of getting the SELinux information you need is by using man -k _selinux, which searches the database of man pages for man pages that match _selinux in the name or description of the man page. On RHEL 8, however, these man pages are not installed by default. To install them, you need to install the policycoreutils-devel package, after which you can use the command sepolicy manpage -a -p /usr/share/man/man8 to install the SELinux man pages. Exercise 22-3 guides you through the procedure you need to apply to install the application-specific SELinux man pages.

Tip

Exercise 22-3 shows an essential skill. Make sure that you master this procedure before taking the exam.

Exercise 22-3 Installing SELinux-Specific Man Pages

  1. Type man -k _selinux. You’ll probably see just one or two man pages.

  2. Type yum provides */sepolicy. This shows you the name of the RPM that contains the sepolicy binary, which is policycoreutils-devel.

  3. Type yum -y install policycoreutils-devel to install this package.

  4. Type sepolicy manpage -a -p /usr/share/man/man8 to install the man pages.

  5. Type man -k _selinux. You’ll see no changes yet.

  6. Type mandb to update the database that contains names and descriptions of all man pages that are installed.

  7. Once the mandb command has finished (this can take a few minutes), type man -k _selinux. You’ll now see a long list of man pages scrolling by.

  8. Type man -k _selinux | grep http to find the man page that documents SELinux settings for the httpd service and scroll through it. Notice that it is a complete list of all that you can do with SELinux on the httpd service.

Restoring Default File Contexts

In the previous section, you learned how to apply context types using semanage. You also applied the context settings from the policy to the file system using restorecon. The restorecon command is a useful command because in the policy the default settings are defined for most files and directories on your computer. If the wrong context setting is ever applied, you just have to type restorecon to reapply it from the policy to the file system.

Using restorecon this way can be useful to fix problems on new files. Before explaining how to do it, let’s take a look at how new context settings are applied:

Key topic
  • If a new file is created, it inherits the context settings from the parent directory.

  • If a file is copied to a directory, this is considered a new file, so it inherits the context settings from the parent directory.

  • If a file is moved, or copied while keeping its properties (by using cp -a), the original context settings of the file are applied.

Especially the latter of these three situations is easily fixed by using restorecon. Exercise 22-4 simulates this problem, and you fix it using restorecon.

It is also possible to relabel the entire file system. Doing so applies all context settings as defined in the policy to the file system. Because the policy should always be leading and contain correct context settings, relabeling a file system may be a good idea. To relabel the file system, you can either use the command restorecon -Rv / or create a file with the name /.autorelabel. The next time your server is restarted, the file system will automatically be relabeled.

A relabeling action sometimes occurs spontaneously. If while troubleshooting a server you have started the server in a mode where SELinux is disabled, and you have applied modifications to the file system, SELinux will detect that the file system has changed without SELinux monitoring it. This will result in an automatic relabeling of the entire file system. Note that on a large file system, relabeling the file system can take a significant amount of time.

Exercise 22-4 Using restorecon to Relabel Files

  1. From a root shell, type ls -Z /etc/hosts. You’ll see the file has the net_conf_t context label.

  2. Type cp /etc/hosts ~ to copy the file to the root home directory. Because copying is considered the creation of a new file, the context setting on the ~/hosts file is set as admin_home_t. Use ls -Z ~/hosts to verify this.

  3. Type mv ~/hosts /etc and confirm that you want to overwrite the existing file.

  4. Type ls -Z /etc/hosts to confirm that the context type is still set to admin_home_t.

  5. Type restorecon -v /etc/hosts to reapply the correct context type. The -v option shows you what is happening.

  6. Type touch /.autorelabel and restart your server. While restarting, make sure to press the Escape key on your keyboard so that you’ll see boot messages. You’ll see that the file system is automatically relabeled.

Using Boolean Settings to Modify SELinux Settings

In the SELinux policy, there are many rules. Some of these rules allow specific activity, whereas other rules deny that activity. Changing rules is not easy, and that is why SELinux Booleans are provided to easily change the behavior of a rule.

An example of a Boolean is ftpd_anon_write, which by default is set to off. That means that even if you have configured your FTP server to allow anonymous writes, the Boolean will still deny it, and the anonymous user cannot upload any files. If a conflict exists between the setting of a parameter in a service configuration file and in a Boolean, the Boolean always takes precedence. But Booleans are easy to change.

To get a list of Booleans on your system, type getsebool -a. If you are looking for Booleans that are set for a specific service, use grep to filter down the results. In Example 22-5, you can see how this command is used to show current Booleans that match FTP.

An alternative way to show current Boolean settings is by using the semanage boolean -l command. This command provides some more details, because it shows the current Boolean setting and the default Boolean setting.

Example 22-5 Displaying Boolean Settings

root@server1 ~]# getsebool -a | grep ftp
ftp_home_dir --> off
ftpd_anon_write --> off
ftpd_connect_all_unreserved --> off
ftpd_connect_db --> off
ftpd_full_access --> off
ftpd_use_cifs --> off
ftpd_use_fusefs --> off
ftpd_use_nfs --> off
ftpd_use_passive_mode --> off
httpd_can_connect_ftp --> off
httpd_enable_ftp_server --> off
sftpd_anon_write --> off
sftpd_enable_homedirs --> off
sftpd_full_access --> off
sftpd_write_ssh_home --> off
tftp_anon_write --> off
tftp_home_dir --> off

To change a Boolean, you can use setsebool. If you want to switch the ftpd_anon_write Boolean to allow anonymous writes, for example, use setsebool ftpd_anon_write on. This changes the runtime value of the Boolean but does not change it permanently. To apply permanent changes to a Boolean, use setsebool -P. Notice that this takes longer, because parts of the policy need to be recompiled to apply the modification. In Exercise 22-5, you apply these commands to see how Booleans are working.

Exercise 22-5 Working with SELinux Booleans

  1. From a root shell, type getsebool -a | grep ftp. You’ll see the ftpd_anon_write Boolean, with its current value set to off.

  2. Type setsebool ftpd_anon_write on. This changes the value in the runtime.

  3. Type getsebool ftpd_anon_write. It shows the value of the Boolean as on.

  4. Type semanage boolean -l | grep ftpd_anon. Notice that this command shows the runtime configuration set to on, but the permanent setting is still set to off.

  5. Use setsebool -P ftpd_anon_write on to switch the runtime and the default setting for the Boolean to on.

  6. Repeat semanage boolean -l | grep ftpd_anon. Notice that it is now set to on, on.

Diagnosing and Addressing SELinux Policy Violations

Configuring a system with SELinux can be a challenging task. To make it easier to understand what is happening, SELinux logs everything it is doing. The primary source to get logging information is the audit log, which is in /var/log/audit/audit.log. SELinux messages are logged with type=AVC in the audit log. So, to see what SELinux is doing, you can use the command grep AVC /var/log/audit/audit.log. If SELinux messages have been logged, this command shows a result as in Example 22-6.

Example 22-6 Getting SELinux Messages from audit.log

[root@server1 ~]# grep AVC /var/log/audit/audit.log | grep http
type=AVC msg=audit(1559986797.093:185): avc:  denied  { getattr }
  for  pid=32939 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986797.093:186): avc:  denied  { getattr }
  for  pid=32939 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986815.360:188): avc:  denied  { getattr }
  for  pid=32939 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986815.360:189): avc:  denied  { getattr }
  for  pid=32939 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986883.549:192): avc:  denied  { getattr }
  for  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986883.550:193): avc:  denied  { getattr }
  for  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=0
type=AVC msg=audit(1559986927.406:197): avc:  denied  { getattr }
  for  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=1
type=AVC msg=audit(1559986927.406:198): avc:  denied  { read } for
  pid=33214 comm="httpd" name="index.html" dev="dm-0" ino=35321780 sco
  ntext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:
  default_t:s0 tclass=file permissive=1
type=AVC msg=audit(1559986927.406:198): avc:  denied  { open }
  for  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=1
type=AVC msg=audit(1559986927.406:199): avc:  denied  { map }
  for  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=1

At first sight, the SELinux log messages look complicated. If you look a bit closer, though, they are not that hard to understand. Let’s take a closer look at the last line in the log file:

type=AVC msg=audit(1559986927.406:199): avc:  denied  { map } for
  pid=33214 comm="httpd" path="/web/index.html" dev="dm-0"
  ino=35321780 scontext=system_u:system_r:httpd_t:s0 tcontext=
  unconfined_u:object_r:default_t:s0 tclass=file permissive=1

The first relevant part in this line is the text avc: denied { map }. That means that a map request was denied, so some process has tried to read attributes of a file and that was denied, because it is a policy violation. Following that message, we can see comm=httpd, which means that the command trying to issue the getattr request was httpd, and we can see path=”web/index.html”, which is the file that this process has tried to access.

In the last part of the log line, we can get information about the source context and the target context. The source context (which is the context setting of the httpd command) is set to http_t, and the target context (which is the context setting of the /web/index.html file) is set to default_t. And apparently, SELinux did not like that too much. So, to fix this, you would have to relabel the file, as discussed earlier in the chapter.

Making SELinux Analyzing Easier

Based on the information you find in the audit.log, you may be able to decide what you need to do to fix the problem. Because the information in the audit.log is not easy to understand, there is sealert. First, you may need to install sealert by using yum -y install setroubleshoot-server. Then, it is a good idea to restart your server to make sure that all processes that are involved are restarted correctly. The next time an SELinux message is written to the audit log, an easier-to-understand message is written to syslog and, by default, can be read in /var/log/messages. Example 22-7 shows an output example.

Example 22-7 sealert Makes Analyzing SELinux Logs Easier

Nov 2 10:01:40 server1 setroubleshoot: Plugin Exception restorecon
Nov 2 10:01:40 server1 setroubleshoot: SELinux is preventing /usr/
  sbin/httpd from getattr access on the file. For complete SELinux
  messages. run sealert -l 0ed02423-1149-4561-b6a0-8ea2957329ea
Nov 2 10:01:40 server1 python: SELinux is preventing /usr/sbin/httpd
  from getattr access on the file.

***** Plugin catchall_labels (83.8 confidence) suggests
  *******************

If you want to allow httpd to have getattr access on the file
Then you need to change the label on $FIX_TARGET_PATH
Do
# semanage fcontext -a -t FILE_TYPE '$FIX_TARGET_PATH'
where FILE_TYPE is one of the following: NetworkManager_exec_t,
  NetworkManager_log_t,
--removed 5 pages of the "one of the following" output --
Then execute:
restorecon -v '$FIX_TARGET_PATH'


***** Plugin catchall (17.1 confidence) suggests
  **************************

If you believe that httpd should be allowed getattr access on the
  file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# grep httpd /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp

The useful thing about sealert is that it tries to analyze what has happened and, based on the analysis, suggests what you need to do to fix the problem. The not-so-useful part is that in some cases (as was the case in this example), hundreds of possible context types are shown, and the administrator has to choose the right one. (I removed five pages of output in Example 22-6 to keep it readable.) So, if you do not know what you are doing, you risk getting completely lost.

When working with sealert, you can see that different plug-ins are called, and every plug-in has a confidence score. If, as in the example in Example 22-6, one plug-in has an 83.8% confidence score, while the other has only a 17.1% confidence score, it may be obvious that the former approach is what you should choose. Unfortunately, however, it is not always that readable.

Tip

If you are not sure what SELinux is trying to tell you, install the setroubleshoot-server package and analyze what sealert shows. The information that is shown by sealert is often a lot more readable. Sometimes it will not help you at all, whereas sometimes the information can prove quite helpful.

Preparing for SELinux Coverage on the Exam

If this is the first time you’ve read about SELinux, you may find it overwhelming. That’s natural, because SELinux is rather overwhelming. In this chapter I’ve tried to give you a rather complete overview of how SELinux works. Fortunately, you don’t have to know all of this material for the RHCSA exam.

In the current specification of the RHCSA exam, there is nothing about configuration of services. SELinux is mostly useful for configuring services, but you don’t have to install and secure any web, FTP, or file services on the RHCSA 8 exam. What does remain are the following tasks, and you better make sure you master them well before taking the exam:

  • Ensure that SELinux is enabled and in enforcing mode by editing /etc/sysconfig/selinux.

  • Use restorecon to reapply the right context to a file or directory.

  • Use sealert to troubleshoot why SELinux isn’t working.

  • Make sure you know how to troubleshoot SELinux port-related issues.

Summary

This chapter provided an RHCSA-level introduction to SELinux. You’ve learned why SELinux is needed for security and how SELinux uses context as the main feature to apply security. You’ve also learned how to set the default SELinux mode and how to analyze in case things go wrong.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have several choices for exam preparation: the end-of-chapter labs; the memory tables in Appendix B; Chapter 26, “Final Preparation”; and the practice exams.

Review All Key Topics

Review the most important topics in the chapter, noted with the Key Topic icon in the outer margin of the page. Table 22-3 lists a reference of these key topics and the page number on which each is found.

Key topic

Table 22-3 Key Topics for Chapter 22

Key Topic Element

Description

Page

Table 22-2

SELinux core elements

475

List

Elements a context label can be applied to

479

List

Three parts of a context label

480

List

How new context settings are applied

486

Complete Tables and Lists from Memory

Print a copy of Appendix B, “Memory Tables” (found on the companion website), or at least the section for this chapter, and complete the tables and lists from memory. Appendix C, “Memory Tables Answer Key,” includes completed tables and lists to check your work.

Define Key Terms

Define the following key terms from this chapter and check your answers in the glossary:

policy

enforcing

permissive

context

context type

source context

target context

audit log

Review Questions

The questions that follow are meant to help you test your knowledge of concepts and terminology and the breadth of your knowledge. You can find the answers to these questions in Appendix A.

1. You want to put SELinux temporarily in permissive mode. Which command do you use?

2. You need a list of all available Booleans. Which command do you use?

3. You do not see any service-specific SELinux man page. What solution do you need to apply?

4. What is the name of the package you need to install to get easy-to-read SELinux log messages in the audit log?

5. What commands do you need to run to apply the httpd_sys_content_t context type to the directory /web?

6. When would you use the chcon command?

7. Which file do you need to change if you want to completely disable SELinux?

8. Where does SELinux log all of its messages?

9. You have no clue which context types are available for the ftp service. What command enables you to get more specific information?

10. Your service does not work as expected, and you want to know whether it is due to SELinux or something else. What is the easiest way to find out?

End-of-Chapter Lab

You have now learned how SELinux works. To practice managing this essential service, work through this end-of-chapter lab about SELinux.

Lab 22.1

1. Change the Apache document root to /web. In this directory, create a file with the name index.html and give it the contents welcome to my web server. Restart the httpd process and try to access the web server. This will not work. Fix the problem.

2. In the home directory of the user root, create a file with the name hosts and give it the following contents:

192.168.4.200 labipa.example.com
192.168.4.210 server1.example.com
192.168.4.220 server2.example.com

3. Move the file to the /etc directory and do what is necessary to give this file the correct context.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.165.66