@@ -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,43 @@ 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+
667+ err := filepath .Walk (vtpm .StatePath , func (path string , info os.FileInfo , err error ) error {
668+ return selinux .SetFileLabel (path , fileLabel )
669+ })
670+
671+ err = selinux .SetFSCreateLabel (fileLabel )
672+ if err != nil {
673+ return err
674+ }
675+ err = ioutil .WriteFile ("/sys/fs/selinux/context" , []byte (processLabel ), 0000 )
676+ if err != nil {
677+ return err
678+ }
679+ err = selinux .SetExecLabel (processLabel )
680+ if err != nil {
681+ return err
682+ }
683+
684+ return nil
685+ }
686+
687+ // resetSELinux resets the prepared SELinux labels
688+ func (vtpm * VTPM ) resetSELinux () {
689+ selinux .SetExecLabel ("" )
690+ selinux .SetFSCreateLabel ("" )
691+ ioutil .WriteFile ("/sys/fs/selinux/context" , []byte ("" ), 0000 )
692+ }
693+
694+ // teardownSELinux cleans up SELinux for next spawned process
695+ func (vtpm * VTPM ) teardownSELinux () {
696+ vtpm .resetSELinux ()
697+ }
0 commit comments