Source file src/crypto/internal/upki/index.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  	"bytes"
     9  	"cmp"
    10  	"encoding/binary"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"os"
    15  	"slices"
    16  	"syscall"
    17  )
    18  
    19  // On-disk layout of index.bin from
    20  // https://c2sp.org/upki-revocation@v1.0.0.
    21  //
    22  //	HEADER (14 bytes):
    23  //	  magic:         [8]byte    "upkiidx1"
    24  //	  num_filenames: u16 BE
    25  //	  num_log_ids:   u32 BE
    26  //
    27  //	TABLES (read eagerly):
    28  //	  filename[num_filenames]:   [32]byte  restricted ASCII, NULL-padded
    29  //	  log_dir[num_log_ids]:                sorted lexicographically by log_id
    30  //	    log_id:      [32]byte
    31  //	    offset:      u64 BE                file offset of entry section
    32  //	    num_entries: u16 BE
    33  //
    34  //	ENTRY SECTIONS (read on demand via ReadAt):
    35  //	  entry[num_entries]:
    36  //	    filter_index:  u16 BE
    37  //	    min_timestamp: u64 BE
    38  //	    max_timestamp: u64 BE
    39  //
    40  // The legacy "upkiidx0" format encoded num_filenames and filter_index as u8;
    41  // it is not supported.
    42  const (
    43  	IndexFilename = "index.bin"
    44  	indexMagic    = "upkiidx1"
    45  	filenameSize  = 32 // NULL-padded filename slot, restricted ASCII
    46  
    47  	headerSize      = 8 + 2 + 4  // 8 byte magic + num_filenames(u16) + num_log_ids(u32)
    48  	logDirEntrySize = 32 + 8 + 2 // 32 byte log_id + entry-section offset(u64) + count(u16)
    49  	entrySize       = 2 + 8 + 8  // filter_idx(u16) + min_ts(u64) + max_ts(u64)
    50  )
    51  
    52  var (
    53  	// ErrNoData reports that the cache index is absent or inaccessible.
    54  	ErrNoData = errors.New("upki: no revocation data")
    55  
    56  	errInvalidIndex = errors.New("upki: invalid index")
    57  )
    58  
    59  // OpenIndex opens the UPKI index at path. If the path is missing, a parent
    60  // is not a directory, or access is denied, the error wraps ErrNoData.
    61  func OpenIndex(path string) (*os.File, error) {
    62  	f, err := openCacheFile(path)
    63  	if errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) || errors.Is(err, os.ErrPermission) {
    64  		return nil, fmt.Errorf("%w: %w", ErrNoData, err)
    65  	}
    66  	return f, err
    67  }
    68  
    69  // index is the in-memory index of revocation filter coverage built from an
    70  // upki revocation index.bin.
    71  //
    72  // Its purpose is to avoid needing to read each of the cached clubcard
    73  // filters into memory for each revocation check.
    74  //
    75  // Constructing an index reads the fixed header, the filename table, and
    76  // the log-id directory eagerly. Per-log entry sections are read on demand
    77  // via [io.ReaderAt.ReadAt] during [index.lookup].
    78  //
    79  // index is safe for concurrent [index.lookup] calls: after construction
    80  // only the [io.ReaderAt] is used, and [io.ReaderAt.ReadAt] does not share
    81  // state with itself.
    82  type index struct {
    83  	filenames []string
    84  	logDir    []byte // packed: numLogs * logDirEntrySize
    85  	numLogs   int
    86  	r         *os.File
    87  }
    88  
    89  // newIndex eagerly reads the header and lookup tables from f. Entry sections
    90  // are read on demand during [index.lookup].
    91  func newIndex(f *os.File) (*index, error) {
    92  	// header is: magic[8] | num_filenames(u16 BE) | num_log_ids(u32 BE).
    93  	var header [headerSize]byte
    94  	if _, err := readFullAt(f, header[:], 0); err != nil {
    95  		return nil, fmt.Errorf("%w: read header: %w", errInvalidIndex, err)
    96  	}
    97  	if !bytes.Equal(header[:8], []byte(indexMagic)) {
    98  		return nil, fmt.Errorf("%w: bad magic", errInvalidIndex)
    99  	}
   100  	numFilenames := int(binary.BigEndian.Uint16(header[8:10]))
   101  	numLogIDs := binary.BigEndian.Uint32(header[10:14])
   102  
   103  	// The filename table and log directory are contiguous and their sizes are
   104  	// fully determined by the header. Compute their size before converting
   105  	// num_log_ids to int so a large value cannot wrap on 32-bit platforms.
   106  	filenamesLen := numFilenames * filenameSize
   107  	tablesLen := int64(filenamesLen) + int64(numLogIDs)*logDirEntrySize
   108  	info, err := f.Stat()
   109  	if err != nil {
   110  		return nil, fmt.Errorf("%w: stat index: %w", errInvalidIndex, err)
   111  	}
   112  	if int64(headerSize)+tablesLen > info.Size() || tablesLen > int64(^uint(0)>>1) {
   113  		return nil, fmt.Errorf("%w: read tables: %w", errInvalidIndex, io.ErrUnexpectedEOF)
   114  	}
   115  	numLogs := int(numLogIDs)
   116  	tables := make([]byte, int(tablesLen))
   117  	if _, err := readFullAt(f, tables, headerSize); err != nil {
   118  		return nil, fmt.Errorf("%w: read tables: %w", errInvalidIndex, err)
   119  	}
   120  	filenamesBuf := tables[:filenamesLen]
   121  	logDir := tables[filenamesLen:]
   122  
   123  	filenames := make([]string, numFilenames)
   124  	for i := range numFilenames {
   125  		slot := filenamesBuf[i*filenameSize : (i+1)*filenameSize]
   126  		end := bytes.IndexByte(slot, 0)
   127  		if end < 0 {
   128  			end = filenameSize
   129  		}
   130  
   131  		name := string(slot[:end])
   132  		if err := validateFilterFilename(name); err != nil {
   133  			return nil, fmt.Errorf("%w: filename table entry %d: %w", errInvalidIndex, i, err)
   134  		}
   135  
   136  		filenames[i] = name
   137  	}
   138  
   139  	if err := validateLogDirOrder(logDir, numLogs); err != nil {
   140  		return nil, err
   141  	}
   142  	tablesEnd := int64(headerSize) + tablesLen
   143  	if err := validateEntrySections(logDir, numLogs, tablesEnd, info.Size()); err != nil {
   144  		return nil, err
   145  	}
   146  
   147  	return &index{
   148  		filenames: filenames,
   149  		logDir:    logDir,
   150  		numLogs:   numLogs,
   151  		r:         f,
   152  	}, nil
   153  }
   154  
   155  // validateFilterFilename enforces the spec's filter filename restrictions:
   156  // 1 to 32 bytes, only ASCII `A`-`Z`, `a`-`z`, `0`-`9`, `-`, `.`, and `_`,
   157  // and never the names "." or "..".
   158  //
   159  // Filenames from the index are used to open filter files relative to the
   160  // cache directory, so this must reject anything that could escape it (path
   161  // separators, "..", NUL is already excluded by slot parsing) before any
   162  // name reaches a filesystem operation. An index containing a violating
   163  // name is malformed.
   164  func validateFilterFilename(name string) error {
   165  	if len(name) == 0 {
   166  		return errors.New("empty filename")
   167  	}
   168  	if name == "." || name == ".." {
   169  		return fmt.Errorf("filename %q is a directory reference", name)
   170  	}
   171  	for i := 0; i < len(name); i++ {
   172  		switch c := name[i]; {
   173  		case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9',
   174  			c == '-', c == '.', c == '_':
   175  		default:
   176  			return fmt.Errorf("filename contains disallowed byte 0x%02x", c)
   177  		}
   178  	}
   179  
   180  	return nil
   181  }
   182  
   183  // validateLogDirOrder checks that the log directory is strictly ascending by
   184  // log_id.
   185  //
   186  // The spec requires entries to be sorted lexicographically with no duplicate
   187  // log_id. Checking for strict ordering enforces both at once.
   188  //
   189  // findLog's binary search depends on this order, so an unsorted directory would
   190  // otherwise miss present logs (yielding a wrong not-covered result), while a
   191  // duplicate would make lookups nondeterministic.
   192  func validateLogDirOrder(logDir []byte, numLogs int) error {
   193  	for i := 1; i < numLogs; i++ {
   194  		prev := logDir[(i-1)*logDirEntrySize : (i-1)*logDirEntrySize+32]
   195  		cur := logDir[i*logDirEntrySize : i*logDirEntrySize+32]
   196  		if bytes.Compare(prev, cur) >= 0 {
   197  			return fmt.Errorf("%w: log directory not strictly sorted by log id at index %d",
   198  				errInvalidIndex, i)
   199  		}
   200  	}
   201  
   202  	return nil
   203  }
   204  
   205  // validateEntrySections checks every log directory entry's on-demand entry
   206  // section against the spec's bounds: it MUST lie entirely within the file,
   207  // MUST NOT overlap the header, filename table, or log directory, and SHOULD
   208  // NOT overlap another log's entry section.
   209  func validateEntrySections(logDir []byte, numLogs int, tablesEnd, fileSize int64) error {
   210  	type span struct{ start, end int64 }
   211  
   212  	spans := make([]span, 0, numLogs)
   213  	for i := range numLogs {
   214  		off := i * logDirEntrySize
   215  		entryOffset := int64(binary.BigEndian.Uint64(logDir[off+32 : off+40]))
   216  		count := int64(binary.BigEndian.Uint16(logDir[off+40 : off+42]))
   217  		sectionLen := count * entrySize
   218  
   219  		if entryOffset < tablesEnd {
   220  			return fmt.Errorf("%w: entry section offset %d overlaps header/tables (end %d)",
   221  				errInvalidIndex, entryOffset, tablesEnd)
   222  		}
   223  		if entryOffset > fileSize || sectionLen > fileSize-entryOffset {
   224  			return fmt.Errorf("%w: entry section at offset %d with length %d exceeds file size %d",
   225  				errInvalidIndex, entryOffset, sectionLen, fileSize)
   226  		}
   227  
   228  		if sectionLen > 0 {
   229  			spans = append(spans, span{start: entryOffset, end: entryOffset + sectionLen})
   230  		}
   231  	}
   232  
   233  	// The spec leaves overlap between distinct logs' entry sections
   234  	// unspecified and says implementations SHOULD reject it; aliased
   235  	// sections would make one log's entries silently double as another's.
   236  	slices.SortFunc(spans, func(a, b span) int { return cmp.Compare(a.start, b.start) })
   237  	for i := 1; i < len(spans); i++ {
   238  		if spans[i].start < spans[i-1].end {
   239  			return fmt.Errorf("%w: entry sections [%d, %d) and [%d, %d) overlap",
   240  				errInvalidIndex, spans[i-1].start, spans[i-1].end, spans[i].start, spans[i].end)
   241  		}
   242  	}
   243  
   244  	return nil
   245  }
   246  
   247  // lookup finds the filter files that cover the given CT log id at the
   248  // given timestamp, returning the covering filters' basenames in index
   249  // entry order.
   250  //
   251  // It binary-searches the in-memory log-id directory and on a hit issues
   252  // a single [io.ReaderAt.ReadAt] against that log's entry section. Every
   253  // entry whose interval [min, max] contains timestamp contributes its
   254  // filter. A log can have several covering filters for the same instant
   255  // and a conclusive revocation answer may come from any of them, so
   256  // callers must consult all the returned filters, not just the first.
   257  //
   258  // The result is empty (with a nil error) when no entry covers the
   259  // (log id, timestamp). In this case the log is not indexed, or it is
   260  // indexed but the timestamp falls outside every recorded interval.
   261  func (idx *index) lookup(id logID, ts timestamp) ([]string, error) {
   262  	dirOffset, ok := idx.findLog(id)
   263  	if !ok {
   264  		return nil, nil
   265  	}
   266  
   267  	// log-dir entry is: log_id[32] | entry_offset(u64) | count(u16).
   268  	entryOffset := binary.BigEndian.Uint64(idx.logDir[dirOffset+32 : dirOffset+40])
   269  	count := binary.BigEndian.Uint16(idx.logDir[dirOffset+40 : dirOffset+42])
   270  
   271  	buf := make([]byte, int(count)*entrySize)
   272  	if _, err := readFullAt(idx.r, buf, int64(entryOffset)); err != nil {
   273  		return nil, fmt.Errorf("%w: read entries: %w", errInvalidIndex, err)
   274  	}
   275  
   276  	var filenames []string
   277  	for i := range int(count) {
   278  		// entry is: filter_idx(u16) | min_ts(u64) | max_ts(u64).
   279  		off := i * entrySize
   280  		filterIdx := int(binary.BigEndian.Uint16(buf[off : off+2]))
   281  		if filterIdx >= len(idx.filenames) {
   282  			return nil, fmt.Errorf("%w: entry filter index %d out of range", errInvalidIndex, filterIdx)
   283  		}
   284  		minTS := binary.BigEndian.Uint64(buf[off+2 : off+10])
   285  		maxTS := binary.BigEndian.Uint64(buf[off+10 : off+18])
   286  		if minTS > uint64(ts) || uint64(ts) > maxTS {
   287  			continue
   288  		}
   289  
   290  		filenames = append(filenames, idx.filenames[filterIdx])
   291  	}
   292  
   293  	return filenames, nil
   294  }
   295  
   296  // findLog binary-searches the lexicographically-sorted log-id directory
   297  // for logID and returns the byte offset (within idx.logDir) of the
   298  // matching entry, or (0, false) if absent.
   299  //
   300  // Hand-rolled rather than sort.Search / slices.BinarySearchFunc because
   301  // the directory is a packed byte buffer with no element type, and we don't
   302  // want to transform to a slice.
   303  func (idx *index) findLog(id logID) (int, bool) {
   304  	lo, hi := 0, idx.numLogs
   305  	target := id[:]
   306  	for lo < hi {
   307  		mid := int(uint(lo+hi) >> 1)
   308  		off := mid * logDirEntrySize
   309  		cmp := bytes.Compare(idx.logDir[off:off+32], target)
   310  		switch {
   311  		case cmp < 0:
   312  			lo = mid + 1
   313  		case cmp > 0:
   314  			hi = mid
   315  		default:
   316  			return off, true
   317  		}
   318  	}
   319  
   320  	return 0, false
   321  }
   322  
   323  func readFullAt(r io.ReaderAt, buf []byte, off int64) (int, error) {
   324  	n, err := r.ReadAt(buf, off)
   325  	if err == io.EOF && n == len(buf) {
   326  		return n, nil
   327  	}
   328  	if err == nil && n < len(buf) {
   329  		return n, io.ErrUnexpectedEOF
   330  	}
   331  
   332  	return n, err
   333  }
   334  

View as plain text