diff --git a/libcontainer/vtpm/vtpm.go b/libcontainer/vtpm/vtpm.go index 998fdec4f9b..5033747b430 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" ) @@ -441,6 +442,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) @@ -472,6 +477,7 @@ again: return false, err } + vtpm.resetSELinux() vtpm.resetAppArmor() cmd = exec.Command("swtpm_bios", "-n", "-cs", "-u", "--tpm-device", tpmname) @@ -515,6 +521,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error { vtpm.CloseServer() + vtpm.teardownSELinux() vtpm.teardownAppArmor() vtpm.Tpm_dev_num = VTPM_DEV_NUM_INVALID @@ -648,3 +655,43 @@ 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() + + err := filepath.Walk(vtpm.StatePath, func(path string, info os.FileInfo, err error) error { + 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() +}