certutil

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2021 License: MPL-2.0 Imports: 29 Imported by: 54

Documentation

Overview

Package certutil contains helper functions that are mostly used with the PKI backend but can be generally useful. Functionality includes helpers for converting a certificate/private key bundle between DER and PEM, printing certificate serial numbers, and more.

Functionality specific to the PKI backend includes some types and helper methods to make requesting certificates from the backend easy.

Index

Constants

View Source
const (
	PrivateKeyTypeP521 = "p521"
)

Variables

This section is empty.

Functions

func AddExtKeyUsageOids added in v0.1.11

func AddExtKeyUsageOids(data *CreationBundle, certTemplate *x509.Certificate)

addExtKeyUsageOids adds custom extended key usage OIDs to certificate

func AddKeyUsages added in v0.1.11

func AddKeyUsages(data *CreationBundle, certTemplate *x509.Certificate)

addKeyUsages adds appropriate key usages to the template given the creation information

func AddPolicyIdentifiers added in v0.1.11

func AddPolicyIdentifiers(data *CreationBundle, certTemplate *x509.Certificate)

addPolicyIdentifiers adds certificate policies extension

func ComparePublicKeys

func ComparePublicKeys(key1Iface, key2Iface crypto.PublicKey) (bool, error)

ComparePublicKeys compares two public keys and returns true if they match

func GeneratePrivateKey

func GeneratePrivateKey(keyType string, keyBits int, container ParsedPrivateKeyContainer) error

GeneratePrivateKey generates a private key with the specified type and key bits.

func GeneratePrivateKeyWithRandomSource added in v0.2.0

func GeneratePrivateKeyWithRandomSource(keyType string, keyBits int, container ParsedPrivateKeyContainer, entropyReader io.Reader) error

GeneratePrivateKeyWithRandomSource generates a private key with the specified type and key bits. GeneratePrivateKeyWithRandomSource uses randomness from the entropyReader to generate the private key.

func GenerateSerialNumber

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

GenerateSerialNumber generates a serial number suitable for a certificate

func GenerateSerialNumberWithRandomSource added in v0.2.0

func GenerateSerialNumberWithRandomSource(randReader io.Reader) (*big.Int, error)

GenerateSerialNumberWithRandomSource generates a serial number suitable for a certificate with custom entropy.

func GetHexFormatted

func GetHexFormatted(buf []byte, sep string) string

GetHexFormatted returns the byte buffer formatted in hex with the specified separator between bytes.

func GetSubjKeyID

func GetSubjKeyID(privateKey crypto.Signer) ([]byte, error)

GetSubjKeyID returns the subject key ID, e.g. the SHA1 sum of the marshaled public key

func HandleOtherCSRSANs added in v0.1.11

func HandleOtherCSRSANs(in *x509.CertificateRequest, sans map[string][]string) error

func HandleOtherSANs added in v0.1.11

func HandleOtherSANs(in *x509.Certificate, sans map[string][]string) error

func NewCertPool added in v0.2.0

func NewCertPool(reader io.Reader) (*x509.CertPool, error)

func ParseHexFormatted

func ParseHexFormatted(in, sep string) []byte

ParseHexFormatted returns the raw bytes from a formatted hex string

func ParsePublicKeyPEM

func ParsePublicKeyPEM(data []byte) (interface{}, error)

ParsePublicKeyPEM is used to parse RSA and ECDSA public keys from PEMs

func StringToOid added in v0.1.11

func StringToOid(in string) (asn1.ObjectIdentifier, error)

func ValidateKeyTypeLength added in v0.1.11

func ValidateKeyTypeLength(keyType string, keyBits int) error

Types

type BlockType

type BlockType string

BlockType indicates the serialization format of the key

const (
	PKCS1Block BlockType = "RSA PRIVATE KEY"
	PKCS8Block BlockType = "PRIVATE KEY"
	ECBlock    BlockType = "EC PRIVATE KEY"
)

Well-known formats

type CAInfoBundle added in v0.1.11

type CAInfoBundle struct {
	ParsedCertBundle
	URLs *URLEntries
}

func (*CAInfoBundle) GetCAChain added in v0.1.11

func (b *CAInfoBundle) GetCAChain() []*CertBlock

type CSRBundle

type CSRBundle struct {
	PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"`
	CSR            string         `json:"csr" structs:"csr" mapstructure:"csr"`
	PrivateKey     string         `json:"private_key" structs:"private_key" mapstructure:"private_key"`
}

CSRBundle contains a key type, a PEM-encoded private key, and a PEM-encoded CSR

func (*CSRBundle) ToParsedCSRBundle

func (c *CSRBundle) ToParsedCSRBundle() (*ParsedCSRBundle, error)

ToParsedCSRBundle converts a string-based CSR bundle to a byte-based raw CSR bundle

type CertBlock

type CertBlock struct {
	Certificate *x509.Certificate
	Bytes       []byte
}

CertBlock contains the DER-encoded certificate and the PEM block's byte array

type CertBundle

type CertBundle struct {
	PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"`
	Certificate    string         `json:"certificate" structs:"certificate" mapstructure:"certificate"`
	IssuingCA      string         `json:"issuing_ca" structs:"issuing_ca" mapstructure:"issuing_ca"`
	CAChain        []string       `json:"ca_chain" structs:"ca_chain" mapstructure:"ca_chain"`
	PrivateKey     string         `json:"private_key" structs:"private_key" mapstructure:"private_key"`
	SerialNumber   string         `json:"serial_number" structs:"serial_number" mapstructure:"serial_number"`
}

CertBundle contains a key type, a PEM-encoded private key, a PEM-encoded certificate, and a string-encoded serial number, returned from a successful Issue request

func (*CertBundle) ToPEMBundle

func (c *CertBundle) ToPEMBundle() string

ToPEMBundle converts a string-based certificate bundle to a PEM-based string certificate bundle in trust path order, leaf certificate first

func (*CertBundle) ToParsedCertBundle

func (c *CertBundle) ToParsedCertBundle() (*ParsedCertBundle, error)

ToParsedCertBundle converts a string-based certificate bundle to a byte-based raw certificate bundle

type CertExtKeyUsage added in v0.1.11

type CertExtKeyUsage int
const (
	AnyExtKeyUsage CertExtKeyUsage = 1 << iota
	ServerAuthExtKeyUsage
	ClientAuthExtKeyUsage
	CodeSigningExtKeyUsage
	EmailProtectionExtKeyUsage
	IpsecEndSystemExtKeyUsage
	IpsecTunnelExtKeyUsage
	IpsecUserExtKeyUsage
	TimeStampingExtKeyUsage
	OcspSigningExtKeyUsage
	MicrosoftServerGatedCryptoExtKeyUsage
	NetscapeServerGatedCryptoExtKeyUsage
	MicrosoftCommercialCodeSigningExtKeyUsage
	MicrosoftKernelCodeSigningExtKeyUsage
)

type ClusterKeyParams

type ClusterKeyParams struct {
	Type string   `json:"type" structs:"type" mapstructure:"type"`
	X    *big.Int `json:"x" structs:"x" mapstructure:"x"`
	Y    *big.Int `json:"y" structs:"y" mapstructure:"y"`
	D    *big.Int `json:"d" structs:"d" mapstructure:"d"`
}

This can be one of a few key types so the different params may or may not be filled

type CreationBundle added in v0.1.11

type CreationBundle struct {
	Params        *CreationParameters
	SigningBundle *CAInfoBundle
	CSR           *x509.CertificateRequest
}

type CreationParameters added in v0.1.11

type CreationParameters struct {
	Subject                       pkix.Name
	DNSNames                      []string
	EmailAddresses                []string
	IPAddresses                   []net.IP
	URIs                          []*url.URL
	OtherSANs                     map[string][]string
	IsCA                          bool
	KeyType                       string
	KeyBits                       int
	NotAfter                      time.Time
	KeyUsage                      x509.KeyUsage
	ExtKeyUsage                   CertExtKeyUsage
	ExtKeyUsageOIDs               []string
	PolicyIdentifiers             []string
	BasicConstraintsValidForNonCA bool

	// Only used when signing a CA cert
	UseCSRValues        bool
	PermittedDNSDomains []string

	// URLs to encode into the certificate
	URLs *URLEntries

	// The maximum path length to encode
	MaxPathLength int

	// The duration the certificate will use NotBefore
	NotBeforeDuration time.Duration
}

type IssueData

type IssueData struct {
	TTL        string `json:"ttl" structs:"ttl" mapstructure:"ttl"`
	CommonName string `json:"common_name" structs:"common_name" mapstructure:"common_name"`
	OU         string `json:"ou" structs:"ou" mapstructure:"ou"`
	AltNames   string `json:"alt_names" structs:"alt_names" mapstructure:"alt_names"`
	IPSANs     string `json:"ip_sans" structs:"ip_sans" mapstructure:"ip_sans"`
	CSR        string `json:"csr" structs:"csr" mapstructure:"csr"`
	OtherSANs  string `json:"other_sans" structs:"other_sans" mapstructure:"other_sans"`
}

IssueData is a structure that is suitable for marshaling into a request; either via JSON, or into a map[string]interface{} via the structs package

type ParsedCSRBundle

type ParsedCSRBundle struct {
	PrivateKeyType  PrivateKeyType
	PrivateKeyBytes []byte
	PrivateKey      crypto.Signer
	CSRBytes        []byte
	CSR             *x509.CertificateRequest
}

ParsedCSRBundle contains a key type, a DER-encoded private key, and a DER-encoded certificate request

func CreateCSR added in v0.1.11

func CreateCSR(data *CreationBundle, addBasicConstraints bool) (*ParsedCSRBundle, error)

CreateCSR creates a CSR with the default rand.Reader to generate a cert/keypair. This is currently only meant for use when generating an intermediate certificate.

func CreateCSRWithRandomSource added in v0.2.0

func CreateCSRWithRandomSource(data *CreationBundle, addBasicConstraints bool, randReader io.Reader) (*ParsedCSRBundle, error)

CreateCSRWithRandomSource creates a CSR with a custom io.Reader for randomness to generate a cert/keypair.

func (*ParsedCSRBundle) SetParsedPrivateKey

func (p *ParsedCSRBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte)

SetParsedPrivateKey sets the private key parameters on the bundle

func (*ParsedCSRBundle) ToCSRBundle

func (p *ParsedCSRBundle) ToCSRBundle() (*CSRBundle, error)

ToCSRBundle converts a byte-based raw DER certificate bundle to a PEM-based string certificate bundle

type ParsedCertBundle

type ParsedCertBundle struct {
	PrivateKeyType   PrivateKeyType
	PrivateKeyFormat BlockType
	PrivateKeyBytes  []byte
	PrivateKey       crypto.Signer
	CertificateBytes []byte
	Certificate      *x509.Certificate
	CAChain          []*CertBlock
}

ParsedCertBundle contains a key type, a DER-encoded private key, and a DER-encoded certificate

func CreateCertificate added in v0.1.11

func CreateCertificate(data *CreationBundle) (*ParsedCertBundle, error)

CreateCertificate uses CreationBundle and the default rand.Reader to generate a cert/keypair.

func CreateCertificateWithRandomSource added in v0.2.0

func CreateCertificateWithRandomSource(data *CreationBundle, randReader io.Reader) (*ParsedCertBundle, error)

CreateCertificateWithRandomSource uses CreationBundle and a custom io.Reader for randomness to generate a cert/keypair.

func ParsePEMBundle

func ParsePEMBundle(pemBundle string) (*ParsedCertBundle, error)

ParsePEMBundle takes a string of concatenated PEM-format certificate and private key values and decodes/parses them, checking validity along the way. The first certificate must be the subject certificate and issuing certificates may follow. There must be at most one private key.

func ParsePKIJSON

func ParsePKIJSON(input []byte) (*ParsedCertBundle, error)

ParsePKIJSON takes a JSON-encoded string and returns a ParsedCertBundle.

This can be either the output of an issue call from the PKI backend or just its data member; or, JSON not coming from the PKI backend.

func ParsePKIMap

func ParsePKIMap(data map[string]interface{}) (*ParsedCertBundle, error)

ParsePKIMap takes a map (for instance, the Secret.Data returned from the PKI backend) and returns a ParsedCertBundle.

func SignCertificate added in v0.1.11

func SignCertificate(data *CreationBundle) (*ParsedCertBundle, error)

SignCertificate performs the heavy lifting of generating a certificate from a CSR. Returns a ParsedCertBundle sans private keys.

func SignCertificateWithRandomSource added in v0.2.0

func SignCertificateWithRandomSource(data *CreationBundle, randReader io.Reader) (*ParsedCertBundle, error)

SignCertificateWithRandomSource generates a certificate from a CSR, using custom randomness from the randReader. Returns a ParsedCertBundle sans private keys.

func (*ParsedCertBundle) GetCertificatePath

func (p *ParsedCertBundle) GetCertificatePath() []*CertBlock

GetCertificatePath returns a slice of certificates making up a path, pulled from the parsed cert bundle

func (*ParsedCertBundle) GetTLSConfig

func (p *ParsedCertBundle) GetTLSConfig(usage TLSUsage) (*tls.Config, error)

getTLSConfig returns a TLS config generally suitable for client authentication. The returned TLS config can be modified slightly to be made suitable for a server requiring client authentication; specifically, you should set the value of ClientAuth in the returned config to match your needs.

func (*ParsedCertBundle) SetParsedPrivateKey

func (p *ParsedCertBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte)

SetParsedPrivateKey sets the private key parameters on the bundle

func (*ParsedCertBundle) ToCertBundle

func (p *ParsedCertBundle) ToCertBundle() (*CertBundle, error)

ToCertBundle converts a byte-based raw DER certificate bundle to a PEM-based string certificate bundle

func (*ParsedCertBundle) Verify

func (p *ParsedCertBundle) Verify() error

Verify checks if the parsed bundle is valid. It validates the public key of the certificate to the private key and checks the certificate trust chain for path issues.

type ParsedPrivateKeyContainer

type ParsedPrivateKeyContainer interface {
	SetParsedPrivateKey(crypto.Signer, PrivateKeyType, []byte)
}

ParsedPrivateKeyContainer allows common key setting for certs and CSRs

type PrivateKeyType

type PrivateKeyType string

PrivateKeyType holds a string representation of the type of private key (ec or rsa) referenced in CertBundle and ParsedCertBundle. This uses colloquial names rather than official names, to eliminate confusion

const (
	UnknownPrivateKey PrivateKeyType = ""
	RSAPrivateKey     PrivateKeyType = "rsa"
	ECPrivateKey      PrivateKeyType = "ec"
)

Well-known PrivateKeyTypes

type Secret

type Secret struct {
	Data map[string]interface{} `json:"data"`
}

Secret is used to attempt to unmarshal a Vault secret JSON response, as a convenience

type TLSUsage

type TLSUsage int

TLSUsage controls whether the intended usage of a *tls.Config returned from ParsedCertBundle.getTLSConfig is for server use, client use, or both, which affects which values are set

const (
	TLSUnknown TLSUsage = 0
	TLSServer  TLSUsage = 1 << iota
	TLSClient
)

Well-known TLSUsage types

type URLEntries added in v0.1.11

type URLEntries struct {
	IssuingCertificates   []string `json:"issuing_certificates" structs:"issuing_certificates" mapstructure:"issuing_certificates"`
	CRLDistributionPoints []string `json:"crl_distribution_points" structs:"crl_distribution_points" mapstructure:"crl_distribution_points"`
	OCSPServers           []string `json:"ocsp_servers" structs:"ocsp_servers" mapstructure:"ocsp_servers"`
}

Jump to

Keyboard shortcuts

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