Source file src/crypto/hmac/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 hmac
     6  
     7  import (
     8  	"crypto/internal/cryptotest"
     9  	"internal/testenv"
    10  	"os"
    11  	"path/filepath"
    12  	"regexp"
    13  	"testing"
    14  )
    15  
    16  const linkerTestProgram = `
    17  package main
    18  import (
    19  	"crypto/hmac"
    20  	"crypto/sha256"
    21  )
    22  func main() {
    23  	h := hmac.New(sha256.New, []byte("key"))
    24  	h.Write([]byte("hello"))
    25  	if len(h.Sum(nil)) != 32 {
    26  		panic("bad length")
    27  	}
    28  	println("OK")
    29  }
    30  `
    31  
    32  // TestLinker ensures that using crypto/hmac with one hash does not bring the
    33  // other hashes or the DRBG into the binary. In particular, the approved hash
    34  // check must not pull in SHA-3, and nothing must pull in the DRBG.
    35  func TestLinker(t *testing.T) {
    36  	if testing.Short() {
    37  		t.Skip("test requires running 'go build'")
    38  	}
    39  	testenv.MustHaveGoBuild(t)
    40  	// Older modules check the hash type with a type switch that imports SHA-3.
    41  	cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.28.0")
    42  
    43  	dir := t.TempDir()
    44  	hello := filepath.Join(dir, "hello.go")
    45  	if err := os.WriteFile(hello, []byte(linkerTestProgram), 0664); err != nil {
    46  		t.Fatal(err)
    47  	}
    48  
    49  	run := func(args ...string) string {
    50  		cmd := testenv.Command(t, args[0], args[1:]...)
    51  		cmd.Dir = dir
    52  		out, err := testenv.CleanCmdEnv(cmd).CombinedOutput()
    53  		if err != nil {
    54  			t.Fatalf("%v: %v\n%s", args, err, string(out))
    55  		}
    56  		return string(out)
    57  	}
    58  
    59  	run(testenv.GoToolPath(t), "build", "-o", "hello.exe", "hello.go")
    60  	if out := run("./hello.exe"); out != "OK\n" {
    61  		t.Error("unexpected output:", out)
    62  	}
    63  
    64  	// In a snapshot, the module packages are crypto/internal/fips140/v1.2.3/...
    65  	symbolRE := regexp.MustCompile(`(?m)T (crypto/(?:internal/fips140/(?:v[^/]+/)?)?([a-z0-9]+)\..*)$`)
    66  
    67  	var consistent bool
    68  	nm := run(testenv.GoToolPath(t), "tool", "nm", "hello.exe")
    69  	for _, match := range symbolRE.FindAllStringSubmatch(nm, -1) {
    70  		symbol, pkg := match[1], match[2]
    71  		if pkg == "hmac" {
    72  			consistent = true
    73  		}
    74  		switch pkg {
    75  		case "sha3", "sha512", "drbg":
    76  			t.Errorf("unexpected symbol in program using only HMAC-SHA-256: %s", symbol)
    77  		}
    78  	}
    79  	if !consistent {
    80  		t.Error("no HMAC symbols found in program using crypto/hmac, test is broken")
    81  	}
    82  }
    83  

View as plain text