Overview
chcon is a command for manually changing SELinux security contexts. An SELinux context consists of four fields: user, role, type, and level. This information is used by SELinux policies to allow or deny file access. Incorrect context settings can lead to 'Permission denied' errors or create security vulnerabilities, so it should be used with caution.
Key Features
- Change SELinux context of files and directories
- Modify specific context fields (user, role, type, level) individually
- Set context by referencing another file
- Recursively change directory contents
Key Options
The chcon command uses various options to control how SELinux contexts are changed.
Specifying Context
Reference and Recursion
Other
Generated command:
Try combining the commands.
Description:
`chcon` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Learn how to effectively manage SELinux contexts of files through various usage examples of the chcon command.
Changing File Type Context
chcon -t httpd_sys_content_t myfile.txt
Changes the SELinux type of the file 'myfile.txt' to 'httpd_sys_content_t'. This is commonly used for files that a web server needs to access.
Recursively Changing Type Context for Directory and Sub-files
chcon -R -t httpd_sys_content_t /var/www/html
Changes the type of the '/var/www/html' directory and all its sub-files and directories to 'httpd_sys_content_t'.
Changing Context by Referencing Another File
chcon --reference=/etc/passwd newfile.txt
Sets the context of 'newfile.txt' by referencing the SELinux context of the '/etc/passwd' file.
Changing File User and Role Context
chcon -u user_u -r user_r testfile
Changes the SELinux user part of the file 'testfile' to 'user_u' and the role part to 'user_r'.
Tips & Precautions
Points to note and useful tips when using chcon.
Checking SELinux Context
You can check the current SELinux context of a file using the `ls -Z` command.
- ls -Z /path/to/file
- ls -Zd /path/to/directory (to check the context of the directory itself)
Recommended to Use restorecon
In most cases, it is recommended to use the `restorecon` command instead of `chcon` to restore the context according to the file system's default SELinux policy. `chcon` should be used for temporary changes or specific purposes. For permanent changes, it is advisable to add them to the policy using `semanage fcontext` and then run `restorecon`.
- restorecon -v /path/to/file
- restorecon -Rv /path/to/directory
Risks of Incorrect Context
Incorrect SELinux contexts can prevent applications from accessing files, leading to service disruptions. Be especially cautious when changing the context of critical system files such as web server files, databases, and log files.