From b7e7aa778671710fcacc095e0f7bb5b1d0e6400f Mon Sep 17 00:00:00 2001 From: Stefan Berger Date: Sat, 4 Jan 2020 19:49:09 -0500 Subject: [PATCH] vtpm: Run swtpm with an SELinux label On systems supporting SELinux run swtpm with an SELinux label applied. Also label the required files in the state directory. Signed-off-by: Stefan Berger --- libcontainer/vtpm/vtpm.go | 56 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/libcontainer/vtpm/vtpm.go b/libcontainer/vtpm/vtpm.go index a12114a568f..6f99ec664bb 100644 --- a/libcontainer/vtpm/vtpm.go +++ b/libcontainer/vtpm/vtpm.go @@ -16,6 +16,7 @@ import ( "unsafe" "github.com/opencontainers/runc/libcontainer/apparmor" + selinux "github.com/opencontainers/selinux/go-selinux" "github.com/sirupsen/logrus" ) @@ -444,6 +445,10 @@ again: if err != nil { return false, err } + err = vtpm.setupSELinux() + if err != nil { + return false, err + } tpmname := vtpm.GetTPMDevname() fdstr := fmt.Sprintf("%d", vtpm.fd) @@ -475,6 +480,7 @@ again: return false, err } + vtpm.resetSELinux() vtpm.resetAppArmor() cmd = exec.Command("swtpm_bios", "-n", "-cs", "-u", "--tpm-device", tpmname) @@ -518,6 +524,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error { vtpm.CloseServer() + vtpm.teardownSELinux() vtpm.teardownAppArmor() vtpm.Tpm_dev_num = VTPM_DEV_NUM_INVALID @@ -651,3 +658,52 @@ func (vtpm *VTPM) teardownAppArmor() { vtpm.aaprofile = "" } } + +// setupSELinux labels the swtpm files with SELinux labels if SELinux is enabled +func (vtpm *VTPM) setupSELinux() error { + if !selinux.GetEnabled() { + return nil + } + + processLabel, fileLabel := selinux.ContainerLabels() + if len(processLabel) == 0 || len(fileLabel) == 0 { + return nil + } + + err := filepath.Walk(vtpm.StatePath, func(path string, info os.FileInfo, err error) error { + if (err != nil) { + return err + } + if (info.IsDir() && path != vtpm.StatePath) { + return filepath.SkipDir + } + return selinux.SetFileLabel(path, fileLabel) + }) + + err = selinux.SetFSCreateLabel(fileLabel) + if err != nil { + return err + } + err = ioutil.WriteFile("/sys/fs/selinux/context", []byte(processLabel), 0000) + if err != nil { + return err + } + err = selinux.SetExecLabel(processLabel) + if err != nil { + return err + } + + return nil +} + +// resetSELinux resets the prepared SELinux labels +func (vtpm *VTPM) resetSELinux() { + selinux.SetExecLabel("") + selinux.SetFSCreateLabel("") + ioutil.WriteFile("/sys/fs/selinux/context", []byte(""), 0000) +} + +// teardownSELinux cleans up SELinux for next spawned process +func (vtpm *VTPM) teardownSELinux() { + vtpm.resetSELinux() +}