x509

package
v0.0.0-...-6f32cff Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2018 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package x509 parses X.509-encoded keys and certificates.

On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively.

This is a fork of the go library crypto/x509 package, it's more relaxed about certificates that it'll accept, and exports the TBSCertificate structure.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// OID values for CRL extensions (TBSCertList.Extensions), RFC 5280 s5.2.
	OIDExtensionCRLNumber                = asn1.ObjectIdentifier{2, 5, 29, 20}
	OIDExtensionDeltaCRLIndicator        = asn1.ObjectIdentifier{2, 5, 29, 27}
	OIDExtensionIssuingDistributionPoint = asn1.ObjectIdentifier{2, 5, 29, 28}
	// OID values for CRL entry extensions (RevokedCertificate.Extensions), RFC 5280 s5.3
	OIDExtensionCRLReasons        = asn1.ObjectIdentifier{2, 5, 29, 21}
	OIDExtensionInvalidityDate    = asn1.ObjectIdentifier{2, 5, 29, 24}
	OIDExtensionCertificateIssuer = asn1.ObjectIdentifier{2, 5, 29, 29}
)
View Source
var (
	Unspecified          = RevocationReasonCode(0)
	KeyCompromise        = RevocationReasonCode(1)
	CACompromise         = RevocationReasonCode(2)
	AffiliationChanged   = RevocationReasonCode(3)
	Superseded           = RevocationReasonCode(4)
	CessationOfOperation = RevocationReasonCode(5)
	CertificateHold      = RevocationReasonCode(6)
	RemoveFromCRL        = RevocationReasonCode(8)
	PrivilegeWithdrawn   = RevocationReasonCode(9)
	AACompromise         = RevocationReasonCode(10)
)

RevocationReasonCode values.

View Source
var (
	OIDPublicKeyRSA         = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
	OIDPublicKeyDSA         = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
	OIDPublicKeyECDSA       = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
	OIDPublicKeyRSAObsolete = asn1.ObjectIdentifier{2, 5, 8, 1, 1}
)
  • RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters

RFC 3279, 2.3 Public Key Algorithms

pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)

rsadsi(113549) pkcs(1) 1 }

rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }

id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)

x9-57(10040) x9cm(4) 1 }

RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters

id-ecPublicKey OBJECT IDENTIFIER ::= {
      iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
View Source
var (
	OIDNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
	OIDNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
	OIDNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
	OIDNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
)

RFC 5480, 2.1.1.1. Named Curve

secp224r1 OBJECT IDENTIFIER ::= {
  iso(1) identified-organization(3) certicom(132) curve(0) 33 }
secp256r1 OBJECT IDENTIFIER ::= {
  iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
  prime(1) 7 }
secp384r1 OBJECT IDENTIFIER ::= {
  iso(1) identified-organization(3) certicom(132) curve(0) 34 }
secp521r1 OBJECT IDENTIFIER ::= {
  iso(1) identified-organization(3) certicom(132) curve(0) 35 }

NB: secp256r1 is equivalent to prime256v1

View Source
var (
	OIDExtensionArc                        = asn1.ObjectIdentifier{2, 5, 29} // id-ce RFC5280 s4.2.1
	OIDExtensionSubjectKeyId               = asn1.ObjectIdentifier{2, 5, 29, 14}
	OIDExtensionKeyUsage                   = asn1.ObjectIdentifier{2, 5, 29, 15}
	OIDExtensionExtendedKeyUsage           = asn1.ObjectIdentifier{2, 5, 29, 37}
	OIDExtensionAuthorityKeyId             = asn1.ObjectIdentifier{2, 5, 29, 35}
	OIDExtensionBasicConstraints           = asn1.ObjectIdentifier{2, 5, 29, 19}
	OIDExtensionSubjectAltName             = asn1.ObjectIdentifier{2, 5, 29, 17}
	OIDExtensionCertificatePolicies        = asn1.ObjectIdentifier{2, 5, 29, 32}
	OIDExtensionNameConstraints            = asn1.ObjectIdentifier{2, 5, 29, 30}
	OIDExtensionCRLDistributionPoints      = asn1.ObjectIdentifier{2, 5, 29, 31}
	OIDExtensionIssuerAltName              = asn1.ObjectIdentifier{2, 5, 29, 18}
	OIDExtensionSubjectDirectoryAttributes = asn1.ObjectIdentifier{2, 5, 29, 9}
	OIDExtensionInhibitAnyPolicy           = asn1.ObjectIdentifier{2, 5, 29, 54}
	OIDExtensionPolicyConstraints          = asn1.ObjectIdentifier{2, 5, 29, 36}
	OIDExtensionPolicyMappings             = asn1.ObjectIdentifier{2, 5, 29, 33}
	OIDExtensionFreshestCRL                = asn1.ObjectIdentifier{2, 5, 29, 46}

	OIDExtensionAuthorityInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1}
	OIDExtensionSubjectInfoAccess   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 11}
	// OIDExtensionCTPoison is defined in RFC 6962 s3.1.
	OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
	// OIDExtensionCTSCT is defined in RFC 6962 s3.3.
	OIDExtensionCTSCT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
)

OID values for standard extensions from RFC 5280.

View Source
var (
	OIDAuthorityInfoAccessOCSP    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
	OIDAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
)
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.

View Source
var IncorrectPasswordError = errors.New("x509: decryption password incorrect")

IncorrectPasswordError is returned when an incorrect password is detected.

Functions

func BuildPrecertTBS

func BuildPrecertTBS(tbsData []byte, preIssuer *Certificate) ([]byte, error)

BuildPrecertTBS builds a Certificate Transparency pre-certificate (RFC 6962 s3.1) from the given DER-encoded TBSCertificate, returning a DER-encoded TBSCertificate.

This function removes the CT poison extension (there must be exactly 1 of these), preserving the order of other extensions.

If preIssuer is provided, this should be a special intermediate certificate that was used to sign the precert (indicated by having the special CertificateTransparency extended key usage). In this case, the issuance information of the pre-cert is updated to reflect the next issuer in the chain, i.e. the issuer of this special intermediate:

  • The precert's Issuer is changed to the Issuer of the intermediate
  • The precert's AuthorityKeyId is changed to the AuthorityKeyId of the intermediate.

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)

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

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.)

The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

func CreateCertificateRequest

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

CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used: Attributes, DNSNames, EmailAddresses, ExtraExtensions, IPAddresses, SignatureAlgorithm, and Subject. 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 DecryptPEMBlock

func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)

DecryptPEMBlock takes a password encrypted PEM block and the password used to encrypt it and returns a slice of decrypted DER encoded bytes. It inspects the DEK-Info header to determine the algorithm used for decryption. If no DEK-Info header is present, an error is returned. If an incorrect password is detected an IncorrectPasswordError is returned. Because of deficiencies in the encrypted-PEM format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.

func EncryptPEMBlock

func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)

EncryptPEMBlock returns a PEM block of the specified type holding the given DER-encoded data encrypted with the specified algorithm and password.

func IsEncryptedPEMBlock

func IsEncryptedPEMBlock(b *pem.Block) bool

IsEncryptedPEMBlock returns if the PEM block is password encrypted.

func MarshalECPrivateKey

func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

MarshalECPrivateKey marshals an EC private key into ASN.1, DER format.

func MarshalPKCS1PrivateKey

func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.

func MarshalPKIXPublicKey

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

MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.

func OIDFromNamedCurve

func OIDFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool)

OIDFromNamedCurve returns the OID used to specify the use of the given elliptic curve.

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 ParseECPrivateKey

func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)

ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.

func ParsePKCS1PrivateKey

func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)

ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See RFC 5208.

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)

ParsePKIXPublicKey parses a DER encoded public key. These values are typically found in PEM blocks with "BEGIN PUBLIC KEY".

Supported key types include RSA, DSA, and ECDSA. Unknown key types result in an error.

On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey, or *ecdsa.PublicKey.

Example
package main

import (
	"crypto/dsa"
	"crypto/ecdsa"
	"crypto/rsa"
	"encoding/pem"
	"fmt"

	"github.com/google/certificate-transparency-go/x509"
)

func main() {
	const pubPEM = `
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
-----END PUBLIC KEY-----`

	block, _ := pem.Decode([]byte(pubPEM))
	if block == nil {
		panic("failed to parse PEM block containing the public key")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic("failed to parse DER encoded public key: " + err.Error())
	}

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		fmt.Println("pub is of type RSA:", pub)
	case *dsa.PublicKey:
		fmt.Println("pub is of type DSA:", pub)
	case *ecdsa.PublicKey:
		fmt.Println("pub is of type ECDSA:", pub)
	default:
		panic("unknown type of public key")
	}
}
Output:

func RemoveCTPoison

func RemoveCTPoison(tbsData []byte) ([]byte, error)

RemoveCTPoison takes a DER-encoded TBSCertificate and removes the CT poison extension (preserving the order of other extensions), and returns the result still as a DER-encoded TBSCertificate. This function will fail if there is not exactly 1 CT poison extension present.

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) 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) Subjects

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

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

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          interface{}

	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 indicates whether IsCA, MaxPathLen,
	// and MaxPathLenZero are valid.
	BasicConstraintsValid bool
	IsCA                  bool

	// MaxPathLen and MaxPathLenZero indicate the presence and
	// value of the BasicConstraints' "pathLenConstraint".
	//
	// When parsing a certificate, a positive non-zero MaxPathLen
	// means that the field was specified, -1 means it was unset,
	// and MaxPathLenZero being true mean that the field was
	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
	// should be treated equivalent to -1 (unset).
	//
	// When generating a certificate, an unset pathLenConstraint
	// can be requested with either MaxPathLen == -1 or using the
	// zero value for both MaxPathLen and MaxPathLenZero.
	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

	// Name constraints
	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
	PermittedDNSDomains         []string
	ExcludedDNSDomains          []string

	// CRL Distribution Points
	CRLDistributionPoints []string

	PolicyIdentifiers []asn1.ObjectIdentifier

	// Certificate Transparency SCT extension contents; this is a TLS-encoded
	// SignedCertificateTimestampList (RFC 6962 s3.3).
	RawSCT  []byte
	SCTList SignedCertificateTimestampList
}

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 ParseTBSCertificate

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

ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data. The parsed data is returned in a Certificate struct for ease of access.

func (*Certificate) CheckCRLSignature

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

CheckCRLSignature checks that the signature in crl is from c.

func (*Certificate) CheckCertificateListSignature

func (c *Certificate) CheckCertificateListSignature(crl *CertificateList) error

CheckCertificateListSignature 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 interface{}, 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

Equal indicates whether two Certificate objects are equal (by comparing their DER-encoded values).

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 and system roots are unavailable the returned error will be of type SystemRootsError.

WARNING: this doesn't do any revocation checking.

Example
package main

import (
	"encoding/pem"

	"github.com/google/certificate-transparency-go/x509"
)

func main() {
	// Verifying with a custom list of root certificates.

	const rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJE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/KfglbLyyYygcQq
0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
-----END CERTIFICATE-----`

	// First, create the set of root certificates. For this example we only
	// have one. It's also possible to omit this in order to use the
	// default root set of the current operating system.
	roots := x509.NewCertPool()
	ok := roots.AppendCertsFromPEM([]byte(rootPEM))
	if !ok {
		panic("failed to parse root certificate")
	}

	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		panic("failed to parse certificate PEM")
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		panic("failed to parse certificate: " + err.Error())
	}

	opts := x509.VerifyOptions{
		DNSName: "mail.google.com",
		Roots:   roots,
	}

	if _, err := cert.Verify(opts); err != nil {
		panic("failed to verify certificate: " + err.Error())
	}
}
Output:

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.

type CertificateInvalidError

type CertificateInvalidError struct {
	Cert   *Certificate
	Reason InvalidReason
}

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 CertificateList

type CertificateList struct {
	Raw                asn1.RawContent
	TBSCertList        TBSCertList
	SignatureAlgorithm pkix.AlgorithmIdentifier
	SignatureValue     asn1.BitString
}

CertificateList represents the ASN.1 structure of the same name from RFC 5280, s5.1. It has the same content as pkix.CertificateList, but the contents include parsed versions of any extensions.

func ParseCertificateList

func ParseCertificateList(clBytes []byte) (*CertificateList, error)

ParseCertificateList parses a CertificateList (e.g. 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 ParseCertificateListDER

func ParseCertificateListDER(derBytes []byte) (*CertificateList, error)

ParseCertificateListDER parses a DER encoded CertificateList from the given bytes. For non-fatal errors, this function returns both an error and a CertificateList object.

func (*CertificateList) ExpiredAt

func (certList *CertificateList) ExpiredAt(now time.Time) bool

ExpiredAt reports whether now is past the expiry time of certList.

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          interface{}

	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
}

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 ErrCategory

type ErrCategory int

ErrCategory indicates the category of an x509.Error.

const (
	UnknownCategory ErrCategory = iota
	// Errors in ASN.1 encoding
	InvalidASN1Encoding
	InvalidASN1Content
	InvalidASN1DER
	// Errors in ASN.1 relative to schema
	InvalidValueRange
	InvalidASN1Type
	UnexpectedAdditionalData
	// Errors in X.509
	PoorlyFormedCertificate // Fails a SHOULD clause
	MalformedCertificate    // Fails a MUST clause
	PoorlyFormedCRL         // Fails a SHOULD clause
	MalformedCRL            // Fails a MUST clause
	// Errors relative to CA/Browser Forum guidelines
	BaselineRequirementsFailure
	EVRequirementsFailure
	// Other errors
	InsecureAlgorithm
	UnrecognizedValue
)

ErrCategory values.

func (ErrCategory) String

func (category ErrCategory) String() string

type Error

type Error struct {
	ID       ErrorID
	Category ErrCategory
	Summary  string
	Field    string
	SpecRef  string
	SpecText string
	// Fatal indicates that parsing has been aborted.
	Fatal bool
}

Error implements the error interface and describes a single error in an X.509 certificate or CRL.

func NewError

func NewError(id ErrorID, args ...interface{}) Error

NewError builds a new x509.Error based on the template for the given id.

func (Error) Error

func (err Error) Error() string

func (Error) VerboseError

func (err Error) VerboseError() string

VerboseError creates a more verbose error string, including spec details.

type ErrorID

type ErrorID int

ErrorID is an identifier for an x509.Error, to allow filtering.

const (
	ErrInvalidID ErrorID = iota
	ErrInvalidCertList
	ErrTrailingCertList
	ErrUnexpectedlyCriticalCertListExtension
	ErrUnexpectedlyNonCriticalCertListExtension
	ErrInvalidCertListAuthKeyID
	ErrTrailingCertListAuthKeyID
	ErrInvalidCertListIssuerAltName
	ErrInvalidCertListCRLNumber
	ErrTrailingCertListCRLNumber
	ErrNegativeCertListCRLNumber
	ErrInvalidCertListDeltaCRL
	ErrTrailingCertListDeltaCRL
	ErrNegativeCertListDeltaCRL
	ErrInvalidCertListIssuingDP
	ErrTrailingCertListIssuingDP
	ErrCertListIssuingDPMultipleTypes
	ErrCertListIssuingDPInvalidFullName
	ErrInvalidCertListFreshestCRL
	ErrInvalidCertListAuthInfoAccess
	ErrTrailingCertListAuthInfoAccess
	ErrUnhandledCriticalCertListExtension
	ErrUnexpectedlyCriticalRevokedCertExtension
	ErrUnexpectedlyNonCriticalRevokedCertExtension
	ErrInvalidRevocationReason
	ErrTrailingRevocationReason
	ErrInvalidRevocationInvalidityDate
	ErrTrailingRevocationInvalidityDate
	ErrInvalidRevocationIssuer
	ErrUnhandledCriticalRevokedCertExtension

	ErrMaxID
)

To preserve error IDs, only append to this list, never insert.

func ErrorFilter

func ErrorFilter(ignore string) []ErrorID

ErrorFilter builds a list of error IDs (suitable for use with Errors.Filter) from a comma-separated string.

type Errors

type Errors struct {
	Errs []Error
}

Errors implements the error interface and holds a collection of errors found in a certificate or CRL.

func (*Errors) AddID

func (e *Errors) AddID(id ErrorID, args ...interface{})

AddID adds the Error identified by the given id to an x509.Errors.

func (*Errors) Empty

func (e *Errors) Empty() bool

Empty indicates whether e has no errors.

func (*Errors) Error

func (e *Errors) Error() string

Error converts to a string.

func (*Errors) Fatal

func (e *Errors) Fatal() bool

Fatal indicates whether e includes a fatal error

func (Errors) Filter

func (e Errors) Filter(filtered []ErrorID) Errors

Filter creates a new Errors object with any entries from the filtered list of IDs removed.

func (*Errors) FirstFatal

func (e *Errors) FirstFatal() error

FirstFatal returns the first fatal error in e, or nil if there is no fatal error.

func (*Errors) VerboseError

func (e *Errors) VerboseError() string

VerboseError creates a more verbose error string, including spec details.

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
	ExtKeyUsageCertificateTransparency
)

ExtKeyUsage values:

type GeneralNames

type GeneralNames struct {
	DNSNames       []string
	EmailAddresses []string
	DirectoryNames []pkix.Name
	URIs           []string
	IPNets         []net.IPNet
	RegisteredIDs  []asn1.ObjectIdentifier
	OtherNames     []OtherName
}

GeneralNames holds a collection of names related to a certificate.

func (GeneralNames) Empty

func (gn GeneralNames) Empty() bool

Empty indicates whether a GeneralNames object is empty.

func (GeneralNames) Len

func (gn GeneralNames) Len() int

Len returns the total number of names in a GeneralNames object.

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

InsecureAlgorithmError results when the signature algorithm for a certificate is known to be insecure.

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 include the name
	// being checked.
	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
)

type IssuingDistributionPoint

type IssuingDistributionPoint struct {
	DistributionPoint          distributionPointName `asn1:"optional,tag:0"`
	OnlyContainsUserCerts      bool                  `asn1:"optional,tag:1"`
	OnlyContainsCACerts        bool                  `asn1:"optional,tag:2"`
	OnlySomeReasons            asn1.BitString        `asn1:"optional,tag:3"`
	IndirectCRL                bool                  `asn1:"optional,tag:4"`
	OnlyContainsAttributeCerts bool                  `asn1:"optional,tag:5"`
}

IssuingDistributionPoint represents the ASN.1 structure of the same name

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
)

KeyUsage values:

type NonFatalErrors

type NonFatalErrors struct {
	Errors []error
}

NonFatalErrors is an error type which can hold a number of other errors. It's used to collect a range of non-fatal errors which occur while parsing a certificate, that way we can still match on certs which technically are invalid.

func (*NonFatalErrors) AddError

func (e *NonFatalErrors) AddError(err error)

Adds an error to the list of errors contained by NonFatalErrors.

func (NonFatalErrors) Error

func (e NonFatalErrors) Error() string

Returns a string consisting of the values of Error() from all of the errors contained in |e|

func (*NonFatalErrors) HasError

func (e *NonFatalErrors) HasError() bool

Returns true if |e| contains at least one error

type OtherName

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

OtherName 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 }

type PEMCipher

type PEMCipher int
const (
	PEMCipherDES PEMCipher
	PEMCipher3DES
	PEMCipherAES128
	PEMCipherAES192
	PEMCipherAES256
)

Possible values for the EncryptPEMBlock encryption algorithm.

type PublicKeyAlgorithm

type PublicKeyAlgorithm int

PublicKeyAlgorithm indicates the algorithm used for a certificate's public key.

const (
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
	DSA
	ECDSA
)

PublicKeyAlgorithm values:

type ReasonFlag

type ReasonFlag int

ReasonFlag holds a bitmask of applicable revocation reasons, from RFC 5280 s4.2.1.13

const (
	UnusedFlag ReasonFlag = 1 << iota
	KeyCompromiseFlag
	CACompromiseFlag
	AffiliationChangedFlag
	SupersededFlag
	CessationOfOperationFlag
	CertificateHoldFlag
	PrivilegeWithdrawnFlag
	AACompromiseFlag
)

ReasonFlag values.

type RevocationReasonCode

type RevocationReasonCode asn1.Enumerated

RevocationReasonCode represents the reason for a certificate revocation; see RFC 5280 s5.3.1.

type RevokedCertificate

type RevokedCertificate struct {
	pkix.RevokedCertificate
	// Cracked out extensions:
	RevocationReason RevocationReasonCode
	InvalidityDate   time.Time
	Issuer           GeneralNames
}

RevokedCertificate represents the unnamed ASN.1 structure that makes up the revokedCertificates member of the TBSCertList structure from RFC 5280, s5.1. It has the same content as pkix.RevokedCertificate but the extensions are included in a parsed format.

type SerializedSCT

type SerializedSCT struct {
	Val []byte `tls:"minlen:1,maxlen:65535"`
}

SerializedSCT represents a single TLS-encoded signed certificate timestamp, from RFC6962 s3.3.

type SignatureAlgorithm

type SignatureAlgorithm int

SignatureAlgorithm indicates the algorithm used to sign a certificate.

const (
	UnknownSignatureAlgorithm SignatureAlgorithm = iota
	MD2WithRSA
	MD5WithRSA
	SHA1WithRSA
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
	DSAWithSHA1
	DSAWithSHA256
	ECDSAWithSHA1
	ECDSAWithSHA256
	ECDSAWithSHA384
	ECDSAWithSHA512
	SHA256WithRSAPSS
	SHA384WithRSAPSS
	SHA512WithRSAPSS
)

SignatureAlgorithm values:

func SignatureAlgorithmFromAI

func SignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm

SignatureAlgorithmFromAI converts an PKIX algorithm identifier to the equivalent local constant.

func (SignatureAlgorithm) String

func (algo SignatureAlgorithm) String() string

type SignedCertificateTimestampList

type SignedCertificateTimestampList struct {
	SCTList []SerializedSCT `tls:"minlen:1,maxlen:65335"`
}

SignedCertificateTimestampList is a list of signed certificate timestamps, from RFC6962 s3.3.

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

type TBSCertList

type TBSCertList struct {
	Raw                 asn1.RawContent
	Version             int
	Signature           pkix.AlgorithmIdentifier
	Issuer              pkix.RDNSequence
	ThisUpdate          time.Time
	NextUpdate          time.Time
	RevokedCertificates []*RevokedCertificate
	Extensions          []pkix.Extension
	// Cracked out extensions:
	AuthorityKeyID               []byte
	IssuerAltNames               GeneralNames
	CRLNumber                    int
	BaseCRLNumber                int // -1 if no delta CRL present
	IssuingDistributionPoint     IssuingDistributionPoint
	IssuingDPFullNames           GeneralNames
	FreshestCRLDistributionPoint []string
	OCSPServer                   []string
	IssuingCertificateURL        []string
}

TBSCertList represents the ASN.1 structure of the same name from RFC 5280, section 5.1. It has the same content as pkix.TBSCertificateList but the extensions are included in a parsed format.

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct {
	ID asn1.ObjectIdentifier
}

UnhandledCriticalExtension results when the certificate contains an extension that is marked as critical but which is not handled by this library.

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           string
	Intermediates     *CertPool
	Roots             *CertPool // if nil, the system roots are used
	CurrentTime       time.Time // if zero, the current time is used
	DisableTimeChecks bool
	// KeyUsage specifies which Extended Key Usage values are acceptable.
	// An empty list means ExtKeyUsageServerAuth. Key usage is considered a
	// constraint down the chain which mirrors Windows CryptoAPI behavior,
	// but not the spec. To accept any key usage, include ExtKeyUsageAny.
	KeyUsages []ExtKeyUsage
}

VerifyOptions contains parameters for Certificate.Verify. It's a structure because other PKIX verification APIs have ended up needing many options.

Directories

Path Synopsis
Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.

Jump to

Keyboard shortcuts

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