Source file src/crypto/internal/upki/check.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 upki
     6  
     7  import (
     8  	"crypto/sha256"
     9  	"crypto/x509"
    10  	"errors"
    11  	"fmt"
    12  	"io/fs"
    13  	"os"
    14  	"path/filepath"
    15  
    16  	"golang.org/x/crypto/cryptobyte"
    17  	"golang.org/x/crypto/cryptobyte/asn1"
    18  )
    19  
    20  // Result is the aggregate result of checking a leaf certificate across all
    21  // of its verified chains.
    22  type Result uint8
    23  
    24  const (
    25  	// NotCovered means the cache could not determine the certificate's status.
    26  	// Reasons include: the leaf has no embedded SCTs, no filter covers any of
    27  	// the SCT (log ID, timestamp) pairs, the covering filters' own coverage
    28  	// disagrees with the index, or covering filters were found but every one
    29  	// reported the issuer as not enrolled.
    30  	NotCovered Result = iota
    31  
    32  	// Revoked means a covering filter listed the certificate as revoked.
    33  	Revoked
    34  
    35  	// NotRevoked means at least one covering filter answered conclusively that
    36  	// the certificate is not in its revoked set, and no covering filter listed
    37  	// it as revoked.
    38  	NotRevoked
    39  )
    40  
    41  var (
    42  	errMalformedSCTExtension   = errors.New("upki: malformed SCT extension")
    43  	errMalformedTBSCertificate = errors.New("upki: malformed TBSCertificate")
    44  )
    45  
    46  // Check checks the end-entity certificate in chains against the C2SP
    47  // revocation cache in dir. The chains must already have been verified. Check
    48  // takes ownership of indexFile and closes it before returning.
    49  func Check(dir string, indexFile *os.File, chains [][]*x509.Certificate) (Result, error) {
    50  	defer func() { _ = indexFile.Close() }()
    51  
    52  	if len(chains) == 0 || len(chains[0]) == 0 {
    53  		return NotCovered, errors.New("upki: no verified certificate chains")
    54  	}
    55  
    56  	leaf := chains[0][0]
    57  	scts, err := ExtractSCTs(leaf)
    58  	if err != nil {
    59  		return NotCovered, fmt.Errorf("upki: extracting SCTs: %w", err)
    60  	}
    61  	if len(scts) == 0 {
    62  		return NotCovered, nil
    63  	}
    64  
    65  	serial, err := rawSerial(leaf)
    66  	if err != nil {
    67  		return NotCovered, fmt.Errorf("upki: extracting serial: %w", err)
    68  	}
    69  
    70  	for attempt := 0; ; attempt++ {
    71  		c := checker{
    72  			dir:     dir,
    73  			chains:  chains,
    74  			serial:  serial,
    75  			scts:    scts,
    76  			filters: make(map[string]*revocationFilter),
    77  		}
    78  		result, err := c.checkIndex(indexFile)
    79  		if err == nil {
    80  			return result, nil
    81  		}
    82  		if !errors.Is(err, fs.ErrNotExist) || attempt == maxIndexReopens {
    83  			return NotCovered, err
    84  		}
    85  
    86  		// A filter named by the open index, or the index itself, disappeared.
    87  		// The cache update contract means the index was superseded, so reopen
    88  		// it and retry.
    89  		_ = indexFile.Close()
    90  		nextIndex, openErr := OpenIndex(filepath.Join(dir, IndexFilename))
    91  		if openErr != nil {
    92  			return NotCovered, fmt.Errorf("upki: reopening superseded index: %w", openErr)
    93  		}
    94  		indexFile = nextIndex
    95  	}
    96  }
    97  
    98  // maxIndexReopens bounds how many times a single [Check] call reopens a
    99  // superseded index before surfacing the missing-filter error, per the spec's
   100  // allowance to bound retries under pathological cache update patterns.
   101  const maxIndexReopens = 2
   102  
   103  // checker holds the state shared by the chain and filter checks in one pass.
   104  type checker struct {
   105  	idx     *index
   106  	dir     string
   107  	chains  [][]*x509.Certificate
   108  	serial  []byte
   109  	scts    []SCT
   110  	filters map[string]*revocationFilter
   111  }
   112  
   113  func (c *checker) checkIndex(f *os.File) (Result, error) {
   114  	idx, err := newIndex(f)
   115  	if err != nil {
   116  		return NotCovered, err
   117  	}
   118  	c.idx = idx
   119  
   120  	return c.checkChains()
   121  }
   122  
   123  func (c *checker) checkChains() (Result, error) {
   124  	// Every verified chain's second certificate verified the leaf's
   125  	// signature, so the chains share one issuer public key and, unless two
   126  	// intermediates encode that key with different SPKI bytes, one lookup
   127  	// key. Query each distinct key once rather than once per chain.
   128  	notRevoked := false
   129  	seen := make(map[issuerSPKIHash]bool, 1)
   130  	for _, chain := range c.chains {
   131  		if len(chain) < 2 {
   132  			continue
   133  		}
   134  
   135  		issuerHash := sha256.Sum256(chain[1].RawSubjectPublicKeyInfo)
   136  		if seen[issuerHash] {
   137  			continue
   138  		}
   139  		seen[issuerHash] = true
   140  
   141  		key := newLookupKey(issuerHash, c.serial)
   142  		result, err := c.checkChain(&key)
   143  		if err != nil {
   144  			return NotCovered, err
   145  		}
   146  		switch result {
   147  		case Revoked:
   148  			// Every verified chain describes the same leaf. Finding its
   149  			// issuer-and-serial pair revoked on any valid path is conclusive.
   150  			// Another path cannot make the same leaf acceptable.
   151  			return Revoked, nil
   152  		case NotRevoked:
   153  			notRevoked = true
   154  		}
   155  	}
   156  	if notRevoked {
   157  		return NotRevoked, nil
   158  	}
   159  
   160  	return NotCovered, nil
   161  }
   162  
   163  func (c *checker) checkChain(key *lookupKey) (Result, error) {
   164  	notRevoked := false
   165  	seen := make(map[string]bool)
   166  	for _, sct := range c.scts {
   167  		filenames, err := c.idx.lookup(sct.logID, sct.timestamp)
   168  		if err != nil {
   169  			return NotCovered, err
   170  		}
   171  		for _, filename := range filenames {
   172  			if seen[filename] {
   173  				continue
   174  			}
   175  			seen[filename] = true
   176  
   177  			status, err := c.queryFilter(filename, key)
   178  			if err != nil {
   179  				return NotCovered, err
   180  			}
   181  
   182  			switch status {
   183  			case statusRevoked:
   184  				return Revoked, nil
   185  			case statusGood:
   186  				// Conclusive, but a later filter may still revoke. Remember
   187  				// the result but keep looking.
   188  				notRevoked = true
   189  			case statusNotCovered, statusNotEnrolled:
   190  				// The filter couldn't answer: either its own coverage
   191  				// disagrees with the index about this SCT, or it has no
   192  				// block for the issuer. Keep looking. The spec says an
   193  				// implementation SHOULD treat the former as an error, but
   194  				// the reference implementation does not, and failing
   195  				// closed on a producer bug that other consumers tolerate
   196  				// would single out Go clients. If no filter answers the
   197  				// result is NotCovered, which the caller's policy decides.
   198  			}
   199  		}
   200  	}
   201  	if notRevoked {
   202  		return NotRevoked, nil
   203  	}
   204  
   205  	return NotCovered, nil
   206  }
   207  
   208  // queryFilter loads, parses, and queries filename, reusing a parsed filter
   209  // when another verified chain selected the same file.
   210  func (c *checker) queryFilter(filename string, key *lookupKey) (filterStatus, error) {
   211  	filter, ok := c.filters[filename]
   212  	if !ok {
   213  		data, err := readFilterFile(filepath.Join(c.dir, filename))
   214  		if err != nil {
   215  			return statusNotCovered, fmt.Errorf("upki: reading filter %s: %w", filename, err)
   216  		}
   217  		filter, err = parseFilter(data)
   218  		if err != nil {
   219  			return statusNotCovered, fmt.Errorf("upki: parsing filter %s: %w", filename, err)
   220  		}
   221  		c.filters[filename] = filter
   222  	}
   223  
   224  	return filter.contains(key, c.scts), nil
   225  }
   226  
   227  // ExtractSCTs decodes the RFC 6962 SignedCertificateTimestampList
   228  // extension from cert and returns one [SCT] per entry.
   229  //
   230  // Returns (nil, nil) when the extension is absent.
   231  //
   232  // Entries using unknown SCT versions are ignored.
   233  //
   234  // It returns errMalformedSCTExtension if the extension is present but malformed.
   235  //
   236  // See RFC 6962 §3.3 for more information.
   237  func ExtractSCTs(cert *x509.Certificate) ([]SCT, error) {
   238  	var raw []byte
   239  	for _, ext := range cert.Extensions {
   240  		if ext.Id.Equal(embeddedSCTOID) {
   241  			raw = ext.Value
   242  			break
   243  		}
   244  	}
   245  	if raw == nil {
   246  		return nil, nil
   247  	}
   248  
   249  	// The contents of the ASN.1 OCTET STRING in an X.509 certificate
   250  	// extension are:
   251  	//
   252  	//	opaque SerializedSCT<1..2^16-1>;
   253  	//	struct {
   254  	//	    SerializedSCT sct_list<1..2^16-1>;
   255  	//	} SignedCertificateTimestampList;
   256  
   257  	outer := cryptobyte.String(raw)
   258  	var inner cryptobyte.String
   259  	if !outer.ReadASN1(&inner, asn1.OCTET_STRING) || !outer.Empty() {
   260  		return nil, fmt.Errorf("%w: outer wrapper", errMalformedSCTExtension)
   261  	}
   262  
   263  	var listBytes cryptobyte.String
   264  	if !inner.ReadUint16LengthPrefixed(&listBytes) || !inner.Empty() {
   265  		return nil, fmt.Errorf("%w: sct list", errMalformedSCTExtension)
   266  	}
   267  
   268  	var out []SCT
   269  	for !listBytes.Empty() {
   270  		var serialized cryptobyte.String
   271  		if !listBytes.ReadUint16LengthPrefixed(&serialized) {
   272  			return nil, fmt.Errorf("%w: serialized sct", errMalformedSCTExtension)
   273  		}
   274  
   275  		//	struct {
   276  		//	    Version sct_version;          // uint8, v1 == 0
   277  		//	    LogID id;                     // 32 bytes
   278  		//	    uint64 timestamp;
   279  		//	    CtExtensions extensions;      // opaque<0..2^16-1>
   280  		//	    DigitallySigned signature;
   281  		//	} SignedCertificateTimestamp;
   282  
   283  		var version uint8
   284  		if !serialized.ReadUint8(&version) {
   285  			return nil, fmt.Errorf("%w: sct version", errMalformedSCTExtension)
   286  		}
   287  		if version != 0 {
   288  			continue
   289  		}
   290  
   291  		var s SCT
   292  		if !serialized.CopyBytes(s.logID[:]) {
   293  			return nil, fmt.Errorf("%w: sct log id", errMalformedSCTExtension)
   294  		}
   295  
   296  		var ts uint64
   297  		if !serialized.ReadUint64(&ts) {
   298  			return nil, fmt.Errorf("%w: sct timestamp", errMalformedSCTExtension)
   299  		}
   300  		s.timestamp = timestamp(ts)
   301  
   302  		// Validate (but discard) the CtExtensions length prefix to
   303  		// catch truncated SCTs. The trailing signature is not parsed:
   304  		// the outer length-prefix already delimits this SerializedSCT.
   305  		var ext cryptobyte.String
   306  		if !serialized.ReadUint16LengthPrefixed(&ext) {
   307  			return nil, fmt.Errorf("%w: sct extensions", errMalformedSCTExtension)
   308  		}
   309  
   310  		out = append(out, s)
   311  	}
   312  
   313  	return out, nil
   314  }
   315  
   316  // SCT is a parsed Signed Certificate Timestamp from a leaf certificate's
   317  // embedded SCT extension.
   318  //
   319  // It carries the two fields CRLite needs to pick covering filters: the
   320  // CT log's identifier and the log's reported issuance timestamp.
   321  //
   322  // Important: The SCT's signature is intentionally not retained.
   323  // In the revocation checking context we assume the CT log inclusion
   324  // proof was already validated.
   325  type SCT struct {
   326  	logID     logID
   327  	timestamp timestamp
   328  }
   329  
   330  // logID is a 32-byte CT log identifier (SHA-256 of the log's public key).
   331  type logID [32]byte
   332  
   333  // timestamp is a millisecond-since-epoch CT timestamp.
   334  type timestamp uint64
   335  
   336  // RFC 6962 §3.3
   337  var embeddedSCTOID = []int{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
   338  
   339  // rawSerial returns the certificate's serial number as the DER-encoded
   340  // contents of the serialNumber INTEGER, preserving any leading sign
   341  // byte.
   342  //
   343  // In contrast, [x509.Certificate.SerialNumber] is a *big.Int which discards
   344  // the leading sign byte. CRLite hashes the original DER bytes as a lookup
   345  // input, so we parse the raw serial DER ourselves here.
   346  func rawSerial(cert *x509.Certificate) ([]byte, error) {
   347  	//	TBSCertificate ::= SEQUENCE {
   348  	//	    version [0] EXPLICIT INTEGER DEFAULT v1,
   349  	//	    serialNumber CertificateSerialNumber,
   350  	//	    ...
   351  	//	}
   352  	tbs := cryptobyte.String(cert.RawTBSCertificate)
   353  	var inner cryptobyte.String
   354  	if !tbs.ReadASN1(&inner, asn1.SEQUENCE) {
   355  		return nil, fmt.Errorf("%w: outer sequence", errMalformedTBSCertificate)
   356  	}
   357  
   358  	// Skip optional [0] EXPLICIT version, if present.
   359  	if inner.PeekASN1Tag(asn1.Tag(0).Constructed().ContextSpecific()) {
   360  		var version cryptobyte.String
   361  		if !inner.ReadASN1(&version, asn1.Tag(0).Constructed().ContextSpecific()) {
   362  			return nil, fmt.Errorf("%w: version", errMalformedTBSCertificate)
   363  		}
   364  	}
   365  
   366  	var serial cryptobyte.String
   367  	if !inner.ReadASN1(&serial, asn1.INTEGER) {
   368  		return nil, fmt.Errorf("%w: serial", errMalformedTBSCertificate)
   369  	}
   370  
   371  	return serial, nil
   372  }
   373  

View as plain text