Source file src/crypto/rand/rand_linux_test.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rand_test
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/rand/internal/seccomp"
    10  	"internal/syscall/unix"
    11  	"internal/testenv"
    12  	"os"
    13  	"runtime"
    14  	"syscall"
    15  	"testing"
    16  )
    17  
    18  func TestNoGetrandom(t *testing.T) {
    19  	if os.Getenv("GO_GETRANDOM_DISABLED") == "1" {
    20  		// We are running under seccomp, the rest of the test suite will take
    21  		// care of actually testing the implementation, we check that getrandom
    22  		// is actually disabled.
    23  		_, err := unix.GetRandom(make([]byte, 16), 0)
    24  		if err != syscall.ENOSYS {
    25  			t.Errorf("GetRandom returned %v, want ENOSYS", err)
    26  		} else {
    27  			t.Log("GetRandom returned ENOSYS as expected")
    28  		}
    29  		return
    30  	}
    31  
    32  	if testing.Short() {
    33  		t.Skip("skipping test in short mode")
    34  	}
    35  	testenv.MustHaveExec(t)
    36  	testenv.MustHaveCGO(t)
    37  
    38  	done := make(chan struct{})
    39  	go func() {
    40  		defer close(done)
    41  		// Call LockOSThread in a new goroutine, where we will apply the seccomp
    42  		// filter. We exit without unlocking the thread, so the thread will die
    43  		// and won't be reused.
    44  		runtime.LockOSThread()
    45  
    46  		if err := seccomp.DisableGetrandom(); err != nil {
    47  			t.Errorf("failed to disable getrandom: %v", err)
    48  			return
    49  		}
    50  
    51  		cmd := testenv.Command(t, os.Args[0], "-test.v")
    52  		cmd.Env = append(os.Environ(), "GO_GETRANDOM_DISABLED=1")
    53  		out, err := cmd.CombinedOutput()
    54  		if err != nil {
    55  			t.Errorf("subprocess failed: %v\n%s", err, out)
    56  			return
    57  		}
    58  
    59  		if !bytes.Contains(out, []byte("GetRandom returned ENOSYS")) {
    60  			t.Errorf("subprocess did not disable getrandom")
    61  		}
    62  		if !bytes.Contains(out, []byte("TestRead")) {
    63  			t.Errorf("subprocess did not run TestRead")
    64  		}
    65  	}()
    66  	<-done
    67  }
    68  

View as plain text