Debian Codegraph @

src/crypto/internal/sysrand/rand_linux_test.go

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