SELinux tips

Context rules

Temporarily changing a label on a directory

Following will temporarily change the context of a directory (or a file).

chcon -R -t samba_share_t mydir/

Permanently changing a lable on a directory

This is done on two steps

  1. define a new context rule
semanage fcontext -a -t samba_share_t "/path/to/directory(/.*)?"
  1. when the new context is created, apply it
restorecon -R -v /path/to/directory

Notes:

  • -a flag adds a new context
  • -t specifies the type
  • -R makes restorecon work recursively
  • -v provides verbose output

Custom policies

  1. Location where this would be happening is

/etc/selinux/targeted/modules/mycontext

  1. Then we create a TypeEnforcement (.te) file, for example samba_extra.te
module samba_extra 1.0;

require {
        type samba_server_t; # We'll need the Samba server type
}

# No specific rules needed here, as we're relying on file context
  1. To create a custom policy, we need to create a new FileContext (.fc) file. For example it could be called samba_extra.fc
/mnt/samba_share(/.*)?   --      system_u:object_r:samba_share_t:s0
  1. We need to compile/build the Module (.mod) file
checkmodule -M -m -o samba_extra.mod samba_extra.te
  1. Then we need to package it into PolicyPackage (.pp) file
semodule_package -o samba_extra.pp -m samba_extra.mod
  1. Once it is built, we need to install it
sudo semodule -i samba_extra.pp
  1. And finally apply the rules to target directories
sudo restorecon -Rv /mnt/samba_share  # Replace with your actual path