1
2
3
4
5 package cryptotest
6
7 import (
8 "crypto/internal/fips140"
9 "internal/testenv"
10 "regexp"
11 "strconv"
12 "strings"
13 "testing"
14 )
15
16 func MustSupportFIPS140(tb testing.TB) {
17 tb.Helper()
18 if err := fips140.Supported(); err != nil {
19 tb.Skipf("test requires FIPS 140 mode: %v", err)
20 }
21 }
22
23
24
25 func MustMinimumFIPS140ModuleVersion(tb testing.TB, min string) {
26 tb.Helper()
27 if fips140.Version() == "latest" {
28 return
29 }
30 if parseFIPS140MinorVersion(tb, fips140.Version()) < parseFIPS140MinorVersion(tb, min) {
31 tb.Skipf("test requires FIPS 140-3 module %s or later", min)
32 }
33 }
34
35 func parseFIPS140MinorVersion(tb testing.TB, version string) int {
36 tb.Helper()
37 v, ok := strings.CutPrefix(version, "v1.")
38 if !ok {
39 tb.Fatalf("unexpected FIPS 140 version format: %q", version)
40 }
41 v, _, ok = strings.Cut(v, ".")
42 if !ok {
43 tb.Fatalf("unexpected FIPS 140 version format: %q", version)
44 }
45 i, err := strconv.Atoi(v)
46 if err != nil {
47 tb.Fatalf("unexpected FIPS 140 version format %q: %v", version, err)
48 }
49 return i
50 }
51
52 func RerunWithFIPS140Enabled(t *testing.T) {
53 t.Helper()
54 MustSupportFIPS140(t)
55 nameRegex := "^" + regexp.QuoteMeta(t.Name()) + "$"
56 cmd := testenv.Command(t, testenv.Executable(t), "-test.run="+nameRegex, "-test.v")
57 cmd.Env = append(cmd.Environ(), "GODEBUG=fips140=on")
58 out, err := cmd.CombinedOutput()
59 t.Logf("running with GODEBUG=fips140=on:\n%s", out)
60 if err != nil {
61 t.Errorf("fips140=on subprocess failed: %v", err)
62 }
63 }
64
65 func RerunWithFIPS140Enforced(t *testing.T) {
66 t.Helper()
67 MustSupportFIPS140(t)
68 nameRegex := "^" + regexp.QuoteMeta(t.Name()) + "$"
69 cmd := testenv.Command(t, testenv.Executable(t), "-test.run="+nameRegex, "-test.v")
70 cmd.Env = append(cmd.Environ(), "GODEBUG=fips140=only")
71 out, err := cmd.CombinedOutput()
72 t.Logf("running with GODEBUG=fips140=only:\n%s", out)
73 if err != nil {
74 t.Errorf("fips140=only subprocess failed: %v", err)
75 }
76 }
77
View as plain text