Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

chcon

Change the SELinux context of files directly — only for a quick test, because restorecon or a relabel undoes it.

Level
RHCSA exam
Group
SELinux and security
Needs root
Yes
Package
coreutils

What it does

chcon -t TYPE FILE writes a new label on the file but does not add a rule to the policy. The next restorecon or full relabel sets the old label again. For permanent labels use semanage fcontext + restorecon.

How to write it

chcon [OPTION]... CONTEXT FILE...
chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...
chcon [OPTION]... --reference=RFILE FILE...

Options 13

Most used

-t, --type=TYPE
Set the type.
-u, --user=USER
Set the SELinux user.
-r, --role=ROLE
Set the role.
-l, --range=RANGE
Set the level/range.
--reference=RFILE
Copy the context of RFILE.
-R, --recursive
Whole trees.
-v, --verbose
Report every file.
-h, --no-dereference
Change links themselves.
--dereference
Change the targets of links (default).
-H, -L, -P
Link handling with -R.
--preserve-root, --no-preserve-root
Protect / with -R.
--help
Show help.
--version
Show the version.

Examples 10

$ run as a normal user# run as root (or with sudo)

  1. 1Test a type quickly

    chcon -t httpd_sys_content_t /srv/test/index.html

    Works until the next restorecon.

  2. 2Copy the label of another file

    chcon --reference=/var/www/html /srv/web

    Same context as /var/www/html.

  3. 3A whole folder

    chcon -R -t httpd_sys_content_t /srv/web

    Still temporary.

  4. 4Watch it disappear

    restorecon -v /srv/test/index.html

    The label goes back to the policy rule.

  5. 5The permanent way

    semanage fcontext -a -t httpd_sys_content_t "/srv/web(/.*)?"; restorecon -Rv /srv/web

    Use this on the exam.

  6. 6Break a label for a lab

    chcon -t user_home_t /var/www/html/index.html

    Practice finding AVC denials.

  7. 7Show the full context

    ls -Z /srv/web

    Check the result.

  8. 8Set the full context at once

    chcon system_u:object_r:httpd_sys_content_t:s0 /srv/web/index.html

    All four parts.

  9. 9Container volume label (alternative)

    podman run -v /srv/data:/data:Z …

    :Z lets podman set the right label instead of chcon.

  10. 10Find files with temporary labels

    restorecon -Rvn /srv

    Shows labels that differ from the policy (chcon changes too).

Exit codes

0 :: Done. 1 :: Error.