How can I copy SELinux context from one directory and apply it to another?

Example use scenario is when creating a new local user outside of the default /home path, like this:

$ sudo useradd -d /websites Tim

This creates Tim's home directory /websites and sets correct permissions and ownership for Tim, however its SELinux context is different from other users, as seen here:

# ls -dZ /websites
drwx------. Tim Tim system_u:object_r:etc_runtime_t:s0 /websites

What I want to do is copy the SELinux context from an other user's /home directory and apply it to Tim's /websites directory.

Other user's SELinux context is like this:

# ls -Z /home/
drwx------. Ben  Ben  unconfined_u:object_r:user_home_dir_t:s0 Ben
drwx------. Bob  Bob  unconfined_u:object_r:user_home_dir_t:s0 Bob
drwx------. lexy lexy unconfined_u:object_r:user_home_dir_t:s0 lexy
  • 1
    This is simply done using the -e flag as in. semanage fcontext -a -e /home/Ben '/websites(/.*)?' After that you'd have to run restorecon as in restorecon -vvRF /websites` and the new file context will be applied. – Valentin Bajrami Mar 29 '17 at 11:31
  • 1
    Cheers @val0x00ff - Using equivalence seems a reasonable way of duplicating SELinux contexts. If you add this as answer and note the switches I will accept it. The -w switch on retorecon appears to be a typo btw. – Alxs Mar 31 '17 at 6:37
  • 1
    @ Alxs, it's a v twice which denodes verbosity and I added this as an answer. – Valentin Bajrami Mar 31 '17 at 21:59
  • Thanks for that @val0x00ff. I think I'm finally due for some reading glasses. :) – Alxs Apr 1 '17 at 3:24

This is simply done using the -a and -e flags as in:

semanage fcontext -a -e /home/Ben '/websites(/.*)?' 

-a : add,

-e : equivalence

After that you'd have to run restorecon as in:

restorecon -vvRF /websites

and the new file context will be applied.

-v : show changes in file labels,

-R : recursive,

-F : force reset of context

It is also possible to change the SELinux file context with:

semanage fcontext -a -t httpd_sys_content_t '/website(/.*)?'

This will assign the new filecontext regardless.

-a : add,

-t : type

  • Thanks for the details Anthon. A single quote was missing but that's fixed now. – Valentin Bajrami Apr 1 '17 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.