pki

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pki holds the certificate-path logic the TLS evaluation needs: the analysis of a served chain, path validation per anchor set (with the constraints root programs apply), certificate-name matching, and decoders for a stapled OCSP response and an SCT list.

It is pure: it never touches the network, never reads the clock (the time is always an argument) and never reads a store. Every decoder bounds its input and is fuzzed.

Index

Constants

View Source
const (
	IssueOrder     = "order"     // a certificate does not certify the one before it
	IssueRoot      = "root"      // a self-signed root was sent (harmless, wasted bytes)
	IssueDuplicate = "duplicate" // the same certificate was sent twice
	IssueUnrelated = "unrelated" // a certificate on no path from the leaf
	IssueUnparsed  = "unparsed"  // a certificate that does not parse
)

Issue kinds found in a served chain (RFC 8446 §4.4.2, RFC 5246 §7.4.2).

View Source
const (
	SigValid       = "valid"
	SigInvalid     = "invalid"
	SigUnsupported = "unsupported"
	SigNoIssuer    = "no-issuer"
)

Signature outcomes.

View Source
const MaxOCSPBytes = 64 << 10

MaxOCSPBytes bounds a stapled response.

View Source
const (
	MaxSCTs = 64
)

Bounds on SCT data, generous for anything a real certificate carries.

View Source
const MaxServedCerts = 16

MaxServedCerts bounds the chain a server can make us analyse.

Variables

This section is empty.

Functions

func Fingerprint

func Fingerprint(c *x509.Certificate) string

Fingerprint is the lower-case hex SHA-256 of a certificate's DER.

func Issued

func Issued(parent, child *x509.Certificate) bool

Issued reports whether parent issued child: the names chain and the signature verifies.

func NameMatch

func NameMatch(leaf *x509.Certificate, host string) (matchedBy string, err error)

NameMatch checks the host against the leaf's DNS and IP SANs; the CN is never used (RFC 9525). MatchedBy names the SAN that matched.

func SelfSigned

func SelfSigned(c *x509.Certificate) bool

SelfSigned reports whether c is signed by its own key under its own name.

Types

type Issue

type Issue struct {
	Kind   string `json:"kind"`
	Index  int    `json:"index"` // position in the served order, 0 = leaf
	Detail string `json:"detail"`
}

Issue is one problem with how a chain was served.

type OCSP

type OCSP struct {
	// Status is the outer responseStatus by its RFC name ("successful",
	// "tryLater", ...). The remaining fields are empty unless it is "successful".
	Status     string
	ProducedAt time.Time
	// ResponderName is the byName responder (an RFC 4514 string); ResponderKeyHash
	// the byKey one. Exactly one is set.
	ResponderName    string
	ResponderKeyHash []byte
	Responses        []SingleResponse
	// Certs are the certificates carried in the response (a delegated responder).
	Certs []*x509.Certificate
	// contains filtered or unexported fields
}

OCSP is a decoded OCSP response (RFC 6960 §4.2.1). Only the fields the evaluation reads are kept.

func ParseOCSP

func ParseOCSP(der []byte) (*OCSP, error)

ParseOCSP decodes a DER OCSP response. It verifies nothing; see Match and VerifySignature.

func (*OCSP) Match

func (o *OCSP) Match(leaf, issuer *x509.Certificate) (*SingleResponse, bool)

Match returns the single response for leaf as issued by issuer: the serial is equal and the issuer name and key hashes match, computed with the response's own hash algorithm. A response naming a hash we cannot compute never matches.

func (*OCSP) VerifySignature

func (o *OCSP) VerifySignature(issuer *x509.Certificate) (string, *x509.Certificate)

VerifySignature checks the response signature: by the issuer itself, or by a delegated responder certificate carried in the response that the issuer signed and that has the OCSPSigning extended key usage (RFC 6960 §4.2.2.2). It returns the outcome and, when delegated, the responder certificate.

type Root

type Root struct {
	SHA256 string // lower-case hex SHA-256 of DER
	DER    []byte
	// DistrustAfter is Mozilla's "Distrust for TLS After Date": a leaf whose
	// notBefore is after it is not trusted through this root. Zero means none.
	DistrustAfter time.Time
	// SCTNotAfter is Chrome's sct_not_after: a leaf is trusted through this root
	// only with an SCT timestamped at or before it. Zero means none.
	SCTNotAfter time.Time
	// PermittedDNS are DNS-name constraints a root program applies to this root
	// on top of the certificate's own (for example "tr").
	PermittedDNS []string
}

Root is one trust anchor with the constraints its root program applies.

type SCT

type SCT struct {
	Version    uint8
	LogID      [32]byte
	Timestamp  time.Time
	Extensions []byte
	HashAlg    uint8
	SigAlg     uint8
	Signature  []byte
}

SCT is one Signed Certificate Timestamp (RFC 6962 §3.2). Its signature is decoded but not verified: T1 checks presence and names the log, nothing more.

func EmbeddedSCTs

func EmbeddedSCTs(c *x509.Certificate) ([]SCT, error)

EmbeddedSCTs decodes the SCT list extension of a certificate. It returns nil, nil when there is none.

func ParseSCT

func ParseSCT(b []byte) (SCT, error)

ParseSCT decodes one SerializedSCT body (the form crypto/tls hands over from the TLS extension, without the uint16 length prefix).

func ParseSCTList

func ParseSCTList(b []byte) ([]SCT, error)

ParseSCTList decodes a SignedCertificateTimestampList (RFC 6962 §3.3): a uint16 total length and then uint16-length-prefixed SCTs. Every length is checked against what remains; at most MaxSCTs are accepted.

type Served

type Served struct {
	// Certs are the parsed certificates in served order; an entry is nil when
	// that certificate did not parse.
	Certs []*x509.Certificate
	// Path is the served indexes on the certification path from the leaf
	// upwards, following issuer signatures among the served certificates.
	Path      []int
	Issues    []Issue
	SizeBytes int
}

Served is the analysis of a chain exactly as the server sent it.

func AnalyzeServed

func AnalyzeServed(der [][]byte) (*Served, error)

AnalyzeServed parses and analyses a served chain (leaf first). It fails only when there is no leaf it can parse.

func (*Served) ExpiresFirst

func (s *Served) ExpiresFirst() []int

ExpiresFirst lists the served-path certificates above the leaf whose notAfter is before the leaf's: the chain breaks before the leaf does.

func (*Served) Intermediates

func (s *Served) Intermediates() []*x509.Certificate

Intermediates are every parsed served certificate except the leaf, for path building.

func (*Served) IssuerOf

func (s *Served) IssuerOf() *x509.Certificate

IssuerOf returns the served certificate that issued the leaf, if any.

func (*Served) Leaf

func (s *Served) Leaf() *x509.Certificate

Leaf is the first served certificate.

func (*Served) MissingIssuer

func (s *Served) MissingIssuer(stores ...*Store) (missing bool, issuerDN string, aia []string)

MissingIssuer reports whether the top of the served path is neither a root nor issued by any anchor in the stores: an intermediate the server should have sent is missing. When it is, the issuer's name and the top certificate's AIA caIssuers URLs are returned.

func (*Served) Top

func (s *Served) Top() *x509.Certificate

Top is the highest certificate on the served path.

type SingleResponse

type SingleResponse struct {
	HashAlg    string // "SHA-1", "SHA-256", ... or the OID
	NameHash   []byte
	KeyHash    []byte
	Serial     *big.Int
	Status     string // "good", "revoked" or "unknown"
	RevokedAt  time.Time
	Reason     int // RFC 5280 CRLReason, -1 when absent
	ThisUpdate time.Time
	NextUpdate time.Time // zero when absent
	SCTs       []SCT
	SCTError   string
	// contains filtered or unexported fields
}

SingleResponse is the status of one certificate.

type Store

type Store struct {
	Name     string // "Mozilla", "Chrome", "private"
	Snapshot string // date of the snapshot, empty for private anchors
	// Constrained marks a root-program store whose constraints are applied.
	Constrained bool
	// contains filtered or unexported fields
}

Store is a named set of trust anchors: a bundled root-program snapshot or an operator's private CA bundle.

func NewStore

func NewStore(name, snapshot string, constrained bool, roots []Root) (*Store, error)

NewStore parses every root. A root that does not parse, or whose SHA256 does not match its DER, is an error: a store is never silently smaller than its source.

func (*Store) Certificates

func (s *Store) Certificates() []*x509.Certificate

Certificates returns the parsed roots, in source order.

func (*Store) Len

func (s *Store) Len() int

Len is the number of distinct roots.

func (*Store) Root

func (s *Store) Root(sha string) (Root, bool)

Root returns the root with this fingerprint.

type StoreResult

type StoreResult struct {
	Store    string `json:"store"`
	Snapshot string `json:"snapshot,omitempty"`
	Trusted  bool   `json:"trusted"`
	// Path is the validated chain, leaf first, by SHA-256; the last entry is the
	// anchor. Empty when nothing validated.
	Path []string `json:"path,omitempty"`
	// Error says why nothing validated; Distrust says which root-program
	// constraint stopped an otherwise valid path.
	Error    string `json:"error,omitempty"`
	Distrust string `json:"distrust,omitempty"`
	// ExpiredOnly is set when the path validates except that a certificate on it
	// is outside its validity at the evaluation time: the expiry finding covers
	// it, so "untrusted" is not raised a second time.
	ExpiredOnly bool `json:"expiredOnly,omitempty"`
}

StoreResult is the outcome of validating one served chain against one anchor set.

func Validate

func Validate(s *Served, store *Store, now time.Time, sctTimes []time.Time) StoreResult

Validate builds a path from the served leaf to an anchor in store, using the served certificates as the only intermediates (no AIA fetching, no system pool), for TLS server authentication at now. sctTimes are the timestamps of every SCT seen for the leaf (embedded, TLS, OCSP); they decide Chrome's sct_not_after constraint.

Directories

Path Synopsis
Package pkitest builds small test PKIs at test time: a root, intermediates and leaf variants with exactly the properties a fixture needs.
Package pkitest builds small test PKIs at test time: a root, intermediates and leaf variants with exactly the properties a fixture needs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL