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 firewalldStep 2: Start and Enable Firewalld
Start the firewalld service and enable it to start at boot.
sudo systemctl start firewalld
sudo systemctl enable firewalldStep 3: Verify Firewalld Status
Check the status of the firewalld service to ensure it is running.
sudo systemctl status firewalldSample 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 --nopidBasic Firewall-Cmd Commands
Listing Firewall Rules
- List All Zones:
sudo firewall-cmd --get-zones- List Active Zones:
sudo firewall-cmd --get-active-zones- List Services and Ports in a Zone:
sudo firewall-cmd --zone=<zone> --list-allExample:
sudo firewall-cmd --zone=public --list-allAdding and Removing Services
- Add a Service to a Zone:
sudo firewall-cmd --zone=<zone> --add-service=<service> --permanentExample:
sudo firewall-cmd --zone=public --add-service=http --permanent- Remove a Service from a Zone:
sudo firewall-cmd --zone=<zone> --remove-service=<service> --permanentExample:
sudo firewall-cmd --zone=public --remove-service=http --permanentAdding and Removing Ports
- Add a Port to a Zone:
sudo firewall-cmd --zone=<zone> --add-port=<port>/<protocol> --permanentExample:
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent- Remove a Port from a Zone:
sudo firewall-cmd --zone=<zone> --remove-port=<port>/<protocol> --permanentExample:
sudo firewall-cmd --zone=public --remove-port=8080/tcp --permanentReloading the Firewall
After making changes, reload the firewall to apply the new rules.
sudo firewall-cmd --reloadPractical Examples
Example 1: Allow HTTP and HTTPS Traffic
- 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- Reload the Firewall:
sudo firewall-cmd --reload- Verify the HTTP and HTTPS Services are Allowed:
sudo firewall-cmd --zone=public --list-servicesExample 2: Allow Custom Port 8080/TCP
- Add Port 8080/TCP to the Public Zone:
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent- Reload the Firewall:
sudo firewall-cmd --reload- Verify Port 8080/TCP is Allowed:
sudo firewall-cmd --zone=public --list-portsExample 3: Allow SSH Access Only from a Specific IP Address
- Create a New Zone:
sudo firewall-cmd --permanent --new-zone=restricted- Allow Access to the New Zone from a Specific IP Address:
sudo firewall-cmd --zone=restricted --add-source=<ip_address> --permanentExample:
sudo firewall-cmd --zone=restricted --add-source=192.168.1.50 --permanent- Reload the Firewall:
sudo firewall-cmd --reload- Verify the New Zone Configuration:
sudo firewall-cmd --zone=restricted --list-allAdditional Tips
- Check Firewall Status:Use the
firewall-cmd --statecommand to check iffirewalldis running.
sudo firewall-cmd --state- Get Default Zone:Use the
firewall-cmd --get-default-zonecommand 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 --reloadcommand to reload thefirewalldconfiguration after making changes.
sudo firewall-cmd --reload- Temporary Rules:Use the
--permanentflag 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=httpConclusion
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 Files:
666 - umask:
022 - Effective Permissions:
666 - 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.
umaskSample Output:
0022Setting umask Temporarily
To set the umask value temporarily for the current shell session, use the umask command followed by the desired value.
umask 027Setting umask Permanently
To set the umask value permanently, add the umask command to the appropriate shell configuration file.
For Bash Shell
- Edit the
~/.bashrcFile:
nano ~/.bashrc- Add the
umaskCommand:
umask 027- Save and Exit.
- Apply the Changes:
source ~/.bashrcFor System-Wide Settings
- Edit the
/etc/bashrcor/etc/profileFile:
sudo nano /etc/bashrcorsudo nano /etc/profile- Add the
umaskCommand:
umask 027- Save and Exit.
- Apply the Changes:
source /etc/bashrc
# or
source /etc/profileSetting 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
- Set Default ACL for a Directory:
sudo setfacl -d -m u::rwx /shared- Set Default ACL for a Group:
sudo setfacl -d -m g:developers:rwx /shared- Set Default ACL for Others:
sudo setfacl -d -m o::rx /sharedViewing ACLs
Use the getfacl command to view the ACLs of a file or directory.
getfacl /sharedSample 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-xPractical Examples
Example 1: Set umask for a User
- View the Current
umaskValue:
umask- Set the
umaskValue Temporarily:
umask 027- Set the
umaskValue Permanently for the User:
nano ~/.bashrc- Add the
umaskCommand:
umask 027- Save and Exit.
- Apply the Changes:
source ~/.bashrcExample 2: Set System-Wide umask
- Edit the
/etc/profileFile:
sudo nano /etc/profile- Add the
umaskCommand:
umask 027- Save and Exit.
- Apply the Changes:
source /etc/profileExample 3: Set Default ACLs for a Directory
- Set Default ACL for the
/sharedDirectory:
sudo setfacl -d -m u::rwx /shared
sudo setfacl -d -m g:developers:rwx /shared
sudo setfacl -d -m o::rx /shared- Verify the Default ACLs:
getfacl /sharedAdditional Tips
- Check Effective Permissions:Use the
nameicommand to check the effective permissions of a path.
namei -l /path/to/file- Remove Default ACLs:Use the
setfaclcommand with the-xoption to remove default ACLs.
sudo setfacl -x d:u::rwx /shared- Set Recursive ACLs:Use the
-Roption with thesetfaclcommand to set ACLs recursively.
sudo setfacl -R -m u::rwx /shared- Check Default
umaskValue:The defaultumaskvalue for new users can be found in the/etc/login.defsfile.
grep UMASK /etc/login.defs- Set
umaskfor Specific Applications:Some applications allow settingumaskvalues 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"Step 2: Follow the Prompts
- 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.
- Enter a Passphrase (Optional):
Enter passphrase (empty for no passphrase):Enter a passphrase for added security or press Enter to leave it empty.
- 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.100Step 2: Manually Copy the Public Key (Alternative Method)
If ssh-copy-id is not available, you can manually copy the public key.
- Display the Public Key:
cat ~/.ssh/id_rsa.pub- 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
- Connect to the Remote Server Using SSH:
ssh <user>@<remote_host>- 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.
- Start the SSH Agent:
eval "$(ssh-agent -s)"- Add the SSH Key to the Agent:
ssh-add ~/.ssh/id_rsaRemoving SSH Keys from the SSH Agent
- Remove a Specific Key:
ssh-add -d ~/.ssh/id_rsa- Remove All Keys:
ssh-add -DRevoking SSH Keys
To revoke access, remove the corresponding public key from the ~/.ssh/authorized_keys file on the remote server.
- Edit the
authorized_keysFile:
ssh <user>@<remote_host>
nano ~/.ssh/authorized_keys- Remove the Public Key:Delete the line containing the public key to be revoked.
- Save and Exit.
Practical Examples
Example 1: Generate SSH Keys and Configure Key-Based Authentication
- Generate an RSA Key Pair:
ssh-keygen -t rsa -b 2048 -C "your_email@example.com"- Copy the Public Key to the Remote Server:
ssh-copy-id alice@192.168.1.100- Verify SSH Key-Based Authentication:
ssh alice@192.168.1.100Example 2: Manually Copy the Public Key to the Remote Server
- Display the Public Key:
cat ~/.ssh/id_rsa.pub- 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"- Verify SSH Key-Based Authentication:
ssh alice@192.168.1.100Example 3: Add SSH Key to the SSH Agent
- Start the SSH Agent:
eval "$(ssh-agent -s)"- Add the SSH Key to the Agent:
ssh-add ~/.ssh/id_rsaExample 4: Revoke SSH Key Access
- Edit the
authorized_keysFile on the Remote Server:
ssh alice@192.168.1.100
nano ~/.ssh/authorized_keys- Remove the Public Key:Delete the line containing the public key to be revoked.
- Save and Exit.
Additional Tips
- Check SSH Configuration:Ensure the SSH server is configured to allow key-based authentication. Edit the
/etc/ssh/sshd_configfile and verify the following settings:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keysRestart 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_configfile and set:
PasswordAuthentication noRestart the SSH service to apply changes:
sudo systemctl restart sshdConclusion
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.
sestatusSample 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: 31Using getenforce
Use the getenforce command to check the current SELinux mode.
getenforceSample Output:
EnforcingSetting SELinux Mode Temporarily
Using setenforce
The setenforce command is used to change the SELinux mode temporarily until the next reboot.
Syntax
sudo setenforce <mode>0orpermissive: Set SELinux to permissive mode.1orenforcing: Set SELinux to enforcing mode.
Examples
- Set SELinux to Permissive Mode:
sudo setenforce 0
# or
sudo setenforce permissive- Set SELinux to Enforcing Mode:
sudo setenforce 1
# or
sudo setenforce enforcingVerify the Change
Use the getenforce command to verify the current SELinux mode.
getenforceSample Output:
Permissiveor
EnforcingSetting SELinux Mode Permanently
Editing the SELinux Configuration File
To set the SELinux mode permanently, edit the /etc/selinux/config file.
- Open the Configuration File:
sudo nano /etc/selinux/config- Modify the
SELINUXParameter:
# 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=enforcingor
SELINUX=permissive- Save and Exit.
- Reboot the System:
sudo rebootVerify the Change
After rebooting, use the sestatus or getenforce command to verify the current SELinux mode.
sestatusor
getenforcePractical Examples
Example 1: Set SELinux to Permissive Mode Temporarily
- Set SELinux to Permissive Mode:
sudo setenforce 0- Verify the Change:
getenforceExample 2: Set SELinux to Enforcing Mode Temporarily
- Set SELinux to Enforcing Mode:
sudo setenforce 1- Verify the Change:
getenforceExample 3: Set SELinux to Permissive Mode Permanently
- Edit the SELinux Configuration File:
sudo nano /etc/selinux/config- Modify the
SELINUXParameter:
SELINUX=permissive- Save and Exit.
- Reboot the System:
sudo reboot- Verify the Change:
sestatusExample 4: Set SELinux to Enforcing Mode Permanently
- Edit the SELinux Configuration File:
sudo nano /etc/selinux/config- Modify the
SELINUXParameter:
SELINUX=enforcing- Save and Exit.
- Reboot the System:
sudo reboot- Verify the Change:
sestatusAdditional Tips
- Check SELinux Status:Use the
sestatuscommand to check detailed SELinux status.
sestatus- View SELinux Logs:SELinux logs can be found in
/var/log/audit/audit.log. Use theausearchandaudit2allowtools to analyze and create policies.
sudo ausearch -m avc -ts recent
sudo audit2allow -w -a- Disable SELinux:To disable SELinux, set
SELINUX=disabledin the/etc/selinux/configfile 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=enforcingorSELINUX=permissivein the/etc/selinux/configfile and rebooting the system.
SELINUX=enforcing- Temporary vs. Permanent Changes:Use
setenforcefor temporary changes that do not persist across reboots. Edit/etc/selinux/configfor 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_u,user_u) - role: SELinux role (e.g.,
object_r,system_r) - type: SELinux type (e.g.,
httpd_sys_content_t,ssh_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
- List SELinux Context of a File:
ls -Z /etc/passwdSample Output:
-rw-r--r--. root root system_u:object_r:etc_t:s0 /etc/passwd- List SELinux Context of a Directory:
ls -Z /var/www/htmlSample Output:
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /var/www/htmlUsing 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
- Display SELinux Context of a File:
stat -c %C /etc/passwdSample Output:
system_u:object_r:etc_t:s0Listing SELinux Process Contexts
Using ps -eZ
The ps -eZ command displays the SELinux context of running processes.
Syntax
ps -eZExample
- List SELinux Context of All Processes:
ps -eZSample 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 httpdUsing 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
- List SELinux Context of
sshdProcesses:
ps -Z -C sshdSample Output:
LABEL PID TTY TIME CMD
system_u:system_r:sshd_t:s0 1234 ? 00:00:00 sshdPractical Examples
Example 1: List SELinux Context of Files and Directories
- List SELinux Context of the
/etc/passwdFile:
ls -Z /etc/passwd- List SELinux Context of the
/var/www/htmlDirectory:
ls -Z /var/www/html- Display SELinux Context of the
/etc/passwdFile Usingstat:
stat -c %C /etc/passwdExample 2: List SELinux Context of Running Processes
- List SELinux Context of All Processes:
ps -eZ- List SELinux Context of
httpdProcesses:
ps -Z -C httpdAdditional Tips
- Change SELinux File Context:Use the
chconcommand 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
restoreconcommand 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> -Zcommand to list SELinux contexts for processes owned by a specific user.
ps -u alice -Z- View SELinux Contexts in
findCommand:Use the-printfoption with thefindcommand 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
- Restore Default Context for a Single File:
sudo restorecon /etc/passwd- Restore Default Context for a Directory:
sudo restorecon /var/www/html- Restore Default Context Recursively for a Directory:
sudo restorecon -R /var/www/html- Restore Default Context Verbosely for a Directory:
sudo restorecon -Rv /var/www/htmlExample: Restore Default Contexts
- Restore Default Context for the
/etc/passwdFile:
sudo restorecon /etc/passwd- Restore Default Context Recursively for the
/var/www/htmlDirectory:
sudo restorecon -R /var/www/htmlUsing 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
- Add a Custom File Context:
sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"- Modify an Existing File Context:
sudo semanage fcontext -m -t httpd_sys_content_t "/custom/web(/.*)?"- Delete a Custom File Context:
sudo semanage fcontext -d "/custom/web(/.*)?"- List All File Contexts:
sudo semanage fcontext -lApplying Changes with restorecon
After adding or modifying file contexts with semanage, use restorecon to apply the changes.
Example
- Add a Custom File Context for
/custom/web:
sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"- Apply the Changes:
sudo restorecon -R /custom/webPractical Examples
Example 1: Restore Default Contexts for System Files
- Restore Default Context for the
/etc/shadowFile:
sudo restorecon /etc/shadow- Restore Default Context Recursively for the
/var/logDirectory:
sudo restorecon -R /var/logExample 2: Add and Apply Custom File Contexts
- Add a Custom File Context for
/data/web:
sudo semanage fcontext -a -t httpd_sys_content_t "/data/web(/.*)?"- Apply the Changes:
sudo restorecon -R /data/webExample 3: Modify and Apply Custom File Contexts
- Modify the File Context for
/data/web:
sudo semanage fcontext -m -t httpd_sys_content_t "/data/web(/.*)?"- Apply the Changes:
sudo restorecon -R /data/webExample 4: Delete a Custom File Context
- Delete the Custom File Context for
/data/web:
sudo semanage fcontext -d "/data/web(/.*)?"- Restore Default Contexts:
sudo restorecon -R /data/webAdditional Tips
- Check Current File Contexts:Use the
ls -Zcommand 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 -lcommand to view the SELinux policy for file contexts.
sudo semanage fcontext -l- Restore Contexts for Home Directories:Use the
restoreconcommand to restore contexts for user home directories.
sudo restorecon -R /home- Restore Contexts for Specific Types:Use the
-toption withrestoreconto 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 -eAdd the following line to run restorecon daily:
0 2 * * * /usr/sbin/restorecon -R /var/www/htmlConclusion
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 -lExample
- List All SELinux Port Labels:
sudo semanage port -lSample Output:
http_port_t tcp 80, 443
ssh_port_t tcp 22
dns_port_t tcp 53
dns_port_t udp 53Adding 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 (tcporudp).<port_number>: Specify the port number.
Example
- Add a New Port Label for HTTP on Port 8080:
sudo semanage port -a -t http_port_t -p tcp 8080- Verify the New Port Label:
sudo semanage port -l | grep 8080Sample Output:
http_port_t tcp 8080, 80, 443Modifying 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 (tcporudp).<port_number>: Specify the port number.
Example
- Modify the Port Label for HTTP to Include Port 8081:
sudo semanage port -m -t http_port_t -p tcp 8081- Verify the Modified Port Label:
sudo semanage port -l | grep 8081Sample Output:
http_port_t tcp 8081, 80, 443Deleting 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 (tcporudp).<port_number>: Specify the port number.
Example
- Delete the Port Label for HTTP on Port 8080:
sudo semanage port -d -t http_port_t -p tcp 8080- Verify the Deleted Port Label:
sudo semanage port -l | grep 8080Sample Output:(No output, indicating the port label has been deleted.)
Practical Examples
Example 1: Add a New Port Label for a Custom Service
- Add a New Port Label for a Custom Service on Port 9090:
sudo semanage port -a -t custom_service_port_t -p tcp 9090- Verify the New Port Label:
sudo semanage port -l | grep 9090Sample Output:
custom_service_port_t tcp 9090Example 2: Modify an Existing Port Label
- Modify the Port Label for HTTP to Include Port 8082:
sudo semanage port -m -t http_port_t -p tcp 8082- Verify the Modified Port Label:
sudo semanage port -l | grep 8082Sample Output:
http_port_t tcp 8082, 80, 443Example 3: Delete an Existing Port Label
- Delete the Port Label for a Custom Service on Port 9090:
sudo semanage port -d -t custom_service_port_t -p tcp 9090- Verify the Deleted Port Label:
sudo semanage port -l | grep 9090Sample Output:(No output, indicating the port label has been deleted.)
Additional Tips
- Check Current Port Labels:Use the
semanage port -lcommand 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
restoreconcommand on the SELinux policy files.
sudo restorecon -R /etc/selinux/targeted/contexts/files- View SELinux Policy for Ports:Use the
semanage port -lcommand to view the SELinux policy for ports.
sudo semanage port -l- Use
audit2allowto Troubleshoot Port Issues:If you encounter issues with SELinux port labels, use theaudit2allowtool 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.ppConclusion
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 -aExample
- List All SELinux Booleans:
sudo getsebool -aSample 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
- View the State of the
httpd_can_network_connectBoolean:
sudo getsebool httpd_can_network_connectSample Output:
httpd_can_network_connect --> offSetting SELinux Booleans
Using setsebool
The setsebool command is used to set the state of SELinux booleans.
Syntax
sudo setsebool <boolean_name> <on|off>Example
- Enable the
httpd_can_network_connectBoolean:
sudo setsebool httpd_can_network_connect on- Disable the
httpd_can_network_connectBoolean:
sudo setsebool httpd_can_network_connect offSetting 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
- Enable Multiple Booleans and Make the Changes Persistent:
sudo setsebool -P httpd_can_network_connect=on httpd_enable_cgi=onPractical Examples
Example 1: Enable a Boolean Temporarily
- Enable the
httpd_can_network_connectBoolean:
sudo setsebool httpd_can_network_connect on- Verify the Change:
sudo getsebool httpd_can_network_connectSample Output:
httpd_can_network_connect --> onExample 2: Enable a Boolean Persistently
- Enable the
httpd_can_network_connectBoolean Persistently:
sudo setsebool -P httpd_can_network_connect on- Verify the Change:
sudo getsebool httpd_can_network_connectSample Output:
httpd_can_network_connect --> onExample 3: Disable a Boolean Temporarily
- Disable the
httpd_can_network_connectBoolean:
sudo setsebool httpd_can_network_connect off- Verify the Change:
sudo getsebool httpd_can_network_connectSample Output:
httpd_can_network_connect --> offExample 4: Enable Multiple Booleans Persistently
- Enable the
httpd_can_network_connectandhttpd_enable_cgiBooleans Persistently:
sudo setsebool -P httpd_can_network_connect=on httpd_enable_cgi=on- Verify the Changes:
sudo getsebool httpd_can_network_connect
sudo getsebool httpd_enable_cgi
Sample Output:
httpd_can_network_connect --> on
httpd_enable_cgi --> onAdditional Tips
- List Booleans with Descriptions:Use the
semanage boolean -lcommand to list SELinux booleans with descriptions.
sudo semanage boolean -lSample 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
-Poption withsetseboolto make changes persistent across reboots.
sudo setsebool -P <boolean_name> <on|off>- Check SELinux Status:Use the
sestatuscommand to check the overall status of SELinux.
sestatusSample 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
audit2allowto Troubleshoot:If you encounter issues with SELinux policies, use theaudit2allowtool 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.ppConclusion
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 auditd, ausearch, audit2allow, and setroubleshoot.
Diagnosing SELinux Policy Violations
Step 1: Check SELinux Status
Ensure SELinux is enabled and in enforcing mode.
sestatusSample 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: 31Step 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 recentExample
- Search for Recent SELinux Denials:
sudo ausearch -m avc -ts recentSample 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=fileStep 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 setroubleshootSyntax
sudo sealert -a /var/log/audit/audit.logExample
- Analyze SELinux Denials:
sudo sealert -a /var/log/audit/audit.logSample 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
- 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>.ppExample
- Generate a Custom Policy Module:
sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy- Install the Custom Policy Module:
sudo semodule -i mycustompolicy.ppStep 3: Use SELinux Booleans
Sometimes, enabling an SELinux boolean can resolve policy violations.
Syntax
sudo setsebool -P <boolean_name> <on|off>Example
- Enable the
httpd_enable_homedirsBoolean:
sudo setsebool -P httpd_enable_homedirs onPractical Examples
Example 1: Diagnose and Address an HTTPD Access Denial
- Search for Recent SELinux Denials:
sudo ausearch -m avc -ts recent- Analyze SELinux Denials:
sudo sealert -a /var/log/audit/audit.log- 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
- Generate a Custom Policy Module:
sudo ausearch -m avc -ts recent | audit2allow -M mycustompolicy- Install the Custom Policy Module:
sudo semodule -i mycustompolicy.ppExample 3: Enable an SELinux Boolean
- Enable the
httpd_can_network_connectBoolean:
sudo setsebool -P httpd_can_network_connect onAdditional Tips
- Check Current SELinux Booleans:Use the
getsebool -acommand to check the current state of SELinux booleans.
sudo getsebool -a- List All SELinux File Contexts:Use the
semanage fcontext -lcommand to list all SELinux file contexts.
sudo semanage fcontext -l- Restore Default File Contexts:Use the
restoreconcommand to restore default file contexts.
sudo restorecon -R /path/to/directory- View SELinux Policy Modules:Use the
semodule -lcommand to list all installed SELinux policy modules.
sudo semodule -l- Use
audit2whyfor Quick Analysis:Theaudit2whytool provides a quick explanation of SELinux denials.
sudo ausearch -m avc -ts recent | audit2whyConclusion
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.
