@@ -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)
@@ -459,6 +460,10 @@ again:
459460 if err != nil {
460461 return false , err
461462 }
463+ err = vtpm .setupSELinux ()
464+ if err != nil {
465+ return false , err
466+ }
462467
463468 tpmname := vtpm .GetTPMDevname ()
464469 fdstr := fmt .Sprintf ("%d" , vtpm .fd )
@@ -490,6 +495,7 @@ again:
490495 return false , err
491496 }
492497
498+ vtpm .resetSELinux ()
493499 vtpm .resetAppArmor ()
494500
495501 cmd = exec .Command ("swtpm_bios" , "-n" , "-cs" , "-u" , "--tpm-device" , tpmname )
@@ -533,6 +539,7 @@ func (vtpm *VTPM) Stop(deleteStatePath bool) error {
533539
534540 vtpm .CloseServer ()
535541
542+ vtpm .teardownSELinux ()
536543 vtpm .teardownAppArmor ()
537544
538545 vtpm .Tpm_dev_num = VTPM_DEV_NUM_INVALID
@@ -666,3 +673,52 @@ func (vtpm *VTPM) teardownAppArmor() {
666673 vtpm .aaprofile = ""
667674 }
668675}
676+
677+ // setupSELinux labels the swtpm files with SELinux labels if SELinux is enabled
678+ func (vtpm * VTPM ) setupSELinux () error {
679+ if ! selinux .GetEnabled () {
680+ return nil
681+ }
682+
683+ processLabel , fileLabel := selinux .ContainerLabels ()
684+ if len (processLabel ) == 0 || len (fileLabel ) == 0 {
685+ return nil
686+ }
687+
688+ err := filepath .Walk (vtpm .StatePath , func (path string , info os.FileInfo , err error ) error {
689+ if (err != nil ) {
690+ return err
691+ }
692+ if (info .IsDir () && path != vtpm .StatePath ) {
693+ return filepath .SkipDir
694+ }
695+ return selinux .SetFileLabel (path , fileLabel )
696+ })
697+
698+ err = selinux .SetFSCreateLabel (fileLabel )
699+ if err != nil {
700+ return err
701+ }
702+ err = ioutil .WriteFile ("/sys/fs/selinux/context" , []byte (processLabel ), 0000 )
703+ if err != nil {
704+ return err
705+ }
706+ err = selinux .SetExecLabel (processLabel )
707+ if err != nil {
708+ return err
709+ }
710+
711+ return nil
712+ }
713+
714+ // resetSELinux resets the prepared SELinux labels
715+ func (vtpm * VTPM ) resetSELinux () {
716+ selinux .SetExecLabel ("" )
717+ selinux .SetFSCreateLabel ("" )
718+ ioutil .WriteFile ("/sys/fs/selinux/context" , []byte ("" ), 0000 )
719+ }
720+
721+ // teardownSELinux cleans up SELinux for next spawned process
722+ func (vtpm * VTPM ) teardownSELinux () {
723+ vtpm .resetSELinux ()
724+ }
0 commit comments