Add shortcut for SELinux detection

Skip parsing of /proc/mounts if SELinux is disabled on the machine.
This commit is contained in:
Jan Safranek 2021-11-01 14:32:30 +01:00
parent 186810eb47
commit 7b07b1ef0e
2 changed files with 22 additions and 3 deletions

View File

@ -29,6 +29,7 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"k8s.io/klog/v2" "k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/util/selinux"
"k8s.io/mount-utils" "k8s.io/mount-utils"
utilpath "k8s.io/utils/path" utilpath "k8s.io/utils/path"
) )
@ -230,8 +231,16 @@ func DoMakeRShared(path string, mountInfoFilename string) error {
return nil return nil
} }
// selinux.SELinuxEnabled implementation for unit tests
type seLinuxEnabledFunc func() bool
// GetSELinux is common implementation of GetSELinuxSupport on Linux. // GetSELinux is common implementation of GetSELinuxSupport on Linux.
func GetSELinux(path string, mountInfoFilename string) (bool, error) { func GetSELinux(path string, mountInfoFilename string, selinuxEnabled seLinuxEnabledFunc) (bool, error) {
// Skip /proc/mounts parsing if SELinux is disabled.
if !selinuxEnabled() {
return false, nil
}
info, err := findMountInfo(path, mountInfoFilename) info, err := findMountInfo(path, mountInfoFilename)
if err != nil { if err != nil {
return false, err return false, err
@ -254,7 +263,7 @@ func GetSELinux(path string, mountInfoFilename string) (bool, error) {
// GetSELinuxSupport returns true if given path is on a mount that supports // GetSELinuxSupport returns true if given path is on a mount that supports
// SELinux. // SELinux.
func (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error) { func (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error) {
return GetSELinux(pathname, procMountInfoPath) return GetSELinux(pathname, procMountInfoPath, selinux.SELinuxEnabled)
} }
// GetOwner returns the integer ID for the user and group of the given path // GetOwner returns the integer ID for the user and group of the given path

View File

@ -157,27 +157,37 @@ func TestGetSELinuxSupport(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
mountPoint string mountPoint string
selinuxEnabled bool
expectedResult bool expectedResult bool
}{ }{
{
"ext4 on / with disabled SELinux",
"/",
false,
false,
},
{ {
"ext4 on /", "ext4 on /",
"/", "/",
true, true,
true,
}, },
{ {
"tmpfs on /var/lib/bar", "tmpfs on /var/lib/bar",
"/var/lib/bar", "/var/lib/bar",
true,
false, false,
}, },
{ {
"nfsv4", "nfsv4",
"/media/nfs_vol", "/media/nfs_vol",
true,
false, false,
}, },
} }
for _, test := range tests { for _, test := range tests {
out, err := GetSELinux(test.mountPoint, filename) out, err := GetSELinux(test.mountPoint, filename, func() bool { return test.selinuxEnabled })
if err != nil { if err != nil {
t.Errorf("Test %s failed with error: %s", test.name, err) t.Errorf("Test %s failed with error: %s", test.name, err)
} }