x509

package
v1.0.2063 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2024 License: Apache-2.0 Imports: 46 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.

Functions

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, publicKey any, priv any) ([]byte, error)

CreateCertificate creates a new certificate based on a template. The following members of template are used: SerialNumber, Subject, NotBefore, NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains, SignatureAlgorithm.

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the signee and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

All keys types that are implemented via crypto.Signer are supported (This includes *rsa.PublicKey and *ecdsa.PublicKey.)

func CreateCertificateRequest

func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)

CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used: Subject, Attributes, SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses. The private key is the private key of the signer.

The returned slice is the certificate request in DER encoding.

All keys types that are implemented via crypto.Signer are supported (This includes *rsa.PublicKey and *ecdsa.PublicKey.)

func ParseCRL

func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)

ParseCRL parses a CRL from the given bytes. It's often the case that PEM encoded CRLs will appear where they should be DER encoded, so this function will transparently handle PEM encoding as long as there isn't any leading garbage.

func ParseDERCRL

func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)

ParseDERCRL parses a DER encoded CRL from the given bytes.

func PasrsePKCS8Key added in v1.0.2053

func PasrsePKCS8Key(privateKey []byte) (*pkcs8, error)

Pasrse PKCS8 Key

func RegisterHash

func RegisterHash(h Hash, f func() hash.Hash)

RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

func SysCertPool added in v1.0.2052

func SysCertPool() (*x509.CertPool, error)

SystemCertPool returns a copy of the system cert pool.

Any mutations to the returned pool are not written to disk and do not affect any other pool.

Types

type CertPool

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

CertPool is a set of certificates.

func NewCertPool

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool

func SystemCertPool() (*CertPool, error)

SystemCertPool returns a copy of the system cert pool.

Any mutations to the returned pool are not written to disk and do not affect any other pool.

func (*CertPool) AddCert

func (s *CertPool) AddCert(cert *Certificate)

AddCert adds a certificate to a pool.

func (*CertPool) AddCertWithConstraint added in v1.0.2053

func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)

AddCertWithConstraint adds a certificate to the pool with the additional constraint. When Certificate.Verify builds a chain which is rooted by cert, it will additionally pass the whole chain to constraint to determine its validity. If constraint returns a non-nil error, the chain will be discarded. constraint may be called concurrently from multiple goroutines.

func (*CertPool) AppendCertsFromPEM

func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.

On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.

func (*CertPool) Clone added in v1.0.2052

func (s *CertPool) Clone() *CertPool

Clone returns a copy of s.

func (*CertPool) Equal added in v1.0.2052

func (s *CertPool) Equal(other *CertPool) bool

Equal reports whether s and other are equal.

func (*CertPool) Subjects deprecated

func (s *CertPool) Subjects() [][]byte

Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.

Deprecated: if s was returned by SystemCertPool, Subjects will not include the system roots.

type Certificate

type Certificate struct {
	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
	RawSubject              []byte // DER encoded Subject
	RawIssuer               []byte // DER encoded Issuer

	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          any

	Version             int
	SerialNumber        *big.Int
	Issuer              pkix.Name
	Subject             pkix.Name
	NotBefore, NotAfter time.Time // Validity bounds.
	KeyUsage            KeyUsage

	// Extensions contains raw X.509 extensions. When parsing certificates,
	// this can be used to extract non-critical extensions that are not
	// parsed by this package. When marshaling certificates, the Extensions
	// field is ignored, see ExtraExtensions.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any
	// marshaled certificates. Values override any extensions that would
	// otherwise be produced based on the other fields. The ExtraExtensions
	// field is not populated when parsing certificates, see Extensions.
	ExtraExtensions []pkix.Extension

	// UnhandledCriticalExtensions contains a list of extension IDs that
	// were not (fully) processed when parsing. Verify will fail if this
	// slice is non-empty, unless verification is delegated to an OS
	// library which understands all the critical extensions.
	//
	// Users can access these extensions using Extensions and can remove
	// elements from this slice if they believe that they have been
	// handled.
	UnhandledCriticalExtensions []asn1.ObjectIdentifier

	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.

	BasicConstraintsValid bool // if true then the next two fields are valid.
	IsCA                  bool

	MaxPathLen int
	// MaxPathLenZero indicates that BasicConstraintsValid==true and
	// MaxPathLen==0 should be interpreted as an actual maximum path length
	// of zero. Otherwise, that combination is interpreted as MaxPathLen
	// not being set.
	MaxPathLenZero bool

	SubjectKeyId   []byte
	AuthorityKeyId []byte

	// RFC 5280, 4.2.2.1 (Authority Information Access)
	OCSPServer            []string
	IssuingCertificateURL []string

	// Subject Alternate Name values
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL

	// Name constraints
	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
	PermittedDNSDomains         []string
	ExcludedDNSDomains          []string
	PermittedIPRanges           []*net.IPNet
	ExcludedIPRanges            []*net.IPNet
	PermittedEmailAddresses     []string
	ExcludedEmailAddresses      []string
	PermittedURIDomains         []string
	ExcludedURIDomains          []string

	// CRL Distribution Points
	CRLDistributionPoints []string

	PolicyIdentifiers []asn1.ObjectIdentifier
}

A Certificate represents an X.509 certificate.

func ParseCertificate

func ParseCertificate(asn1Data []byte) (*Certificate, error)

ParseCertificate parses a single certificate from the given ASN.1 DER data.

func ParseCertificates

func ParseCertificates(asn1Data []byte) ([]*Certificate, error)

ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

func (*Certificate) CheckCRLSignature

func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error

CheckCRLSignature checks that the signature in crl is from c.

func (*Certificate) CheckSignature

func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

CheckSignature verifies that signature is a valid signature over signed from c's public key.

func (*Certificate) CheckSignatureFrom

func (c *Certificate) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

func (*Certificate) CreateCRL

func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)

CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.

func (*Certificate) Equal

func (c *Certificate) Equal(other *Certificate) bool

func (*Certificate) FromX509Certificate

func (c *Certificate) FromX509Certificate(x509Cert *x509.Certificate)

func (*Certificate) ToX509Certificate

func (c *Certificate) ToX509Certificate() *x509.Certificate

func (*Certificate) Verify

func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)

Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.

If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.

Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn't permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.

Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.

Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)

Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported, and will not be used to build chains.

Certificates other than c in the returned chains should not be modified.

WARNING: this function doesn't do any revocation checking.

func (*Certificate) VerifyHostname

func (c *Certificate) VerifyHostname(h string) error

VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.

IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the complete left-most label (e.g. *.example.com).

Note that the legacy Common Name field is ignored.

type CertificateInvalidError

type CertificateInvalidError struct {
	Cert   *Certificate
	Reason InvalidReason
	Detail string
}

CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.

func (CertificateInvalidError) Error

func (e CertificateInvalidError) Error() string

type CertificateRequest

type CertificateRequest struct {
	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
	RawSubject               []byte // DER encoded Subject.

	Version            int
	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          any

	Subject pkix.Name

	// Attributes is the dried husk of a bug and shouldn't be used.
	Attributes []pkix.AttributeTypeAndValueSET

	// Extensions contains raw X.509 extensions. When parsing CSRs, this
	// can be used to extract extensions that are not parsed by this
	// package.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any
	// marshaled CSR. Values override any extensions that would otherwise
	// be produced based on the other fields but are overridden by any
	// extensions specified in Attributes.
	//
	// The ExtraExtensions field is not populated when parsing CSRs, see
	// Extensions.
	ExtraExtensions []pkix.Extension

	// Subject Alternate Name values.
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL
}

CertificateRequest represents a PKCS #10, certificate signature request.

func ParseCertificateRequest

func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.

func (*CertificateRequest) CheckSignature

func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

type ConstraintViolationError

type ConstraintViolationError struct{}

ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn't a certificate signing key.

func (ConstraintViolationError) Error

type ExtKeyUsage

type ExtKeyUsage int

ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

const (
	ExtKeyUsageAny ExtKeyUsage = iota
	ExtKeyUsageServerAuth
	ExtKeyUsageClientAuth
	ExtKeyUsageCodeSigning
	ExtKeyUsageEmailProtection
	ExtKeyUsageIPSECEndSystem
	ExtKeyUsageIPSECTunnel
	ExtKeyUsageIPSECUser
	ExtKeyUsageTimeStamping
	ExtKeyUsageOCSPSigning
	ExtKeyUsageMicrosoftServerGatedCrypto
	ExtKeyUsageNetscapeServerGatedCrypto
)

type Hash

type Hash uint
const (
	MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
	MD5                         // import crypto/md5
	SHA1                        // import crypto/sha1
	SHA224                      // import crypto/sha256
	SHA256                      // import crypto/sha256
	SHA384                      // import crypto/sha512
	SHA512                      // import crypto/sha512
	MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
	RIPEMD160                   // import golang.org/x/crypto/ripemd160
	SHA3_224                    // import golang.org/x/crypto/sha3
	SHA3_256                    // import golang.org/x/crypto/sha3
	SHA3_384                    // import golang.org/x/crypto/sha3
	SHA3_512                    // import golang.org/x/crypto/sha3
	SHA512_224                  // import crypto/sha512
	SHA512_256                  // import crypto/sha512
	BLAKE2s_256                 // import golang.org/x/crypto/blake2s
	BLAKE2b_256                 // import golang.org/x/crypto/blake2b
	BLAKE2b_384                 // import golang.org/x/crypto/blake2b
	BLAKE2b_512                 // import golang.org/x/crypto/blake2b
	SM3
	GOST34112001
	GOST34112012256
	GOST34112012512
)

func (Hash) Available

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

func (Hash) HashFunc

func (h Hash) HashFunc() crypto.Hash

HashFunc simply returns the value of h so that Hash implements SignerOpts.

func (Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

func (Hash) Size

func (h Hash) Size() int

Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn't require that the hash function in question be linked into the program.

func (Hash) String added in v1.0.2052

func (h Hash) String() string

type HostnameError

type HostnameError struct {
	Certificate *Certificate
	Host        string
}

HostnameError results when the set of authorized names doesn't match the requested name.

func (HostnameError) Error

func (h HostnameError) Error() string

type InsecureAlgorithmError

type InsecureAlgorithmError SignatureAlgorithm

An InsecureAlgorithmError

func (InsecureAlgorithmError) Error

func (e InsecureAlgorithmError) Error() string

type InvalidReason

type InvalidReason int
const (
	// NotAuthorizedToSign results when a certificate is signed by another
	// which isn't marked as a CA certificate.
	NotAuthorizedToSign InvalidReason = iota
	// Expired results when a certificate has expired, based on the time
	// given in the VerifyOptions.
	Expired
	// CANotAuthorizedForThisName results when an intermediate or root
	// certificate has a name constraint which doesn't permit a DNS or
	// other name (including IP address) in the leaf certificate.
	CANotAuthorizedForThisName
	// TooManyIntermediates results when a path length constraint is
	// violated.
	TooManyIntermediates
	// IncompatibleUsage results when the certificate's key usage indicates
	// that it may only be used for a different purpose.
	IncompatibleUsage
	// NameMismatch results when the subject name of a parent certificate
	// does not match the issuer name in the child.
	NameMismatch
	// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
	NameConstraintsWithoutSANs
	// UnconstrainedName results when a CA certificate contains permitted
	// name constraints, but leaf certificate contains a name of an
	// unsupported or unconstrained type.
	UnconstrainedName
	// TooManyConstraints results when the number of comparison operations
	// needed to check a certificate exceeds the limit set by
	// VerifyOptions.MaxConstraintComparisions. This limit exists to
	// prevent pathological certificates can consuming excessive amounts of
	// CPU time to verify.
	TooManyConstraints
	// CANotAuthorizedForExtKeyUsage results when an intermediate or root
	// certificate does not permit a requested extended key usage.
	CANotAuthorizedForExtKeyUsage
)

type KeyUsage

type KeyUsage int

KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.

const (
	KeyUsageDigitalSignature KeyUsage = 1 << iota
	KeyUsageContentCommitment
	KeyUsageKeyEncipherment
	KeyUsageDataEncipherment
	KeyUsageKeyAgreement
	KeyUsageCertSign
	KeyUsageCRLSign
	KeyUsageEncipherOnly
	KeyUsageDecipherOnly
)

type PublicKeyAlgorithm

type PublicKeyAlgorithm int
const (
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
	DSA
	ECDSA
	Ed25519
	SM2
	GOST3410
)

type SignatureAlgorithm

type SignatureAlgorithm int
const (
	UnknownSignatureAlgorithm SignatureAlgorithm = iota
	MD2WithRSA
	MD5WithRSA
	SHA1WithRSA
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
	DSAWithSHA1
	DSAWithSHA256
	ECDSAWithSHA1
	ECDSAWithSHA256
	ECDSAWithSHA384
	ECDSAWithSHA512
	SHA256WithRSAPSS
	SHA384WithRSAPSS
	SHA512WithRSAPSS
	PureEd25519
	SM2WithSM3
	SM2WithSHA1
	SM2WithSHA256
	SM3WithRSA
	GOST3410WithGOST34112001
	GOST3410WithGOST34112012256
	GOST3410WithGOST34112012512
)

func (SignatureAlgorithm) String

func (algo SignatureAlgorithm) String() string

type SystemRootsError

type SystemRootsError struct {
	Err error
}

SystemRootsError results when we fail to load the system root certificates.

func (SystemRootsError) Error

func (se SystemRootsError) Error() string

func (SystemRootsError) Unwrap added in v1.0.2052

func (se SystemRootsError) Unwrap() error

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) Error

type UnknownAuthorityError

type UnknownAuthorityError struct {
	Cert *Certificate
	// contains filtered or unexported fields
}

UnknownAuthorityError results when the certificate issuer is unknown

func (UnknownAuthorityError) Error

func (e UnknownAuthorityError) Error() string

type VerifyOptions

type VerifyOptions struct {
	// DNSName, if set, is checked against the leaf certificate with
	// Certificate.VerifyHostname or the platform verifier.
	DNSName string

	// Intermediates is an optional pool of certificates that are not trust
	// anchors, but can be used to form a chain from the leaf certificate to a
	// root certificate.
	Intermediates *CertPool
	// Roots is the set of trusted root certificates the leaf certificate needs
	// to chain up to. If nil, the system roots or the platform verifier are used.
	Roots *CertPool

	// CurrentTime is used to check the validity of all certificates in the
	// chain. If zero, the current time is used.
	CurrentTime time.Time

	// KeyUsages specifies which Extended Key Usage values are acceptable. A
	// chain is accepted if it allows any of the listed values. An empty list
	// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
	KeyUsages []ExtKeyUsage

	// MaxConstraintComparisions is the maximum number of comparisons to
	// perform when checking a given certificate's name constraints. If
	// zero, a sensible default is used. This limit prevents pathological
	// certificates from consuming excessive amounts of CPU time when
	// validating. It does not apply to the platform verifier.
	MaxConstraintComparisions int
}

VerifyOptions contains parameters for Certificate.Verify.

Jump to

Keyboard shortcuts

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