util

package
v0.0.0-...-8f21e7d Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: Apache-2.0 Imports: 24 Imported by: 254

Documentation

Index

Constants

View Source
const (
	// only ECDSA is currently supported
	EcdsaSigAlg SupportedECSignatureAlgorithms = "ECDSA"

	// supported curves when using ECC
	P256Curve SupportedEllipticCurves = "P256"
	P384Curve SupportedEllipticCurves = "P384"
)
View Source
const ClockSkewGracePeriod = time.Minute * 2

ClockSkewGracePeriod defines the period of time a certificate will be valid before its creation. This is meant to handle cases where we have clock skew between the CA and workloads.

View Source
const MinimumRsaKeySize = 2048

MinimumRsaKeySize is the minimum RSA key size to generate certificates to ensure proper security

Variables

View Source
var (

	// OidSubjectAlternativeName The OID for the SAN extension (See
	// http://www.alvestrand.no/objectid/2.5.29.17.html).
	OidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
)

Functions

func AppendCertByte

func AppendCertByte(pemCert []byte, rootCert []byte) []byte

AppendCertByte: Append x.509 rootCert in bytes to existing certificate chain (in bytes)

func AppendRootCerts

func AppendRootCerts(pemCert []byte, rootCertFile string) ([]byte, error)

AppendRootCerts appends root certificates in RootCertFile to the input certificate.

func BuildSANExtension

func BuildSANExtension(identites []Identity) (*pkix.Extension, error)

BuildSANExtension builds a `pkix.Extension` of type "Subject Alternative Name" based on the given identities.

func BuildSubjectAltNameExtension

func BuildSubjectAltNameExtension(hosts string) (*pkix.Extension, error)

BuildSubjectAltNameExtension builds the SAN extension for the certificate.

func DualUseCommonName

func DualUseCommonName(host string) (string, error)

DualUseCommonName extracts a valid CommonName from a comma-delimited host string for dual-use certificates.

func ExtractIDs

func ExtractIDs(exts []pkix.Extension) ([]string, error)

ExtractIDs first finds the SAN extension from the given extension set, then extract identities from the SAN extension.

func ExtractSANExtension

func ExtractSANExtension(exts []pkix.Extension) *pkix.Extension

ExtractSANExtension extracts the "Subject Alternative Name" externsion from the given PKIX extension set.

func FindRootCertFromCertificateChainBytes

func FindRootCertFromCertificateChainBytes(certBytes []byte) ([]byte, error)

FindRootCertFromCertificateChainBytes find the root cert from cert chain

func GenCSR

func GenCSR(options CertOptions) ([]byte, []byte, error)

GenCSR generates a X.509 certificate sign request and private key with the given options.

func GenCSRTemplate

func GenCSRTemplate(options CertOptions) (*x509.CertificateRequest, error)

GenCSRTemplate generates a certificateRequest template with the given options.

func GenCertFromCSR

func GenCertFromCSR(csr *x509.CertificateRequest, signingCert *x509.Certificate, publicKey any,
	signingKey crypto.PrivateKey, subjectIDs []string, ttl time.Duration, isCA bool,
) (cert []byte, err error)

GenCertFromCSR generates a X.509 certificate with the given CSR.

func GenCertKeyFromOptions

func GenCertKeyFromOptions(options CertOptions) (pemCert []byte, pemKey []byte, err error)

GenCertKeyFromOptions generates a X.509 certificate and a private key with the given options.

func GenRootCertFromExistingKey

func GenRootCertFromExistingKey(options CertOptions) (pemCert []byte, pemKey []byte, err error)

GenRootCertFromExistingKey generates a X.509 certificate using existing CA private key. Only called by a self-signed Citadel.

func GetEllipticCurve

func GetEllipticCurve(privKey *crypto.PrivateKey) (elliptic.Curve, error)

GetEllipticCurve returns the type of curve associated with the private key; if ECDSA is used, then only 384 and 256 (default) are returned; if non-ECDSA is used then an error is returned

func GetRSAKeySize

func GetRSAKeySize(privKey crypto.PrivateKey) (int, error)

GetRSAKeySize returns the size if it is RSA key, otherwise it returns an error.

func IsCertExpired

func IsCertExpired(filepath string) (bool, error)

IsCertExpired returns whether a cert expires

func LoadSignerCredsFromFiles

func LoadSignerCredsFromFiles(signerCertFile string, signerPrivFile string) (*x509.Certificate, crypto.PrivateKey, error)

LoadSignerCredsFromFiles loads the signer cert&key from the given files.

signerCertFile: cert file name
signerPrivFile: private key file name

func ParsePemEncodedCSR

func ParsePemEncodedCSR(csrBytes []byte) (*x509.CertificateRequest, error)

ParsePemEncodedCSR constructs a `x509.CertificateRequest` object using the given PEM-encoded certificate signing request.

func ParsePemEncodedCertificate

func ParsePemEncodedCertificate(certBytes []byte) (*x509.Certificate, error)

ParsePemEncodedCertificate constructs a `x509.Certificate` object using the given a PEM-encoded certificate.

func ParsePemEncodedCertificateChain

func ParsePemEncodedCertificateChain(certBytes []byte) ([]*x509.Certificate, []byte, error)

ParsePemEncodedCertificateChain constructs a slice of `x509.Certificate` and `rootCertBytes` objects using the given a PEM-encoded certificate chain.

func ParsePemEncodedKey

func ParsePemEncodedKey(keyBytes []byte) (crypto.PrivateKey, error)

ParsePemEncodedKey takes a PEM-encoded key and parsed the bytes into a `crypto.PrivateKey`.

func PemCertBytestoString

func PemCertBytestoString(caCerts []byte) []string

PemCertBytestoString: takes an array of PEM certs in bytes and returns a string array in the same order with trailing newline characters removed

func TimeBeforeCertExpires

func TimeBeforeCertExpires(certBytes []byte, now time.Time) (time.Duration, error)

TimeBeforeCertExpires returns the time duration before the cert gets expired. It returns an error if it failed to extract the cert expiration timestamp. The returned time duration could be a negative value indicating the cert has already expired.

func Verify

func Verify(certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) error

Verify that the cert chain, root cert and key/cert match.

func VerifyCertificate

func VerifyCertificate(privPem []byte, certChainPem []byte, rootCertPem []byte, expectedFields *VerifyFields) error

VerifyCertificate verifies a given PEM encoded certificate by - building one or more chains from the certificate to a root certificate; - checking fields are set as expected.

Types

type CertOptions

type CertOptions struct {
	// Comma-separated hostnames and IPs to generate a certificate for.
	// This can also be set to the identity running the workload,
	// like kubernetes service account.
	Host string

	// The NotBefore field of the issued certificate.
	NotBefore time.Time

	// TTL of the certificate. NotAfter - NotBefore.
	TTL time.Duration

	// Signer certificate.
	SignerCert *x509.Certificate

	// Signer private key.
	SignerPriv crypto.PrivateKey

	// Signer private key (PEM encoded).
	SignerPrivPem []byte

	// Organization for this certificate.
	Org string

	// The size of RSA private key to be generated.
	RSAKeySize int

	// Whether this certificate is used as signing cert for CA.
	IsCA bool

	// Whether this certificate is self-signed.
	IsSelfSigned bool

	// Whether this certificate is for a client.
	IsClient bool

	// Whether this certificate is for a server.
	IsServer bool

	// Whether this certificate is for dual-use clients (SAN+CN).
	IsDualUse bool

	// If true, the private key is encoded with PKCS#8.
	PKCS8Key bool

	// The type of Elliptical Signature algorithm to use
	// when generating private keys. Currently only ECDSA is supported.
	// If empty, RSA is used, otherwise ECC is used.
	ECSigAlg SupportedECSignatureAlgorithms

	// The type of Elliptical Signature algorithm to use
	// when generating private keys. Currently only ECDSA is supported.
	// If empty, RSA is used, otherwise ECC is used.
	ECCCurve SupportedEllipticCurves

	// Subjective Alternative Name values.
	DNSNames string
}

CertOptions contains options for generating a new certificate.

func GetCertOptionsFromExistingCert

func GetCertOptionsFromExistingCert(certBytes []byte) (opts CertOptions, err error)

GetCertOptionsFromExistingCert parses cert and generates a CertOptions that contains information about the cert. This is the reverse operation of genCertTemplateFromOptions(), and only called by a self-signed Citadel.

func MergeCertOptions

func MergeCertOptions(defaultOpts, deltaOpts CertOptions) CertOptions

MergeCertOptions merges deltaOpts into defaultOpts and returns the merged CertOptions. Only called by a self-signed Citadel.

type Identity

type Identity struct {
	Type  IdentityType
	Value []byte
}

Identity is an object holding both the encoded identifier bytes as well as the type of the identity.

func ExtractIDsFromSAN

func ExtractIDsFromSAN(sanExt *pkix.Extension) ([]Identity, error)

ExtractIDsFromSAN takes a SAN extension and extracts the identities. The logic is mostly borrowed from https://github.com/golang/go/blob/master/src/crypto/x509/x509.go, with the addition of supporting extracting URIs.

type IdentityType

type IdentityType int

IdentityType represents type of an identity. This is used to properly encode an identity into a SAN extension.

const (
	// TypeDNS represents a DNS name.
	TypeDNS IdentityType = iota
	// TypeIP represents an IP address.
	TypeIP
	// TypeURI represents a universal resource identifier.
	TypeURI
)

type KeyCertBundle

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

KeyCertBundle stores the cert, private key, cert chain and root cert for an entity. It is thread safe. The cert and privKey should be a public/private key pair. The cert should be verifiable from the rootCert through the certChain. cert and priveKey are pointers to the cert/key parsed from certBytes/privKeyBytes.

func NewKeyCertBundleFromPem

func NewKeyCertBundleFromPem(certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) *KeyCertBundle

NewKeyCertBundleFromPem returns a new KeyCertBundle, regardless of whether or not the key can be correctly parsed.

func NewKeyCertBundleWithRootCertFromFile

func NewKeyCertBundleWithRootCertFromFile(rootCertFile string) (*KeyCertBundle, error)

NewKeyCertBundleWithRootCertFromFile returns a new KeyCertBundle with the root cert without verification.

func NewVerifiedKeyCertBundleFromFile

func NewVerifiedKeyCertBundleFromFile(certFile string, privKeyFile string, certChainFiles []string, rootCertFile string) (
	*KeyCertBundle, error,
)

NewVerifiedKeyCertBundleFromFile returns a new KeyCertBundle, or error if the provided certs failed the verification.

func NewVerifiedKeyCertBundleFromPem

func NewVerifiedKeyCertBundleFromPem(certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) (
	*KeyCertBundle, error,
)

NewVerifiedKeyCertBundleFromPem returns a new KeyCertBundle, or error if the provided certs failed the verification.

func (*KeyCertBundle) CertOptions

func (b *KeyCertBundle) CertOptions() (*CertOptions, error)

CertOptions returns the certificate config based on currently stored cert.

func (*KeyCertBundle) ExtractCACertExpiryTimestamp

func (b *KeyCertBundle) ExtractCACertExpiryTimestamp() (time.Time, error)

ExtractCACertExpiryTimestamp returns the expiration of the leaf certificate

func (*KeyCertBundle) ExtractRootCertExpiryTimestamp

func (b *KeyCertBundle) ExtractRootCertExpiryTimestamp() (time.Time, error)

ExtractRootCertExpiryTimestamp returns the expiration of the first root cert

func (*KeyCertBundle) GetAll

func (b *KeyCertBundle) GetAll() (cert *x509.Certificate, privKey *crypto.PrivateKey, certChainBytes,
	rootCertBytes []byte,
)

GetAll returns all key/cert in KeyCertBundle together. Getting all values together avoids inconsistency. NOTE: Callers should not modify the content of cert and privKey.

func (*KeyCertBundle) GetAllPem

func (b *KeyCertBundle) GetAllPem() (certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte)

GetAllPem returns all key/cert PEMs in KeyCertBundle together. Getting all values together avoids inconsistency.

func (*KeyCertBundle) GetCertChainPem

func (b *KeyCertBundle) GetCertChainPem() []byte

GetCertChainPem returns the certificate chain PEM.

func (*KeyCertBundle) GetRootCertPem

func (b *KeyCertBundle) GetRootCertPem() []byte

GetRootCertPem returns the root certificate PEM.

func (*KeyCertBundle) UpdateVerifiedKeyCertBundleFromFile

func (b *KeyCertBundle) UpdateVerifiedKeyCertBundleFromFile(certFile string, privKeyFile string, certChainFiles []string, rootCertFile string) error

UpdateVerifiedKeyCertBundleFromFile Verifies and updates KeyCertBundle with new certs

func (*KeyCertBundle) VerifyAndSetAll

func (b *KeyCertBundle) VerifyAndSetAll(certBytes, privKeyBytes, certChainBytes, rootCertBytes []byte) error

VerifyAndSetAll verifies the key/certs, and sets all key/certs in KeyCertBundle together. Setting all values together avoids inconsistency.

type SupportedECSignatureAlgorithms

type SupportedECSignatureAlgorithms string

SupportedECSignatureAlgorithms are the types of EC Signature Algorithms to be used in key generation (e.g. ECDSA or ED2551)

type SupportedEllipticCurves

type SupportedEllipticCurves string

SupportedEllipticCurves are the types of curves to be used in key generation (e.g. P256, P384)

type VerifyFields

type VerifyFields struct {
	NotBefore   time.Time
	TTL         time.Duration // NotAfter - NotBefore
	ExtKeyUsage []x509.ExtKeyUsage
	KeyUsage    x509.KeyUsage
	IsCA        bool
	Org         string
	CommonName  string
	Host        string
}

VerifyFields contains the certificate fields to verify in the test.

Jump to

Keyboard shortcuts

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