Source file src/internal/analysis/fipsdit/fipsdit.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 fipsdit provides an analyzer which checks that exported functions in
     6  // crypto/... do not call into crypto/internal/fips140/... or constant-time
     7  // scalar primitives (crypto/subtle.ConstantTime{Select,ByteEq,Eq,LessOrEq} and
     8  // crypto/internal/constanttime) without enabling Data Independent Timing via
     9  // crypto/subtle.WithDataIndependentTiming.
    10  package fipsdit
    11  
    12  import (
    13  	"fmt"
    14  	"go/ast"
    15  	"go/token"
    16  	"go/types"
    17  	"slices"
    18  	"strings"
    19  
    20  	"golang.org/x/tools/go/analysis"
    21  	"golang.org/x/tools/go/analysis/passes/inspect"
    22  )
    23  
    24  // allowlist contains exported functions and FIPS targets that do not
    25  // require constant-time execution (DIT).
    26  var allowlist = map[string]bool{
    27  	"crypto/internal/fips140/aes.Block.BlockSize":        true,
    28  	"crypto/internal/fips140/aes.CBCDecrypter.BlockSize": true,
    29  	"crypto/internal/fips140/aes.CBCDecrypter.SetIV":     true,
    30  	"crypto/internal/fips140/aes.CBCEncrypter.BlockSize": true,
    31  	"crypto/internal/fips140/aes.CBCEncrypter.SetIV":     true,
    32  	"crypto/internal/fips140/aes.NewCBCDecrypter":        true,
    33  	"crypto/internal/fips140/aes.NewCBCEncrypter":        true,
    34  	"crypto/internal/fips140/aes.NewCTR":                 true,
    35  
    36  	"crypto/internal/fips140/aes/gcm.GCM.NonceSize":                    true,
    37  	"crypto/internal/fips140/aes/gcm.GCM.Overhead":                     true,
    38  	"crypto/internal/fips140/aes/gcm.GCMForTLS12.NonceSize":            true,
    39  	"crypto/internal/fips140/aes/gcm.GCMForTLS12.Overhead":             true,
    40  	"crypto/internal/fips140/aes/gcm.GCMForTLS13.NonceSize":            true,
    41  	"crypto/internal/fips140/aes/gcm.GCMForTLS13.Overhead":             true,
    42  	"crypto/internal/fips140/aes/gcm.GCMWithCounterNonce.NonceSize":    true,
    43  	"crypto/internal/fips140/aes/gcm.GCMWithCounterNonce.Overhead":     true,
    44  	"crypto/internal/fips140/aes/gcm.GCMWithXORCounterNonce.NonceSize": true,
    45  	"crypto/internal/fips140/aes/gcm.GCMWithXORCounterNonce.Overhead":  true,
    46  
    47  	"crypto/internal/fips140/alias.AnyOverlap":     true,
    48  	"crypto/internal/fips140/alias.InexactOverlap": true,
    49  
    50  	// NewModulus is only called with public RSA moduli (via fipsPublicKey).
    51  	"crypto/internal/fips140/bigmod.NewModulus": true,
    52  
    53  	"crypto/internal/fips140/drbg.IsDefaultReader": true,
    54  
    55  	"crypto/internal/fips140/ecdh.NewPublicKey":         true,
    56  	"crypto/internal/fips140/ecdh.P256":                 true,
    57  	"crypto/internal/fips140/ecdh.P384":                 true,
    58  	"crypto/internal/fips140/ecdh.P521":                 true,
    59  	"crypto/internal/fips140/ecdh.PrivateKey.Bytes":     true,
    60  	"crypto/internal/fips140/ecdh.PrivateKey.PublicKey": true,
    61  	"crypto/internal/fips140/ecdh.PublicKey.Bytes":      true,
    62  
    63  	"crypto/internal/fips140/ecdsa.NewPublicKey":         true,
    64  	"crypto/internal/fips140/ecdsa.P224":                 true,
    65  	"crypto/internal/fips140/ecdsa.P256":                 true,
    66  	"crypto/internal/fips140/ecdsa.P384":                 true,
    67  	"crypto/internal/fips140/ecdsa.P521":                 true,
    68  	"crypto/internal/fips140/ecdsa.PrivateKey.Bytes":     true,
    69  	"crypto/internal/fips140/ecdsa.PrivateKey.PublicKey": true,
    70  	"crypto/internal/fips140/ecdsa.PublicKey.Bytes":      true,
    71  	"crypto/internal/fips140/ecdsa.Verify":               true,
    72  
    73  	"crypto/internal/fips140/ed25519.NewPublicKey":         true,
    74  	"crypto/internal/fips140/ed25519.PrivateKey.Bytes":     true,
    75  	"crypto/internal/fips140/ed25519.PrivateKey.PublicKey": true,
    76  	"crypto/internal/fips140/ed25519.Verify":               true,
    77  	"crypto/internal/fips140/ed25519.VerifyCtx":            true,
    78  	"crypto/internal/fips140/ed25519.VerifyPH":             true,
    79  
    80  	"crypto/internal/fips140/hmac.HMAC.BlockSize": true,
    81  	"crypto/internal/fips140/hmac.HMAC.Size":      true,
    82  
    83  	"crypto/internal/fips140/mldsa.NewPublicKey44":       true,
    84  	"crypto/internal/fips140/mldsa.NewPublicKey65":       true,
    85  	"crypto/internal/fips140/mldsa.NewPublicKey87":       true,
    86  	"crypto/internal/fips140/mldsa.PrivateKey.Bytes":     true,
    87  	"crypto/internal/fips140/mldsa.PrivateKey.PublicKey": true,
    88  	"crypto/internal/fips140/mldsa.PublicKey.Bytes":      true,
    89  	"crypto/internal/fips140/mldsa.PublicKey.Equal":      true,
    90  	"crypto/internal/fips140/mldsa.PublicKey.Parameters": true,
    91  	"crypto/internal/fips140/mldsa.Verify":               true,
    92  
    93  	"crypto/internal/fips140/mlkem.DecapsulationKey1024.Bytes":               true,
    94  	"crypto/internal/fips140/mlkem.EncapsulationKey1024.EncapsulateInternal": true,
    95  	"crypto/internal/fips140/mlkem.DecapsulationKey1024.EncapsulationKey":    true,
    96  	"crypto/internal/fips140/mlkem.DecapsulationKey768.Bytes":                true,
    97  	"crypto/internal/fips140/mlkem.EncapsulationKey768.EncapsulateInternal":  true,
    98  	"crypto/internal/fips140/mlkem.DecapsulationKey768.EncapsulationKey":     true,
    99  	"crypto/internal/fips140/mlkem.EncapsulationKey1024.Bytes":               true,
   100  	"crypto/internal/fips140/mlkem.EncapsulationKey768.Bytes":                true,
   101  	"crypto/internal/fips140/mlkem.NewEncapsulationKey768":                   true,
   102  	"crypto/internal/fips140/mlkem.NewEncapsulationKey1024":                  true,
   103  
   104  	"crypto/internal/fips140/nistec.P224Point.Bytes":    true,
   105  	"crypto/internal/fips140/nistec.P224Point.SetBytes": true,
   106  	"crypto/internal/fips140/nistec.P256Point.Bytes":    true,
   107  	"crypto/internal/fips140/nistec.P256Point.SetBytes": true,
   108  	"crypto/internal/fips140/nistec.P384Point.Bytes":    true,
   109  	"crypto/internal/fips140/nistec.P384Point.SetBytes": true,
   110  	"crypto/internal/fips140/nistec.P521Point.Bytes":    true,
   111  	"crypto/internal/fips140/nistec.P521Point.SetBytes": true,
   112  
   113  	"crypto/internal/fips140/rsa.GenerateKey":             true,
   114  	"crypto/internal/fips140/rsa.PSSMaxSaltLength":        true,
   115  	"crypto/internal/fips140/rsa.PrivateKey.Export":       true,
   116  	"crypto/internal/fips140/rsa.PrivateKey.PublicKey":    true,
   117  	"crypto/internal/fips140/rsa.VerifyPKCS1v15":          true,
   118  	"crypto/internal/fips140/rsa.VerifyPSS":               true,
   119  	"crypto/internal/fips140/rsa.VerifyPSSWithSaltLength": true,
   120  
   121  	"crypto/internal/fips140/sha256.New":    true,
   122  	"crypto/internal/fips140/sha256.New224": true,
   123  
   124  	"crypto/internal/fips140/sha3.Digest.AppendBinary":    true,
   125  	"crypto/internal/fips140/sha3.Digest.BlockSize":       true,
   126  	"crypto/internal/fips140/sha3.Digest.MarshalBinary":   true,
   127  	"crypto/internal/fips140/sha3.Digest.Reset":           true,
   128  	"crypto/internal/fips140/sha3.Digest.Size":            true,
   129  	"crypto/internal/fips140/sha3.Digest.UnmarshalBinary": true,
   130  	"crypto/internal/fips140/sha3.New":                    true,
   131  	"crypto/internal/fips140/sha3.New224":                 true,
   132  	"crypto/internal/fips140/sha3.New256":                 true,
   133  	"crypto/internal/fips140/sha3.New384":                 true,
   134  	"crypto/internal/fips140/sha3.New512":                 true,
   135  	"crypto/internal/fips140/sha3.NewCShake128":           true,
   136  	"crypto/internal/fips140/sha3.NewCShake256":           true,
   137  	"crypto/internal/fips140/sha3.NewShake128":            true,
   138  	"crypto/internal/fips140/sha3.NewShake256":            true,
   139  	"crypto/internal/fips140/sha3.SHAKE.AppendBinary":     true,
   140  	"crypto/internal/fips140/sha3.SHAKE.BlockSize":        true,
   141  	"crypto/internal/fips140/sha3.SHAKE.MarshalBinary":    true,
   142  	"crypto/internal/fips140/sha3.SHAKE.Reset":            true,
   143  	"crypto/internal/fips140/sha3.SHAKE.Size":             true,
   144  	"crypto/internal/fips140/sha3.SHAKE.UnmarshalBinary":  true,
   145  
   146  	"crypto/internal/fips140/sha512.New":        true,
   147  	"crypto/internal/fips140/sha512.New384":     true,
   148  	"crypto/internal/fips140/sha512.New512_224": true,
   149  	"crypto/internal/fips140/sha512.New512_256": true,
   150  
   151  	// Check only hashes public certificate metadata (issuer SPKI and serial).
   152  	"crypto/internal/upki.Check": true,
   153  }
   154  
   155  // funcFact is an analysis.Fact exported on *types.Func objects.
   156  type funcFact struct {
   157  	// UnprotectedPath is non-empty if calling this function executes a path
   158  	// to crypto/internal/fips140/... without subtle.WithDataIndependentTiming.
   159  	UnprotectedPath string
   160  
   161  	// ReturnsFIPSType is non-empty if this function returns a concrete type
   162  	// defined in crypto/internal/fips140/... (e.g. "crypto/internal/fips140/sha256.Digest").
   163  	ReturnsFIPSType string
   164  }
   165  
   166  func (*funcFact) AFact() {}
   167  
   168  var Analyzer = &analysis.Analyzer{
   169  	Name:      "fipsditcheck",
   170  	Doc:       "check FIPS 140 Data Independent Timing (DIT) requirements",
   171  	Requires:  []*analysis.Analyzer{inspect.Analyzer},
   172  	FactTypes: []analysis.Fact{(*funcFact)(nil)},
   173  	Run:       run,
   174  }
   175  
   176  func run(pass *analysis.Pass) (any, error) {
   177  	if isFIPS140Pkg(pass.Pkg) || pass.Pkg.Path() == "crypto/internal/constanttime" || !strings.HasPrefix(pass.Pkg.Path(), "crypto") {
   178  		return nil, nil
   179  	}
   180  
   181  	isAllowlisted := func(name string) bool {
   182  		if name == "" {
   183  			return false
   184  		}
   185  		return allowlist[name] || allowlist[normalizeFIPSPath(name)]
   186  	}
   187  
   188  	// Collect non-test function declarations and package-level variable
   189  	// initializer closures in this package.
   190  	type declInfo struct {
   191  		decl *ast.FuncDecl
   192  		fn   *types.Func
   193  	}
   194  	type varLitInfo struct {
   195  		name string
   196  		lit  *ast.FuncLit
   197  	}
   198  	var decls []declInfo
   199  	var pkgFuncs []*types.Func
   200  	var pkgVarLits []varLitInfo
   201  	declMap := make(map[*types.Func]*ast.FuncDecl)
   202  
   203  	for _, file := range pass.Files {
   204  		filename := pass.Fset.File(file.Pos()).Name()
   205  		if strings.HasSuffix(filename, "_test.go") {
   206  			continue
   207  		}
   208  		for _, d := range file.Decls {
   209  			switch decl := d.(type) {
   210  			case *ast.FuncDecl:
   211  				if decl.Name == nil {
   212  					continue
   213  				}
   214  				obj, ok := pass.TypesInfo.Defs[decl.Name].(*types.Func)
   215  				if !ok || obj == nil {
   216  					continue
   217  				}
   218  				obj = obj.Origin()
   219  				decls = append(decls, declInfo{decl: decl, fn: obj})
   220  				pkgFuncs = append(pkgFuncs, obj)
   221  				declMap[obj] = decl
   222  			case *ast.GenDecl:
   223  				if decl.Tok != token.VAR {
   224  					continue
   225  				}
   226  				for _, spec := range decl.Specs {
   227  					vs, ok := spec.(*ast.ValueSpec)
   228  					if !ok {
   229  						continue
   230  					}
   231  					for i, val := range vs.Values {
   232  						varName := pass.Pkg.Path()
   233  						if i < len(vs.Names) {
   234  							varName = pass.Pkg.Path() + "." + vs.Names[i].Name
   235  						}
   236  						ast.Inspect(val, func(n ast.Node) bool {
   237  							if call, ok := n.(*ast.CallExpr); ok && isWithDIT(pass.TypesInfo, call) {
   238  								return false
   239  							}
   240  							if lit, ok := n.(*ast.FuncLit); ok {
   241  								pkgVarLits = append(pkgVarLits, varLitInfo{name: varName, lit: lit})
   242  								return false
   243  							}
   244  							return true
   245  						})
   246  					}
   247  				}
   248  			}
   249  		}
   250  	}
   251  
   252  	// Identify functions that return a concrete crypto/internal/fips140/... type
   253  	// (e.g. returning *sha256.Digest as a hash.Hash interface).
   254  	returnsFIPS := make(map[*types.Func]string)
   255  	for _, info := range decls {
   256  		if info.decl.Type.Results != nil {
   257  			for _, field := range info.decl.Type.Results.List {
   258  				if t := pass.TypesInfo.TypeOf(field.Type); t != nil {
   259  					if fipsType := extractFIPSTypeName(t); fipsType != "" {
   260  						returnsFIPS[info.fn] = fipsType
   261  						break
   262  					}
   263  				}
   264  			}
   265  		}
   266  		if info.decl.Body == nil || returnsFIPS[info.fn] != "" {
   267  			continue
   268  		}
   269  		ast.Inspect(info.decl.Body, func(n ast.Node) bool {
   270  			if _, ok := n.(*ast.FuncLit); ok {
   271  				return false
   272  			}
   273  			// Skip returns guarded by "if !sys.DITSupported { ... }" since the
   274  			// unwrapped FIPS type is only returned when DIT is unavailable.
   275  			if ifStmt, ok := n.(*ast.IfStmt); ok && isNotDITSupported(pass.TypesInfo, ifStmt.Cond) {
   276  				if ifStmt.Else != nil {
   277  					ast.Inspect(ifStmt.Else, func(en ast.Node) bool {
   278  						if _, ok := en.(*ast.FuncLit); ok {
   279  							return false
   280  						}
   281  						if ret, ok := en.(*ast.ReturnStmt); ok {
   282  							for _, expr := range ret.Results {
   283  								if t := pass.TypesInfo.TypeOf(expr); t != nil {
   284  									if fipsType := extractFIPSTypeName(t); fipsType != "" {
   285  										returnsFIPS[info.fn] = fipsType
   286  										return false
   287  									}
   288  								}
   289  							}
   290  						}
   291  						return true
   292  					})
   293  				}
   294  				return false
   295  			}
   296  			ret, ok := n.(*ast.ReturnStmt)
   297  			if !ok {
   298  				return true
   299  			}
   300  			for _, expr := range ret.Results {
   301  				if t := pass.TypesInfo.TypeOf(expr); t != nil {
   302  					if fipsType := extractFIPSTypeName(t); fipsType != "" {
   303  						returnsFIPS[info.fn] = fipsType
   304  						return false
   305  					}
   306  				}
   307  				if call, ok := stripParens(expr).(*ast.CallExpr); ok {
   308  					if callee := calleeFunc(pass.TypesInfo, call); callee != nil {
   309  						if isFIPS140Pkg(callee.Pkg()) {
   310  							if sig, ok := callee.Type().(*types.Signature); ok && sig.Results().Len() > 0 {
   311  								if fipsType := extractFIPSTypeName(sig.Results().At(0).Type()); fipsType != "" {
   312  									returnsFIPS[info.fn] = fipsType
   313  									return false
   314  								}
   315  							}
   316  						} else if callee.Pkg() != pass.Pkg {
   317  							var fact funcFact
   318  							if pass.ImportObjectFact(callee, &fact) && fact.ReturnsFIPSType != "" {
   319  								returnsFIPS[info.fn] = fact.ReturnsFIPSType
   320  								return false
   321  							}
   322  						}
   323  					}
   324  				}
   325  			}
   326  			return true
   327  		})
   328  	}
   329  
   330  	// Propagate returnsFIPS across intra-package wrapper returns.
   331  	for range len(decls) {
   332  		changed := false
   333  		for _, info := range decls {
   334  			if returnsFIPS[info.fn] != "" || info.decl.Body == nil {
   335  				continue
   336  			}
   337  			ast.Inspect(info.decl.Body, func(n ast.Node) bool {
   338  				if _, ok := n.(*ast.FuncLit); ok {
   339  					return false
   340  				}
   341  				ret, ok := n.(*ast.ReturnStmt)
   342  				if !ok {
   343  					return true
   344  				}
   345  				for _, expr := range ret.Results {
   346  					if call, ok := stripParens(expr).(*ast.CallExpr); ok {
   347  						if callee := calleeFunc(pass.TypesInfo, call); callee != nil && callee.Pkg() == pass.Pkg {
   348  							if ft := returnsFIPS[callee]; ft != "" {
   349  								returnsFIPS[info.fn] = ft
   350  								changed = true
   351  								return false
   352  							}
   353  						}
   354  					}
   355  				}
   356  				return true
   357  			})
   358  		}
   359  		if !changed {
   360  			break
   361  		}
   362  	}
   363  
   364  	// Collect concrete FIPS types used to instantiate generic type parameters
   365  	// in this package (e.g. nistCurve[*nistec.P256Point] in crypto/elliptic).
   366  	// Key named-type parameters by (origin TypeName, index) because method
   367  	// declarations create distinct *types.TypeParam objects for receiver type
   368  	// parameters rather than reusing the type declaration's *types.TypeParam.
   369  	type typeParamKey struct {
   370  		owner types.Object
   371  		index int
   372  	}
   373  	typeParamFIPSTypes := make(map[typeParamKey][]string)
   374  	addTypeParamFIPS := func(key typeParamKey, ft string) {
   375  		if !slices.Contains(typeParamFIPSTypes[key], ft) {
   376  			typeParamFIPSTypes[key] = append(typeParamFIPSTypes[key], ft)
   377  		}
   378  	}
   379  	for ident, inst := range pass.TypesInfo.Instances {
   380  		var owner types.Object
   381  		var tparams *types.TypeParamList
   382  		switch obj := pass.TypesInfo.Uses[ident].(type) {
   383  		case *types.TypeName:
   384  			if named, ok := types.Unalias(obj.Type()).(*types.Named); ok {
   385  				owner = named.Origin().Obj()
   386  				tparams = named.TypeParams()
   387  			}
   388  		case *types.Func:
   389  			if sig, ok := obj.Type().(*types.Signature); ok {
   390  				owner = obj.Origin()
   391  				tparams = sig.TypeParams()
   392  			}
   393  		}
   394  		if owner == nil || tparams == nil {
   395  			continue
   396  		}
   397  		for i := range min(tparams.Len(), inst.TypeArgs.Len()) {
   398  			if ft := extractFIPSTypeName(inst.TypeArgs.At(i)); ft != "" {
   399  				addTypeParamFIPS(typeParamKey{owner, i}, ft)
   400  			}
   401  		}
   402  	}
   403  
   404  	// Collect unprotected call edges for each function in the package.
   405  	// First, pre-scan all function bodies to discover local variable FIPS types
   406  	// and concrete FIPS types stored into interface-typed struct fields (e.g.
   407  	// prefixNonceAEAD.aead in crypto/tls).
   408  	fieldFIPSTypes := make(map[*types.Var][]string)
   409  	addFieldFIPS := func(fv *types.Var, ft string) {
   410  		if fv == nil || ft == "" {
   411  			return
   412  		}
   413  		fv = fv.Origin()
   414  		if !slices.Contains(fieldFIPSTypes[fv], ft) {
   415  			fieldFIPSTypes[fv] = append(fieldFIPSTypes[fv], ft)
   416  		}
   417  	}
   418  
   419  	walkers := make([]*unprotectedWalker, len(decls))
   420  	for i, info := range decls {
   421  		fn := info.fn
   422  		if info.decl.Body == nil {
   423  			continue
   424  		}
   425  		if isAllowlisted(formatFuncObj(fn)) || isAllowlisted(fn.FullName()) {
   426  			continue
   427  		}
   428  
   429  		// Map this function's/method's own *types.TypeParam objects to the
   430  		// concrete FIPS types collected for its owner.
   431  		fnTypeParamFIPS := make(map[*types.TypeParam][]string)
   432  		if sig, ok := fn.Type().(*types.Signature); ok {
   433  			if recv := sig.Recv(); recv != nil {
   434  				rt := types.Unalias(recv.Type())
   435  				if ptr, ok := rt.(*types.Pointer); ok {
   436  					rt = types.Unalias(ptr.Elem())
   437  				}
   438  				if named, ok := rt.(*types.Named); ok {
   439  					owner := named.Origin().Obj()
   440  					rtp := sig.RecvTypeParams()
   441  					for j := range rtp.Len() {
   442  						if fts := typeParamFIPSTypes[typeParamKey{owner, j}]; len(fts) > 0 {
   443  							fnTypeParamFIPS[rtp.At(j)] = fts
   444  						}
   445  					}
   446  				}
   447  			}
   448  			ftp := sig.TypeParams()
   449  			for j := range ftp.Len() {
   450  				if fts := typeParamFIPSTypes[typeParamKey{fn.Origin(), j}]; len(fts) > 0 {
   451  					fnTypeParamFIPS[ftp.At(j)] = fts
   452  				}
   453  			}
   454  		}
   455  
   456  		w := &unprotectedWalker{
   457  			pass:               pass,
   458  			fn:                 fn,
   459  			returnsFIPS:        returnsFIPS,
   460  			typeParamFIPSTypes: fnTypeParamFIPS,
   461  			fieldFIPSTypes:     fieldFIPSTypes,
   462  			isAllowlisted:      isAllowlisted,
   463  			varLits:            make(map[*types.Var]*ast.FuncLit),
   464  			varFIPSType:        make(map[*types.Var]string),
   465  			visitedLits:        make(map[*ast.FuncLit]bool),
   466  		}
   467  		w.preScan(info.decl.Body)
   468  		w.scanFieldFIPSTypes(info.decl.Body, addFieldFIPS)
   469  		walkers[i] = w
   470  	}
   471  
   472  	directTarget := make(map[*types.Func]string)
   473  	localCallees := make(map[*types.Func][]*types.Func)
   474  
   475  	for i, info := range decls {
   476  		w := walkers[i]
   477  		if w == nil {
   478  			continue
   479  		}
   480  		ast.Walk(w, info.decl.Body)
   481  
   482  		if w.firstDirect != "" {
   483  			directTarget[info.fn] = w.firstDirect
   484  		}
   485  		localCallees[info.fn] = w.localCalls
   486  	}
   487  
   488  	// Compute shortest unprotected paths to crypto/internal/fips140/...
   489  	dist := make(map[*types.Func]int)
   490  	tailPath := make(map[*types.Func]string)
   491  
   492  	for _, fn := range pkgFuncs {
   493  		if target := directTarget[fn]; target != "" {
   494  			dist[fn] = 1
   495  			tailPath[fn] = target
   496  		}
   497  	}
   498  
   499  	changed := true
   500  	for changed {
   501  		changed = false
   502  		for _, u := range pkgFuncs {
   503  			if isAllowlisted(formatFuncObj(u)) || isAllowlisted(u.FullName()) {
   504  				continue
   505  			}
   506  			for _, v := range localCallees[u] {
   507  				if isAllowlisted(formatFuncObj(v)) || isAllowlisted(v.FullName()) {
   508  					continue
   509  				}
   510  				if d, ok := dist[v]; ok {
   511  					if curD, hasCur := dist[u]; !hasCur || d+1 < curD {
   512  						dist[u] = d + 1
   513  						tailPath[u] = formatFuncObj(v) + " -> " + tailPath[v]
   514  						changed = true
   515  					}
   516  				}
   517  			}
   518  		}
   519  	}
   520  
   521  	// Export facts and report diagnostics on exported functions/methods.
   522  	reportPkg := !isInternalPkg(pass.Pkg.Path())
   523  	for _, info := range decls {
   524  		u := info.fn
   525  		fact := &funcFact{
   526  			ReturnsFIPSType: returnsFIPS[u],
   527  		}
   528  		var unprotectedPath string
   529  		if d, ok := dist[u]; ok && d > 0 && !isAllowlisted(formatFuncObj(u)) && !isAllowlisted(u.FullName()) {
   530  			unprotectedPath = formatFuncObj(u) + " -> " + tailPath[u]
   531  		}
   532  		// Export UnprotectedPath across package boundaries for internal helper packages
   533  		// (or unexported linkname targets). Exported functions in public packages are
   534  		// themselves the DIT boundary and are reported directly in their defining package.
   535  		if isInternalPkg(pass.Pkg.Path()) || !u.Exported() {
   536  			fact.UnprotectedPath = unprotectedPath
   537  		}
   538  		if fact.UnprotectedPath != "" || fact.ReturnsFIPSType != "" {
   539  			pass.ExportObjectFact(u, fact)
   540  		}
   541  
   542  		if reportPkg && unprotectedPath != "" && u.Exported() {
   543  			pass.Reportf(
   544  				info.decl.Name.Pos(),
   545  				"exported function %s calls constant-time/FIPS code without subtle.WithDataIndependentTiming: %s",
   546  				formatFuncObj(u),
   547  				unprotectedPath,
   548  			)
   549  		}
   550  	}
   551  
   552  	// Also check closures inside package-level variable initializers (e.g.
   553  	// crypto/ecdh's p256/p384/p521 nistCurve function fields).
   554  	if reportPkg {
   555  		for _, vl := range pkgVarLits {
   556  			w := &unprotectedWalker{
   557  				pass:           pass,
   558  				returnsFIPS:    returnsFIPS,
   559  				fieldFIPSTypes: fieldFIPSTypes,
   560  				isAllowlisted:  isAllowlisted,
   561  				varLits:        make(map[*types.Var]*ast.FuncLit),
   562  				varFIPSType:    make(map[*types.Var]string),
   563  				visitedLits:    make(map[*ast.FuncLit]bool),
   564  			}
   565  			w.preScan(vl.lit.Body)
   566  			ast.Walk(w, vl.lit.Body)
   567  			path := w.firstDirect
   568  			if path == "" {
   569  				bestD := 0
   570  				for _, v := range w.localCalls {
   571  					if isAllowlisted(formatFuncObj(v)) || isAllowlisted(v.FullName()) {
   572  						continue
   573  					}
   574  					if d, ok := dist[v]; ok && (bestD == 0 || d < bestD) {
   575  						bestD = d
   576  						path = formatFuncObj(v) + " -> " + tailPath[v]
   577  					}
   578  				}
   579  			}
   580  			if path != "" {
   581  				pass.Reportf(
   582  					vl.lit.Pos(),
   583  					"package variable %s initializer calls constant-time/FIPS code without subtle.WithDataIndependentTiming: %s -> %s",
   584  					vl.name,
   585  					vl.name,
   586  					path,
   587  				)
   588  			}
   589  		}
   590  	}
   591  
   592  	return nil, nil
   593  }
   594  
   595  type unprotectedWalker struct {
   596  	pass               *analysis.Pass
   597  	fn                 *types.Func
   598  	returnsFIPS        map[*types.Func]string
   599  	typeParamFIPSTypes map[*types.TypeParam][]string
   600  	fieldFIPSTypes     map[*types.Var][]string
   601  	isAllowlisted      func(string) bool
   602  
   603  	varLits     map[*types.Var]*ast.FuncLit
   604  	varFIPSType map[*types.Var]string
   605  	visitedLits map[*ast.FuncLit]bool
   606  
   607  	firstDirect string
   608  	localCalls  []*types.Func
   609  }
   610  
   611  func (w *unprotectedWalker) recordDirect(targetPath string) {
   612  	if w.firstDirect == "" {
   613  		w.firstDirect = targetPath
   614  	}
   615  }
   616  
   617  func (w *unprotectedWalker) recordLocal(callee *types.Func) {
   618  	if slices.Contains(w.localCalls, callee) {
   619  		return
   620  	}
   621  	w.localCalls = append(w.localCalls, callee)
   622  }
   623  
   624  // preScan finds local variables assigned closures or FIPS-backed values.
   625  func (w *unprotectedWalker) preScan(body *ast.BlockStmt) {
   626  	ast.Inspect(body, func(n ast.Node) bool {
   627  		switch stmt := n.(type) {
   628  		case *ast.AssignStmt:
   629  			for i, rhs := range stmt.Rhs {
   630  				if i >= len(stmt.Lhs) {
   631  					break
   632  				}
   633  				ident, ok := stripParens(stmt.Lhs[i]).(*ast.Ident)
   634  				if !ok {
   635  					continue
   636  				}
   637  				v := lookupVar(w.pass.TypesInfo, ident)
   638  				if v == nil {
   639  					continue
   640  				}
   641  				if lit, ok := stripParens(rhs).(*ast.FuncLit); ok {
   642  					w.varLits[v] = lit
   643  				}
   644  				if ft := w.exprFIPSType(rhs); ft != "" {
   645  					w.varFIPSType[v] = ft
   646  				}
   647  			}
   648  		case *ast.ValueSpec:
   649  			for i, val := range stmt.Values {
   650  				if i >= len(stmt.Names) {
   651  					break
   652  				}
   653  				v := lookupVar(w.pass.TypesInfo, stmt.Names[i])
   654  				if v == nil {
   655  					continue
   656  				}
   657  				if lit, ok := stripParens(val).(*ast.FuncLit); ok {
   658  					w.varLits[v] = lit
   659  				}
   660  				if ft := w.exprFIPSType(val); ft != "" {
   661  					w.varFIPSType[v] = ft
   662  				}
   663  			}
   664  		}
   665  		return true
   666  	})
   667  }
   668  
   669  // scanFieldFIPSTypes records concrete FIPS types stored into struct fields via
   670  // composite literals or field assignments (e.g. &prefixNonceAEAD{aead: aead}).
   671  func (w *unprotectedWalker) scanFieldFIPSTypes(body *ast.BlockStmt, add func(*types.Var, string)) {
   672  	resolve := func(expr ast.Expr) string {
   673  		if ft := w.exprFIPSType(expr); ft != "" {
   674  			return ft
   675  		}
   676  		if ident, ok := stripParens(expr).(*ast.Ident); ok {
   677  			if v := lookupVar(w.pass.TypesInfo, ident); v != nil {
   678  				return w.varFIPSType[v]
   679  			}
   680  		}
   681  		return ""
   682  	}
   683  	ast.Inspect(body, func(n ast.Node) bool {
   684  		switch node := n.(type) {
   685  		case *ast.CompositeLit:
   686  			t := w.pass.TypesInfo.TypeOf(node)
   687  			if t == nil {
   688  				return true
   689  			}
   690  			t = types.Unalias(t)
   691  			if ptr, ok := t.(*types.Pointer); ok {
   692  				t = types.Unalias(ptr.Elem())
   693  			}
   694  			st, ok := t.Underlying().(*types.Struct)
   695  			if !ok {
   696  				return true
   697  			}
   698  			for i, elt := range node.Elts {
   699  				if kv, ok := elt.(*ast.KeyValueExpr); ok {
   700  					if ident, ok := stripParens(kv.Key).(*ast.Ident); ok {
   701  						if fv, ok := w.pass.TypesInfo.Uses[ident].(*types.Var); ok {
   702  							add(fv, resolve(kv.Value))
   703  						}
   704  					}
   705  				} else if i < st.NumFields() {
   706  					add(st.Field(i), resolve(elt))
   707  				}
   708  			}
   709  		case *ast.AssignStmt:
   710  			for i, lhs := range node.Lhs {
   711  				if i >= len(node.Rhs) {
   712  					break
   713  				}
   714  				sel, ok := stripParens(lhs).(*ast.SelectorExpr)
   715  				if !ok {
   716  					continue
   717  				}
   718  				if s, ok := w.pass.TypesInfo.Selections[sel]; ok {
   719  					if fv, ok := s.Obj().(*types.Var); ok {
   720  						add(fv, resolve(node.Rhs[i]))
   721  					}
   722  				}
   723  			}
   724  		}
   725  		return true
   726  	})
   727  }
   728  
   729  func (w *unprotectedWalker) exprFIPSType(expr ast.Expr) string {
   730  	if t := w.pass.TypesInfo.TypeOf(expr); t != nil {
   731  		if ft := extractFIPSTypeName(t); ft != "" {
   732  			return ft
   733  		}
   734  		if tup, ok := t.(*types.Tuple); ok && tup.Len() > 0 {
   735  			if ft := extractFIPSTypeName(tup.At(0).Type()); ft != "" {
   736  				return ft
   737  			}
   738  		}
   739  	}
   740  	if call, ok := stripParens(expr).(*ast.CallExpr); ok {
   741  		if callee := calleeFunc(w.pass.TypesInfo, call); callee != nil {
   742  			if ft := w.returnsFIPS[callee]; ft != "" {
   743  				return ft
   744  			}
   745  			if callee.Pkg() != w.pass.Pkg {
   746  				var fact funcFact
   747  				if w.pass.ImportObjectFact(callee, &fact) && fact.ReturnsFIPSType != "" {
   748  					return fact.ReturnsFIPSType
   749  				}
   750  			}
   751  		}
   752  	}
   753  	return ""
   754  }
   755  
   756  func (w *unprotectedWalker) Visit(node ast.Node) ast.Visitor {
   757  	if node == nil {
   758  		return nil
   759  	}
   760  
   761  	switch n := node.(type) {
   762  	case *ast.AssignStmt:
   763  		for _, lhs := range n.Lhs {
   764  			if ident, ok := stripParens(lhs).(*ast.Ident); ok && w.pass.TypesInfo.Defs[ident] != nil {
   765  				continue
   766  			}
   767  			ast.Walk(w, lhs)
   768  		}
   769  		for i, rhs := range n.Rhs {
   770  			if _, isLit := stripParens(rhs).(*ast.FuncLit); isLit && i < len(n.Lhs) {
   771  				if ident, ok := stripParens(n.Lhs[i]).(*ast.Ident); ok {
   772  					if v := lookupVar(w.pass.TypesInfo, ident); v != nil && w.varLits[v] != nil {
   773  						continue
   774  					}
   775  				}
   776  			}
   777  			ast.Walk(w, rhs)
   778  		}
   779  		return nil
   780  
   781  	case *ast.ValueSpec:
   782  		if n.Type != nil {
   783  			ast.Walk(w, n.Type)
   784  		}
   785  		for i, val := range n.Values {
   786  			if _, isLit := stripParens(val).(*ast.FuncLit); isLit && i < len(n.Names) {
   787  				if v := lookupVar(w.pass.TypesInfo, n.Names[i]); v != nil && w.varLits[v] != nil {
   788  					continue
   789  				}
   790  			}
   791  			ast.Walk(w, val)
   792  		}
   793  		return nil
   794  
   795  	case *ast.CallExpr:
   796  		if isWithDIT(w.pass.TypesInfo, n) {
   797  			if len(n.Args) > 0 {
   798  				arg := stripParens(n.Args[0])
   799  				if !isFuncValueOrLit(arg) {
   800  					ast.Walk(w, arg)
   801  				}
   802  			}
   803  			return nil
   804  		}
   805  
   806  		// Check if calling a method on an interface variable, struct field, or
   807  		// generic type parameter holding a concrete FIPS type.
   808  		if sel, ok := stripParens(n.Fun).(*ast.SelectorExpr); ok {
   809  			if xIdent, ok := stripParens(sel.X).(*ast.Ident); ok {
   810  				if v := lookupVar(w.pass.TypesInfo, xIdent); v != nil {
   811  					if fipsType := w.varFIPSType[v]; fipsType != "" {
   812  						targetName := fipsType + "." + sel.Sel.Name
   813  						if !w.isAllowlisted(targetName) {
   814  							w.recordDirect(targetName)
   815  						}
   816  					}
   817  				}
   818  			}
   819  			if xSel, ok := stripParens(sel.X).(*ast.SelectorExpr); ok {
   820  				if fieldSel, ok := w.pass.TypesInfo.Selections[xSel]; ok {
   821  					if fv, ok := fieldSel.Obj().(*types.Var); ok {
   822  						for _, fipsType := range w.fieldFIPSTypes[fv.Origin()] {
   823  							targetName := fipsType + "." + sel.Sel.Name
   824  							if !w.isAllowlisted(targetName) {
   825  								w.recordDirect(targetName)
   826  							}
   827  						}
   828  					}
   829  				}
   830  			}
   831  			if recvType := w.pass.TypesInfo.TypeOf(sel.X); recvType != nil {
   832  				if tp, ok := types.Unalias(recvType).(*types.TypeParam); ok {
   833  					for _, fipsType := range w.typeParamFIPSTypes[tp] {
   834  						targetName := fipsType + "." + sel.Sel.Name
   835  						if !w.isAllowlisted(targetName) {
   836  							w.recordDirect(targetName)
   837  						}
   838  					}
   839  				}
   840  			}
   841  		}
   842  
   843  		if callee := calleeFunc(w.pass.TypesInfo, n); callee != nil {
   844  			calleeName := formatFuncObj(callee)
   845  			if !w.isAllowlisted(calleeName) && !w.isAllowlisted(callee.FullName()) {
   846  				if isFIPS140Pkg(callee.Pkg()) || isSubtleIntrinsic(w.pass.Pkg, callee) {
   847  					w.recordDirect(calleeName)
   848  				} else if callee.Pkg() == w.pass.Pkg {
   849  					w.recordLocal(callee)
   850  				} else {
   851  					var fact funcFact
   852  					if w.pass.ImportObjectFact(callee, &fact) && fact.UnprotectedPath != "" {
   853  						w.recordDirect(fact.UnprotectedPath)
   854  					}
   855  				}
   856  			}
   857  		}
   858  
   859  		ast.Walk(w, n.Fun)
   860  		for _, arg := range n.Args {
   861  			ast.Walk(w, arg)
   862  		}
   863  		return nil
   864  
   865  	case *ast.Ident:
   866  		if v := lookupVar(w.pass.TypesInfo, n); v != nil {
   867  			if lit, ok := w.varLits[v]; ok && !w.visitedLits[lit] {
   868  				w.visitedLits[lit] = true
   869  				ast.Walk(w, lit.Body)
   870  			}
   871  		}
   872  		return nil
   873  
   874  	case *ast.FuncLit:
   875  		if !w.visitedLits[n] {
   876  			w.visitedLits[n] = true
   877  			ast.Walk(w, n.Body)
   878  		}
   879  		return nil
   880  	}
   881  
   882  	return w
   883  }
   884  
   885  func isWithDIT(info *types.Info, call *ast.CallExpr) bool {
   886  	callee := calleeFunc(info, call)
   887  	if callee == nil || callee.Pkg() == nil {
   888  		return false
   889  	}
   890  	return callee.Pkg().Path() == "crypto/subtle" && callee.Name() == "WithDataIndependentTiming"
   891  }
   892  
   893  func isFuncValueOrLit(expr ast.Expr) bool {
   894  	switch stripParens(expr).(type) {
   895  	case *ast.FuncLit, *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.IndexListExpr:
   896  		return true
   897  	default:
   898  		return false
   899  	}
   900  }
   901  
   902  func calleeFunc(info *types.Info, call *ast.CallExpr) *types.Func {
   903  	if call == nil {
   904  		return nil
   905  	}
   906  	fun := stripParens(call.Fun)
   907  	switch f := fun.(type) {
   908  	case *ast.IndexExpr:
   909  		fun = stripParens(f.X)
   910  	case *ast.IndexListExpr:
   911  		fun = stripParens(f.X)
   912  	}
   913  
   914  	switch f := fun.(type) {
   915  	case *ast.Ident:
   916  		if fn, ok := info.Uses[f].(*types.Func); ok {
   917  			return fn.Origin()
   918  		}
   919  	case *ast.SelectorExpr:
   920  		if sel, ok := info.Selections[f]; ok {
   921  			if fn, ok := sel.Obj().(*types.Func); ok {
   922  				return fn.Origin()
   923  			}
   924  		}
   925  		if fn, ok := info.Uses[f.Sel].(*types.Func); ok {
   926  			return fn.Origin()
   927  		}
   928  	}
   929  	return nil
   930  }
   931  
   932  func lookupVar(info *types.Info, ident *ast.Ident) *types.Var {
   933  	if ident == nil {
   934  		return nil
   935  	}
   936  	if v, ok := info.Defs[ident].(*types.Var); ok {
   937  		return v.Origin()
   938  	}
   939  	if v, ok := info.Uses[ident].(*types.Var); ok {
   940  		return v.Origin()
   941  	}
   942  	return nil
   943  }
   944  
   945  func stripParens(expr ast.Expr) ast.Expr {
   946  	for {
   947  		p, ok := expr.(*ast.ParenExpr)
   948  		if !ok {
   949  			return expr
   950  		}
   951  		expr = p.X
   952  	}
   953  }
   954  
   955  func isNotDITSupported(info *types.Info, cond ast.Expr) bool {
   956  	u, ok := stripParens(cond).(*ast.UnaryExpr)
   957  	if !ok || u.Op.String() != "!" {
   958  		return false
   959  	}
   960  	sel, ok := stripParens(u.X).(*ast.SelectorExpr)
   961  	if !ok || sel.Sel.Name != "DITSupported" {
   962  		return false
   963  	}
   964  	obj := info.Uses[sel.Sel]
   965  	return obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "internal/runtime/sys"
   966  }
   967  
   968  // normalizeFIPSPath strips any versioned FIPS 140-3 snapshot segment (such as
   969  // "v1.26.0" or "v1.0.0-c2097c7c") immediately following "crypto/internal/fips140/".
   970  func normalizeFIPSPath(path string) string {
   971  	const prefix = "crypto/internal/fips140/"
   972  	rest, ok := strings.CutPrefix(path, prefix)
   973  	if !ok {
   974  		return path
   975  	}
   976  	seg, after, hasSlash := strings.Cut(rest, "/")
   977  	if len(seg) >= 2 && seg[0] == 'v' && seg[1] >= '0' && seg[1] <= '9' {
   978  		if hasSlash {
   979  			return prefix + after
   980  		}
   981  		return "crypto/internal/fips140"
   982  	}
   983  	return path
   984  }
   985  
   986  func isFIPS140Pkg(pkg *types.Package) bool {
   987  	if pkg == nil {
   988  		return false
   989  	}
   990  	return strings.HasPrefix(normalizeFIPSPath(pkg.Path()), "crypto/internal/fips140/")
   991  }
   992  
   993  func isSubtleIntrinsic(callerPkg *types.Package, callee *types.Func) bool {
   994  	if callee == nil || callee.Pkg() == nil {
   995  		return false
   996  	}
   997  	switch callee.Pkg().Path() {
   998  	case "crypto/subtle":
   999  		switch callee.Name() {
  1000  		case "ConstantTimeSelect", "ConstantTimeByteEq", "ConstantTimeEq", "ConstantTimeLessOrEq":
  1001  			return true
  1002  		}
  1003  	case "crypto/internal/constanttime":
  1004  		if callerPkg == nil || callerPkg.Path() != "crypto/subtle" {
  1005  			return true
  1006  		}
  1007  	}
  1008  	return false
  1009  }
  1010  
  1011  func isInternalPkg(path string) bool {
  1012  	return path == "internal" || strings.HasPrefix(path, "internal/") || strings.Contains(path, "/internal/")
  1013  }
  1014  
  1015  func extractFIPSTypeName(t types.Type) string {
  1016  	if t == nil {
  1017  		return ""
  1018  	}
  1019  	t = types.Unalias(t)
  1020  	if ptr, ok := t.(*types.Pointer); ok {
  1021  		t = types.Unalias(ptr.Elem())
  1022  	}
  1023  	if named, ok := t.(*types.Named); ok {
  1024  		obj := named.Obj()
  1025  		if obj != nil && isFIPS140Pkg(obj.Pkg()) {
  1026  			return normalizeFIPSPath(obj.Pkg().Path()) + "." + obj.Name()
  1027  		}
  1028  	}
  1029  	return ""
  1030  }
  1031  
  1032  func formatFuncObj(fn *types.Func) string {
  1033  	if fn == nil {
  1034  		return ""
  1035  	}
  1036  	fn = fn.Origin()
  1037  	pkgPath := ""
  1038  	if fn.Pkg() != nil {
  1039  		pkgPath = normalizeFIPSPath(fn.Pkg().Path())
  1040  	}
  1041  	if sig, ok := fn.Type().(*types.Signature); ok && sig.Recv() != nil {
  1042  		recvType := types.Unalias(sig.Recv().Type())
  1043  		if ptr, ok := recvType.(*types.Pointer); ok {
  1044  			recvType = types.Unalias(ptr.Elem())
  1045  		}
  1046  		if named, ok := recvType.(*types.Named); ok && named.Obj() != nil {
  1047  			return fmt.Sprintf("%s.%s.%s", pkgPath, named.Obj().Name(), fn.Name())
  1048  		}
  1049  	}
  1050  	if pkgPath != "" {
  1051  		return fmt.Sprintf("%s.%s", pkgPath, fn.Name())
  1052  	}
  1053  	return fn.Name()
  1054  }
  1055  

View as plain text