github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/sandbox/selinux/selinux_linux.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2018 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package selinux
    21  
    22  import (
    23  	"bytes"
    24  	"fmt"
    25  	"io/ioutil"
    26  	"path/filepath"
    27  
    28  	"github.com/snapcore/snapd/osutil"
    29  )
    30  
    31  // IsEnabled checks whether SELinux is enabled
    32  func IsEnabled() (bool, error) {
    33  	mnt, err := getSELinuxMount()
    34  	if err != nil {
    35  		return false, fmt.Errorf("failed to obtain SELinux mount path: %v", err)
    36  	}
    37  	return mnt != "", nil
    38  }
    39  
    40  // IsEnabled checks whether SELinux is in enforcing mode
    41  func IsEnforcing() (bool, error) {
    42  	mnt, err := getSELinuxMount()
    43  	if err != nil {
    44  		return false, fmt.Errorf("failed to obtain SELinux mount path: %v", err)
    45  	}
    46  	if mnt == "" {
    47  		// not enabled
    48  		return false, nil
    49  	}
    50  
    51  	rawState, err := ioutil.ReadFile(filepath.Join(mnt, "enforce"))
    52  	if err != nil {
    53  		return false, err
    54  	}
    55  	switch {
    56  	case bytes.Equal(rawState, []byte("0")):
    57  		return false, nil
    58  	case bytes.Equal(rawState, []byte("1")):
    59  		return true, nil
    60  	}
    61  	return false, fmt.Errorf("unknown SELinux status: %s", rawState)
    62  }
    63  
    64  func getSELinuxMount() (string, error) {
    65  	mountinfo, err := osutil.LoadMountInfo()
    66  	if err != nil {
    67  		return "", err
    68  	}
    69  	for _, entry := range mountinfo {
    70  		if entry.FsType == "selinuxfs" {
    71  			return entry.MountDir, nil
    72  		}
    73  	}
    74  	return "", nil
    75  }