Skip to content

Commit 98f315b

Browse files
committed
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 <[email protected]>
1 parent fa4e365 commit 98f315b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

libcontainer/vtpm/vtpm.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"unsafe"
1717

1818
"github.com/opencontainers/runc/libcontainer/apparmor"
19+
selinux "github.com/opencontainers/selinux/go-selinux"
1920

2021
"github.com/sirupsen/logrus"
2122
)
@@ -441,6 +442,10 @@ again:
441442
if err != nil {
442443
return false, err
443444
}
445+
err = vtpm.setupSELinux()
446+
if err != nil {
447+
return false, err
448+
}
444449

445450
tpmname := vtpm.GetTPMDevname()
446451
fdstr := fmt.Sprintf("%d", vtpm.fd)
@@ -472,6 +477,7 @@ again:
472477
return false, err
473478
}
474479

480+
vtpm.resetSELinux()
475481
vtpm.resetAppArmor()
476482

477483
cmd = exec.Command("swtpm_bios", "-n", "-cs", "-u", "--tpm-device", tpmname)
@@ -515,6 +521,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error {
515521

516522
vtpm.CloseServer()
517523

524+
vtpm.teardownSELinux()
518525
vtpm.teardownAppArmor()
519526

520527
vtpm.Tpm_dev_num = VTPM_DEV_NUM_INVALID
@@ -648,3 +655,52 @@ func (vtpm *VTPM) teardownAppArmor() {
648655
vtpm.aaprofile = ""
649656
}
650657
}
658+
659+
// setupSELinux labels the swtpm files with SELinux labels if SELinux is enabled
660+
func (vtpm *VTPM) setupSELinux() error {
661+
if !selinux.GetEnabled() {
662+
return nil
663+
}
664+
665+
processLabel, fileLabel := selinux.ContainerLabels()
666+
if len(processLabel) == 0 || len(fileLabel) == 0 {
667+
return nil
668+
}
669+
670+
err := filepath.Walk(vtpm.StatePath, func(path string, info os.FileInfo, err error) error {
671+
if (err != nil) {
672+
return err
673+
}
674+
if (info.IsDir() && path != vtpm.StatePath) {
675+
return filepath.SkipDir
676+
}
677+
return selinux.SetFileLabel(path, fileLabel)
678+
})
679+
680+
err = selinux.SetFSCreateLabel(fileLabel)
681+
if err != nil {
682+
return err
683+
}
684+
err = ioutil.WriteFile("/sys/fs/selinux/context", []byte(processLabel), 0000)
685+
if err != nil {
686+
return err
687+
}
688+
err = selinux.SetExecLabel(processLabel)
689+
if err != nil {
690+
return err
691+
}
692+
693+
return nil
694+
}
695+
696+
// resetSELinux resets the prepared SELinux labels
697+
func (vtpm *VTPM) resetSELinux() {
698+
selinux.SetExecLabel("")
699+
selinux.SetFSCreateLabel("")
700+
ioutil.WriteFile("/sys/fs/selinux/context", []byte(""), 0000)
701+
}
702+
703+
// teardownSELinux cleans up SELinux for next spawned process
704+
func (vtpm *VTPM) teardownSELinux() {
705+
vtpm.resetSELinux()
706+
}

0 commit comments

Comments
 (0)