@@ -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)
@@ -444,6 +445,10 @@ again:
444445 if err != nil {
445446 return false , err
446447 }
448+ err = vtpm .setupSELinux ()
449+ if err != nil {
450+ return false , err
451+ }
447452
448453 tpmname := vtpm .GetTPMDevname ()
449454 fdstr := fmt .Sprintf ("%d" , vtpm .fd )
@@ -475,6 +480,7 @@ again:
475480 return false , err
476481 }
477482
483+ vtpm .resetSELinux ()
478484 vtpm .resetAppArmor ()
479485
480486 cmd = exec .Command ("swtpm_bios" , "-n" , "-cs" , "-u" , "--tpm-device" , tpmname )
@@ -518,6 +524,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error {
518524
519525 vtpm .CloseServer ()
520526
527+ vtpm .teardownSELinux ()
521528 vtpm .teardownAppArmor ()
522529
523530 vtpm .Tpm_dev_num = VTPM_DEV_NUM_INVALID
@@ -651,3 +658,52 @@ func (vtpm *VTPM) teardownAppArmor() {
651658 vtpm .aaprofile = ""
652659 }
653660}
661+
662+ // setupSELinux labels the swtpm files with SELinux labels if SELinux is enabled
663+ func (vtpm * VTPM ) setupSELinux () error {
664+ if ! selinux .GetEnabled () {
665+ return nil
666+ }
667+
668+ processLabel , fileLabel := selinux .ContainerLabels ()
669+ if len (processLabel ) == 0 || len (fileLabel ) == 0 {
670+ return nil
671+ }
672+
673+ err := filepath .Walk (vtpm .StatePath , func (path string , info os.FileInfo , err error ) error {
674+ if (err != nil ) {
675+ return err
676+ }
677+ if (info .IsDir () && path != vtpm .StatePath ) {
678+ return filepath .SkipDir
679+ }
680+ return selinux .SetFileLabel (path , fileLabel )
681+ })
682+
683+ err = selinux .SetFSCreateLabel (fileLabel )
684+ if err != nil {
685+ return err
686+ }
687+ err = ioutil .WriteFile ("/sys/fs/selinux/context" , []byte (processLabel ), 0000 )
688+ if err != nil {
689+ return err
690+ }
691+ err = selinux .SetExecLabel (processLabel )
692+ if err != nil {
693+ return err
694+ }
695+
696+ return nil
697+ }
698+
699+ // resetSELinux resets the prepared SELinux labels
700+ func (vtpm * VTPM ) resetSELinux () {
701+ selinux .SetExecLabel ("" )
702+ selinux .SetFSCreateLabel ("" )
703+ ioutil .WriteFile ("/sys/fs/selinux/context" , []byte ("" ), 0000 )
704+ }
705+
706+ // teardownSELinux cleans up SELinux for next spawned process
707+ func (vtpm * VTPM ) teardownSELinux () {
708+ vtpm .resetSELinux ()
709+ }
0 commit comments