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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x