certutil

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: MPL-2.0 Imports: 33 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 (
	SignCIEPSMode  = "sign"
	IssueCIEPSMode = "issue"
	ACMECIEPSMode  = "acme"
	ICACIEPSMode   = "ica"
)
View Source
const (
	PrivateKeyTypeP521 = "p521"
)

Variables

View Source
var (
	ExtensionBasicConstraintsOID = []int{2, 5, 29, 19}
	ExtensionSubjectAltNameOID   = []int{2, 5, 29, 17}
)
View Source
var CRLNumberOID = asn1.ObjectIdentifier([]int{2, 5, 29, 20})

OID for RFC 5280 CRL Number extension.

> id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 }

View Source
var DeltaCRLIndicatorOID = asn1.ObjectIdentifier([]int{2, 5, 29, 27})

OID for RFC 5280 Delta CRL Indicator CRL extension.

> id-ce-deltaCRLIndicator OBJECT IDENTIFIER ::= { id-ce 27 }

View Source
var ExtendedKeyUsageOID = asn1.ObjectIdentifier([]int{2, 5, 29, 37})

OID for Extended Key Usage from RFC 5280 : https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12

id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }

View Source
var InvSignatureAlgorithmNames = map[x509.SignatureAlgorithm]string{
	x509.SHA256WithRSA:    "SHA256WithRSA",
	x509.SHA384WithRSA:    "SHA384WithRSA",
	x509.SHA512WithRSA:    "SHA512WithRSA",
	x509.ECDSAWithSHA256:  "ECDSAWithSHA256",
	x509.ECDSAWithSHA384:  "ECDSAWithSHA384",
	x509.ECDSAWithSHA512:  "ECDSAWithSHA512",
	x509.SHA256WithRSAPSS: "SHA256WithRSAPSS",
	x509.SHA384WithRSAPSS: "SHA384WithRSAPSS",
	x509.SHA512WithRSAPSS: "SHA512WithRSAPSS",
	x509.PureEd25519:      "Ed25519",
}

Mapping of constant values<->constant names for SignatureAlgorithm

View Source
var KeyUsageOID = asn1.ObjectIdentifier([]int{2, 5, 29, 15})

OID for KeyUsage from RFC 2459 : https://www.rfc-editor.org/rfc/rfc2459.html#section-4.2.1.3

> id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }

View Source
var OidExtensionSubjectAltName = asn1.ObjectIdentifier([]int{2, 5, 29, 17})

OIDs for X.509 SAN Extension

View Source
var SignatureAlgorithmNames = map[string]x509.SignatureAlgorithm{
	"sha256withrsa":    x509.SHA256WithRSA,
	"sha384withrsa":    x509.SHA384WithRSA,
	"sha512withrsa":    x509.SHA512WithRSA,
	"ecdsawithsha256":  x509.ECDSAWithSHA256,
	"ecdsawithsha384":  x509.ECDSAWithSHA384,
	"ecdsawithsha512":  x509.ECDSAWithSHA512,
	"sha256withrsapss": x509.SHA256WithRSAPSS,
	"sha384withrsapss": x509.SHA384WithRSAPSS,
	"sha512withrsapss": x509.SHA512WithRSAPSS,
	"pureed25519":      x509.PureEd25519,
	"ed25519":          x509.PureEd25519,
}

Mapping of constant names<->constant values for SignatureAlgorithm

View Source
var SubjectPilotUserIDAttributeOID = asn1.ObjectIdentifier{0, 9, 2342, 19200300, 100, 1, 1}

Subject Attribute OIDs

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, based on CreationBundle

func ComparePublicKeys

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

ComparePublicKeys compares two public keys and returns true if they match, returns an error if public key types are mismatched, or they are an unsupported key type.

func ComparePublicKeysAndType added in v0.5.0

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

ComparePublicKeysAndType compares two public keys and returns true if they match, false if their types or contents differ, and an error on unsupported key types.

func CreateBasicConstraintExtension added in v0.9.2

func CreateBasicConstraintExtension(isCa bool, maxPath int) (pkix.Extension, error)

CreateBasicConstraintExtension create a basic constraint extension based on inputs, if isCa is false, an empty value sequence will be returned with maxPath being ignored. If isCa is true maxPath can be set to -1 to not set a maxPath value.

func CreateDeltaCRLIndicatorExt added in v0.6.0

func CreateDeltaCRLIndicatorExt(completeCRLNumber int64) (pkix.Extension, error)

CreateDeltaCRLIndicatorExt allows creating correctly formed delta CRLs that point back to the last complete CRL that they're based on.

func CreatePolicyInformationExtensionFromStorageStrings added in v0.5.1

func CreatePolicyInformationExtensionFromStorageStrings(policyIdentifiers []string) (*pkix.Extension, error)

CreatePolicyInformationExtensionFromStorageStrings parses the stored policyIdentifiers, which might be JSON Policy Identifier with Qualifier Entries or String OIDs, and returns an extension if everything parsed correctly, and an error if constructing

func DefaultOrValueHashBits added in v0.4.0

func DefaultOrValueHashBits(keyType string, keyBits int, hashBits int) (int, error)

Returns default signature hash bit length for the specified key type and bits, or the present value if hashBits is non-zero. Returns an error under certain internal circumstances.

func DefaultOrValueKeyBits added in v0.4.0

func DefaultOrValueKeyBits(keyType string, keyBits int) (int, error)

Returns default key bits for the specified key type, or the present value if keyBits is non-zero.

func DetermineExcludeCnFromCertSans added in v0.11.0

func DetermineExcludeCnFromCertSans(certificate x509.Certificate) bool

func DetermineExcludeCnFromCsrSans added in v0.11.0

func DetermineExcludeCnFromCsrSans(csr x509.CertificateRequest) bool

func FindBitLength added in v0.11.0

func FindBitLength(publicKey any) int

func FindSignatureBits added in v0.11.0

func FindSignatureBits(algo x509.SignatureAlgorithm) int

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 GetKeyType added in v0.11.0

func GetKeyType(goKeyType string) string

func GetPublicKeySize added in v0.3.0

func GetPublicKeySize(key crypto.PublicKey) int

GetPublicKeySize returns the key size in bits for a given arbitrary crypto.PublicKey Returns -1 for an unsupported key type.

func GetSubjKeyID

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

GetSubjKeyID returns the subject key ID. The computed ID is the SHA-1 hash of the marshaled public key according to https://tools.ietf.org/html/rfc5280#section-4.2.1.2 (1)

func GetSubjectKeyID added in v0.9.1

func GetSubjectKeyID(pub interface{}) ([]byte, error)

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 IsPSS added in v0.11.0

func IsPSS(algorithm x509.SignatureAlgorithm) bool

func MakeAltNamesCommaSeparatedString added in v0.11.0

func MakeAltNamesCommaSeparatedString(names []string, emails []string) string

func MakeIpAddressCommaSeparatedString added in v0.11.0

func MakeIpAddressCommaSeparatedString(addresses []net.IP) string

func MakeUriCommaSeparatedString added in v0.11.0

func MakeUriCommaSeparatedString(uris []*url.URL) string

func NewCertPool added in v0.2.0

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

func ParseBasicConstraintExtension added in v0.9.2

func ParseBasicConstraintExtension(ext pkix.Extension) (bool, int, error)

ParseBasicConstraintExtension parses a basic constraint pkix.Extension, useful if attempting to validate CSRs are requesting CA privileges as Go does not expose its implementation. Values returned are IsCA, MaxPathLen or error. If MaxPathLen was not set, a value of -1 will be returned.

func ParseCertificateToFields added in v0.11.0

func ParseCertificateToFields(certificate x509.Certificate) (map[string]interface{}, error)

func ParseCertsPEM added in v0.9.2

func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error)

ParseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array Returns an error if a certificate could not be parsed, or if the data does not contain any certificates

func ParseCsrToFields added in v0.11.0

func ParseCsrToFields(csr x509.CertificateRequest) (map[string]interface{}, 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 ValidateDefaultOrValueKeyTypeSignatureLength added in v0.4.0

func ValidateDefaultOrValueKeyTypeSignatureLength(keyType string, keyBits int, hashBits int) (int, int, error)

Validates that the combination of keyType, keyBits, and hashBits are valid together; replaces individual calls to ValidateSignatureLength and ValidateKeyTypeLength. Also updates the value of keyBits and hashBits on return.

func ValidateKeyTypeLength added in v0.1.11

func ValidateKeyTypeLength(keyType string, keyBits int) error

func ValidateSignatureLength added in v0.3.0

func ValidateSignatureLength(keyType string, hashBits int) error

Validates that the length of the hash (in bits) used in the signature calculation is a known, approved value.

Types

type BlockType

type BlockType string

BlockType indicates the serialization format of the key

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

Well-known formats

func ParseDERKey added in v0.5.0

func ParseDERKey(privateKeyBytes []byte) (signer crypto.Signer, format BlockType, err error)

func ParsePEMKey added in v0.5.0

func ParsePEMKey(keyPem string) (crypto.Signer, BlockType, error)

type CAInfoBundle added in v0.1.11

type CAInfoBundle struct {
	ParsedCertBundle
	URLs                 *URLEntries
	LeafNotAfterBehavior NotAfterBehavior
	RevocationSigAlg     x509.SignatureAlgorithm
}

func (*CAInfoBundle) GetCAChain added in v0.1.11

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

func (*CAInfoBundle) GetFullChain added in v0.4.0

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

type CIEPSIssuanceConfig added in v0.9.2

type CIEPSIssuanceConfig struct {
	AIAValues            *URLEntries `json:"aia_values"`
	LeafNotAfterBehavior string      `json:"leaf_not_after_behavior"`
	MountDefaultTTL      string      `json:"mount_default_ttl"`
	MountMaxTTL          string      `json:"mount_max_ttl"`
}

Configuration of the issuer and mount at the time of this request; states the issuer's templated AIA information (falling back to the mount-global config if no per-issuer AIA info is set, the issuer's leaf_not_after_behavior (permit/truncate/err) for TTLs exceeding the issuer's validity period, and the mount's default and max TTL.

type CIEPSIssuanceMode added in v0.9.2

type CIEPSIssuanceMode string

Source of the issuance request: sign implies that the key material was generated by the user and submitted via a CSR request but only ACL level validation was applied; issue implies that Vault created the key material on behalf of the user with ACL level validation occurring; ACME implies that the user submitted a CSR and that additional ACME validation has occurred before sending the request to the external service for construction.

type CIEPSRequest added in v0.9.2

type CIEPSRequest struct {
	Version int    `json:"request_version"`
	UUID    string `json:"request_uuid"`
	Sync    bool   `json:"synchronous"`

	UserRequestKV     map[string]interface{} `json:"user_request_key_values"`
	IdentityRequestKV map[string]interface{} `json:"identity_request_key_values,omitempty"`
	ACMERequestKV     map[string]interface{} `json:"acme_request_key_values,omitempty"`
	VaultRequestKV    CIEPSVaultParams       `json:"vault_request_values"`

	// Vault guarantees that UserRequestKV will contain a csr parameter
	// for all request types; this field is useful for engine implementations
	// to have in parsed format. We assume that this is sent in PEM format,
	// aligning with other Vault requests.
	ParsedCSR *x509.CertificateRequest `json:"-"`
}

Outer request object sent by Vault to the external CIEPS service.

The top-level fields denote properties about the CIEPS request, with various request fields containing untrusted and trusted input respectively.

func (*CIEPSRequest) ParseUserCSR added in v0.9.2

func (req *CIEPSRequest) ParseUserCSR() error

type CIEPSResponse added in v0.9.2

type CIEPSResponse struct {
	UUID              string            `json:"request_uuid"`
	Error             string            `json:"error,omitempty"`
	Warnings          []string          `json:"warnings,omitempty"`
	Certificate       string            `json:"certificate"`
	ParsedCertificate *x509.Certificate `json:"-"`
	IssuerRef         string            `json:"issuer_ref"`
	StoreCert         bool              `json:"store_certificate"`
	GenerateLease     bool              `json:"generate_lease"`
}

Expected response object from the external CIEPS service.

When parsing, Vault will disallow unknown fields, failing the parse if unknown fields are sent.

func (*CIEPSResponse) MarshalCertificate added in v0.9.2

func (c *CIEPSResponse) MarshalCertificate() error

type CIEPSVaultParams added in v0.9.2

type CIEPSVaultParams struct {
	PolicyName string `json:"policy_name,omitempty"`
	Mount      string `json:"mount"`
	Namespace  string `json:"ns"`

	// These indicate the type of the cluster node talking to the CIEPS
	// service. When IsPerfStandby=true, setting StoreCert=true in the
	// response will result in Vault forwarding the client's request
	// up to the Performance Secondary's active node and re-trying the
	// operation (including re-submitting the request to the CIEPS
	// service).
	//
	// Any response returned by the CIEPS service in this case will be
	// ignored and not signed by the CA's keys.
	//
	// IsPRSecondary is set to false when a local mount is used on a
	// PR Secondary; in this scenario, PR Secondary nodes behave like
	// PR Primary nodes. From a CIEPS service perspective, no behavior
	// difference is expected between PR Primary and PR Secondary nodes;
	// both will issue and store certificates on their active nodes.
	// This information is included for audit tracking purposes.
	IsPerfStandby bool `json:"vault_is_performance_standby"`
	IsPRSecondary bool `json:"vault_is_performance_secondary"`

	IssuanceMode CIEPSIssuanceMode `json:"issuance_mode"`

	GeneratedKey bool `json:"vault_generated_private_key"`

	IssuerName string `json:"requested_issuer_name"`
	IssuerID   string `json:"requested_issuer_id"`
	IssuerCert string `json:"requested_issuer_cert"`

	Config CIEPSIssuanceConfig `json:"requested_issuance_config"`
}

Structured parameters sent by Vault or explicitly validated by Vault prior to sending.

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

func (*CertBundle) ToParsedCertBundleWithExtractor added in v0.4.0

func (c *CertBundle) ToParsedCertBundleWithExtractor(privateKeyExtractor PrivateKeyExtractor) (*ParsedCertBundle, error)

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
	SignatureBits                 int
	UsePSS                        bool
	ForceAppendCaChain            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

	// The explicit SKID to use; especially useful for cross-signing.
	SKID []byte
}

func ParseCertificateToCreationParameters added in v0.11.0

func ParseCertificateToCreationParameters(certificate x509.Certificate) (creationParameters CreationParameters, err error)

func ParseCsrToCreationParameters added in v0.11.0

func ParseCsrToCreationParameters(csr x509.CertificateRequest) (CreationParameters, error)

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 KeyBundle added in v0.5.0

type KeyBundle struct {
	PrivateKeyType  PrivateKeyType
	PrivateKeyBytes []byte
	PrivateKey      crypto.Signer
}

func CreateKeyBundle added in v0.5.0

func CreateKeyBundle(keyType string, keyBits int, randReader io.Reader) (KeyBundle, error)

CreateKeyBundle create a KeyBundle struct object which includes a generated key of keyType with keyBits leveraging the randomness from randReader.

func CreateKeyBundleWithKeyGenerator added in v0.5.0

func CreateKeyBundleWithKeyGenerator(keyType string, keyBits int, randReader io.Reader, keyGenerator KeyGenerator) (KeyBundle, error)

CreateKeyBundleWithKeyGenerator create a KeyBundle struct object which includes a generated key of keyType with keyBits leveraging the randomness from randReader and delegates the actual key generation to keyGenerator

func (*KeyBundle) SetParsedPrivateKey added in v0.5.0

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

SetParsedPrivateKey sets the private key parameters on the bundle

func (*KeyBundle) ToPrivateKeyPemString added in v0.5.0

func (p *KeyBundle) ToPrivateKeyPemString() (string, error)

type KeyGenerator added in v0.4.0

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

KeyGenerator Allow us to override how/what generates the private key

type NotAfterBehavior added in v0.5.0

type NotAfterBehavior int
const (
	ErrNotAfterBehavior NotAfterBehavior = iota
	TruncateNotAfterBehavior
	PermitNotAfterBehavior
)

func (NotAfterBehavior) String added in v0.5.0

func (n NotAfterBehavior) String() string

type OtherNameRaw added in v0.11.0

type OtherNameRaw struct {
	TypeID asn1.ObjectIdentifier
	Value  asn1.RawValue
}

otherNameRaw describes a name related to a certificate which is not in one of the standard name formats. RFC 5280, 4.2.1.6:

OtherName ::= SEQUENCE {
     type-id    OBJECT IDENTIFIER,
     Value      [0] EXPLICIT ANY DEFINED BY type-id }

func (*OtherNameRaw) ExtractUTF8String added in v0.11.0

func (oraw *OtherNameRaw) ExtractUTF8String() (*OtherNameUtf8, error)

ExtractUTF8String returns the UTF8 string contained in the Value, or an error if none is present.

type OtherNameUtf8 added in v0.11.0

type OtherNameUtf8 struct {
	Oid   string
	Value string
}

func GetOtherSANsFromX509Extensions added in v0.11.0

func GetOtherSANsFromX509Extensions(exts []pkix.Extension) ([]OtherNameUtf8, error)

GetOtherSANsFromX509Extensions is used to find all the extensions which have the identifier (OID) of a SAN (Subject Alternative Name), and then look at each extension to find out if it is one of a set of well-known types (like IP SANs) or "other". Currently, the only OtherSANs vault supports are of type UTF8.

func (OtherNameUtf8) String added in v0.11.0

func (o OtherNameUtf8) String() string

String() turns an OtherNameUtf8 object into the storage or field-value used to assign that name to a certificate in an API call

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 CreateCSRWithKeyGenerator added in v0.4.0

func CreateCSRWithKeyGenerator(data *CreationBundle, addBasicConstraints bool, randReader io.Reader, keyGenerator KeyGenerator) (*ParsedCSRBundle, error)

CreateCSRWithKeyGenerator creates a CSR with a custom io.Reader for randomness to generate a cert/keypair with the provided private key generator.

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 CreateCertificateWithKeyGenerator added in v0.4.0

func CreateCertificateWithKeyGenerator(data *CreationBundle, randReader io.Reader, keyGenerator KeyGenerator) (*ParsedCertBundle, error)

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) ToTLSCertificate added in v0.9.2

func (p *ParsedCertBundle) ToTLSCertificate() tls.Certificate

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 PolicyIdentifierWithQualifierEntry added in v0.5.1

type PolicyIdentifierWithQualifierEntry struct {
	PolicyIdentifierOid string `json:"oid",mapstructure:"oid"`
	CPS                 string `json:"cps,omitempty",mapstructure:"cps"`
	Notice              string `json:"notice,omitempty",mapstructure:"notice"`
}

PolicyIdentifierWithQualifierEntry Structure for Internal Storage

func GetPolicyIdentifierFromString added in v0.5.1

func GetPolicyIdentifierFromString(policyIdentifier string) (*PolicyIdentifierWithQualifierEntry, error)

GetPolicyIdentifierFromString parses out the internal structure of a Policy Identifier

type PrivateKeyExtractor added in v0.4.0

type PrivateKeyExtractor func(c *CertBundle, parsedBundle *ParsedCertBundle) error

PrivateKeyExtractor extract out a private key from the passed in CertBundle and set the appropriate bits within the ParsedCertBundle.

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"
	Ed25519PrivateKey PrivateKeyType = "ed25519"
	ManagedPrivateKey PrivateKeyType = "ManagedPrivateKey"
)

Well-known PrivateKeyTypes

func GetPrivateKeyTypeFromPublicKey added in v0.11.0

func GetPrivateKeyTypeFromPublicKey(pubKey crypto.PublicKey) PrivateKeyType

GetPrivateKeyTypeFromPublicKey based on the public key, return the PrivateKeyType that would be associated with it, returning UnknownPrivateKey for unsupported types

func GetPrivateKeyTypeFromSigner added in v0.5.0

func GetPrivateKeyTypeFromSigner(signer crypto.Signer) PrivateKeyType

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