chcon

Change SELinux security context of files and directories.

Category: Security SELinux context filesystem labels

Install

# Typically included with coreutils / policycoreutils

# RHEL / Alma / Rocky
sudo dnf install policycoreutils

# Debian / Ubuntu (SELinux systems)
sudo apt install policycoreutils

# openSUSE
sudo zypper install policycoreutils

# Arch
sudo pacman -S policycoreutils

What it does

chcon modifies the SELinux security context of files or directories. SELinux uses labels (contexts) to determine access rules beyond traditional Unix permissions.

How it works (mechanical)

  • Writes new SELinux context labels directly to filesystem extended attributes.
  • Changes apply immediately.
  • Does not modify SELinux policy — only the label on the file.
  • Changes may be overwritten by restorecon or system relabel operations.
  • Requires SELinux-enabled system.

Quick Start

# Show current context
ls -Z filename

# Change type context
sudo chcon -t httpd_sys_content_t filename

10 Practical Examples

# 1) View file context
ls -Z file.txt
# 2) Change only type
sudo chcon -t httpd_sys_content_t index.html
# 3) Change user and role
sudo chcon -u system_u -r object_r file.txt
# 4) Change full context explicitly
sudo chcon system_u:object_r:httpd_sys_content_t:s0 file.txt
# 5) Recursive change on directory
sudo chcon -R -t httpd_sys_content_t /var/www/html
# 6) Match context from reference file
sudo chcon --reference=/var/www/html/index.html newfile.html
# 7) Verify context after change
ls -Zd /var/www/html
# 8) Temporary fix for service access issue
sudo chcon -t httpd_sys_rw_content_t upload_dir
# 9) Compare with restorecon (policy-based restore)
sudo restorecon -v file.txt
# 10) Check SELinux status
getenforce

Notes & Gotchas

  • Changes are temporary if system policy relabels the file.
  • Use semanage fcontext for persistent context changes.
  • Incorrect labels can break services (e.g., Apache, SSH).
  • Only meaningful on SELinux-enabled systems.
  • Always verify with ls -Z after changes.

Historical Context

SELinux introduced mandatory access controls beyond traditional Unix permissions. chcon provides administrators a direct way to modify security labels for troubleshooting or temporary adjustments.

Modern Equivalent

For persistent policy adjustments, use semanage fcontext combined with restorecon. chcon remains useful for immediate, temporary fixes.

Related Commands

  • restorecon — restore default SELinux context.
  • semanage — manage SELinux policy configuration.
  • ls -Z — view SELinux context.
  • getenforce — check SELinux enforcement mode.
  • setenforce — change SELinux enforcement mode.