Source file src/crypto/tls/upki_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 tls
     6  
     7  import (
     8  	"crypto/ecdsa"
     9  	"crypto/elliptic"
    10  	"crypto/internal/upki"
    11  	"crypto/rand"
    12  	"crypto/sha256"
    13  	"crypto/x509"
    14  	"crypto/x509/pkix"
    15  	"errors"
    16  	"fmt"
    17  	"internal/testenv"
    18  	"math/big"
    19  	"os"
    20  	"path/filepath"
    21  	"runtime"
    22  	"slices"
    23  	"testing"
    24  	"time"
    25  
    26  	"golang.org/x/crypto/cryptobyte"
    27  )
    28  
    29  const (
    30  	tlsUPKITestLeafSerial       int64  = 42
    31  	tlsUPKITestNoSCTSerial      int64  = 43
    32  	tlsUPKITestMalformedSerial  int64  = 44
    33  	tlsUPKITestOtherSerial      int64  = 45
    34  	tlsUPKITestRootSerialOffset int64  = 1000
    35  	tlsUPKITestSCTTime          uint64 = 1000
    36  	tlsUPKITestCoverageLow      uint64 = 0
    37  	tlsUPKITestCoverageHigh     uint64 = 2000
    38  	tlsUPKITestServerName              = "test.golang.example"
    39  	tlsUPKITestFilterName              = "test.filter"
    40  )
    41  
    42  var (
    43  	tlsUPKITestLogID = [32]byte{1, 2, 3}
    44  	tlsUPKITestTime  = time.Date(2026, time.November, 14, 12, 0, 0, 0, time.UTC)
    45  )
    46  
    47  // TestCheckUPKIRevocation exercises the default and overridden policy matrix,
    48  // as well as malformed cache and certificate inputs, at the TLS policy boundary.
    49  func TestCheckUPKIRevocation(t *testing.T) {
    50  	t.Parallel()
    51  
    52  	chain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
    53  	noSCTChain := newTLSUPKITestChain(t, tlsUPKITestNoSCTSerial, nil)
    54  	malformedSCTChain := newTLSUPKITestChain(t, tlsUPKITestMalformedSerial, []byte{0x04, 0x05, 0})
    55  	otherChain := newTLSUPKITestChain(t, tlsUPKITestOtherSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
    56  
    57  	goodCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash}})
    58  	revokedCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash, inverted: true}})
    59  	notEnrolledCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: otherChain.issuerHash}})
    60  	notCoveredCache := writeTLSUPKITestCacheFiles(t, tlsUPKIEmptyIndex(), nil)
    61  	malformedIndexCache := writeTLSUPKITestCacheFiles(t, []byte("not an index"), nil)
    62  	malformedFilterCache := writeTLSUPKITestCacheFiles(t, tlsUPKIIndex(tlsUPKITestLogID), map[string][]byte{
    63  		tlsUPKITestFilterName: []byte("not a filter"),
    64  	})
    65  	missingCache := filepath.Join(t.TempDir(), "missing")
    66  
    67  	allowAll := UPKIRevocationConfig{
    68  		Directory:   goodCache,
    69  		MissingData: UPKIRevocationPolicyAllow,
    70  		NotCovered:  UPKIRevocationPolicyAllow,
    71  		MissingSCTs: UPKIRevocationPolicyAllow,
    72  	}
    73  	tests := []struct {
    74  		name   string
    75  		config *Config
    76  		chains [][]*x509.Certificate
    77  		// wantError, when set, must be matched by errors.Is. wantAnyError
    78  		// requires an error without pinning which one, for cases whose error
    79  		// is an unexported sentinel or a plain message.
    80  		wantError    error
    81  		wantAnyError bool
    82  	}{
    83  		{
    84  			name:   "conclusively not revoked",
    85  			config: &Config{UPKIRevocation: UPKIRevocationConfig{Directory: goodCache}},
    86  			chains: chain.verifiedChains(),
    87  		},
    88  		{
    89  			name:      "revoked",
    90  			config:    &Config{UPKIRevocation: UPKIRevocationConfig{Directory: revokedCache, NotCovered: UPKIRevocationPolicyAllow}},
    91  			chains:    chain.verifiedChains(),
    92  			wantError: ErrUPKIRevoked,
    93  		},
    94  		{
    95  			name:   "disabled",
    96  			config: &Config{UPKIRevocation: UPKIRevocationConfig{Disabled: true, Directory: revokedCache}},
    97  			chains: chain.verifiedChains(),
    98  		},
    99  		{
   100  			name:   "no verified chains",
   101  			config: &Config{UPKIRevocation: UPKIRevocationConfig{Directory: revokedCache}},
   102  		},
   103  		{
   104  			name:   "missing SCT default",
   105  			config: &Config{UPKIRevocation: UPKIRevocationConfig{Directory: missingCache}},
   106  			chains: noSCTChain.verifiedChains(),
   107  		},
   108  		{
   109  			name: "missing SCT allow",
   110  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   111  				Directory: missingCache, MissingSCTs: UPKIRevocationPolicyAllow,
   112  			}},
   113  			chains: noSCTChain.verifiedChains(),
   114  		},
   115  		{
   116  			name: "missing SCT reject",
   117  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   118  				Directory: missingCache, MissingSCTs: UPKIRevocationPolicyReject,
   119  			}},
   120  			chains:       noSCTChain.verifiedChains(),
   121  			wantAnyError: true,
   122  		},
   123  		{
   124  			name:      "missing data default",
   125  			config:    &Config{UPKIRevocation: UPKIRevocationConfig{Directory: missingCache}},
   126  			chains:    chain.verifiedChains(),
   127  			wantError: upki.ErrNoData,
   128  		},
   129  		{
   130  			name: "missing data allow",
   131  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   132  				Directory: missingCache, MissingData: UPKIRevocationPolicyAllow,
   133  			}},
   134  			chains: chain.verifiedChains(),
   135  		},
   136  		{
   137  			name:      "cache path is a file",
   138  			config:    &Config{UPKIRevocation: UPKIRevocationConfig{Directory: filepath.Join(goodCache, upki.IndexFilename)}},
   139  			chains:    chain.verifiedChains(),
   140  			wantError: upki.ErrNoData,
   141  		},
   142  		{
   143  			name: "cache path is a file allow",
   144  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   145  				Directory: filepath.Join(goodCache, upki.IndexFilename), MissingData: UPKIRevocationPolicyAllow,
   146  			}},
   147  			chains: chain.verifiedChains(),
   148  		},
   149  		{
   150  			name:   "not covered default",
   151  			config: &Config{UPKIRevocation: UPKIRevocationConfig{Directory: notCoveredCache}},
   152  			chains: chain.verifiedChains(),
   153  		},
   154  		{
   155  			name: "not covered reject",
   156  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   157  				Directory: notCoveredCache, NotCovered: UPKIRevocationPolicyReject,
   158  			}},
   159  			chains:       chain.verifiedChains(),
   160  			wantAnyError: true,
   161  		},
   162  		{
   163  			name: "issuer not enrolled reject",
   164  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   165  				Directory: notEnrolledCache, NotCovered: UPKIRevocationPolicyReject,
   166  			}},
   167  			chains:       chain.verifiedChains(),
   168  			wantAnyError: true,
   169  		},
   170  		{
   171  			name:         "malformed SCT with explicit cache",
   172  			config:       &Config{UPKIRevocation: allowAll},
   173  			chains:       malformedSCTChain.verifiedChains(),
   174  			wantAnyError: true,
   175  		},
   176  		{
   177  			name: "malformed SCT with unavailable explicit cache",
   178  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   179  				Directory: missingCache, MissingData: UPKIRevocationPolicyAllow,
   180  			}},
   181  			chains:       malformedSCTChain.verifiedChains(),
   182  			wantAnyError: true,
   183  		},
   184  		{
   185  			name: "malformed index",
   186  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   187  				Directory:   malformedIndexCache,
   188  				MissingData: UPKIRevocationPolicyAllow, NotCovered: UPKIRevocationPolicyAllow,
   189  			}},
   190  			chains:       chain.verifiedChains(),
   191  			wantAnyError: true,
   192  		},
   193  		{
   194  			name: "malformed filter",
   195  			config: &Config{UPKIRevocation: UPKIRevocationConfig{
   196  				Directory:   malformedFilterCache,
   197  				MissingData: UPKIRevocationPolicyAllow, NotCovered: UPKIRevocationPolicyAllow,
   198  			}},
   199  			chains:       chain.verifiedChains(),
   200  			wantAnyError: true,
   201  		},
   202  	}
   203  	for _, test := range tests {
   204  		t.Run(test.name, func(t *testing.T) {
   205  			t.Parallel()
   206  			err := test.config.checkUPKIRevocation(test.chains)
   207  			switch {
   208  			case test.wantError != nil:
   209  				if !errors.Is(err, test.wantError) {
   210  					t.Fatalf("checkUPKIRevocation error = %v, want %v", err, test.wantError)
   211  				}
   212  			case test.wantAnyError:
   213  				if err == nil {
   214  					t.Fatal("checkUPKIRevocation succeeded, want an error")
   215  				}
   216  			case err != nil:
   217  				t.Fatalf("checkUPKIRevocation: %v", err)
   218  			}
   219  		})
   220  	}
   221  }
   222  
   223  // TestUPKIRevocationInvalidPolicy verifies that every policy field rejects
   224  // values outside the public enumeration.
   225  func TestUPKIRevocationInvalidPolicy(t *testing.T) {
   226  	t.Parallel()
   227  
   228  	chain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, nil)
   229  	for _, field := range []string{"MissingData", "NotCovered", "MissingSCTs"} {
   230  		t.Run(field, func(t *testing.T) {
   231  			t.Parallel()
   232  			config := UPKIRevocationConfig{}
   233  			switch field {
   234  			case "MissingData":
   235  				config.MissingData = 255
   236  			case "NotCovered":
   237  				config.NotCovered = 255
   238  			case "MissingSCTs":
   239  				config.MissingSCTs = 255
   240  			}
   241  			err := (&Config{UPKIRevocation: config}).checkUPKIRevocation(chain.verifiedChains())
   242  			if err == nil {
   243  				t.Fatal("invalid policy was accepted")
   244  			}
   245  		})
   246  	}
   247  }
   248  
   249  // TestUPKIPolicyReject covers the default-policy resolver independently of
   250  // cache lookup, including its rejection of unknown policy values.
   251  func TestUPKIPolicyReject(t *testing.T) {
   252  	t.Parallel()
   253  
   254  	tests := []struct {
   255  		policy        UPKIRevocationPolicy
   256  		defaultReject bool
   257  		want          bool
   258  		wantError     bool
   259  	}{
   260  		{UPKIRevocationPolicyDefault, false, false, false},
   261  		{UPKIRevocationPolicyDefault, true, true, false},
   262  		{UPKIRevocationPolicyAllow, true, false, false},
   263  		{UPKIRevocationPolicyReject, false, true, false},
   264  		{UPKIRevocationPolicy(255), false, false, true},
   265  	}
   266  	for _, test := range tests {
   267  		name := fmt.Sprintf("policy=%d/default=%v", test.policy, test.defaultReject)
   268  		t.Run(name, func(t *testing.T) {
   269  			t.Parallel()
   270  			got, err := upkiPolicyReject(test.policy, test.defaultReject)
   271  			if got != test.want || (err != nil) != test.wantError {
   272  				t.Errorf("upkiPolicyReject = %v, %v; want %v, error=%v", got, err, test.want, test.wantError)
   273  			}
   274  		})
   275  	}
   276  }
   277  
   278  // TestOpenUPKICacheIndex verifies ordered cache discovery and the no-cache
   279  // result used by the missing-data policy.
   280  func TestOpenUPKICacheIndex(t *testing.T) {
   281  	t.Parallel()
   282  
   283  	missing := filepath.Join(t.TempDir(), "missing")
   284  	present := t.TempDir()
   285  	if err := os.WriteFile(filepath.Join(present, upki.IndexFilename), []byte("index"), 0o644); err != nil {
   286  		t.Fatal(err)
   287  	}
   288  
   289  	notDir := filepath.Join(present, upki.IndexFilename)
   290  	dir, index, err := openUPKICacheIndex([]string{missing, notDir, present})
   291  	if err != nil {
   292  		t.Fatal(err)
   293  	}
   294  	if index == nil || dir != present {
   295  		t.Fatalf("openUPKICacheIndex = %q, %v, want %q and a file", dir, index, present)
   296  	}
   297  	index.Close()
   298  
   299  	dir, index, err = openUPKICacheIndex([]string{missing})
   300  	if !errors.Is(err, upki.ErrNoData) || !errors.Is(err, os.ErrNotExist) || index != nil || dir != "" {
   301  		t.Fatalf("openUPKICacheIndex(missing) = %q, %v, %v", dir, index, err)
   302  	}
   303  
   304  	t.Run("permission denied", func(t *testing.T) {
   305  		blocked := t.TempDir()
   306  		path := filepath.Join(blocked, upki.IndexFilename)
   307  		if err := os.WriteFile(path, nil, 0); err != nil {
   308  			t.Fatal(err)
   309  		}
   310  		if _, err := os.ReadFile(path); err == nil {
   311  			t.Skip("process can read a mode-000 file")
   312  		}
   313  		_, _, err := openUPKICacheIndex([]string{blocked, missing})
   314  		if !errors.Is(err, upki.ErrNoData) || !errors.Is(err, os.ErrPermission) {
   315  			t.Fatalf("openUPKICacheIndex(blocked) = %v, want ErrNoData wrapping permission error", err)
   316  		}
   317  		dir, index, err := openUPKICacheIndex([]string{blocked, present})
   318  		if err != nil {
   319  			t.Fatal(err)
   320  		}
   321  		defer index.Close()
   322  		if dir != present {
   323  			t.Fatalf("selected %q, want %q", dir, present)
   324  		}
   325  	})
   326  }
   327  
   328  // TestUPKIRevocationDirectories records the platform-specific cache search
   329  // order, including systems without a per-user cache directory.
   330  func TestUPKIRevocationDirectories(t *testing.T) {
   331  	t.Parallel()
   332  
   333  	tests := []struct {
   334  		name        string
   335  		goos        string
   336  		userCache   string
   337  		programData string
   338  		want        []string
   339  	}{
   340  		{
   341  			name:      "unix",
   342  			goos:      "linux",
   343  			userCache: filepath.Join("", "user-cache"),
   344  			want: []string{
   345  				filepath.Join("user-cache", "upki", "revocation"),
   346  				"/var/cache/upki/revocation",
   347  			},
   348  		},
   349  		{
   350  			name:      "darwin",
   351  			goos:      "darwin",
   352  			userCache: filepath.Join("", "user-cache"),
   353  			want: []string{
   354  				filepath.Join("user-cache", "dev.rustls.upki", "revocation"),
   355  				"/Library/Caches/dev.rustls.upki/revocation",
   356  			},
   357  		},
   358  		{
   359  			name:        "windows",
   360  			goos:        "windows",
   361  			userCache:   filepath.Join("", "user-cache"),
   362  			programData: filepath.Join("", "program-data"),
   363  			want: []string{
   364  				filepath.Join("user-cache", "rustls", "upki", "cache", "revocation"),
   365  				filepath.Join("program-data", "rustls", "upki", "cache", "revocation"),
   366  			},
   367  		},
   368  		{
   369  			name: "no user cache",
   370  			goos: "linux",
   371  			want: []string{"/var/cache/upki/revocation"},
   372  		},
   373  	}
   374  	for _, test := range tests {
   375  		t.Run(test.name, func(t *testing.T) {
   376  			t.Parallel()
   377  			got := upkiRevocationDirectories(test.goos, test.userCache, test.programData)
   378  			if !slices.Equal(got, test.want) {
   379  				t.Errorf("upkiRevocationDirectories = %q, want %q", got, test.want)
   380  			}
   381  		})
   382  	}
   383  }
   384  
   385  // TestUPKIRevocationDefaultDiscovery exercises platform cache discovery with
   386  // a zero-valued UPKIRevocationConfig by pointing the user cache directory at
   387  // a temporary cache. It is not parallel because it sets the environment.
   388  func TestUPKIRevocationDefaultDiscovery(t *testing.T) {
   389  	switch runtime.GOOS {
   390  	case "windows", "darwin", "ios", "plan9":
   391  		t.Skipf("os.UserCacheDir does not honor XDG_CACHE_HOME on %s", runtime.GOOS)
   392  	}
   393  
   394  	chain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
   395  	setTLSUPKIUserCache(t, chain)
   396  
   397  	clientConfig := chain.clientConfig("")
   398  	if err := clientConfig.checkUPKIRevocation(chain.verifiedChains()); !errors.Is(err, ErrUPKIRevoked) {
   399  		t.Fatalf("checkUPKIRevocation = %v, want ErrUPKIRevoked", err)
   400  	}
   401  	clientErr, _ := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   402  	if !errors.Is(clientErr, ErrUPKIRevoked) {
   403  		t.Fatalf("handshake error = %v, want ErrUPKIRevoked", clientErr)
   404  	}
   405  
   406  	malformed := newTLSUPKITestChain(t, tlsUPKITestMalformedSerial, []byte{0x04, 0x05, 0})
   407  	clientConfig = malformed.clientConfig("")
   408  	clientErr, _ = runTLSUPKIHandshake(t, clientConfig, malformed.serverConfig())
   409  	var verificationErr *CertificateVerificationError
   410  	if !errors.As(clientErr, &verificationErr) {
   411  		t.Fatalf("malformed SCT with a discovered cache: got %v, want certificate verification error", clientErr)
   412  	}
   413  
   414  	// Without a user cache, discovery falls through to the system cache,
   415  	// which may exist on the machine running the tests.
   416  	t.Setenv("XDG_CACHE_HOME", t.TempDir())
   417  	if _, err := os.Stat("/var/cache/upki/revocation/index.bin"); err == nil {
   418  		t.Log("system cache present; skipping the no-cache assertion")
   419  		return
   420  	}
   421  	clientConfig = chain.clientConfig("")
   422  	if err := clientConfig.checkUPKIRevocation(chain.verifiedChains()); err != nil {
   423  		t.Fatalf("checkUPKIRevocation with no cache = %v, want nil", err)
   424  	}
   425  	if clientErr, serverErr := runTLSUPKIHandshake(t, malformed.clientConfig(""), malformed.serverConfig()); clientErr != nil || serverErr != nil {
   426  		t.Fatalf("malformed SCT without a cache: client=%v, server=%v", clientErr, serverErr)
   427  	}
   428  	clientConfig.UPKIRevocation = UPKIRevocationConfig{MissingData: UPKIRevocationPolicyReject}
   429  	if err := clientConfig.checkUPKIRevocation(chain.verifiedChains()); !errors.Is(err, upki.ErrNoData) {
   430  		t.Fatalf("required cache = %v, want ErrNoData", err)
   431  	}
   432  }
   433  
   434  // setTLSUPKIUserCache points the user cache directory at a temporary cache
   435  // in which chain's certificate is revoked. It sets the environment, so the
   436  // calling test must not be parallel.
   437  func setTLSUPKIUserCache(t *testing.T, chain tlsUPKITestChain) {
   438  	t.Helper()
   439  
   440  	userCache := t.TempDir()
   441  	t.Setenv("XDG_CACHE_HOME", userCache)
   442  	cacheDir := filepath.Join(userCache, "upki", "revocation")
   443  	if err := os.MkdirAll(cacheDir, 0o755); err != nil {
   444  		t.Fatal(err)
   445  	}
   446  	writeTLSUPKITestCacheFilesIn(t, cacheDir, tlsUPKIIndex(tlsUPKITestLogID), map[string][]byte{
   447  		tlsUPKITestFilterName: tlsUPKIFilter(tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash, inverted: true}}),
   448  	})
   449  }
   450  
   451  // TestUPKIRevocationGODEBUG verifies that tlsupki=0 disables checking for
   452  // configurations that rely on platform-default discovery and leaves an
   453  // explicitly configured directory alone. It is not parallel because it sets
   454  // the environment.
   455  func TestUPKIRevocationGODEBUG(t *testing.T) {
   456  	switch runtime.GOOS {
   457  	case "windows", "darwin", "ios", "plan9":
   458  		t.Skipf("os.UserCacheDir does not honor XDG_CACHE_HOME on %s", runtime.GOOS)
   459  	}
   460  
   461  	chain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
   462  	setTLSUPKIUserCache(t, chain)
   463  	explicitCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash, inverted: true}})
   464  
   465  	tests := []struct {
   466  		name      string
   467  		godebug   string
   468  		config    UPKIRevocationConfig
   469  		wantError error
   470  	}{
   471  		{name: "default discovery", godebug: "tlsupki=1", wantError: ErrUPKIRevoked},
   472  		{name: "default discovery disabled", godebug: "tlsupki=0"},
   473  		{name: "explicit directory", godebug: "tlsupki=1", config: UPKIRevocationConfig{Directory: explicitCache}, wantError: ErrUPKIRevoked},
   474  		{name: "explicit directory not disabled", godebug: "tlsupki=0", config: UPKIRevocationConfig{Directory: explicitCache}, wantError: ErrUPKIRevoked},
   475  	}
   476  	for _, test := range tests {
   477  		t.Run(test.name, func(t *testing.T) {
   478  			testenv.SetGODEBUG(t, test.godebug)
   479  			clientConfig := chain.clientConfig("")
   480  			clientConfig.UPKIRevocation = test.config
   481  			err := clientConfig.checkUPKIRevocation(chain.verifiedChains())
   482  			if test.wantError != nil && !errors.Is(err, test.wantError) {
   483  				t.Fatalf("checkUPKIRevocation = %v, want %v", err, test.wantError)
   484  			}
   485  			if test.wantError == nil && err != nil {
   486  				t.Fatalf("checkUPKIRevocation = %v, want nil", err)
   487  			}
   488  			clientErr, _ := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   489  			if test.wantError != nil && !errors.Is(clientErr, test.wantError) {
   490  				t.Fatalf("handshake error = %v, want %v", clientErr, test.wantError)
   491  			}
   492  			if test.wantError == nil && clientErr != nil {
   493  				t.Fatalf("handshake error = %v, want nil", clientErr)
   494  			}
   495  		})
   496  	}
   497  }
   498  
   499  // TestUPKIRevocationHandshake verifies the ordering and error wrapping of
   500  // revocation checks in the client handshake.
   501  func TestUPKIRevocationHandshake(t *testing.T) {
   502  	t.Parallel()
   503  
   504  	chain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
   505  	revokedCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash, inverted: true}})
   506  	goodCache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{{issuer: chain.issuerHash}})
   507  	malformedCache := writeTLSUPKITestCacheFiles(t, []byte("not an index"), nil)
   508  
   509  	t.Run("revoked before callbacks", func(t *testing.T) {
   510  		t.Parallel()
   511  		var callbacks []string
   512  		clientConfig := chain.clientConfig(revokedCache)
   513  		clientConfig.VerifyPeerCertificate = func([][]byte, [][]*x509.Certificate) error {
   514  			callbacks = append(callbacks, "VerifyPeerCertificate")
   515  
   516  			return nil
   517  		}
   518  		clientConfig.VerifyConnection = func(ConnectionState) error {
   519  			callbacks = append(callbacks, "VerifyConnection")
   520  
   521  			return nil
   522  		}
   523  		clientErr, _ := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   524  		if !errors.Is(clientErr, ErrUPKIRevoked) {
   525  			t.Fatalf("client error = %v, want ErrUPKIRevoked", clientErr)
   526  		}
   527  		var verificationError *CertificateVerificationError
   528  		if !errors.As(clientErr, &verificationError) {
   529  			t.Fatalf("client error %T, want *CertificateVerificationError", clientErr)
   530  		}
   531  		if len(callbacks) != 0 {
   532  			t.Errorf("callbacks ran before revocation rejection: %v", callbacks)
   533  		}
   534  	})
   535  
   536  	t.Run("accepted before callbacks", func(t *testing.T) {
   537  		t.Parallel()
   538  		var callbacks []string
   539  		clientConfig := chain.clientConfig(goodCache)
   540  		clientConfig.VerifyPeerCertificate = func([][]byte, [][]*x509.Certificate) error {
   541  			callbacks = append(callbacks, "VerifyPeerCertificate")
   542  
   543  			return nil
   544  		}
   545  		clientConfig.VerifyConnection = func(ConnectionState) error {
   546  			callbacks = append(callbacks, "VerifyConnection")
   547  
   548  			return nil
   549  		}
   550  		clientErr, serverErr := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   551  		if clientErr != nil || serverErr != nil {
   552  			t.Fatalf("handshake errors: client=%v server=%v", clientErr, serverErr)
   553  		}
   554  		if want := []string{"VerifyPeerCertificate", "VerifyConnection"}; !slices.Equal(callbacks, want) {
   555  			t.Errorf("callbacks = %v, want %v", callbacks, want)
   556  		}
   557  	})
   558  
   559  	t.Run("normal verification happens first", func(t *testing.T) {
   560  		t.Parallel()
   561  		clientConfig := chain.clientConfig(malformedCache)
   562  		clientConfig.ServerName = "wrong.golang.example"
   563  		clientErr, _ := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   564  		var verificationError *CertificateVerificationError
   565  		if !errors.As(clientErr, &verificationError) {
   566  			t.Fatalf("client error %v, want *CertificateVerificationError", clientErr)
   567  		}
   568  		var hostnameError x509.HostnameError
   569  		if !errors.As(verificationError.Err, &hostnameError) {
   570  			t.Fatalf("verification error = %v, want x509.HostnameError", verificationError.Err)
   571  		}
   572  	})
   573  
   574  	t.Run("InsecureSkipVerify bypasses revocation", func(t *testing.T) {
   575  		t.Parallel()
   576  		clientConfig := chain.clientConfig(revokedCache)
   577  		clientConfig.InsecureSkipVerify = true
   578  		clientErr, serverErr := runTLSUPKIHandshake(t, clientConfig, chain.serverConfig())
   579  		if clientErr != nil || serverErr != nil {
   580  			t.Fatalf("handshake errors: client=%v server=%v", clientErr, serverErr)
   581  		}
   582  	})
   583  }
   584  
   585  // TestUPKIRevocationDoesNotCheckClientCertificates ensures that the client-only
   586  // feature does not accidentally apply server-side policy to client certificates.
   587  func TestUPKIRevocationDoesNotCheckClientCertificates(t *testing.T) {
   588  	t.Parallel()
   589  
   590  	clientConfig := testConfigClient()
   591  	serverConfig := testConfigServer()
   592  	serverConfig.ClientAuth = RequireAndVerifyClientCert
   593  	serverConfig.ClientCAs = testClientRootCertPool
   594  	serverConfig.UPKIRevocation = UPKIRevocationConfig{MissingSCTs: UPKIRevocationPolicyReject}
   595  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
   596  		t.Fatalf("handshake: %v", err)
   597  	}
   598  }
   599  
   600  // TestUPKIRevocationResumption verifies that a newly revoked cached certificate
   601  // prevents resumption and causes a full handshake with the replacement chain.
   602  func TestUPKIRevocationResumption(t *testing.T) {
   603  	for _, version := range []uint16{VersionTLS12, VersionTLS13} {
   604  		t.Run(VersionName(version), func(t *testing.T) {
   605  			t.Parallel()
   606  
   607  			oldChain := newTLSUPKITestChain(t, tlsUPKITestLeafSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
   608  			newChain := newTLSUPKITestChain(t, tlsUPKITestNoSCTSerial, tlsUPKISCTExtensionValue(t, tlsUPKITestLogID, tlsUPKITestSCTTime))
   609  			cache := writeTLSUPKITestCache(t, tlsUPKITestLogID, []tlsUPKITestBlock{
   610  				{issuer: oldChain.issuerHash},
   611  				{issuer: newChain.issuerHash},
   612  			})
   613  
   614  			roots := x509.NewCertPool()
   615  			roots.AddCert(oldChain.root)
   616  			roots.AddCert(newChain.root)
   617  			clientConfig := oldChain.clientConfig(cache)
   618  			clientConfig.RootCAs = roots
   619  			sessionCache := &countingSessionCache{ClientSessionCache: NewLRUClientSessionCache(1)}
   620  			clientConfig.ClientSessionCache = sessionCache
   621  			clientConfig.MinVersion, clientConfig.MaxVersion = version, version
   622  			serverConfig := oldChain.serverConfig()
   623  			serverConfig.MinVersion, serverConfig.MaxVersion = version, version
   624  
   625  			_, state, err := testHandshake(t, clientConfig, serverConfig)
   626  			if err != nil || state.DidResume {
   627  				t.Fatalf("initial handshake = resume %v, error %v", state.DidResume, err)
   628  			}
   629  			_, state, err = testHandshake(t, clientConfig, serverConfig)
   630  			if err != nil || !state.DidResume {
   631  				t.Fatalf("control resumption = resume %v, error %v", state.DidResume, err)
   632  			}
   633  
   634  			filter := tlsUPKIFilter(tlsUPKITestLogID, []tlsUPKITestBlock{
   635  				{issuer: oldChain.issuerHash, inverted: true},
   636  				{issuer: newChain.issuerHash},
   637  			})
   638  			if err := os.WriteFile(filepath.Join(cache, tlsUPKITestFilterName), filter, 0o644); err != nil {
   639  				t.Fatal(err)
   640  			}
   641  			serverConfig.Certificates = []Certificate{newChain.certificate}
   642  
   643  			_, state, err = testHandshake(t, clientConfig, serverConfig)
   644  			if err != nil {
   645  				t.Fatalf("replacement handshake: %v", err)
   646  			}
   647  			if state.DidResume {
   648  				t.Error("resumed a session whose cached certificate is now revoked")
   649  			}
   650  			if got := state.PeerCertificates[0].SerialNumber.Int64(); got != tlsUPKITestNoSCTSerial {
   651  				t.Errorf("replacement serial = %d, want %d", got, tlsUPKITestNoSCTSerial)
   652  			}
   653  			if sessionCache.deletions != 1 {
   654  				t.Errorf("session cache deletions = %d, want 1 for the revoked session", sessionCache.deletions)
   655  			}
   656  		})
   657  	}
   658  }
   659  
   660  // countingSessionCache counts the deletions (a Put with a nil session) the
   661  // client performs on the wrapped cache.
   662  type countingSessionCache struct {
   663  	ClientSessionCache
   664  	deletions int
   665  }
   666  
   667  func (c *countingSessionCache) Put(key string, session *ClientSessionState) {
   668  	if session == nil {
   669  		c.deletions++
   670  	}
   671  	c.ClientSessionCache.Put(key, session)
   672  }
   673  
   674  // runTLSUPKIHandshake performs both halves of an in-memory handshake and
   675  // returns each peer's error so tests can inspect the client failure precisely.
   676  func runTLSUPKIHandshake(t *testing.T, clientConfig, serverConfig *Config) (clientErr, serverErr error) {
   677  	t.Helper()
   678  
   679  	clientConn, serverConn := localPipe(t)
   680  	clientDone := make(chan error, 1)
   681  	go func() {
   682  		clientDone <- Client(clientConn, clientConfig).Handshake()
   683  		clientConn.Close()
   684  	}()
   685  	serverErr = Server(serverConn, serverConfig).Handshake()
   686  	serverConn.Close()
   687  	clientErr = <-clientDone
   688  
   689  	return clientErr, serverErr
   690  }
   691  
   692  type tlsUPKITestChain struct {
   693  	certificate Certificate
   694  	leaf        *x509.Certificate
   695  	root        *x509.Certificate
   696  	issuerHash  [32]byte
   697  }
   698  
   699  // newTLSUPKITestChain creates a root and server certificate whose verified
   700  // chain, TLS configurations, and issuer hash are all available to a test.
   701  func newTLSUPKITestChain(t *testing.T, serial int64, sctExtension []byte) tlsUPKITestChain {
   702  	t.Helper()
   703  
   704  	rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   705  	if err != nil {
   706  		t.Fatal(err)
   707  	}
   708  	rootTemplate := &x509.Certificate{
   709  		SerialNumber:          big.NewInt(serial + tlsUPKITestRootSerialOffset),
   710  		Subject:               pkix.Name{CommonName: "UPKI test root"},
   711  		NotBefore:             tlsUPKITestTime.Add(-time.Hour),
   712  		NotAfter:              tlsUPKITestTime.Add(time.Hour),
   713  		IsCA:                  true,
   714  		BasicConstraintsValid: true,
   715  		KeyUsage:              x509.KeyUsageCertSign,
   716  	}
   717  	rootDER, err := x509.CreateCertificate(rand.Reader, rootTemplate, rootTemplate, &rootKey.PublicKey, rootKey)
   718  	if err != nil {
   719  		t.Fatal(err)
   720  	}
   721  	root, err := x509.ParseCertificate(rootDER)
   722  	if err != nil {
   723  		t.Fatal(err)
   724  	}
   725  
   726  	leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   727  	if err != nil {
   728  		t.Fatal(err)
   729  	}
   730  	leafTemplate := &x509.Certificate{
   731  		SerialNumber: big.NewInt(serial),
   732  		Subject:      pkix.Name{CommonName: tlsUPKITestServerName},
   733  		DNSNames:     []string{tlsUPKITestServerName},
   734  		NotBefore:    tlsUPKITestTime.Add(-time.Hour),
   735  		NotAfter:     tlsUPKITestTime.Add(time.Hour),
   736  		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
   737  	}
   738  	if sctExtension != nil {
   739  		leafTemplate.ExtraExtensions = []pkix.Extension{{
   740  			Id:    []int{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2},
   741  			Value: sctExtension,
   742  		}}
   743  	}
   744  	leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, root, &leafKey.PublicKey, rootKey)
   745  	if err != nil {
   746  		t.Fatal(err)
   747  	}
   748  	leaf, err := x509.ParseCertificate(leafDER)
   749  	if err != nil {
   750  		t.Fatal(err)
   751  	}
   752  
   753  	return tlsUPKITestChain{
   754  		certificate: Certificate{Certificate: [][]byte{leafDER}, PrivateKey: leafKey, Leaf: leaf},
   755  		leaf:        leaf,
   756  		root:        root,
   757  		issuerHash:  sha256.Sum256(root.RawSubjectPublicKeyInfo),
   758  	}
   759  }
   760  
   761  func (chain tlsUPKITestChain) verifiedChains() [][]*x509.Certificate {
   762  	return [][]*x509.Certificate{{chain.leaf, chain.root}}
   763  }
   764  
   765  func (chain tlsUPKITestChain) clientConfig(cache string) *Config {
   766  	roots := x509.NewCertPool()
   767  	roots.AddCert(chain.root)
   768  
   769  	return &Config{
   770  		RootCAs:    roots,
   771  		ServerName: tlsUPKITestServerName,
   772  		Time:       func() time.Time { return tlsUPKITestTime },
   773  		UPKIRevocation: UPKIRevocationConfig{
   774  			Directory: cache,
   775  		},
   776  	}
   777  }
   778  
   779  func (chain tlsUPKITestChain) serverConfig() *Config {
   780  	return &Config{
   781  		Certificates: []Certificate{chain.certificate},
   782  		Time:         func() time.Time { return tlsUPKITestTime },
   783  	}
   784  }
   785  
   786  // writeTLSUPKITestCache writes the minimal matching index and filter pair used
   787  // by most TLS tests.
   788  func writeTLSUPKITestCache(t *testing.T, logID [32]byte, blocks []tlsUPKITestBlock) string {
   789  	t.Helper()
   790  
   791  	return writeTLSUPKITestCacheFiles(t, tlsUPKIIndex(logID), map[string][]byte{
   792  		tlsUPKITestFilterName: tlsUPKIFilter(logID, blocks),
   793  	})
   794  }
   795  
   796  // writeTLSUPKITestCacheFiles materializes an arbitrary cache layout so tests
   797  // can also exercise malformed and missing files.
   798  func writeTLSUPKITestCacheFiles(t *testing.T, index []byte, filters map[string][]byte) string {
   799  	t.Helper()
   800  	dir := t.TempDir()
   801  	writeTLSUPKITestCacheFilesIn(t, dir, index, filters)
   802  
   803  	return dir
   804  }
   805  
   806  // writeTLSUPKITestCacheFilesIn writes a cache layout into an existing dir.
   807  func writeTLSUPKITestCacheFilesIn(t *testing.T, dir string, index []byte, filters map[string][]byte) {
   808  	t.Helper()
   809  	if err := os.WriteFile(filepath.Join(dir, upki.IndexFilename), index, 0o644); err != nil {
   810  		t.Fatal(err)
   811  	}
   812  	for name, data := range filters {
   813  		if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
   814  			t.Fatal(err)
   815  		}
   816  	}
   817  }
   818  
   819  type tlsUPKITestBlock struct {
   820  	issuer   [32]byte
   821  	inverted bool
   822  }
   823  
   824  // tlsUPKIFilter encodes the narrow rank-zero Clubcard form needed by these
   825  // tests. It follows C2SP upki-revocation v1.0.0:
   826  // https://c2sp.org/upki-revocation@v1.0.0#revocation-filter-files.
   827  //
   828  // The TLS tests cannot reuse crypto/internal/upki's _test.go encoder without
   829  // turning test-only code into a shipped package, so this copy intentionally
   830  // supports only one coverage interval and rank-zero blocks.
   831  func tlsUPKIFilter(logID [32]byte, blocks []tlsUPKITestBlock) []byte {
   832  	var builder cryptobyte.Builder
   833  	builder.AddUint8(4)
   834  	builder.AddUint8(0)
   835  	builder.AddUint16(1)
   836  	builder.AddBytes(logID[:])
   837  	builder.AddUint64(tlsUPKITestCoverageLow)
   838  	builder.AddUint64(tlsUPKITestCoverageHigh)
   839  	builder.AddUint32(uint32(len(blocks)))
   840  	for _, block := range blocks {
   841  		builder.AddBytes(block.issuer[:])
   842  		builder.AddUint32(0)
   843  		builder.AddUint8(0)
   844  		builder.AddUint32(0)
   845  		builder.AddUint32(0)
   846  		builder.AddUint32(0)
   847  		if block.inverted {
   848  			builder.AddUint8(1)
   849  		} else {
   850  			builder.AddUint8(0)
   851  		}
   852  		builder.AddUint16(0)
   853  	}
   854  	builder.AddUint8(0)
   855  	builder.AddUint32(0)
   856  
   857  	return builder.BytesOrPanic()
   858  }
   859  
   860  // tlsUPKIIndex encodes a one-filter index as specified by C2SP
   861  // upki-revocation v1.0.0:
   862  // https://c2sp.org/upki-revocation@v1.0.0#the-index.
   863  func tlsUPKIIndex(logID [32]byte) []byte {
   864  	var builder cryptobyte.Builder
   865  	builder.AddBytes([]byte("upkiidx1"))
   866  	builder.AddUint16(1)
   867  	builder.AddUint32(1)
   868  	filename := make([]byte, 32)
   869  	copy(filename, tlsUPKITestFilterName)
   870  	builder.AddBytes(filename)
   871  	builder.AddBytes(logID[:])
   872  	builder.AddUint64(14 + 32 + 42)
   873  	builder.AddUint16(1)
   874  	builder.AddUint16(0)
   875  	builder.AddUint64(tlsUPKITestCoverageLow)
   876  	builder.AddUint64(tlsUPKITestCoverageHigh)
   877  
   878  	return builder.BytesOrPanic()
   879  }
   880  
   881  // tlsUPKIEmptyIndex encodes a valid index with no filter files.
   882  func tlsUPKIEmptyIndex() []byte {
   883  	var builder cryptobyte.Builder
   884  	builder.AddBytes([]byte("upkiidx1"))
   885  	builder.AddUint16(0)
   886  	builder.AddUint32(0)
   887  
   888  	return builder.BytesOrPanic()
   889  }
   890  
   891  // tlsUPKISCTExtensionValue encodes an RFC 6962 ยง3.3
   892  // SignedCertificateTimestampList containing one v1 SCT. The signature is
   893  // omitted because revocation lookup uses only the log ID and timestamp.
   894  func tlsUPKISCTExtensionValue(t *testing.T, logID [32]byte, timestamp uint64) []byte {
   895  	t.Helper()
   896  
   897  	var serialized cryptobyte.Builder
   898  	serialized.AddUint8(0)
   899  	serialized.AddBytes(logID[:])
   900  	serialized.AddUint64(timestamp)
   901  	serialized.AddUint16(0)
   902  	serializedBytes := serialized.BytesOrPanic()
   903  
   904  	var contents cryptobyte.Builder
   905  	contents.AddUint16(uint16(2 + len(serializedBytes)))
   906  	contents.AddUint16(uint16(len(serializedBytes)))
   907  	contents.AddBytes(serializedBytes)
   908  
   909  	var extension cryptobyte.Builder
   910  	extension.AddASN1OctetString(contents.BytesOrPanic())
   911  	encoded, err := extension.Bytes()
   912  	if err != nil {
   913  		t.Fatal(err)
   914  	}
   915  
   916  	return encoded
   917  }
   918  

View as plain text