Source file src/crypto/internal/sysrand/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 sysrand_test
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/internal/sysrand/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  
    37  	done := make(chan struct{})
    38  	go func() {
    39  		defer close(done)
    40  		// Call LockOSThread in a new goroutine, where we will apply the seccomp
    41  		// filter. We exit without unlocking the thread, so the thread will die
    42  		// and won't be reused.
    43  		runtime.LockOSThread()
    44  
    45  		if err := seccomp.DisableGetrandom(); err != nil {
    46  			t.Errorf("failed to disable getrandom: %v", err)
    47  			return
    48  		}
    49  
    50  		cmd := testenv.Command(t, os.Args[0], "-test.v")
    51  		cmd.Env = append(os.Environ(), "GO_GETRANDOM_DISABLED=1")
    52  		out, err := cmd.CombinedOutput()
    53  		if err != nil {
    54  			t.Errorf("subprocess failed: %v\n%s", err, out)
    55  			return
    56  		}
    57  
    58  		if !bytes.Contains(out, []byte("GetRandom returned ENOSYS")) {
    59  			t.Errorf("subprocess did not disable getrandom")
    60  		}
    61  		if !bytes.Contains(out, []byte("TestRead")) {
    62  			t.Errorf("subprocess did not run TestRead")
    63  		}
    64  	}()
    65  	<-done
    66  }
    67  

View as plain text