Source file src/crypto/rand/link_test.go

     1  // Copyright 2026 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
     6  
     7  import (
     8  	"internal/testenv"
     9  	"os"
    10  	"path/filepath"
    11  	"regexp"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  const linkerTestProgram = `
    17  package main
    18  import "crypto/rand"
    19  func main() {
    20  	b := make([]byte, 32)
    21  	rand.Read(b)
    22  	println("OK")
    23  }
    24  `
    25  
    26  // TestLinker ensures that using crypto/rand does not bring unrelated
    27  // algorithms into the binary. In particular, the DRBG uses AES-CTR, but that
    28  // must not pull in GCM or the crypto/cipher package.
    29  func TestLinker(t *testing.T) {
    30  	if testing.Short() {
    31  		t.Skip("test requires running 'go build'")
    32  	}
    33  	testenv.MustHaveGoBuild(t)
    34  
    35  	dir := t.TempDir()
    36  	hello := filepath.Join(dir, "hello.go")
    37  	if err := os.WriteFile(hello, []byte(linkerTestProgram), 0664); err != nil {
    38  		t.Fatal(err)
    39  	}
    40  
    41  	run := func(args ...string) string {
    42  		cmd := testenv.Command(t, args[0], args[1:]...)
    43  		cmd.Dir = dir
    44  		out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
    45  		if err != nil {
    46  			t.Fatalf("%v: %v\n%s", args, err, string(out))
    47  		}
    48  		return string(out)
    49  	}
    50  
    51  	run(testenv.GoToolPath(t), "build", "-o", "hello.exe", "hello.go")
    52  	if out := run("./hello.exe"); out != "OK\n" {
    53  		t.Error("unexpected output:", out)
    54  	}
    55  
    56  	// In a snapshot, all the paths are crypto/internal/fips140/v1.2.3/...
    57  	// Remove the version number for the checks below.
    58  	snapshot := regexp.MustCompile(`^crypto/internal/fips140/v[^/]+/`)
    59  
    60  	var consistent bool
    61  	nm := run(testenv.GoToolPath(t), "tool", "nm", "hello.exe")
    62  	for _, match := range regexp.MustCompile(`(?m)T (crypto/.*)$`).FindAllStringSubmatch(nm, -1) {
    63  		symbol := snapshot.ReplaceAllString(match[1], "crypto/internal/fips140/")
    64  		if strings.HasPrefix(symbol, "crypto/internal/fips140/drbg.") {
    65  			consistent = true
    66  		}
    67  		if strings.HasPrefix(symbol, "crypto/internal/fips140/aes/gcm.") ||
    68  			strings.HasPrefix(symbol, "crypto/cipher.") {
    69  			t.Errorf("unexpected symbol in program using only crypto/rand: %s", symbol)
    70  		}
    71  	}
    72  	if !consistent {
    73  		t.Error("no DRBG symbols found in program using crypto/rand, test is broken")
    74  	}
    75  }
    76  

View as plain text