certcommon

package
v0.0.0-...-cf30d46 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultKeySize is the default RSA key size
	DefaultKeySize = 2048

	// DefaultOrganization is the default organization name
	DefaultOrganization = "Wazuh"

	// DefaultOrganizationalUnit is the default organizational unit
	DefaultOrganizationalUnit = "Security"

	// DefaultCountry is the default country code
	DefaultCountry = "US"

	// DefaultState is the default state/province
	DefaultState = "California"

	// DefaultLocality is the default city/locality
	DefaultLocality = "San Francisco"

	// DefaultAdminCommonName is the default common name for admin certificates
	DefaultAdminCommonName = "admin"
)
View Source
const (
	// DefaultCAValidityStr is the default CA validity as a duration string
	DefaultCAValidityStr = "3650d" // 10 years

	// DefaultNodeValidityStr is the default node certificate validity
	DefaultNodeValidityStr = "365d" // 1 year

	// DefaultCARenewalThresholdStr is the default CA renewal threshold
	DefaultCARenewalThresholdStr = "60d"

	// DefaultNodeRenewalThresholdStr is the default node certificate renewal threshold
	DefaultNodeRenewalThresholdStr = "30d"
)

Default durations as strings (for CRD defaults)

Variables

View Source
var ErrInvalidCertificatePEM = errors.New("invalid certificate PEM data")

ErrInvalidCertificatePEM is returned when the certificate PEM data is invalid.

Functions

func AdminDN

func AdminDN(opts DNOptions) string

AdminDN returns the admin Distinguished Name using the given options

func CertificateDomainMismatch

func CertificateDomainMismatch(cert *x509.Certificate) bool

CertificateDomainMismatch checks if a certificate's SANs match the configured cluster domain. Returns true if any SAN contains a Kubernetes FQDN with a different cluster domain suffix.

This function examines DNS names in the certificate looking for patterns like:

  • service.namespace.svc.cluster.local
  • pod.service.namespace.svc.cluster.local

If the domain after ".svc." doesn't match the configured dns.ClusterDomain(), it indicates a mismatch that requires certificate regeneration.

func ConvertPrivateKeyPEMToPKCS8

func ConvertPrivateKeyPEMToPKCS8(keyPEM []byte) ([]byte, error)

ConvertPrivateKeyPEMToPKCS8 converts a supported private key PEM (PKCS#1 RSA, SEC1 EC, or PKCS#8) to PKCS#8 PEM format.

func DaysFromDuration

func DaysFromDuration(d time.Duration) int

DaysFromDuration converts a time.Duration to days (rounded down)

func DefaultAdminDN

func DefaultAdminDN() string

DefaultAdminDN returns the default Distinguished Name for admin certificates

func DefaultNodesDN

func DefaultNodesDN() string

DefaultNodesDN returns the default Distinguished Name pattern for node certificates Uses wildcard CN=* to match any node certificate

func DurationFromDays

func DurationFromDays(days int) time.Duration

DurationFromDays converts days to time.Duration

func DurationFromHours

func DurationFromHours(hours int) time.Duration

DurationFromHours converts hours to time.Duration

func DurationFromMinutes

func DurationFromMinutes(minutes int) time.Duration

DurationFromMinutes converts minutes to time.Duration

func EncodePrivateKeyToPEM

func EncodePrivateKeyToPEM(key crypto.PrivateKey) ([]byte, error)

EncodePrivateKeyToPEM encodes a private key to PEM format Uses PKCS#8 format for ECDSA keys for OpenSearch compatibility

func ExtractDomainFromSAN

func ExtractDomainFromSAN(san string) (string, bool)

ExtractDomainFromSAN extracts the cluster domain from a Kubernetes FQDN SAN. Returns the domain and true if extraction was successful, or empty string and false otherwise.

The function finds the LAST occurrence of ".svc." to correctly handle edge cases where the service or namespace name might contain "svc" as a substring.

Examples:

  • "my-service.my-ns.svc.cluster.local" -> "cluster.local", true
  • "my-pod.my-svc.my-ns.svc.custom.domain" -> "custom.domain", true
  • "pod.svc.ns.svc.cluster.local" -> "cluster.local", true (service named "svc")
  • "localhost" -> "", false
  • "external.example.com" -> "", false

func FormatCertDuration

func FormatCertDuration(d time.Duration) string

FormatCertDuration formats a time.Duration as a human-readable string Uses the most appropriate unit (days, hours, or minutes)

func FormatDN

func FormatDN(commonName, ou, org, locality, state, country string) string

FormatDN formats a Distinguished Name string from the given components Format: CN={commonName},OU={ou},O={org},L={locality},ST={state},C={country}

func GeneratePrivateKey

func GeneratePrivateKey(algorithm KeyAlgorithm, keySize int, curve ECDSACurve) (crypto.PrivateKey, error)

GeneratePrivateKey generates a private key based on the algorithm

func GenerateSerialNumber

func GenerateSerialNumber() (*big.Int, error)

GenerateSerialNumber generates a random serial number for certificates

func GetCertificateExpiry

func GetCertificateExpiry(certPEM []byte) (time.Time, error)

GetCertificateExpiry extracts the expiry time from a PEM-encoded certificate

func GetCurve

func GetCurve(curve ECDSACurve) elliptic.Curve

GetCurve returns the elliptic.Curve for the given ECDSACurve

func GetPublicKey

func GetPublicKey(key crypto.PrivateKey) crypto.PublicKey

GetPublicKey extracts the public key from a private key

func HoursFromDuration

func HoursFromDuration(d time.Duration) int

HoursFromDuration converts a time.Duration to hours (rounded down)

func MinutesFromDuration

func MinutesFromDuration(d time.Duration) int

MinutesFromDuration converts a time.Duration to minutes (rounded down)

func MustParseCertDuration

func MustParseCertDuration(s string) time.Duration

MustParseCertDuration parses a duration string and panics on error Use only for known-good values (e.g., constants)

func NodesDN

func NodesDN(opts DNOptions) string

NodesDN returns the nodes Distinguished Name pattern using the given options Uses wildcard CN=* to match any node certificate

func ParseCertDuration

func ParseCertDuration(s string) (time.Duration, error)

ParseCertDuration parses a duration string like "365d", "24h", "30m" Supported units:

  • d: days (24 hours)
  • h: hours
  • m: minutes

Examples: "365d" (1 year), "24h" (1 day), "30m" (30 minutes), "10m" (10 minutes) Returns the duration as time.Duration

func ParseCertificateFromPEM

func ParseCertificateFromPEM(certPEM []byte) (*x509.Certificate, error)

ParseCertificateFromPEM parses a PEM-encoded certificate and returns the x509.Certificate. This is a convenience wrapper for certificate domain validation.

func ParsePrivateKeyFromPEM

func ParsePrivateKeyFromPEM(keyPEM []byte) (crypto.PrivateKey, error)

ParsePrivateKeyFromPEM parses a private key from PEM data

func RequiresDomainRegeneration

func RequiresDomainRegeneration(cert *x509.Certificate, secretName, namespace string, log logr.Logger) bool

RequiresDomainRegeneration checks if a certificate needs regeneration due to domain mismatch. If a mismatch is detected, it logs detailed information for audit purposes.

Parameters:

  • cert: The x509 certificate to validate
  • secretName: Name of the secret containing the certificate (for logging)
  • namespace: Namespace of the secret (for logging)
  • log: Logger for audit trail

Returns true if the certificate should be regenerated due to domain mismatch.

Types

type CAConfig

type CAConfig struct {
	CommonName         string
	Organization       string
	OrganizationalUnit string
	Country            string
	State              string
	Locality           string
	Validity           time.Duration // Certificate validity as duration
	KeySize            int           // Only used for RSA
	KeyAlgorithm       KeyAlgorithm
	ECDSACurve         ECDSACurve
}

CAConfig holds configuration for CA certificate generation

func DefaultCAConfig

func DefaultCAConfig(commonName string) *CAConfig

DefaultCAConfig returns a CAConfig with default values

type CAResult

type CAResult struct {
	Certificate    *x509.Certificate
	PrivateKey     crypto.PrivateKey
	CertificatePEM []byte
	PrivateKeyPEM  []byte
}

CAResult contains the generated CA certificate and private key

func GenerateCA

func GenerateCA(config *CAConfig) (*CAResult, error)

GenerateCA generates a new CA certificate and private key

func ParseCA

func ParseCA(certPEM, keyPEM []byte) (*CAResult, error)

ParseCA parses a CA certificate and private key from PEM data

func (*CAResult) DaysUntilExpiry

func (ca *CAResult) DaysUntilExpiry() int

DaysUntilExpiry returns the number of days until the certificate expires

func (*CAResult) GetCertificate

func (ca *CAResult) GetCertificate() *x509.Certificate

GetCertificate returns the x509 certificate

func (*CAResult) GetCertificatePEM

func (ca *CAResult) GetCertificatePEM() []byte

GetCertificatePEM returns the PEM-encoded certificate

func (*CAResult) GetPrivateKey

func (ca *CAResult) GetPrivateKey() crypto.PrivateKey

GetPrivateKey returns the private key

func (*CAResult) GetPrivateKeyPEM

func (ca *CAResult) GetPrivateKeyPEM() []byte

GetPrivateKeyPEM returns the PEM-encoded private key

func (*CAResult) IsExpired

func (ca *CAResult) IsExpired() bool

IsExpired checks if the CA certificate is expired

func (*CAResult) NeedsRenewal

func (ca *CAResult) NeedsRenewal(threshold time.Duration) bool

NeedsRenewal checks if the CA certificate needs renewal The threshold parameter specifies how long before expiry to trigger renewal

type CertificateResult

type CertificateResult interface {
	// IsExpired checks if the certificate has expired
	IsExpired() bool
	// NeedsRenewal checks if the certificate needs renewal given a threshold duration
	NeedsRenewal(threshold time.Duration) bool
	// DaysUntilExpiry returns the number of days until the certificate expires
	DaysUntilExpiry() int
	// GetCertificate returns the x509 certificate
	GetCertificate() *x509.Certificate
	// GetPrivateKey returns the private key
	GetPrivateKey() crypto.PrivateKey
	// GetCertificatePEM returns the PEM-encoded certificate
	GetCertificatePEM() []byte
	// GetPrivateKeyPEM returns the PEM-encoded private key
	GetPrivateKeyPEM() []byte
}

CertificateResult is the common interface for all certificate generation results. All certificate types (CA, Node, Admin, Dashboard, Filebeat) implement this interface.

type DNOptions

type DNOptions struct {
	CommonName         string // Usually auto-generated, only used internally
	OrganizationalUnit string
	Organization       string
	Locality           string
	State              string
	Country            string
}

DNOptions holds the options for generating Distinguished Names Note: CommonName is typically auto-generated based on certificate type:

  • CA: "<cluster>-ca"
  • Indexer nodes: "<cluster>-indexer"
  • Admin: "admin" (required by OpenSearch security plugin)
  • Dashboard: "<cluster>-dashboard"
  • Filebeat: "<cluster>-filebeat"

func DefaultDNOptions

func DefaultDNOptions() DNOptions

DefaultDNOptions returns the default DN options

type DomainValidationResult

type DomainValidationResult struct {
	// HasMismatch indicates if the certificate has SANs with a different cluster domain
	HasMismatch bool
	// ExpectedDomain is the configured cluster domain
	ExpectedDomain string
	// MismatchedSANs contains the SANs that don't match the expected domain
	MismatchedSANs []string
	// ActualDomains contains the domains found in the certificate SANs
	ActualDomains []string
}

DomainValidationResult contains the result of a certificate domain validation.

func ValidateCertificateDomain

func ValidateCertificateDomain(cert *x509.Certificate) DomainValidationResult

ValidateCertificateDomain performs a detailed validation of certificate SANs against the configured cluster domain. Returns a DomainValidationResult with details about any mismatches found.

type ECDSACurve

type ECDSACurve string

ECDSACurve represents the elliptic curve used for ECDSA

const (
	// ECDSACurveP256 uses the P-256 curve (also known as secp256r1 or prime256v1)
	// Provides ~128 bits of security
	ECDSACurveP256 ECDSACurve = "P256"
	// ECDSACurveP384 uses the P-384 curve (also known as secp384r1)
	// Provides ~192 bits of security
	ECDSACurveP384 ECDSACurve = "P384"
	// ECDSACurveP521 uses the P-521 curve (also known as secp521r1)
	// Provides ~256 bits of security (highest level)
	ECDSACurveP521 ECDSACurve = "P521"
)

type KeyAlgorithm

type KeyAlgorithm string

KeyAlgorithm represents the algorithm used for key generation

const (
	// KeyAlgorithmRSA uses RSA for key generation (default)
	KeyAlgorithmRSA KeyAlgorithm = "RSA"
	// KeyAlgorithmECDSA uses ECDSA for key generation
	KeyAlgorithmECDSA KeyAlgorithm = "ECDSA"
)

Jump to

Keyboard shortcuts

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