Source file src/cmd/go/internal/fips140/fips140.go

     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  // Package fips implements support for the GOFIPS140 build setting.
     6  //
     7  // The GOFIPS140 build setting controls two aspects of the build:
     8  //
     9  //   - Whether binaries are built to default to running in FIPS-140 mode,
    10  //     meaning whether they default to GODEBUG=fips140=on or =off.
    11  //
    12  //   - Which copy of the crypto/internal/fips140 source code to use.
    13  //     The default is obviously GOROOT/src/crypto/internal/fips140,
    14  //     but earlier snapshots that have differing levels of external
    15  //     validation and certification are stored in GOROOT/lib/fips140
    16  //     and can be substituted into the build instead.
    17  //
    18  // This package provides the logic needed by the rest of the go command
    19  // to make those decisions and implement the resulting policy.
    20  //
    21  // [Init] must be called to initialize the FIPS logic. It may fail and
    22  // call base.Fatalf.
    23  //
    24  // When GOFIPS140=off, [Enabled] returns false, and the build is
    25  // unchanged from its usual behaviors.
    26  //
    27  // When GOFIPS140 is anything else, [Enabled] returns true, and the build
    28  // sets the default GODEBUG to include fips140=on. This will make
    29  // binaries change their behavior at runtime to confirm to various
    30  // FIPS-140 details. [cmd/go/internal/load.defaultGODEBUG] calls
    31  // [fips.Enabled] when preparing the default settings.
    32  //
    33  // For all builds, FIPS code and data is laid out in contiguous regions
    34  // that are conceptually concatenated into a "fips object file" that the
    35  // linker hashes and then binaries can re-hash at startup to detect
    36  // corruption of those symbols. When [Enabled] is true, the link step
    37  // passes -fipso={a.Objdir}/fips.o to the linker to save a copy of the
    38  // fips.o file. Since the first build target always uses a.Objdir set to
    39  // $WORK/b001, a build like
    40  //
    41  //	GOFIPS140=latest go build -work my/binary
    42  //
    43  // will leave fips.o behind in $WORK/b001
    44  // (unless the build result is cached, of course).
    45  //
    46  // When GOFIPS140 is set to something besides off and latest, [Snapshot]
    47  // returns true, indicating that the build should replace the latest copy
    48  // of crypto/internal/fips140 with an earlier snapshot. The reason to do
    49  // this is to use a copy that has been through additional lab validation
    50  // (an "in-process" module) or NIST certification (a "certified" module).
    51  // The snapshots are stored in GOROOT/lib/fips140 in module zip form.
    52  // When a snapshot is being used, Init unpacks it into the module cache
    53  // and then uses that directory as the source location.
    54  //
    55  // A FIPS snapshot like v1.2.3 is integrated into the build in two different ways.
    56  //
    57  // First, the snapshot's fips140 directory replaces crypto/internal/fips140
    58  // using fsys.Bind. The effect is to appear to have deleted crypto/internal/fips140
    59  // and everything below it, replacing it with the single subdirectory
    60  // crypto/internal/fips140/v1.2.3, which now has the FIPS packages.
    61  // This virtual file system replacement makes patterns like std and crypto...
    62  // automatically see the snapshot packages instead of the original packages
    63  // as they walk GOROOT/src/crypto/internal/fips140.
    64  //
    65  // Second, ResolveImport is called to resolve an import like crypto/internal/fips140/sha256.
    66  // When snapshot v1.2.3 is being used, ResolveImport translates that path to
    67  // crypto/internal/fips140/v1.2.3/sha256 and returns the actual source directory
    68  // in the unpacked snapshot. Using the actual directory instead of the
    69  // virtual directory GOROOT/src/crypto/internal/fips140/v1.2.3 makes sure
    70  // that other tools using go list -json output can find the sources,
    71  // as well as making sure builds have a real directory in which to run the
    72  // assembler, compiler, and so on. The translation of the import path happens
    73  // in the same code that handles mapping golang.org/x/mod to
    74  // cmd/vendor/golang.org/x/mod when building commands.
    75  //
    76  // It is not strictly required to include v1.2.3 in the import path when using
    77  // a snapshot - we could make things work without doing that - but including
    78  // the v1.2.3 gives a different version of the code a different name, which is
    79  // always a good general rule. In particular, it will mean that govulncheck need
    80  // not have any special cases for crypto/internal/fips140 at all. The reports simply
    81  // need to list the relevant symbols in a given Go version. (For example, if a bug
    82  // is only in the in-tree copy but not the snapshots, it doesn't list the snapshot
    83  // symbols; if it's in any snapshots, it has to list the specific snapshot symbols
    84  // in addition to the “normal” symbol.)
    85  package fips140
    86  
    87  import (
    88  	"context"
    89  	"os"
    90  	"path"
    91  	"path/filepath"
    92  	"slices"
    93  	"strings"
    94  
    95  	"cmd/go/internal/base"
    96  	"cmd/go/internal/cfg"
    97  	"cmd/go/internal/fsys"
    98  	"cmd/go/internal/modfetch"
    99  	"cmd/go/internal/str"
   100  
   101  	"golang.org/x/mod/module"
   102  	"golang.org/x/mod/semver"
   103  )
   104  
   105  // Init initializes the FIPS settings.
   106  // It must be called before using any other functions in this package.
   107  // If initialization fails, Init calls base.Fatalf.
   108  func Init() {
   109  	if initDone {
   110  		return
   111  	}
   112  	initDone = true
   113  	initVersion()
   114  	initDir()
   115  	if Snapshot() {
   116  		fsys.Bind(Dir(), filepath.Join(cfg.GOROOT, "src/crypto/internal/fips140"))
   117  	}
   118  
   119  	// ExperimentErr != nil if GOEXPERIMENT failed to parse. Typically
   120  	// cmd/go main will exit in this case, but it is allowed during
   121  	// toolchain selection, as the GOEXPERIMENT may be valid for the
   122  	// selected toolchain version.
   123  	if cfg.ExperimentErr == nil && cfg.Experiment.BoringCrypto && Enabled() {
   124  		base.Fatalf("go: cannot use GOFIPS140 with GOEXPERIMENT=boringcrypto")
   125  	}
   126  	if slices.Contains(cfg.BuildContext.BuildTags, "purego") && Enabled() {
   127  		base.Fatalf("go: cannot use GOFIPS140 with the purego build tag")
   128  	}
   129  }
   130  
   131  var initDone bool
   132  
   133  // checkInit panics if Init has not been called.
   134  func checkInit() {
   135  	if !initDone {
   136  		panic("fips: not initialized")
   137  	}
   138  }
   139  
   140  // Version reports the GOFIPS140 version in use,
   141  // which is either "off", "latest", or a version like "v1.2.3".
   142  // If GOFIPS140 is set to an alias like "inprocess" or "certified",
   143  // Version returns the underlying version.
   144  func Version() string {
   145  	checkInit()
   146  	return version
   147  }
   148  
   149  // Enabled reports whether FIPS mode is enabled at all.
   150  // That is, it reports whether GOFIPS140 is set to something besides "off".
   151  func Enabled() bool {
   152  	checkInit()
   153  	return version != "off"
   154  }
   155  
   156  // Snapshot reports whether FIPS mode is using a source snapshot
   157  // rather than $GOROOT/src/crypto/internal/fips140.
   158  // That is, it reports whether GOFIPS140 is set to something besides "latest" or "off".
   159  func Snapshot() bool {
   160  	checkInit()
   161  	return version != "latest" && version != "off"
   162  }
   163  
   164  var version string
   165  
   166  func initVersion() {
   167  	// For off and latest, use the local source tree.
   168  	v := cfg.GOFIPS140
   169  	if v == "off" || v == "" {
   170  		version = "off"
   171  		return
   172  	}
   173  	if v == "latest" {
   174  		version = "latest"
   175  		return
   176  	}
   177  
   178  	// Otherwise version must exist in lib/fips140, either as
   179  	// a .zip (a source snapshot like v1.2.0.zip)
   180  	// or a .txt (a redirect like inprocess.txt, containing a version number).
   181  	if strings.Contains(v, "/") || strings.Contains(v, `\`) || strings.Contains(v, "..") {
   182  		base.Fatalf("go: malformed GOFIPS140 version %q", cfg.GOFIPS140)
   183  	}
   184  	if cfg.GOROOT == "" {
   185  		base.Fatalf("go: missing GOROOT for GOFIPS140")
   186  	}
   187  
   188  	file := filepath.Join(cfg.GOROOT, "lib", "fips140", v)
   189  	if data, err := os.ReadFile(file + ".txt"); err == nil {
   190  		v = strings.TrimSpace(string(data))
   191  		file = filepath.Join(cfg.GOROOT, "lib", "fips140", v)
   192  		if _, err := os.Stat(file + ".zip"); err != nil {
   193  			base.Fatalf("go: unknown GOFIPS140 version %q (from %q)", v, cfg.GOFIPS140)
   194  		}
   195  	}
   196  
   197  	if _, err := os.Stat(file + ".zip"); err == nil {
   198  		// Found version. Add a build tag.
   199  		cfg.BuildContext.BuildTags = append(cfg.BuildContext.BuildTags, "fips140"+semver.MajorMinor(v))
   200  		version = v
   201  		return
   202  	}
   203  
   204  	base.Fatalf("go: unknown GOFIPS140 version %q", v)
   205  }
   206  
   207  // Dir reports the directory containing the crypto/internal/fips140 source code.
   208  // If Snapshot() is false, Dir returns GOROOT/src/crypto/internal/fips140.
   209  // Otherwise Dir ensures that the snapshot has been unpacked into the
   210  // module cache and then returns the directory in the module cache
   211  // corresponding to the crypto/internal/fips140 directory.
   212  func Dir() string {
   213  	checkInit()
   214  	return dir
   215  }
   216  
   217  var dir string
   218  
   219  func initDir() {
   220  	v := version
   221  	if v == "latest" || v == "off" {
   222  		dir = filepath.Join(cfg.GOROOT, "src/crypto/internal/fips140")
   223  		return
   224  	}
   225  
   226  	mod := module.Version{Path: "golang.org/fips140", Version: v}
   227  	file := filepath.Join(cfg.GOROOT, "lib/fips140", v+".zip")
   228  	zdir, err := modfetch.NewFetcher().Unzip(context.Background(), mod, file)
   229  	if err != nil {
   230  		base.Fatalf("go: unpacking GOFIPS140=%v: %v", v, err)
   231  	}
   232  	dir = filepath.Join(zdir, "fips140")
   233  }
   234  
   235  // ResolveImport resolves the import path imp.
   236  // If it is of the form crypto/internal/fips140/foo
   237  // (not crypto/internal/fips140/v1.2.3/foo)
   238  // and we are using a snapshot, then LookupImport
   239  // rewrites the path to crypto/internal/fips140/v1.2.3/foo
   240  // and returns that path and its location in the unpacked
   241  // FIPS snapshot.
   242  func ResolveImport(imp string) (newPath, dir string, ok bool) {
   243  	checkInit()
   244  	const fips = "crypto/internal/fips140"
   245  	if !Snapshot() || !str.HasPathPrefix(imp, fips) {
   246  		return "", "", false
   247  	}
   248  	fipsv := path.Join(fips, version)
   249  	var sub string
   250  	if str.HasPathPrefix(imp, fipsv) {
   251  		sub = "." + imp[len(fipsv):]
   252  	} else {
   253  		sub = "." + imp[len(fips):]
   254  	}
   255  	newPath = path.Join(fips, version, sub)
   256  	dir = filepath.Join(Dir(), version, sub)
   257  	return newPath, dir, true
   258  }
   259  

View as plain text