pki

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 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 (
	CRLGood    = "good"
	CRLRevoked = "revoked"
	CRLUnknown = "unknown"
)

CRL status values. Unknown is never a pass: it says the CRL could not answer.

View Source
const (
	CRLSigValid    = "valid"
	CRLSigInvalid  = "invalid"
	CRLSigNoIssuer = "no-issuer"
)

CRL signature results.

View Source
const (
	// KindKeyCompromise: the private key is public or recoverable, so anyone can sign as this CA.
	KindKeyCompromise = "key-compromise"
	// KindCADistrust: root programs have blocked the certificate, though its key is not known to be public.
	KindCADistrust = "ca-distrust"
)

Kinds of distrust-list entry.

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

View Source
var CRLReasons = map[int]string{0: "unspecified", 1: "keyCompromise", 2: "cACompromise", 3: "affiliationChanged",
	4: "superseded", 5: "cessationOfOperation", 6: "certificateHold", 8: "removeFromCRL", 9: "privilegeWithdrawn", 10: "aACompromise"}

CRLReasons names RFC 5280 §5.3.1 reason codes.

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 IssuerSerialKey added in v0.5.0

func IssuerSerialKey(c *x509.Certificate) string

IssuerSerialKey is the issuer-and-serial match key of a certificate.

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 Paths added in v0.4.1

func Paths(s *Served, store *Store) [][]*x509.Certificate

Paths returns every path from the served leaf to a root in store along which each signature verifies under its issuer's key and the names chain, leaf first, root last. The served certificates are the only intermediates (no AIA fetching). No validity period, key usage, name constraint, root-program constraint or distrust list is applied: Paths answers "is there a cryptographic path?", and evaluation reports the rest as findings on that path. It exists because crypto/x509 silently drops paths through keys it has hardcoded as distrusted, which would hide the very path an evaluation has to show.

func SPKIFingerprint added in v0.4.1

func SPKIFingerprint(c *x509.Certificate) string

SPKIFingerprint is the lower-case hex SHA-256 of a certificate's SubjectPublicKeyInfo.

func SelfSigned

func SelfSigned(c *x509.Certificate) bool

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

Types

type CRLResult added in v0.4.1

type CRLResult struct {
	Position int    `json:"position"` // served index of the certificate checked
	SHA256   string `json:"sha256"`   // the certificate checked
	URL      string `json:"url,omitempty"`

	Status    string    `json:"status"`              // good | revoked | unknown
	Reason    string    `json:"reason,omitempty"`    // the CRL's reason code, when revoked
	RevokedAt time.Time `json:"revokedAt,omitempty"` // when revoked
	// Signature is valid (the certificate's issuer signed the CRL), invalid, or
	// no-issuer (the issuer was not available to check it); empty when the CRL
	// was never read.
	Signature  string    `json:"signature,omitempty"`
	ThisUpdate time.Time `json:"thisUpdate,omitempty"`
	NextUpdate time.Time `json:"nextUpdate,omitempty"`
	Number     string    `json:"crlNumber,omitempty"`
	// Issuer is the SHA-256 of the certificate whose key verified the CRL.
	Issuer string `json:"issuer,omitempty"`

	FetchedAt time.Time `json:"fetchedAt,omitempty"`
	Size      int       `json:"size,omitempty"`
	CRLSHA256 string    `json:"crlSha256,omitempty"`
	// Problem says why the status is unknown (or what else was wrong).
	Problem string `json:"problem,omitempty"`
}

CRLResult is what one CRL says about one certificate on a served path. It is a status beside the trust verdict, never a gate on it.

func JudgeCRL added in v0.4.1

func JudgeCRL(rl *x509.RevocationList, url string, subject, issuer *x509.Certificate, now time.Time) CRLResult

JudgeCRL says what the CRL rl, fetched from url, says about subject, whose issuer is issuer (nil when the evaluation does not have it). It checks, in order: that the CRL is issued under the subject's issuer name, that the issuer's key signed it, that it is not dated in the future, that it is a complete CRL whose scope (issuing distribution point) covers the subject, and then whether the subject's serial is listed. Anything that stops the CRL from answering gives CRLUnknown with the reason in Problem. Staleness (nextUpdate passed) is left to evaluation, which knows its own clock.

The caller fills Position, SHA256, FetchedAt, Size and CRLSHA256.

type Distrust added in v0.4.1

type Distrust struct {
	// contains filtered or unexported fields
}

Distrust is a list of keys and certificates no path should rely on, matched by the SHA-256 of the SubjectPublicKeyInfo (one entry covers every certificate for that key: the original, its cross-signs and any reissue), of the certificate's DER, or by issuer name and serial number (how root programs such as Mozilla's OneCRL revoke a CA certificate). A nil *Distrust matches nothing.

func NewDistrust added in v0.4.1

func NewDistrust() *Distrust

NewDistrust returns an empty list.

func (*Distrust) Add added in v0.4.1

func (d *Distrust) Add(spki string, certs []string, l Listed)

Add lists a key (spki, lower-case hex, may be empty) and certificates (lower-case hex SHA-256 of DER) under l.

func (*Distrust) AddIssuerSerial added in v0.5.0

func (d *Distrust) AddIssuerSerial(issuerSHA, serial string, l Listed)

AddIssuerSerial lists one certificate by its issuer and serial number: issuerSHA is the lower-case hex SHA-256 of the issuer Name's DER, serial the lower-case hex of the serial number's magnitude (no leading zero bytes). An existing key or fingerprint entry for the same certificate wins, since it says more.

func (*Distrust) Has added in v0.5.0

func (d *Distrust) Has(spki string) bool

Has reports whether a key is already listed (lower-case hex SPKI SHA-256).

func (*Distrust) Len added in v0.4.1

func (d *Distrust) Len() int

Len is the number of distinct keys and certificates listed.

func (*Distrust) ListedOnPath added in v0.4.1

func (d *Distrust) ListedOnPath(path []*x509.Certificate) []ListedOn

ListedOnPath returns every listed certificate on a path (leaf first).

func (*Distrust) ListedOnPathIn added in v0.5.0

func (d *Distrust) ListedOnPathIn(path []*x509.Certificate, store string) []ListedOn

ListedOnPathIn returns the listed certificates on a path whose entry applies to the named store (leaf first). An empty store name returns every listed certificate.

func (*Distrust) Lookup added in v0.4.1

func (d *Distrust) Lookup(c *x509.Certificate) (Listed, bool)

Lookup matches a parsed certificate.

func (*Distrust) LookupHashes added in v0.4.1

func (d *Distrust) LookupHashes(certSHA, spkiSHA string) (Listed, bool)

LookupHashes matches by certificate SHA-256 and/or SPKI SHA-256 (lower-case hex; either may be empty), for certificates known only by their facts.

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 Listed added in v0.4.1

type Listed struct {
	Name     string   `json:"name"`     // the CA's name, for display
	Kind     string   `json:"kind"`     // KindKeyCompromise | KindCADistrust
	Incident string   `json:"incident"` // incident id, e.g. "emudhra-2026-10"
	Title    string   `json:"title"`    // the incident's title
	Since    string   `json:"since"`    // YYYY-MM-DD the problem became public
	Summary  string   `json:"summary"`
	Sources  []string `json:"sources"`
	// Stores are the root stores whose programs block this entry (store names, e.g. "Mozilla").
	// Empty means every store, private anchors included: a key whose private half is public is
	// unsafe whoever trusts it. One program's block (Mozilla's OneCRL) changes only that store's
	// verdict; the finding still says it, naming the program.
	Stores []string `json:"stores,omitempty"`
}

Listed is what a distrust list says about one key: what it is, why it is listed and where that is published. An entry is a fact about the key, not a verdict on a path: evaluation reports it and carries on.

func (Listed) AppliesTo added in v0.5.0

func (l Listed) AppliesTo(store string) bool

AppliesTo reports whether the entry changes the verdict of the named store.

func (Listed) Phrase added in v0.4.1

func (l Listed) Phrase() string

Phrase describes the entry in a clause: "whose private key is public (title, since)".

type ListedOn added in v0.4.1

type ListedOn struct {
	Position int    `json:"position"` // 0 = leaf, counting up the path
	SHA256   string `json:"sha256"`
	Listed
}

ListedOn is one listed certificate found on a path.

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, or which listed key, stopped a path that exists.
	Error    string `json:"error,omitempty"`
	Distrust string `json:"distrust,omitempty"`
	// Listed are the certificates on Path that the distrust list names. Path is
	// then the signature-valid path through them: the evaluation reports it
	// rather than losing it.
	Listed []ListedOn `json:"listed,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, dl *Distrust) 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.

dl is the distrust list (nil for none). It applies to every store, private ones included: a path through a listed key is reported as distrusted, with the path and the listed certificates, whatever crypto/x509 did with it (Go 1.27.3 and later drop such paths silently, older versions accept them).

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