[RHCSA] 09 – Manage security

    09.1 – Configure firewall settings using firewall-cmd/firewalld

    Overview

    firewalld is a dynamic firewall management tool in RHEL that provides a way to manage firewall rules. The firewall-cmd command-line utility is used to interact with firewalld. This guide covers how to configure firewall settings using firewall-cmd.


    Installing and Enabling Firewalld

    Step 1: Install Firewalld

    Ensure the firewalld package is installed on your system.

    sudo yum install firewalld

    Step 2: Start and Enable Firewalld

    Start the firewalld service and enable it to start at boot.

    sudo systemctl start firewalld
    sudo systemctl enable firewalld

    Step 3: Verify Firewalld Status

    Check the status of the firewalld service to ensure it is running.

    sudo systemctl status firewalld

    Sample Output:

     firewalld.service - firewalld - dynamic firewall daemon
       Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
       Active: active (running) since Mon 2023-10-01 12:00:00 UTC; 1h 30min ago
         Docs: man:firewalld(1)
     Main PID: 1234 (firewalld)
        Tasks: 2
       Memory: 5.0M
       CGroup: /system.slice/firewalld.service
               └─1234 /usr/sbin/firewalld --nofork --nopid

    Basic Firewall-Cmd Commands

    Listing Firewall Rules

    1. List All Zones:
    sudo firewall-cmd --get-zones
    1. List Active Zones:
    sudo firewall-cmd --get-active-zones
    1. List Services and Ports in a Zone:
    sudo firewall-cmd --zone=<zone> --list-all

    Example:

    sudo firewall-cmd --zone=public --list-all

    Adding and Removing Services

    1. Add a Service to a Zone:
    sudo firewall-cmd --zone=<zone> --add-service=<service> --permanent

    Example:

    sudo firewall-cmd --zone=public --add-service=http --permanent
    1. Remove a Service from a Zone:
    sudo firewall-cmd --zone=<zone> --remove-service=<service> --permanent

    Example:

    sudo firewall-cmd --zone=public --remove-service=http --permanent

    Adding and Removing Ports

    1. Add a Port to a Zone:
    sudo firewall-cmd --zone=<zone> --add-port=<port>/<protocol> --permanent

    Example:

    sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
    1. Remove a Port from a Zone:
    sudo firewall-cmd --zone=<zone> --remove-port=<port>/<protocol> --permanent

    Example:

    sudo firewall-cmd --zone=public --remove-port=8080/tcp --permanent

    Reloading the Firewall

    After making changes, reload the firewall to apply the new rules.

    sudo firewall-cmd --reload

    Practical Examples

    Example 1: Allow HTTP and HTTPS Traffic

    1. Add the HTTP and HTTPS Services to the Public Zone:
    sudo firewall-cmd --zone=public --add-service=http --permanent
    sudo firewall-cmd --zone=public --add-service=https --permanent
    1. Reload the Firewall:
    sudo firewall-cmd --reload
    1. Verify the HTTP and HTTPS Services are Allowed:
    sudo firewall-cmd --zone=public --list-services

    Example 2: Allow Custom Port 8080/TCP

    1. Add Port 8080/TCP to the Public Zone:
    sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
    1. Reload the Firewall:
    sudo firewall-cmd --reload
    1. Verify Port 8080/TCP is Allowed:
    sudo firewall-cmd --zone=public --list-ports

    Example 3: Allow SSH Access Only from a Specific IP Address

    1. Create a New Zone:
    sudo firewall-cmd --permanent --new-zone=restricted
    1. Allow Access to the New Zone from a Specific IP Address:
    sudo firewall-cmd --zone=restricted --add-source=<ip_address> --permanent

    Example:

    sudo firewall-cmd --zone=restricted --add-source=192.168.1.50 --permanent
    1. Reload the Firewall:
    sudo firewall-cmd --reload
    1. Verify the New Zone Configuration:
    sudo firewall-cmd --zone=restricted --list-all

    Additional Tips

    • Check Firewall Status:Use the firewall-cmd --state command to check if firewalld is running.
    sudo firewall-cmd --state
    • Get Default Zone:Use the firewall-cmd --get-default-zone command to get the default zone.
    sudo firewall-cmd --get-default-zone
    • Change Default Zone:Use the firewall-cmd --set-default-zone=<zone> command to change the default zone.
    sudo firewall-cmd --set-default-zone=public
    • Rich Rules:Use rich rules for more complex firewall rules.Example: Allow SSH from a specific IP address.
    sudo firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.50" service name="ssh" accept'
    • Remove Rich Rules:Example: Remove the rich rule for SSH.
    sudo firewall-cmd --permanent --zone=public --remove-rich-rule='rule family="ipv4" source address="192.168.1.50" service name="ssh" accept'
    • Reload Firewalld Configuration:Use the firewall-cmd --reload command to reload the firewalld configuration after making changes.
    sudo firewall-cmd --reload
    • Temporary Rules:Use the --permanent flag to make rules persistent across reboots. Without this flag, rules are temporary and will be lost after a reboot.Example: Add a temporary rule to allow HTTP traffic.
    sudo firewall-cmd --zone=public --add-service=http

    Conclusion

    Configuring firewall settings using firewall-cmd and firewalld is essential for securing your system and controlling network traffic. Mastery of these tasks ensures that you can effectively manage firewall rules and maintain network security, which is crucial for the RHCSA exam.


    These notes should help you understand how to configure firewall settings using firewall-cmd and firewalld for the RHCSA exam.

    09.2 – Manage default file permissions

    Manage Default File Permissions

    Overview

    Default file permissions in Linux are controlled by the umask setting, which determines the default permissions for newly created files and directories. This guide covers how to manage default file permissions using umask and how to set default ACLs (Access Control Lists) for directories.


    Understanding umask

    What is umask?

    umask (user file creation mode mask) is a shell built-in command that sets the default file permissions for newly created files and directories. It subtracts permissions from the system’s default permissions.

    Default Permissions

    • Files: The default permissions are 666 (read and write for owner, group, and others).
    • Directories: The default permissions are 777 (read, write, and execute for owner, group, and others).

    Calculating Effective Permissions

    The effective permissions are calculated by subtracting the umask value from the default permissions.

    Example

    • Default Permissions for Files666
    • umask022
    • Effective Permissions666 - 022 = 644 (read and write for owner, read-only for group and others)

    Setting umask

    Viewing the Current umask

    Use the umask command to view the current umask value.

    umask

    Sample Output:

    0022

    Setting umask Temporarily

    To set the umask value temporarily for the current shell session, use the umask command followed by the desired value.

    umask 027

    Setting umask Permanently

    To set the umask value permanently, add the umask command to the appropriate shell configuration file.

    For Bash Shell

    1. Edit the ~/.bashrc File:
    nano ~/.bashrc
    1. Add the umask Command:
    umask 027
    1. Save and Exit.
    2. Apply the Changes:
    source ~/.bashrc

    For System-Wide Settings

    1. Edit the /etc/bashrc or /etc/profile File:
    sudo nano /etc/bashrcorsudo nano /etc/profile
    1. Add the umask Command:
    umask 027
    1. Save and Exit.
    2. Apply the Changes:
    source /etc/bashrc
    # or
    source /etc/profile

    Setting Default ACLs

    What are Default ACLs?

    Default ACLs (Access Control Lists) are used to set default permissions for files and directories within a directory. When a new file or directory is created within a directory that has default ACLs, it inherits the default ACLs.

    Setting Default ACLs

    Use the setfacl command to set default ACLs.

    Syntax

    sudo setfacl -d -m <acl> <directory>

    Examples

    1. Set Default ACL for a Directory:
    sudo setfacl -d -m u::rwx /shared
    1. Set Default ACL for a Group:
    sudo setfacl -d -m g:developers:rwx /shared
    1. Set Default ACL for Others:
    sudo setfacl -d -m o::rx /shared

    Viewing ACLs

    Use the getfacl command to view the ACLs of a file or directory.

    getfacl /shared

    Sample Output:

    # file: shared
    # owner: root
    # group: root
    user::rwx
    group::r-x
    other::r-x
    default:user::rwx
    default:group::r-x
    default:other::r-x

    Practical Examples

    Example 1: Set umask for a User

    1. View the Current umask Value:
    umask
    1. Set the umask Value Temporarily:
    umask 027
    1. Set the umask Value Permanently for the User:
    nano ~/.bashrc
    1. Add the umask Command:
    umask 027
    1. Save and Exit.
    2. Apply the Changes:
    source ~/.bashrc

    Example 2: Set System-Wide umask

    1. Edit the /etc/profile File:
    sudo nano /etc/profile
    1. Add the umask Command:
    umask 027
    1. Save and Exit.
    2. Apply the Changes:
    source /etc/profile

    Example 3: Set Default ACLs for a Directory

    1. Set Default ACL for the /shared Directory:
    sudo setfacl -d -m u::rwx /shared
    sudo setfacl -d -m g:developers:rwx /shared
    sudo setfacl -d -m o::rx /shared
    1. Verify the Default ACLs:
    getfacl /shared

    Additional Tips

    • Check Effective Permissions:Use the namei command to check the effective permissions of a path.
    namei -l /path/to/file
    • Remove Default ACLs:Use the setfacl command with the -x option to remove default ACLs.
    sudo setfacl -x d:u::rwx /shared
    • Set Recursive ACLs:Use the -R option with the setfacl command to set ACLs recursively.
    sudo setfacl -R -m u::rwx /shared
    • Check Default umask Value:The default umask value for new users can be found in the /etc/login.defs file.
    grep UMASK /etc/login.defs
    • Set umask for Specific Applications:Some applications allow setting umask values in their configuration files. Check the documentation for the specific application.

    Conclusion

    Managing default file permissions using umask and default ACLs ensures that files and directories have the appropriate permissions when they are created. Mastery of these tasks is crucial for maintaining system security and efficiency, which is essential for the RHCSA exam.


    These notes should help you understand how to manage default file permissions for the RHCSA exam.

    09.3 – Configure key-based authentication for SSH

    Overview

    Key-based authentication for SSH enhances security by using a pair of cryptographic keys (a public key and a private key) instead of passwords. This guide covers how to generate SSH keys, configure SSH key-based authentication, and manage SSH keys.


    Generating SSH Keys

    Step 1: Generate an SSH Key Pair

    Use the ssh-keygen command to generate a new SSH key pair.

    Syntax

    ssh-keygen -t <key_type> -b <key_bits> -C "<comment>"

    Example

    Generate an RSA key pair with 2048 bits and a comment:

    ssh-keygen -t rsa -b 2048 -C "your_email@example.com"

    1 vulnerability

    Step 2: Follow the Prompts

    1. Specify the File to Save the Key:
    Enter file in which to save the key (/home/your_user/.ssh/id_rsa):

    Press Enter to accept the default location or specify a different path.

    1. Enter a Passphrase (Optional):
    Enter passphrase (empty for no passphrase):

    Enter a passphrase for added security or press Enter to leave it empty.

    1. Confirm the Passphrase:
    Enter same passphrase again:

    Re-enter the passphrase.

    Step 3: Verify the Generated Keys

    The generated keys are stored in the specified location (default: ~/.ssh/).

    • Private Key~/.ssh/id_rsa
    • Public Key~/.ssh/id_rsa.pub

    Configuring SSH Key-Based Authentication

    Step 1: Copy the Public Key to the Remote Server

    Use the ssh-copy-id command to copy the public key to the remote server.

    Syntax

    ssh-copy-id <user>@<remote_host>

    Example

    Copy the public key to the remote server 192.168.1.100 for user alice:

    ssh-copy-id alice@192.168.1.100

    Step 2: Manually Copy the Public Key (Alternative Method)

    If ssh-copy-id is not available, you can manually copy the public key.

    1. Display the Public Key:
    cat ~/.ssh/id_rsa.pub
    1. Copy the Public Key to the Remote Server:
    ssh <user>@<remote_host> "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo '<public_key>' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

    Replace <public_key> with the output of the cat ~/.ssh/id_rsa.pub command.

    Step 3: Verify SSH Key-Based Authentication

    1. Connect to the Remote Server Using SSH:
    ssh <user>@<remote_host>
    1. Verify That No Password is Prompted:If configured correctly, you should be able to log in without entering a password.

    Managing SSH Keys

    Adding SSH Keys to the SSH Agent

    Use the ssh-agent and ssh-add commands to manage SSH keys.

    1. Start the SSH Agent:
    eval "$(ssh-agent -s)"
    1. Add the SSH Key to the Agent:
    ssh-add ~/.ssh/id_rsa

    Removing SSH Keys from the SSH Agent

    1. Remove a Specific Key:
    ssh-add -d ~/.ssh/id_rsa
    1. Remove All Keys:
    ssh-add -D

    Revoking SSH Keys

    To revoke access, remove the corresponding public key from the ~/.ssh/authorized_keys file on the remote server.

    1. Edit the authorized_keys File:
    ssh <user>@<remote_host>
    nano ~/.ssh/authorized_keys
    1. Remove the Public Key:Delete the line containing the public key to be revoked.
    2. Save and Exit.

    Practical Examples

    Example 1: Generate SSH Keys and Configure Key-Based Authentication

    1. Generate an RSA Key Pair:
    ssh-keygen -t rsa -b 2048 -C "your_email@example.com"
    1. Copy the Public Key to the Remote Server:
    ssh-copy-id alice@192.168.1.100
    1. Verify SSH Key-Based Authentication:
    ssh alice@192.168.1.100

    Example 2: Manually Copy the Public Key to the Remote Server

    1. Display the Public Key:
    cat ~/.ssh/id_rsa.pub
    1. Copy the Public Key to the Remote Server:
    ssh alice@192.168.1.100 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr...' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
    1. Verify SSH Key-Based Authentication:
    ssh alice@192.168.1.100

    Example 3: Add SSH Key to the SSH Agent

    1. Start the SSH Agent:
    eval "$(ssh-agent -s)"
    1. Add the SSH Key to the Agent:
    ssh-add ~/.ssh/id_rsa

    Example 4: Revoke SSH Key Access

    1. Edit the authorized_keys File on the Remote Server:
    ssh alice@192.168.1.100
    nano ~/.ssh/authorized_keys
    1. Remove the Public Key:Delete the line containing the public key to be revoked.
    2. Save and Exit.

    Additional Tips

    • Check SSH Configuration:Ensure the SSH server is configured to allow key-based authentication. Edit the /etc/ssh/sshd_config file and verify the following settings:
    PubkeyAuthentication yes
    AuthorizedKeysFile .ssh/authorized_keys

    Restart the SSH service to apply changes:

    sudo systemctl restart sshd
    • Use Strong Passphrases:When generating SSH keys, use strong passphrases to enhance security.
    • Backup SSH Keys:Keep a backup of your SSH keys in a secure location.
    • Use Different Keys for Different Servers:For added security, use different SSH key pairs for different servers.
    • Disable Password Authentication:After configuring key-based authentication, you can disable password authentication for added security. Edit the /etc/ssh/sshd_config file and set:
    PasswordAuthentication no

    Restart the SSH service to apply changes:

    sudo systemctl restart sshd

    Conclusion

    Configuring key-based authentication for SSH enhances security by using cryptographic keys instead of passwords. Mastery of these tasks ensures secure and efficient access to remote servers, which is crucial for the RHCSA exam.


    These notes should help you understand how to configure key-based authentication for SSH for the RHCSA exam.

    09.4 – Set enforcing and permissive modes for SELinux

    Overview

    SELinux (Security-Enhanced Linux) is a security module that provides a mechanism for supporting access control security policies. SELinux operates in different modes: enforcing, permissive, and disabled. This guide covers how to set enforcing and permissive modes for SELinux.


    SELinux Modes

    • Enforcing: SELinux policy is enforced, and access denials are logged.
    • Permissive: SELinux policy is not enforced, but access denials are logged.
    • Disabled: SELinux is turned off.

    Checking the Current SELinux Mode

    Using sestatus

    Use the sestatus command to check the current SELinux mode.

    sestatus

    Sample Output:

    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
    Max kernel policy version:      31

    Using getenforce

    Use the getenforce command to check the current SELinux mode.

    getenforce

    Sample Output:

    Enforcing

    Setting SELinux Mode Temporarily

    Using setenforce

    The setenforce command is used to change the SELinux mode temporarily until the next reboot.

    Syntax

    sudo setenforce <mode>
    • 0 or permissive: Set SELinux to permissive mode.
    • 1 or enforcing: Set SELinux to enforcing mode.

    Examples

    1. Set SELinux to Permissive Mode:
    sudo setenforce 0
    # or
    sudo setenforce permissive
    1. Set SELinux to Enforcing Mode:
    sudo setenforce 1
    # or
    sudo setenforce enforcing

    Verify the Change

    Use the getenforce command to verify the current SELinux mode.

    getenforce

    Sample Output:

    Permissive

    or

    Enforcing

    Setting SELinux Mode Permanently

    Editing the SELinux Configuration File

    To set the SELinux mode permanently, edit the /etc/selinux/config file.

    1. Open the Configuration File:
    sudo nano /etc/selinux/config
    1. Modify the SELINUX Parameter:
    # 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

    or

    SELINUX=permissive
    1. Save and Exit.
    2. Reboot the System:
    sudo reboot

    Verify the Change

    After rebooting, use the sestatus or getenforce command to verify the current SELinux mode.

    sestatus

    or

    getenforce

    Practical Examples

    Example 1: Set SELinux to Permissive Mode Temporarily

    1. Set SELinux to Permissive Mode:
    sudo setenforce 0
    1. Verify the Change:
    getenforce

    Example 2: Set SELinux to Enforcing Mode Temporarily

    1. Set SELinux to Enforcing Mode:
    sudo setenforce 1
    1. Verify the Change:
    getenforce

    Example 3: Set SELinux to Permissive Mode Permanently

    1. Edit the SELinux Configuration File:
    sudo nano /etc/selinux/config
    1. Modify the SELINUX Parameter:
    SELINUX=permissive
    1. Save and Exit.
    2. Reboot the System:
    sudo reboot
    1. Verify the Change:
    sestatus

    Example 4: Set SELinux to Enforcing Mode Permanently

    1. Edit the SELinux Configuration File:
    sudo nano /etc/selinux/config
    1. Modify the SELINUX Parameter:
    SELINUX=enforcing
    1. Save and Exit.
    2. Reboot the System:
    sudo reboot
    1. Verify the Change:
    sestatus

    Additional Tips

    • Check SELinux Status:Use the sestatus command to check detailed SELinux status.
    sestatus
    • View SELinux Logs:SELinux logs can be found in /var/log/audit/audit.log. Use the ausearch and audit2allow tools to analyze and create policies.
    sudo ausearch -m avc -ts recent
    sudo audit2allow -w -a
    • Disable SELinux:To disable SELinux, set SELINUX=disabled in the /etc/selinux/config file and reboot the system. Note that disabling SELinux is not recommended for production environments.
    SELINUX=disabled
    • Re-enable SELinux:If SELinux was previously disabled, re-enable it by setting SELINUX=enforcing or SELINUX=permissive in the /etc/selinux/config file and rebooting the system.
    SELINUX=enforcing
    • Temporary vs. Permanent Changes:Use setenforce for temporary changes that do not persist across reboots. Edit /etc/selinux/config for permanent changes that persist across reboots.

    Conclusion

    Setting enforcing and permissive modes for SELinux is essential for managing security policies on your system. Mastery of these tasks ensures that you can effectively control and monitor access, which is crucial for the RHCSA exam.


    These notes should help you understand how to set enforcing and permissive modes for SELinux for the RHCSA exam.

    09.5 – List and identify SELinux file and process context

    Overview

    SELinux (Security-Enhanced Linux) uses contexts to enforce security policies. Each file and process has an associated SELinux context that defines its security attributes. This guide covers how to list and identify SELinux contexts for files and processes.


    SELinux Context Structure

    An SELinux context consists of four fields:

    user:role:type:level
    • user: SELinux user (e.g., system_uuser_u)
    • role: SELinux role (e.g., object_rsystem_r)
    • type: SELinux type (e.g., httpd_sys_content_tssh_t)
    • level: SELinux level (optional, used for Multi-Level Security)

    Listing SELinux File Contexts

    Using ls -Z

    The ls -Z command displays the SELinux context of files and directories.

    Syntax

    ls -Z <file_or_directory>

    Examples

    1. List SELinux Context of a File:
    ls -Z /etc/passwd

    Sample Output:

    -rw-r--r--. root root system_u:object_r:etc_t:s0       /etc/passwd
    1. List SELinux Context of a Directory:
    ls -Z /var/www/html

    Sample Output:

    drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /var/www/html

    Using stat -c %C

    The stat command with the -c %C option displays the SELinux context of a file or directory.

    Syntax

    stat -c %C <file_or_directory>

    Example

    1. Display SELinux Context of a File:
    stat -c %C /etc/passwd

    Sample Output:

    system_u:object_r:etc_t:s0

    Listing SELinux Process Contexts

    Using ps -eZ

    The ps -eZ command displays the SELinux context of running processes.

    Syntax

    ps -eZ

    Example

    1. List SELinux Context of All Processes:
    ps -eZ

    Sample Output:

    LABEL                             PID TTY          TIME CMD
    system_u:system_r:init_t:s0         1 ?        00:00:01 systemd
    system_u:system_r:sshd_t:s0      1234 ?        00:00:00 sshd
    system_u:system_r:httpd_t:s0     5678 ?        00:00:00 httpd

    Using ps -Z -C <command>

    The ps -Z -C command displays the SELinux context of specific processes by command name.

    Syntax

    ps -Z -C <command>

    Example

    1. List SELinux Context of sshd Processes:
    ps -Z -C sshd

    Sample Output:

    LABEL                             PID TTY          TIME CMD
    system_u:system_r:sshd_t:s0      1234 ?        00:00:00 sshd

    Practical Examples

    Example 1: List SELinux Context of Files and Directories

    1. List SELinux Context of the /etc/passwd File:
    ls -Z /etc/passwd
    1. List SELinux Context of the /var/www/html Directory:
    ls -Z /var/www/html
    1. Display SELinux Context of the /etc/passwd File Using stat:
    stat -c %C /etc/passwd

    Example 2: List SELinux Context of Running Processes

    1. List SELinux Context of All Processes:
    ps -eZ
    1. List SELinux Context of httpd Processes:
    ps -Z -C httpd

    Additional Tips

    • Change SELinux File Context:Use the chcon command to change the SELinux context of a file or directory.
    sudo chcon -t <type> <file_or_directory>

    Example:

    sudo chcon -t httpd_sys_content_t /var/www/html/index.html
    • Restore Default SELinux Context:Use the restorecon command to restore the default SELinux context of a file or directory.
    sudo restorecon <file_or_directory>

    Example:

    sudo restorecon /var/www/html/index.html
    • List SELinux Contexts Recursively:

    Use the ls -ZR command to list SELinux contexts recursively.

    ls -ZR /var/www/html
    • Check SELinux Contexts for a Specific User:Use the ps -u <username> -Z command to list SELinux contexts for processes owned by a specific user.
    ps -u alice -Z
    • View SELinux Contexts in find Command:Use the -printf option with the find command to display SELinux contexts.
    find /var/www/html -printf "%p %Z\n"

    Conclusion

    Listing and identifying SELinux file and process contexts is essential for managing and troubleshooting SELinux policies. Mastery of these tasks ensures that you can effectively control and monitor access, which is crucial for the RHCSA exam.


    These notes should help you understand how to list and identify SELinux file and process contexts for the RHCSA exam.

    09.6 – Restore default file contexts

    Overview

    SELinux (Security-Enhanced Linux) uses contexts to enforce security policies. Sometimes, file contexts may be changed inadvertently, leading to access issues. Restoring default file contexts ensures that files and directories have the correct SELinux labels. This guide covers how to restore default file contexts using the restorecon and semanage commands.


    Using restorecon to Restore Default File Contexts

    What is restorecon?

    The restorecon command is used to restore the default SELinux context for files and directories based on the SELinux policy.

    Syntax

    sudo restorecon [options] <file_or_directory>

    Common Options

    • -R: Recursively apply changes to directories and their contents.
    • -v: Verbose mode, displays detailed information about the changes.

    Examples

    1. Restore Default Context for a Single File:
    sudo restorecon /etc/passwd
    1. Restore Default Context for a Directory:
    sudo restorecon /var/www/html
    1. Restore Default Context Recursively for a Directory:
    sudo restorecon -R /var/www/html
    1. Restore Default Context Verbosely for a Directory:
    sudo restorecon -Rv /var/www/html

    Example: Restore Default Contexts

    1. Restore Default Context for the /etc/passwd File:
    sudo restorecon /etc/passwd
    1. Restore Default Context Recursively for the /var/www/html Directory:
    sudo restorecon -R /var/www/html

    Using semanage to Manage SELinux Contexts

    What is semanage?

    The semanage command is used to manage SELinux policy components, including file contexts. It can be used to add or modify file context definitions.

    Syntax

    sudo semanage fcontext [options] <file_pattern>

    Common Options

    • -a: Add a new file context.
    • -d: Delete a file context.
    • -m: Modify an existing file context.
    • -l: List all file contexts.

    Examples

    1. Add a Custom File Context:
    sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"
    1. Modify an Existing File Context:
    sudo semanage fcontext -m -t httpd_sys_content_t "/custom/web(/.*)?"
    1. Delete a Custom File Context:
    sudo semanage fcontext -d "/custom/web(/.*)?"
    1. List All File Contexts:
    sudo semanage fcontext -l

    Applying Changes with restorecon

    After adding or modifying file contexts with semanage, use restorecon to apply the changes.

    Example

    1. Add a Custom File Context for /custom/web:
    sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"
    1. Apply the Changes:
    sudo restorecon -R /custom/web

    Practical Examples

    Example 1: Restore Default Contexts for System Files

    1. Restore Default Context for the /etc/shadow File:
    sudo restorecon /etc/shadow
    1. Restore Default Context Recursively for the /var/log Directory:
    sudo restorecon -R /var/log

    Example 2: Add and Apply Custom File Contexts

    1. Add a Custom File Context for /data/web:
    sudo semanage fcontext -a -t httpd_sys_content_t "/data/web(/.*)?"
    1. Apply the Changes:
    sudo restorecon -R /data/web

    Example 3: Modify and Apply Custom File Contexts

    1. Modify the File Context for /data/web:
    sudo semanage fcontext -m -t httpd_sys_content_t "/data/web(/.*)?"
    1. Apply the Changes:
    sudo restorecon -R /data/web

    Example 4: Delete a Custom File Context

    1. Delete the Custom File Context for /data/web:
    sudo semanage fcontext -d "/data/web(/.*)?"
    1. Restore Default Contexts:
    sudo restorecon -R /data/web

    Additional Tips

    • Check Current File Contexts:Use the ls -Z command to check the current SELinux context of files and directories.
    ls -Z /path/to/file_or_directory
    • View SELinux Policy for File Contexts:Use the semanage fcontext -l command to view the SELinux policy for file contexts.
    sudo semanage fcontext -l
    • Restore Contexts for Home Directories:Use the restorecon command to restore contexts for user home directories.
    sudo restorecon -R /home
    • Restore Contexts for Specific Types:Use the -t option with restorecon to restore contexts for specific types.
    sudo restorecon -R -t httpd_sys_content_t /var/www/html
    • Automate Context Restoration:Use a cron job or systemd service to automate the restoration of file contexts.

    Example Cron Job:

    sudo crontab -e

    Add the following line to run restorecon daily:

    0 2 * * * /usr/sbin/restorecon -R /var/www/html

    Conclusion

    Restoring default file contexts is essential for maintaining SELinux security policies and ensuring proper access control. Mastery of these tasks ensures that your system remains secure and compliant with SELinux policies, which is crucial for the RHCSA exam.


    These notes should help you understand how to restore default file contexts for the RHCSA exam.

    09.7 – Manage SELinux port labels

    Overview

    SELinux (Security-Enhanced Linux) uses port labels to control which services can bind to specific ports. Managing SELinux port labels involves listing, adding, modifying, and deleting port labels to ensure that services can operate correctly while maintaining security. This guide covers how to manage SELinux port labels using the semanage command.


    Listing SELinux Port Labels

    Using semanage port -l

    The semanage port -l command lists all SELinux port labels.

    Syntax

    sudo semanage port -l

    Example

    1. List All SELinux Port Labels:
    sudo semanage port -l

    Sample Output:

    http_port_t                    tcp      80, 443
    ssh_port_t                     tcp      22
    dns_port_t                     tcp      53
    dns_port_t                     udp      53

    Adding SELinux Port Labels

    Using semanage port -a

    The semanage port -a command adds a new SELinux port label.

    Syntax

    sudo semanage port -a -t <type> -p <protocol> <port_number>
    • -a: Add a new port label.
    • -t <type>: Specify the SELinux type.
    • -p <protocol>: Specify the protocol (tcp or udp).
    • <port_number>: Specify the port number.

    Example

    1. Add a New Port Label for HTTP on Port 8080:
    sudo semanage port -a -t http_port_t -p tcp 8080
    1. Verify the New Port Label:
    sudo semanage port -l | grep 8080

    Sample Output:

    http_port_t                    tcp      8080, 80, 443

    Modifying SELinux Port Labels

    Using semanage port -m

    The semanage port -m command modifies an existing SELinux port label.

    Syntax

    sudo semanage port -m -t <type> -p <protocol> <port_number>
    • -m: Modify an existing port label.
    • -t <type>: Specify the SELinux type.
    • -p <protocol>: Specify the protocol (tcp or udp).
    • <port_number>: Specify the port number.

    Example

    1. Modify the Port Label for HTTP to Include Port 8081:
    sudo semanage port -m -t http_port_t -p tcp 8081
    1. Verify the Modified Port Label:
    sudo semanage port -l | grep 8081

    Sample Output:

    http_port_t                    tcp      8081, 80, 443

    Deleting SELinux Port Labels

    Using semanage port -d

    The semanage port -d command deletes an existing SELinux port label.

    Syntax

    sudo semanage port -d -t <type> -p <protocol> <port_number>
    • -d: Delete an existing port label.
    • -t <type>: Specify the SELinux type.
    • -p <protocol>: Specify the protocol (tcp or udp).
    • <port_number>: Specify the port number.

    Example

    1. Delete the Port Label for HTTP on Port 8080:
    sudo semanage port -d -t http_port_t -p tcp 8080
    1. Verify the Deleted Port Label:
    sudo semanage port -l | grep 8080

    Sample Output:(No output, indicating the port label has been deleted.)


    Practical Examples

    Example 1: Add a New Port Label for a Custom Service

    1. Add a New Port Label for a Custom Service on Port 9090:
    sudo semanage port -a -t custom_service_port_t -p tcp 9090
    1. Verify the New Port Label:
    sudo semanage port -l | grep 9090

    Sample Output:

    custom_service_port_t          tcp      9090

    Example 2: Modify an Existing Port Label

    1. Modify the Port Label for HTTP to Include Port 8082:
    sudo semanage port -m -t http_port_t -p tcp 8082
    1. Verify the Modified Port Label:
    sudo semanage port -l | grep 8082

    Sample Output:

    http_port_t                    tcp      8082, 80, 443

    Example 3: Delete an Existing Port Label

    1. Delete the Port Label for a Custom Service on Port 9090:
    sudo semanage port -d -t custom_service_port_t -p tcp 9090
    1. Verify the Deleted Port Label:
    sudo semanage port -l | grep 9090

    Sample Output:(No output, indicating the port label has been deleted.)


    Additional Tips

    • Check Current Port Labels:Use the semanage port -l command to check the current SELinux port labels.
    sudo semanage port -l
    • Restore Default Port Labels:If you need to restore the default SELinux port labels, you can use the restorecon command on the SELinux policy files.
    sudo restorecon -R /etc/selinux/targeted/contexts/files
    • View SELinux Policy for Ports:Use the semanage port -l command to view the SELinux policy for ports.
    sudo semanage port -l
    • Use audit2allow to Troubleshoot Port Issues:If you encounter issues with SELinux port labels, use the audit2allow tool to generate custom policies based on audit logs.
    sudo ausearch -m avc -ts recent | audit2allow -m mycustompolicy
    sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy
    sudo semodule -i mycustompolicy.pp

    Conclusion

    Managing SELinux port labels is essential for controlling which services can bind to specific ports and ensuring proper security policies. Mastery of these tasks ensures that your system remains secure and compliant with SELinux policies, which is crucial for the RHCSA exam.


    These notes should help you understand how to manage SELinux port labels for the RHCSA exam.

    09.8 – Use boolean settings to modify system SELinux settings

    Overview

    SELinux (Security-Enhanced Linux) uses boolean settings to enable or disable specific security policies dynamically. These booleans allow administrators to modify the behavior of SELinux without changing and recompiling policy files. This guide covers how to list, view, set, and persist SELinux boolean settings using the getsebool and setsebool commands.


    Listing SELinux Booleans

    Using getsebool -a

    The getsebool -a command lists all SELinux booleans and their current states.

    Syntax

    sudo getsebool -a

    Example

    1. List All SELinux Booleans:
    sudo getsebool -a

    Sample Output:

    allow_ftpd_anon_write --> off
    allow_gssd_read_tmp --> off
    allow_httpd_anon_write --> off
    allow_httpd_mod_auth_pam --> off
    allow_httpd_sys_script_anon_write --> off
    ...

    Viewing Specific SELinux Booleans

    Using getsebool

    The getsebool command can be used to view the state of specific SELinux booleans.

    Syntax

    sudo getsebool <boolean_name>

    Example

    1. View the State of the httpd_can_network_connect Boolean:
    sudo getsebool httpd_can_network_connect

    Sample Output:

    httpd_can_network_connect --> off

    Setting SELinux Booleans

    Using setsebool

    The setsebool command is used to set the state of SELinux booleans.

    Syntax

    sudo setsebool <boolean_name> <on|off>

    Example

    1. Enable the httpd_can_network_connect Boolean:
    sudo setsebool httpd_can_network_connect on
    1. Disable the httpd_can_network_connect Boolean:
    sudo setsebool httpd_can_network_connect off

    Setting Multiple Booleans

    You can set multiple booleans at once using the -P option to make the changes persistent across reboots.

    Syntax

    sudo setsebool -P <boolean_name>=<on|off> <boolean_name>=<on|off> ...

    Example

    1. Enable Multiple Booleans and Make the Changes Persistent:
    sudo setsebool -P httpd_can_network_connect=on httpd_enable_cgi=on

    Practical Examples

    Example 1: Enable a Boolean Temporarily

    1. Enable the httpd_can_network_connect Boolean:
    sudo setsebool httpd_can_network_connect on
    1. Verify the Change:
    sudo getsebool httpd_can_network_connect

    Sample Output:

    httpd_can_network_connect --> on

    Example 2: Enable a Boolean Persistently

    1. Enable the httpd_can_network_connect Boolean Persistently:
    sudo setsebool -P httpd_can_network_connect on
    1. Verify the Change:
    sudo getsebool httpd_can_network_connect

    Sample Output:

    httpd_can_network_connect --> on

    Example 3: Disable a Boolean Temporarily

    1. Disable the httpd_can_network_connect Boolean:
    sudo setsebool httpd_can_network_connect off
    1. Verify the Change:
    sudo getsebool httpd_can_network_connect

    Sample Output:

    httpd_can_network_connect --> off

    Example 4: Enable Multiple Booleans Persistently

    1. Enable the httpd_can_network_connect and httpd_enable_cgi Booleans Persistently:
    sudo setsebool -P httpd_can_network_connect=on httpd_enable_cgi=on
    1. Verify the Changes:
    sudo getsebool httpd_can_network_connect
    sudo getsebool httpd_enable_cgi
    

    Sample Output:

    httpd_can_network_connect --> on
    httpd_enable_cgi --> on

    Additional Tips

    • List Booleans with Descriptions:Use the semanage boolean -l command to list SELinux booleans with descriptions.
    sudo semanage boolean -l

    Sample Output:

    SELinux boolean                State  Default Description
    allow_ftpd_anon_write          off    off     Allow ftp servers to allow anonymous users to write files
    allow_gssd_read_tmp            off    off     Allow gssd to read temp files
    allow_httpd_anon_write         off    off     Allow httpd to modify public files used for public file transfer services
    ...
    • Make Boolean Changes Persistent:Use the -P option with setsebool to make changes persistent across reboots.
    sudo setsebool -P <boolean_name> <on|off>
    • Check SELinux Status:Use the sestatus command to check the overall status of SELinux.
    sestatus

    Sample Output:

    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
    Max kernel policy version:      31
    • Use audit2allow to Troubleshoot:If you encounter issues with SELinux policies, use the audit2allow tool to generate custom policies based on audit logs.
    sudo ausearch -m avc -ts recent | audit2allow -m mycustompolicy
    sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy
    sudo semodule -i mycustompolicy.pp

    Conclusion

    Using boolean settings to modify system SELinux settings allows administrators to dynamically adjust security policies without changing and recompiling policy files. Mastery of these tasks ensures that your system remains secure and compliant with SELinux policies, which is crucial for the RHCSA exam.


    These notes should help you understand how to use boolean settings to modify system SELinux settings for the RHCSA exam.

    09.9 – Diagnose and address routine SELinux policy violations

    Overview

    SELinux (Security-Enhanced Linux) enforces security policies that can sometimes lead to access denials or policy violations. Diagnosing and addressing these violations is essential for maintaining system security and functionality. This guide covers how to diagnose and address routine SELinux policy violations using tools like auditdausearchaudit2allow, and setroubleshoot.


    Diagnosing SELinux Policy Violations

    Step 1: Check SELinux Status

    Ensure SELinux is enabled and in enforcing mode.

    sestatus

    Sample Output:

    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
    Max kernel policy version:      31

    Step 2: View SELinux Logs

    SELinux logs are typically found in /var/log/audit/audit.log. Use the ausearch command to search for SELinux denials.

    Syntax

    sudo ausearch -m avc -ts recent

    Example

    1. Search for Recent SELinux Denials:
    sudo ausearch -m avc -ts recent

    Sample Output:

    type=AVC msg=audit(1633024800.123:456): avc:  denied  { read } for  pid=1234 comm="httpd" name="index.html" dev="sda1" ino=5678 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file

    Step 3: Use sealert for Detailed Analysis

    The setroubleshoot package provides the sealert tool for detailed analysis of SELinux denials. Install the package if it’s not already installed.

    sudo yum install setroubleshoot

    Syntax

    sudo sealert -a /var/log/audit/audit.log

    Example

    1. Analyze SELinux Denials:
    sudo sealert -a /var/log/audit/audit.log

    Sample Output:

    SELinux is preventing /usr/sbin/httpd from read access on the file /home/user/index.html.
    
    *****  Plugin httpd_read_user_content (92.2 confidence) suggests   ************************
    
    If you want to allow httpd to read user content
    Then you need to change the label on /home/user/index.html
    Do
    # semanage fcontext -a -t httpd_sys_content_t '/home/user/index.html'
    # restorecon -v '/home/user/index.html'

    Addressing SELinux Policy Violations

    Step 1: Change File Contexts

    Use the chcon or semanage and restorecon commands to change file contexts.

    Example

    1. Change the File Context of /home/user/index.html:
    sudo semanage fcontext -a -t httpd_sys_content_t '/home/user/index.html'
    sudo restorecon -v '/home/user/index.html'

    Step 2: Create Custom SELinux Policies

    Use the audit2allow tool to create custom SELinux policies based on audit logs.

    Syntax

    sudo ausearch -m avc -ts recent | audit2allow -M <policy_name>
    sudo semodule -i <policy_name>.pp

    Example

    1. Generate a Custom Policy Module:
    sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy
    1. Install the Custom Policy Module:
    sudo semodule -i mycustompolicy.pp

    Step 3: Use SELinux Booleans

    Sometimes, enabling an SELinux boolean can resolve policy violations.

    Syntax

    sudo setsebool -P <boolean_name> <on|off>

    Example

    1. Enable the httpd_enable_homedirs Boolean:
    sudo setsebool -P httpd_enable_homedirs on

    Practical Examples

    Example 1: Diagnose and Address an HTTPD Access Denial

    1. Search for Recent SELinux Denials:
    sudo ausearch -m avc -ts recent
    1. Analyze SELinux Denials:
    sudo sealert -a /var/log/audit/audit.log
    1. Change the File Context of /home/user/index.html:
    sudo semanage fcontext -a -t httpd_sys_content_t '/home/user/index.html'
    sudo restorecon -v '/home/user/index.html'

    Example 2: Create and Install a Custom SELinux Policy

    1. Generate a Custom Policy Module:
    sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy
    1. Install the Custom Policy Module:
    sudo semodule -i mycustompolicy.pp

    Example 3: Enable an SELinux Boolean

    1. Enable the httpd_can_network_connect Boolean:
    sudo setsebool -P httpd_can_network_connect on

    Additional Tips

    • Check Current SELinux Booleans:Use the getsebool -a command to check the current state of SELinux booleans.
    sudo getsebool -a
    • List All SELinux File Contexts:Use the semanage fcontext -l command to list all SELinux file contexts.
    sudo semanage fcontext -l
    • Restore Default File Contexts:Use the restorecon command to restore default file contexts.
    sudo restorecon -R /path/to/directory
    • View SELinux Policy Modules:Use the semodule -l command to list all installed SELinux policy modules.
    sudo semodule -l
    • Use audit2why for Quick Analysis:The audit2why tool provides a quick explanation of SELinux denials.
    sudo ausearch -m avc -ts recent | audit2why

    Conclusion

    Diagnosing and addressing routine SELinux policy violations is essential for maintaining system security and functionality. Mastery of these tasks ensures that you can effectively troubleshoot and resolve SELinux-related issues, which is crucial for the RHCSA exam.


    These notes should help you understand how to diagnose and address routine SELinux policy violations for the RHCSA exam.


    Discover more from Altgr Blog

    Subscribe to get the latest posts sent to your email.

    Leave a Reply

    Your email address will not be published. Required fields are marked *