certificate

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package certificate parses, describes, creates, lints and compares X.509 certificates.

Index

Constants

View Source
const (
	SevError   = "error"   // violates a MUST in a standard or is exploitable
	SevWarning = "warning" // violates a SHOULD, or will break common clients
	SevNotice  = "notice"  // unusual but not wrong
)

Severity levels, from most to least serious.

Variables

View Source
var ErrNoCertificate = errors.New("no certificate found")

ErrNoCertificate means the input contained no certificate.

Profiles lists profiles in the order shown by the wizard.

Functions

func Colon

func Colon(h string) string

Colon formats hex as upper-case colon-separated octets (AB:CD:...).

func Create

func Create(req Request) (*x509.Certificate, error)

Create issues a certificate and returns it parsed.

func CreateCSR

func CreateCSR(subject pkix.Name, sans []string, key crypto.Signer) (*x509.CertificateRequest, error)

CreateCSR creates a PKCS#10 certificate signing request.

func EncodeCSRPEM

func EncodeCSRPEM(csr *x509.CertificateRequest) []byte

EncodeCSRPEM encodes a certificate request.

func EncodePEM

func EncodePEM(certs ...*x509.Certificate) []byte

EncodePEM encodes certificates as concatenated PEM blocks.

func EncodePKCS7

func EncodePKCS7(certs []*x509.Certificate) ([]byte, error)

EncodePKCS7 builds a degenerate ("certs-only") PKCS#7 SignedData, the format of .p7b files.

func ExtKeyUsageName

func ExtKeyUsageName(u x509.ExtKeyUsage) string

ExtKeyUsageName returns a readable EKU name.

func ExtensionName

func ExtensionName(oid asn1.ObjectIdentifier) string

ExtensionName returns a readable name for an extension OID, or "".

func FindLeaf

func FindLeaf(certs []*x509.Certificate) *x509.Certificate

FindLeaf picks the end-entity certificate from an unordered bundle: the certificate that issued no other certificate in the set. Ties go to the first such certificate.

func FormatChange

func FormatChange(c Change) []string

FormatChange renders a change in +/- style for text output.

func HasErrors

func HasErrors(f []Finding) bool

HasErrors reports whether any finding has error severity.

func Identical

func Identical(changes []Change) bool

Identical reports whether no field changed.

func IsPEM

func IsPEM(data []byte) bool

IsPEM reports whether data looks like PEM.

func IsSelfSigned

func IsSelfSigned(c *x509.Certificate) bool

IsSelfSigned reports whether c's subject equals its issuer and its signature verifies with its own key.

func Issues

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

Issues reports whether parent signed child: names chain, key identifiers agree when present, and the signature verifies.

func KeyUsageNames

func KeyUsageNames(ku x509.KeyUsage) []string

KeyUsageNames returns the names of the set bits.

func LoadPool

func LoadPool(data []byte) (*x509.CertPool, []*x509.Certificate, error)

LoadPool builds a CertPool from PEM/DER data.

func MaxTLSLifetimeDays

func MaxTLSLifetimeDays(nb time.Time) int

MaxTLSLifetimeDays returns the BR lifetime limit for a certificate issued at nb.

func Order

func Order(leaf *x509.Certificate, pool []*x509.Certificate) []*x509.Certificate

Order returns the path from leaf towards the root using certificates from pool, stopping at a self-signed certificate or when no issuer is found.

func Parse

func Parse(data []byte) ([]*x509.Certificate, error)

Parse returns every certificate in data: PEM (any number of blocks, non-certificate blocks are skipped), DER, or PKCS#7 in either encoding.

func ParseCSR

func ParseCSR(data []byte) (*x509.CertificateRequest, error)

ParseCSR parses a PKCS#10 request in PEM or DER.

func ParsePKCS7

func ParsePKCS7(der []byte) ([]*x509.Certificate, error)

ParsePKCS7 extracts certificates from a PKCS#7 / CMS SignedData structure (typically a .p7b "certs-only" bundle).

func PolicyName

func PolicyName(oid string) string

PolicyName returns a readable certificate policy name, or "".

func SerialHex

func SerialHex(c *x509.Certificate) string

SerialHex formats a serial as colon-separated hex, preserving the sign.

func SignatureStrength

func SignatureStrength(a x509.SignatureAlgorithm) string

SignatureStrength classifies a signature algorithm: modern, deprecated (SHA-1, DSA: collision attacks or withdrawn), insecure (MD2/MD5), unknown.

func SplitSANs

func SplitSANs(sans []string) (dns []string, ips []net.IP, emails []string, uris []*url.URL, err error)

SplitSANs sorts SAN strings into DNS names, IPs, e-mails and URIs.

func UnknownExtKeyUsageName

func UnknownExtKeyUsageName(oid asn1.ObjectIdentifier) string

UnknownExtKeyUsageName names EKU OIDs that crypto/x509 does not model.

func ValidateDNSName

func ValidateDNSName(d string) error

ValidateDNSName checks LDH syntax with an optional leading wildcard label.

Types

type BasicConstraints

type BasicConstraints struct {
	CA       bool `json:"ca"`
	PathLen  *int `json:"path_len,omitempty"`
	Critical bool `json:"critical"`
}

BasicConstraints mirrors the extension.

type Change

type Change struct {
	Field   string   `json:"field"`
	Changed bool     `json:"changed"`
	Old     string   `json:"old,omitempty"`
	New     string   `json:"new,omitempty"`
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
}

Change describes one compared field.

func Diff

func Diff(a, b Info) []Change

Diff compares two certificate descriptions field by field.

type Extension

type Extension struct {
	OID      string `json:"oid"`
	Name     string `json:"name,omitempty"`
	Critical bool   `json:"critical"`
	Known    bool   `json:"known"`
	Size     int    `json:"size"`
}

Extension is one raw extension entry.

type Finding

type Finding struct {
	ID          string `json:"id"`
	Severity    string `json:"severity"`
	Certificate string `json:"certificate"` // subject display name
	What        string `json:"what"`
	Why         string `json:"why"`
	Evidence    string `json:"evidence"`
	Reference   string `json:"reference,omitempty"`
}

Finding is one lint result. Every finding explains WHAT is wrong, WHY it matters, the EVIDENCE observed, and which standard it comes from.

func Lint

func Lint(certs []*x509.Certificate, opts LintOptions) []Finding

Lint checks certs. The first certificate is treated as the leaf unless the bundle is unordered, in which case the leaf is detected. Chain checks run when more than one certificate is supplied or CheckTrust is set.

type Fingerprints

type Fingerprints struct {
	SHA256     string `json:"sha256"`
	SHA1       string `json:"sha1"`
	SPKISHA256 string `json:"spki_sha256"`
}

Fingerprints are hashes identifying a certificate. SHA-1 is included for compatibility with tools that still display it; it is a legacy identifier, not a security mechanism.

func Fingerprint

func Fingerprint(c *x509.Certificate) Fingerprints

Fingerprint computes the fingerprints of c as lowercase hex.

type Info

type Info struct {
	Version            int                `json:"version"`
	Serial             string             `json:"serial"`
	Subject            Name               `json:"subject"`
	Issuer             Name               `json:"issuer"`
	SANs               SANs               `json:"sans"`
	Validity           Validity           `json:"validity"`
	PublicKey          keys.PublicKeyInfo `json:"public_key"`
	SignatureAlgorithm string             `json:"signature_algorithm"`
	SignatureStrength  string             `json:"signature_strength"`
	Fingerprints       Fingerprints       `json:"fingerprints"`
	SelfSigned         bool               `json:"self_signed"`
	IsCA               bool               `json:"is_ca"`
	BasicConstraints   *BasicConstraints  `json:"basic_constraints,omitempty"`
	KeyUsage           []string           `json:"key_usage,omitempty"`
	ExtKeyUsage        []string           `json:"extended_key_usage,omitempty"`
	SubjectKeyID       string             `json:"subject_key_id,omitempty"`
	AuthorityKeyID     string             `json:"authority_key_id,omitempty"`
	CRLDistribution    []string           `json:"crl_distribution_points,omitempty"`
	OCSPServers        []string           `json:"ocsp_servers,omitempty"`
	CAIssuers          []string           `json:"ca_issuers,omitempty"`
	Policies           []Policy           `json:"policies,omitempty"`
	NameConstraints    *NameConstraints   `json:"name_constraints,omitempty"`
	MustStaple         bool               `json:"must_staple"`
	SCTs               []SCT              `json:"scts,omitempty"`
	Extensions         []Extension        `json:"extensions"`
	DERSize            int                `json:"der_size"`
	Warnings           []string           `json:"warnings,omitempty"`
	PEM                string             `json:"pem,omitempty"`
}

Info is the public, stable description of a certificate used for text, JSON and YAML output.

func Describe

func Describe(c *x509.Certificate, opts Options) Info

Describe builds an Info for c.

type LintOptions

type LintOptions struct {
	Now      time.Time
	Hostname string // check the leaf matches this name
	// Roots is used for trust checks when CheckTrust is set; nil = system roots.
	Roots      *x509.CertPool
	CheckTrust bool
}

LintOptions control Lint.

type Name

type Name struct {
	DN                 string   `json:"dn"`
	CommonName         string   `json:"common_name,omitempty"`
	Organization       []string `json:"organization,omitempty"`
	OrganizationalUnit []string `json:"organizational_unit,omitempty"`
	Country            []string `json:"country,omitempty"`
	Province           []string `json:"province,omitempty"`
	Locality           []string `json:"locality,omitempty"`
}

Name is a distinguished name.

func NewName

func NewName(n pkix.Name) Name

NewName converts a pkix.Name.

func (Name) DisplayName

func (n Name) DisplayName() string

DisplayName is the common name, or the full DN when there is none.

type NameConstraints

type NameConstraints struct {
	Critical       bool     `json:"critical"`
	PermittedDNS   []string `json:"permitted_dns,omitempty"`
	ExcludedDNS    []string `json:"excluded_dns,omitempty"`
	PermittedIP    []string `json:"permitted_ip,omitempty"`
	ExcludedIP     []string `json:"excluded_ip,omitempty"`
	PermittedEmail []string `json:"permitted_email,omitempty"`
	ExcludedEmail  []string `json:"excluded_email,omitempty"`
	PermittedURI   []string `json:"permitted_uri,omitempty"`
	ExcludedURI    []string `json:"excluded_uri,omitempty"`
}

NameConstraints mirrors the extension.

type Options

type Options struct {
	Now         time.Time // evaluation time; zero means time.Now()
	WarningDays int       // days before expiry that count as "expiring"; 0 means 30
	IncludePEM  bool
}

Options control Describe.

type Policy

type Policy struct {
	OID  string `json:"oid"`
	Name string `json:"name,omitempty"`
}

Policy is one certificate policy.

type Profile

type Profile string

Profile selects key usages and constraints for a new certificate.

const (
	ProfileServer         Profile = "server"
	ProfileClient         Profile = "client"
	ProfileServerClient   Profile = "server-client"
	ProfileCodeSigning    Profile = "code-signing"
	ProfileEmail          Profile = "email"
	ProfileRootCA         Profile = "root-ca"
	ProfileIntermediateCA Profile = "intermediate-ca"
)

func ParseProfile

func ParseProfile(s string) (Profile, error)

ParseProfile accepts profile names and a few aliases.

func (Profile) IsCA

func (p Profile) IsCA() bool

IsCA reports whether the profile produces a CA certificate.

func (Profile) Label

func (p Profile) Label() string

Label is a human-readable profile name.

type Request

type Request struct {
	Profile   Profile
	Subject   pkix.Name
	SANs      []string // DNS names, IPs, e-mail addresses and URIs, auto-detected
	NotBefore time.Time
	Validity  time.Duration
	// PathLen constrains CA path length; negative means unconstrained.
	PathLen int
	// Key is the subject key. PublicKey may be set instead when signing a CSR.
	Key       crypto.Signer
	PublicKey crypto.PublicKey
	// Issuer and IssuerKey sign the certificate; both nil means self-signed.
	Issuer    *x509.Certificate
	IssuerKey crypto.Signer
}

Request describes a certificate to create.

func RequestFromCSR

func RequestFromCSR(csr *x509.CertificateRequest, profile Profile) Request

RequestFromCSR builds a Request that copies subject and SANs from csr. The CSR's signature must already have been verified (ParseCSR does this).

type SANs

type SANs struct {
	DNS   []string `json:"dns"`
	IP    []string `json:"ip"`
	Email []string `json:"email"`
	URI   []string `json:"uri"`
}

SANs groups subject alternative names by type.

func CertSANs

func CertSANs(c *x509.Certificate) SANs

CertSANs extracts the SANs of c.

func (SANs) All

func (s SANs) All() []string

All returns every SAN value in DNS, IP, email, URI order.

type SCT

type SCT struct {
	Version            int       `json:"version"`
	LogID              string    `json:"log_id"` // base64, as published in CT log lists
	Timestamp          time.Time `json:"timestamp"`
	HashAlgorithm      string    `json:"hash_algorithm"`
	SignatureAlgorithm string    `json:"signature_algorithm"`
}

SCT is a Signed Certificate Timestamp embedded in a certificate (RFC 6962 §3.3).

func EmbeddedSCTs

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

EmbeddedSCTs returns the SCTs in the certificate's SCT list extension.

func ParseSCTList

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

ParseSCTList decodes a TLS-encoded SignedCertificateTimestampList, as found in the certificate extension, the TLS extension, or an OCSP response.

type Validity

type Validity struct {
	NotBefore     time.Time `json:"not_before"`
	NotAfter      time.Time `json:"not_after"`
	LifetimeDays  int       `json:"lifetime_days"`
	DaysRemaining int       `json:"days_remaining"`
	Status        string    `json:"status"` // valid, expiring, expired, not_yet_valid
}

Validity describes the validity period relative to the evaluation time.

func ComputeValidity

func ComputeValidity(nb, na, now time.Time, warningDays int) Validity

ComputeValidity evaluates the validity window at now.

type VerifyOptions

type VerifyOptions struct {
	Roots         *x509.CertPool // nil: system roots
	Intermediates []*x509.Certificate
	Hostname      string
	Now           time.Time
	// KeyUsages defaults to any; TLS callers pass ServerAuth.
	KeyUsages []x509.ExtKeyUsage
}

VerifyOptions control Verify.

type VerifyResult

type VerifyResult struct {
	Trusted bool `json:"trusted"`
	// Missing lists intermediates the verifier had to supply itself (for
	// example fetched via AIA by the macOS or Windows platform verifier):
	// the presented chain is incomplete even though validation succeeded.
	Missing []string `json:"missing_intermediates,omitempty"`
	Chain   []string `json:"chain,omitempty"` // subjects, leaf first, of the first verified chain
	Error   string   `json:"error,omitempty"`
	Reason  string   `json:"reason,omitempty"` // expired, unknown_authority, hostname_mismatch, invalid, ...
}

VerifyResult summarises chain validation.

func Verify

func Verify(leaf *x509.Certificate, opts VerifyOptions) VerifyResult

Verify validates leaf against the trust store.

Jump to

Keyboard shortcuts

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