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)
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 if err != nil {
56 t.Errorf("subprocess failed: %v\n%s", err, out)
57 return
58 }
59
60 if !bytes.Contains(out, []byte("GetRandom returned ENOSYS")) {
61 t.Errorf("subprocess did not disable getrandom")
62 }
63 if !bytes.Contains(out, []byte("TestRead")) {
64 t.Errorf("subprocess did not run TestRead")
65 }
66 }()
67 <-done
68 }