From d8f8e716d79aebb510262b57e03475b8ceafab72 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 81c737d018e..41d07431d40 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" ) @@ -459,6 +460,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) @@ -490,6 +495,7 @@ again: return false, err } + vtpm.resetSELinux() vtpm.resetAppArmor() cmd = exec.Command("swtpm_bios", "-n", "-cs", "-u", "--tpm-device", tpmname) @@ -533,6 +539,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error { vtpm.CloseServer() + vtpm.teardownSELinux() vtpm.teardownAppArmor() vtpm.Tpm_dev_num = VTPM_DEV_NUM_INVALID @@ -666,3 +673,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() +}