@@ -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)
@@ -461,6 +462,10 @@ func (vtpm *VTPM) startSwtpm() error {
461462 if err != nil {
462463 return err
463464 }
465+ err = vtpm .setupSELinux ()
466+ if err != nil {
467+ return err
468+ }
464469
465470 tpmstate := fmt .Sprintf ("dir=%s" , vtpm .StatePath )
466471 pidfile := fmt .Sprintf ("file=%s" , vtpm .getPidFile ())
@@ -492,6 +497,7 @@ func (vtpm *VTPM) startSwtpm() error {
492497 return err
493498 }
494499
500+ vtpm .resetSELinux ()
495501 vtpm .resetAppArmor ()
496502
497503 return nil
@@ -574,6 +580,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error {
574580
575581 vtpm .CloseServer ()
576582
583+ vtpm .teardownSELinux ()
577584 vtpm .teardownAppArmor ()
578585
579586 vtpm .Tpm_dev_num = VTPM_DEV_NUM_INVALID
@@ -706,3 +713,52 @@ func (vtpm *VTPM) teardownAppArmor() {
706713 vtpm .aaprofile = ""
707714 }
708715}
716+
717+ // setupSELinux labels the swtpm files with SELinux labels if SELinux is enabled
718+ func (vtpm * VTPM ) setupSELinux () error {
719+ if ! selinux .GetEnabled () {
720+ return nil
721+ }
722+
723+ processLabel , fileLabel := selinux .ContainerLabels ()
724+ if len (processLabel ) == 0 || len (fileLabel ) == 0 {
725+ return nil
726+ }
727+
728+ err := filepath .Walk (vtpm .StatePath , func (path string , info os.FileInfo , err error ) error {
729+ if err != nil {
730+ return err
731+ }
732+ if info .IsDir () && path != vtpm .StatePath {
733+ return filepath .SkipDir
734+ }
735+ return selinux .SetFileLabel (path , fileLabel )
736+ })
737+
738+ err = selinux .SetFSCreateLabel (fileLabel )
739+ if err != nil {
740+ return err
741+ }
742+ err = ioutil .WriteFile ("/sys/fs/selinux/context" , []byte (processLabel ), 0000 )
743+ if err != nil {
744+ return err
745+ }
746+ err = selinux .SetExecLabel (processLabel )
747+ if err != nil {
748+ return err
749+ }
750+
751+ return nil
752+ }
753+
754+ // resetSELinux resets the prepared SELinux labels
755+ func (vtpm * VTPM ) resetSELinux () {
756+ selinux .SetExecLabel ("" )
757+ selinux .SetFSCreateLabel ("" )
758+ ioutil .WriteFile ("/sys/fs/selinux/context" , []byte ("" ), 0000 )
759+ }
760+
761+ // teardownSELinux cleans up SELinux for next spawned process
762+ func (vtpm * VTPM ) teardownSELinux () {
763+ vtpm .resetSELinux ()
764+ }
0 commit comments