internal

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnnotateInspectTrust added in v0.8.0

func AnnotateInspectTrust(results []InspectResult) error

AnnotateInspectTrust sets the Expired and Trusted fields on certificate results using Mozilla roots for chain verification. Intermediate certificates found in the results are used to build chains.

func ArchiveFormat added in v0.6.0

func ArchiveFormat(path string) string

ArchiveFormat returns the archive format for the given path based on its extension, or "" if the path is not a recognized archive. Handles compound extensions like ".tar.gz" before checking single extensions.

func AssignBundleNames added in v0.7.0

func AssignBundleNames(store *certstore.MemStore, configs []BundleConfig)

AssignBundleNames iterates all certificates in the store and assigns bundle names based on the provided bundle configurations. Call this after ingestion is complete to avoid per-cert overhead during scanning.

func CertAnnotation added in v0.8.0

func CertAnnotation(expired, untrusted int) string

CertAnnotation returns a parenthetical annotation like " (2 expired, 1 untrusted)" for non-zero counts, or an empty string if both are zero.

func ExportBundles

func ExportBundles(ctx context.Context, input ExportBundlesInput) error

ExportBundles iterates over bundle names in the store, finds matching certificates and keys, builds certificate bundles, and writes output files.

func FormatDiagnoses added in v0.8.2

func FormatDiagnoses(diags []Diagnosis) string

FormatDiagnoses formats a slice of Diagnosis as human-readable text.

func FormatInspectResults

func FormatInspectResults(results []InspectResult, format string) (string, error)

FormatInspectResults formats inspection results as text or JSON.

func FormatScanTextSummary added in v0.8.2

func FormatScanTextSummary(input ScanTextSummaryInput) string

FormatScanTextSummary renders the user-facing scan summary for text output.

func FormatVerifyResult

func FormatVerifyResult(r *VerifyResult) string

FormatVerifyResult formats a verify result as human-readable text. When verbose fields are populated (non-empty), they are included in the output.

func GenerateKey

func GenerateKey(input GenerateKeyInput) (crypto.Signer, error)

GenerateKey creates a new crypto.Signer based on algorithm, bits, and curve.

func IsArchive added in v0.6.0

func IsArchive(path string) bool

IsArchive reports whether the given path has a recognized archive extension.

func IsSkippableDir added in v0.6.0

func IsSkippableDir(name string) bool

IsSkippableDir reports whether the given directory name should be skipped during scanning because it cannot contain useful certificate or key files.

func LoadPasswordsFromFile

func LoadPasswordsFromFile(filename string) ([]string, error)

LoadPasswordsFromFile loads passwords from a file, one password per line.

func ParseLogLevel

func ParseLogLevel(level string) slog.Level

ParseLogLevel converts a string log level name to a slog.Level. Recognized values: "debug", "info", "warning"/"warn", "error". Defaults to slog.LevelInfo for unrecognized values.

func ProcessArchive added in v0.6.0

func ProcessArchive(input ProcessArchiveInput) (int, error)

ProcessArchive extracts entries from an archive and processes each one for certificates, keys, and CSRs. Returns the number of entries processed and any error. Archives inside archives are not recursed into (depth 1 only).

func ProcessData added in v0.6.0

func ProcessData(input ProcessDataInput) error

ProcessData ingests certificates, keys, or CSRs from in-memory data. The virtualPath identifies the data source for logging (may be a real path or a synthetic path like "archive.zip:certs/server.pem"). All certificates are ingested regardless of expiry — expired filtering is an output concern.

func ProcessFile

func ProcessFile(input ProcessFileInput) error

ProcessFile reads a file (or stdin when path is "-") and ingests any certificates, keys, or CSRs it contains into the store.

func ProcessPasswords

func ProcessPasswords(passwordList []string, passwordFile string) ([]string, error)

ProcessPasswords loads passwords from CLI flags and optional file, merges with defaults, and deduplicates. Delegates core logic to certkit.DeduplicatePasswords.

func ProcessUserPasswords added in v0.8.2

func ProcessUserPasswords(passwordList []string, passwordFile string) ([]string, error)

ProcessUserPasswords returns only explicitly provided non-empty passwords. Unlike ProcessPasswords, it does not inject built-in defaults.

func ReadFileLimited added in v0.8.2

func ReadFileLimited(path string, maxBytes int64) ([]byte, error)

ReadFileLimited reads a file with an optional hard byte limit.

func SetupLogger

func SetupLogger(level string)

SetupLogger configures the default slog logger with the given level string.

func WalkScanFiles added in v0.8.2

func WalkScanFiles(input WalkScanFilesInput) error

WalkScanFiles iterates scan-eligible files under RootPath.

Types

type ArchiveLimits added in v0.6.0

type ArchiveLimits struct {
	// MaxDecompressionRatio is the maximum allowed ratio of uncompressed to
	// compressed size for a single ZIP entry. TAR entries are not ratio-checked
	// because TAR stores uncompressed data. A ratio of 100 means a 1KB
	// compressed entry may decompress to at most 100KB.
	MaxDecompressionRatio int64

	// MaxTotalSize is the maximum total bytes that may be extracted from a
	// single archive across all entries.
	MaxTotalSize int64

	// MaxEntryCount is the maximum number of entries that will be processed
	// from a single archive. Legitimate certificate archives rarely exceed
	// a few hundred entries.
	MaxEntryCount int

	// MaxEntrySize is the maximum allowed size of a single decompressed entry.
	// Entries exceeding this are skipped. Typically set from --max-file-size.
	MaxEntrySize int64
}

ArchiveLimits controls zip bomb protection thresholds.

func DefaultArchiveLimits added in v0.6.0

func DefaultArchiveLimits() ArchiveLimits

DefaultArchiveLimits returns conservative defaults for archive extraction.

type BundleConfig

type BundleConfig struct {
	CommonNames []string       `yaml:"commonNames"`
	BundleName  string         `yaml:"bundleName"`
	Subject     *SubjectConfig `yaml:"subject,omitempty"`
}

BundleConfig represents one bundle configuration entry from the YAML file.

func LoadBundleConfigs

func LoadBundleConfigs(path string) ([]BundleConfig, error)

LoadBundleConfigs loads bundle configuration from the specified YAML file.

type BundlesYAML

type BundlesYAML struct {
	DefaultSubject *SubjectConfig `yaml:"defaultSubject,omitempty"`
	Bundles        []BundleConfig `yaml:"bundles"`
}

BundlesYAML represents the full YAML structure with defaults and bundles

type CSROptions

type CSROptions struct {
	TemplatePath string // JSON template file
	CertPath     string // PEM cert as template
	CSRPath      string // PEM CSR as template

	KeyPath   string // Existing key (PEM)
	Algorithm string // rsa, ecdsa, ed25519 (default: ecdsa)
	Bits      int    // RSA bits (default: 4096)
	Curve     string // ECDSA curve (default: P-256)

	OutPath   string   // Output directory (default: ".")
	Passwords []string // Passwords for encrypted keys
}

CSROptions holds parameters for CSR generation from various sources.

type CSRResult

type CSRResult struct {
	CSRPEM  string
	KeyPEM  string // empty if existing key was provided
	CSRFile string // empty in stdout mode
	KeyFile string // empty in stdout mode
}

CSRResult holds the PEM output and optional file paths from GenerateCSRFiles. When OutPath is empty, only PEM fields are populated (stdout mode). When OutPath is set, files are written and file path fields are populated.

func GenerateCSRFiles

func GenerateCSRFiles(opts CSROptions) (*CSRResult, error)

GenerateCSRFiles generates a CSR from the specified source and writes csr.pem and optionally key.pem to the output directory.

type ChainCert added in v0.3.5

type ChainCert struct {
	Subject  string `json:"subject"`
	NotAfter string `json:"not_after"`
	SKI      string `json:"subject_key_id,omitempty"`
	IsRoot   bool   `json:"is_root,omitempty"`

	// Verbose-only fields (populated when VerifyInput.Verbose is true).
	Issuer    string   `json:"issuer,omitempty"`
	Serial    string   `json:"serial,omitempty"`
	NotBefore string   `json:"not_before,omitempty"`
	CertType  string   `json:"cert_type,omitempty"`
	KeyAlgo   string   `json:"key_algorithm,omitempty"`
	KeySize   string   `json:"key_size,omitempty"`
	SigAlg    string   `json:"signature_algorithm,omitempty"`
	KeyUsages []string `json:"key_usages,omitempty"`
	EKUs      []string `json:"ekus,omitempty"`
	SHA256    string   `json:"sha256_fingerprint,omitempty"`
	SHA1      string   `json:"sha1_fingerprint,omitempty"`
	AKI       string   `json:"authority_key_id,omitempty"`
}

ChainCert holds display information for one certificate in the chain.

type ContainerContents added in v0.3.4

type ContainerContents = certstore.ContainerContents

ContainerContents is an alias for certstore.ContainerContents.

func LoadContainerFile added in v0.3.4

func LoadContainerFile(path string, passwords []string) (*ContainerContents, error)

LoadContainerFile reads a file and attempts to parse it as PKCS#12, JKS, PKCS#7, PEM, or DER. Returns the leaf certificate, optional private key, and any extra certificates (intermediates/CA certs).

type DiagnoseChainInput added in v0.8.2

type DiagnoseChainInput struct {
	// Cert is the leaf certificate to diagnose.
	Cert *x509.Certificate
	// ExtraCerts are intermediate certificates provided alongside the leaf.
	ExtraCerts []*x509.Certificate
}

DiagnoseChainInput holds the parameters for chain diagnostics.

type Diagnosis added in v0.8.2

type Diagnosis struct {
	// Check is a short label for the diagnostic (e.g. "expired", "self-signed").
	Check string `json:"check"`
	// Status is "pass", "error", or "warn".
	Status string `json:"status"`
	// Detail is a human-readable explanation.
	Detail string `json:"detail"`
}

Diagnosis describes one diagnostic finding when chain verification fails.

func DiagnoseChain added in v0.8.2

func DiagnoseChain(input DiagnoseChainInput) []Diagnosis

DiagnoseChain analyzes why chain verification might fail, returning a list of diagnostic findings. It checks for expiry, not-yet-valid, self-signed leaf, missing intermediates, and weak signatures.

type ExportBundlesInput added in v0.8.2

type ExportBundlesInput struct {
	Configs     []BundleConfig
	OutDir      string
	Store       *certstore.MemStore
	ForceBundle bool
	Duplicates  bool
	P12Password string
}

ExportBundlesInput holds parameters for ExportBundles.

type GenerateKeyInput added in v0.8.2

type GenerateKeyInput struct {
	Algorithm string
	Bits      int
	Curve     string
}

GenerateKeyInput holds parameters for GenerateKey.

type InspectResult

type InspectResult struct {
	Type      string   `json:"type"`
	Subject   string   `json:"subject,omitempty"`
	Issuer    string   `json:"issuer,omitempty"`
	Serial    string   `json:"serial,omitempty"`
	NotBefore string   `json:"not_before,omitempty"`
	NotAfter  string   `json:"not_after,omitempty"`
	CertType  string   `json:"cert_type,omitempty"`
	Expired   *bool    `json:"expired,omitempty"`
	Trusted   *bool    `json:"trusted,omitempty"`
	IsCA      *bool    `json:"is_ca,omitempty"`
	KeyAlgo   string   `json:"key_algorithm,omitempty"`
	KeySize   string   `json:"key_size,omitempty"`
	SANs      []string `json:"sans,omitempty"`
	KeyUsages []string `json:"key_usages,omitempty"`
	EKUs      []string `json:"ekus,omitempty"`
	SHA256    string   `json:"sha256_fingerprint,omitempty"`
	SHA1      string   `json:"sha1_fingerprint,omitempty"`
	SKI       string   `json:"subject_key_id,omitempty"`
	SKILegacy string   `json:"subject_key_id_sha1,omitempty"`
	AKI       string   `json:"authority_key_id,omitempty"`
	SigAlg    string   `json:"signature_algorithm,omitempty"`
	KeyType   string   `json:"key_type,omitempty"`

	// AIAFetched indicates the certificate was resolved via AIA, not from user input.
	AIAFetched bool `json:"aia_fetched,omitempty"`

	// CSR-specific fields. Populated only when Type == "csr".
	CSRSubject string `json:"csr_subject,omitempty"`
	// contains filtered or unexported fields
}

InspectResult holds the inspection details for a single certificate, key, or CSR.

func InspectData added in v0.8.1

func InspectData(data []byte, passwords []string) []InspectResult

InspectData parses raw bytes and returns inspection results for all certificates, keys, and CSRs found. It tries PEM first, then DER and container formats (PKCS#12, PKCS#7, JKS).

func InspectFile

func InspectFile(path string, passwords []string) ([]InspectResult, error)

InspectFile reads a file and returns inspection results for all objects found.

func ResolveInspectAIA added in v0.8.1

func ResolveInspectAIA(ctx context.Context, input ResolveInspectAIAInput) ([]InspectResult, []string)

ResolveInspectAIA fetches missing intermediate certificates via AIA for the given inspect results. It creates a temporary MemStore, adds all certificates from the results, resolves AIA using the provided fetcher, inspects any newly fetched certificates, and returns the extended results along with warnings.

type KeygenOptions

type KeygenOptions struct {
	Algorithm string
	Bits      int
	Curve     string
	OutPath   string
	CN        string
	SANs      []string
}

KeygenOptions holds parameters for key and CSR generation.

type KeygenResult

type KeygenResult struct {
	KeyPEM  string
	PubPEM  string
	CSRPEM  string // empty if no CSR generated
	KeyFile string // empty in stdout mode
	PubFile string // empty in stdout mode
	CSRFile string // empty in stdout mode
}

KeygenResult holds the PEM output and optional file paths from GenerateKeyFiles. When OutPath is empty, only PEM fields are populated (stdout mode). When OutPath is set, files are written and file path fields are populated.

func GenerateKeyFiles

func GenerateKeyFiles(opts KeygenOptions) (*KeygenResult, error)

GenerateKeyFiles generates a key pair and optionally a CSR, writing them to the output path.

type PasswordSets added in v0.8.2

type PasswordSets struct {
	Decode []string
	Export []string
}

PasswordSets holds decode and export password lists.

func ProcessPasswordSets added in v0.8.2

func ProcessPasswordSets(passwordList []string, passwordFile string) (PasswordSets, error)

ProcessPasswordSets loads password inputs once and returns both decode and export password sets.

type ProcessArchiveInput added in v0.6.0

type ProcessArchiveInput struct {
	ArchivePath string
	Data        []byte
	Format      string
	Limits      ArchiveLimits
	Store       *certstore.MemStore
	Passwords   []string
}

ProcessArchiveInput holds the parameters for archive processing.

type ProcessDataInput added in v0.8.2

type ProcessDataInput struct {
	Data        []byte
	VirtualPath string
	Store       *certstore.MemStore
	Passwords   []string
	MaxBytes    int64 // 0 means no limit
}

ProcessDataInput holds parameters for ProcessData.

type ProcessFileInput added in v0.8.2

type ProcessFileInput struct {
	Path      string
	Store     *certstore.MemStore
	Passwords []string
	MaxBytes  int64 // 0 means no limit
}

ProcessFileInput holds parameters for ProcessFile.

type ResolveInspectAIAInput added in v0.8.2

type ResolveInspectAIAInput struct {
	Results              []InspectResult
	Fetch                certstore.AIAFetcher
	AllowPrivateNetworks bool
}

ResolveInspectAIAInput holds parameters for ResolveInspectAIA.

type ScanTextSummaryInput added in v0.8.2

type ScanTextSummaryInput struct {
	Roots                  int
	Intermediates          int
	Leaves                 int
	Keys                   int
	Matched                int
	ExpiredRoots           int
	ExpiredIntermediates   int
	ExpiredLeaves          int
	UntrustedRoots         int
	UntrustedIntermediates int
	UntrustedLeaves        int
}

ScanTextSummaryInput holds fields needed for text scan summaries.

type SubjectConfig

type SubjectConfig struct {
	Country            []string `yaml:"country,omitempty"`            // C
	Province           []string `yaml:"province,omitempty"`           // ST
	Locality           []string `yaml:"locality,omitempty"`           // L
	Organization       []string `yaml:"organization,omitempty"`       // O
	OrganizationalUnit []string `yaml:"organizationalUnit,omitempty"` // OU
}

SubjectConfig represents the X.509 subject fields for certificates

type VerifyInput added in v0.3.4

type VerifyInput struct {
	Cert                 *x509.Certificate
	Key                  crypto.PrivateKey
	ExtraCerts           []*x509.Certificate
	CustomRoots          []*x509.Certificate
	CheckKeyMatch        bool
	CheckChain           bool
	ExpiryDuration       time.Duration
	TrustStore           string
	Verbose              bool
	CheckOCSP            bool
	CheckCRL             bool
	AllowPrivateNetworks bool
}

VerifyInput holds the parsed certificate data and verification options.

type VerifyResult

type VerifyResult struct {
	Subject     string                  `json:"subject"`
	SANs        []string                `json:"sans,omitempty"`
	NotAfter    string                  `json:"not_after"`
	SKI         string                  `json:"subject_key_id,omitempty"`
	KeyMatch    *bool                   `json:"key_match,omitempty"`
	KeyMatchErr string                  `json:"key_match_error,omitempty"`
	KeyInfo     string                  `json:"key_info,omitempty"`
	ChainValid  *bool                   `json:"chain_valid,omitempty"`
	ChainErr    string                  `json:"chain_error,omitempty"`
	Chain       []ChainCert             `json:"chain,omitempty"`
	OCSP        *certkit.OCSPResult     `json:"ocsp,omitempty"`
	CRL         *certkit.CRLCheckResult `json:"crl,omitempty"`
	Expiry      *bool                   `json:"expires_within,omitempty"`
	ExpiryInfo  string                  `json:"expiry_info,omitempty"`
	Errors      []string                `json:"errors,omitempty"`
	Diagnostics []Diagnosis             `json:"diagnostics,omitempty"`

	// Verbose-only fields (populated when VerifyInput.Verbose is true).
	Issuer    string   `json:"issuer,omitempty"`
	Serial    string   `json:"serial,omitempty"`
	NotBefore string   `json:"not_before,omitempty"`
	CertType  string   `json:"cert_type,omitempty"`
	IsCA      *bool    `json:"is_ca,omitempty"`
	KeyAlgo   string   `json:"key_algorithm,omitempty"`
	KeySize   string   `json:"key_size,omitempty"`
	SigAlg    string   `json:"signature_algorithm,omitempty"`
	KeyUsages []string `json:"key_usages,omitempty"`
	EKUs      []string `json:"ekus,omitempty"`
	SHA256    string   `json:"sha256_fingerprint,omitempty"`
	SHA1      string   `json:"sha1_fingerprint,omitempty"`
	AKI       string   `json:"authority_key_id,omitempty"`
}

VerifyResult holds the results of certificate verification checks.

func VerifyCert

func VerifyCert(ctx context.Context, input *VerifyInput) (*VerifyResult, error)

VerifyCert verifies a certificate with optional key matching, chain validation, and expiry checking.

type WalkScanFilesInput added in v0.8.2

type WalkScanFilesInput struct {
	RootPath    string
	MaxFileSize int64
	OnFile      func(path string) error
}

WalkScanFilesInput configures WalkScanFiles.

Directories

Path Synopsis
Package certstore provides a shared certificate and key processing pipeline used by both the CLI and WASM builds.
Package certstore provides a shared certificate and key processing pipeline used by both the CLI and WASM builds.

Jump to

Keyboard shortcuts

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