github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/mergeCode/runc/libcontainer/selinux/selinux_test.go (about)

     1  // +build linux,selinux
     2  
     3  package selinux_test
     4  
     5  import (
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/opencontainers/runc/libcontainer/selinux"
    10  )
    11  
    12  func TestSetfilecon(t *testing.T) {
    13  	if selinux.SelinuxEnabled() {
    14  		tmp := "selinux_test"
    15  		con := "system_u:object_r:bin_t:s0"
    16  		out, _ := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE, 0)
    17  		out.Close()
    18  		err := selinux.Setfilecon(tmp, con)
    19  		if err != nil {
    20  			t.Log("Setfilecon failed")
    21  			t.Fatal(err)
    22  		}
    23  		filecon, err := selinux.Getfilecon(tmp)
    24  		if err != nil {
    25  			t.Log("Getfilecon failed")
    26  			t.Fatal(err)
    27  		}
    28  		if con != filecon {
    29  			t.Fatal("Getfilecon failed, returned %s expected %s", filecon, con)
    30  		}
    31  
    32  		os.Remove(tmp)
    33  	}
    34  }
    35  
    36  func TestSELinux(t *testing.T) {
    37  	var (
    38  		err            error
    39  		plabel, flabel string
    40  	)
    41  
    42  	if selinux.SelinuxEnabled() {
    43  		t.Log("Enabled")
    44  		plabel, flabel = selinux.GetLxcContexts()
    45  		t.Log(plabel)
    46  		t.Log(flabel)
    47  		selinux.FreeLxcContexts(plabel)
    48  		plabel, flabel = selinux.GetLxcContexts()
    49  		t.Log(plabel)
    50  		t.Log(flabel)
    51  		selinux.FreeLxcContexts(plabel)
    52  		t.Log("getenforce ", selinux.SelinuxGetEnforce())
    53  		mode := selinux.SelinuxGetEnforceMode()
    54  		t.Log("getenforcemode ", mode)
    55  
    56  		defer selinux.SelinuxSetEnforce(mode)
    57  		if err := selinux.SelinuxSetEnforce(selinux.Enforcing); err != nil {
    58  			t.Fatalf("enforcing selinux failed: %v", err)
    59  		}
    60  		if err := selinux.SelinuxSetEnforce(selinux.Permissive); err != nil {
    61  			t.Fatalf("setting selinux mode to permissive failed: %v", err)
    62  		}
    63  		selinux.SelinuxSetEnforce(mode)
    64  
    65  		pid := os.Getpid()
    66  		t.Logf("PID:%d MCS:%s\n", pid, selinux.IntToMcs(pid, 1023))
    67  		err = selinux.Setfscreatecon("unconfined_u:unconfined_r:unconfined_t:s0")
    68  		if err == nil {
    69  			t.Log(selinux.Getfscreatecon())
    70  		} else {
    71  			t.Log("setfscreatecon failed", err)
    72  			t.Fatal(err)
    73  		}
    74  		err = selinux.Setfscreatecon("")
    75  		if err == nil {
    76  			t.Log(selinux.Getfscreatecon())
    77  		} else {
    78  			t.Log("setfscreatecon failed", err)
    79  			t.Fatal(err)
    80  		}
    81  		t.Log(selinux.Getpidcon(1))
    82  	} else {
    83  		t.Log("Disabled")
    84  	}
    85  }