Copy a file while preserving SELinux context on Linux

SElinux has now become a important part of any decent Linux System. During the configuration of various service the file SELinux context plays on important role. There are times when you need to copy or make a backup of files with a predefined SELinux context for a later use or you are trying to mimic current configuration. To make a copy of a file while preserving its SELinux context use cp command with --preserve=context option.

For example let’s display a SELinux file context of /etc/services file:

[root@rhel7 ]# ls -Z /etc/services 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /etc/services

During the copy procedure a cp command by default will create a new SELinux file context:

[root@rhel7 ]# cp /etc/services /tmp/
[root@rhel7 ]# ls -Z /tmp/services 
-rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/services

using preserve=context will instruct the cp command to preserve SELinux context:

[root@rhel7 ]# cp --preserve=context /etc/services /tmp/
cp: overwrite ‘/tmp/services’? y
[root@rhel7 ]# ls -Z /tmp/services 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /tmp/services

The above SELinux preserve context procedure also applies for a directory:

[root@rhel7 ]# ls -Zd /etc/
drwxr-xr-x. root root system_u:object_r:etc_t:s0       /etc/
[root@rhel7 ]# cp -r /etc/ /tmp/
[root@rhel7 ]# ls -Zd /tmp/etc/
drwxr-xr-x. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/etc/
[root@rhel7 ]# rm -fr /tmp/etc/
[root@rhel7 ]# cp -r --preserve=context /etc/ /tmp/
[root@rhel7 ]# ls -Zd /tmp/etc/
drwxr-xr-x. root root system_u:object_r:etc_t:s0       /tmp/etc/