...

Source file src/github.com/google/certificate-transparency-go/x509/x509.go

Documentation: github.com/google/certificate-transparency-go/x509

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package x509 parses X.509-encoded keys and certificates.
     6  //
     7  // On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR
     8  // can be used to override the system default locations for the SSL certificate
     9  // file and SSL certificate files directory, respectively.
    10  //
    11  // This is a fork of the Go library crypto/x509 package, primarily adapted for
    12  // use with Certificate Transparency.  Main areas of difference are:
    13  //
    14  //   - Life as a fork:
    15  //   - Rename OS-specific cgo code so it doesn't clash with main Go library.
    16  //   - Use local library imports (asn1, pkix) throughout.
    17  //   - Add version-specific wrappers for Go version-incompatible code (in
    18  //     ptr_*_windows.go).
    19  //   - Laxer certificate parsing:
    20  //   - Add options to disable various validation checks (times, EKUs etc).
    21  //   - Use NonFatalErrors type for some errors and continue parsing; this
    22  //     can be checked with IsFatal(err).
    23  //   - Support for short bitlength ECDSA curves (in curves.go).
    24  //   - Certificate Transparency specific function:
    25  //   - Parsing and marshaling of SCTList extension.
    26  //   - RemoveSCTList() function for rebuilding CT leaf entry.
    27  //   - Pre-certificate processing (RemoveCTPoison(), BuildPrecertTBS(),
    28  //     ParseTBSCertificate(), IsPrecertificate()).
    29  //   - Revocation list processing:
    30  //   - Detailed CRL parsing (in revoked.go)
    31  //   - Detailed error recording mechanism (in error.go, errors.go)
    32  //   - Factor out parseDistributionPoints() for reuse.
    33  //   - Factor out and generalize GeneralNames parsing (in names.go)
    34  //   - Fix CRL commenting.
    35  //   - RPKI support:
    36  //   - Support for SubjectInfoAccess extension
    37  //   - Support for RFC3779 extensions (in rpki.go)
    38  //   - RSAES-OAEP support:
    39  //   - Support for parsing RSASES-OAEP public keys from certificates
    40  //   - Ed25519 support:
    41  //   - Support for parsing and marshaling Ed25519 keys
    42  //   - General improvements:
    43  //   - Export and use OID values throughout.
    44  //   - Export OIDFromNamedCurve().
    45  //   - Export SignatureAlgorithmFromAI().
    46  //   - Add OID value to UnhandledCriticalExtension error.
    47  //   - Minor typo/lint fixes.
    48  package x509
    49  
    50  import (
    51  	"bytes"
    52  	"crypto"
    53  	"crypto/dsa"
    54  	"crypto/ecdsa"
    55  	"crypto/elliptic"
    56  	"crypto/rsa"
    57  	_ "crypto/sha1"
    58  	_ "crypto/sha256"
    59  	_ "crypto/sha512"
    60  	"encoding/pem"
    61  	"errors"
    62  	"fmt"
    63  	"io"
    64  	"math/big"
    65  	"net"
    66  	"net/url"
    67  	"strconv"
    68  	"strings"
    69  	"time"
    70  	"unicode/utf8"
    71  
    72  	"golang.org/x/crypto/cryptobyte"
    73  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    74  	"golang.org/x/crypto/ed25519"
    75  
    76  	"github.com/google/certificate-transparency-go/asn1"
    77  	"github.com/google/certificate-transparency-go/tls"
    78  	"github.com/google/certificate-transparency-go/x509/pkix"
    79  )
    80  
    81  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    82  // in RFC 3280.
    83  type pkixPublicKey struct {
    84  	Algo      pkix.AlgorithmIdentifier
    85  	BitString asn1.BitString
    86  }
    87  
    88  // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
    89  //
    90  // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
    91  // ed25519.PublicKey. More types might be supported in the future.
    92  //
    93  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
    94  func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
    95  	var pki publicKeyInfo
    96  	if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
    97  		return nil, err
    98  	} else if len(rest) != 0 {
    99  		return nil, errors.New("x509: trailing data after ASN.1 of public-key")
   100  	}
   101  	algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
   102  	if algo == UnknownPublicKeyAlgorithm {
   103  		return nil, errors.New("x509: unknown public key algorithm")
   104  	}
   105  	var nfe NonFatalErrors
   106  	pub, err = parsePublicKey(algo, &pki, &nfe)
   107  	if err != nil {
   108  		return pub, err
   109  	}
   110  	// Treat non-fatal errors as fatal for this entrypoint.
   111  	if len(nfe.Errors) > 0 {
   112  		return nil, nfe.Errors[0]
   113  	}
   114  	return pub, nil
   115  }
   116  
   117  func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
   118  	switch pub := pub.(type) {
   119  	case *rsa.PublicKey:
   120  		publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
   121  			N: pub.N,
   122  			E: pub.E,
   123  		})
   124  		if err != nil {
   125  			return nil, pkix.AlgorithmIdentifier{}, err
   126  		}
   127  		publicKeyAlgorithm.Algorithm = OIDPublicKeyRSA
   128  		// This is a NULL parameters value which is required by
   129  		// RFC 3279, Section 2.3.1.
   130  		publicKeyAlgorithm.Parameters = asn1.NullRawValue
   131  	case *ecdsa.PublicKey:
   132  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   133  		oid, ok := OIDFromNamedCurve(pub.Curve)
   134  		if !ok {
   135  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   136  		}
   137  		publicKeyAlgorithm.Algorithm = OIDPublicKeyECDSA
   138  		var paramBytes []byte
   139  		paramBytes, err = asn1.Marshal(oid)
   140  		if err != nil {
   141  			return
   142  		}
   143  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   144  	case ed25519.PublicKey:
   145  		publicKeyBytes = pub
   146  		publicKeyAlgorithm.Algorithm = OIDPublicKeyEd25519
   147  	default:
   148  		return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
   149  	}
   150  
   151  	return publicKeyBytes, publicKeyAlgorithm, nil
   152  }
   153  
   154  // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
   155  //
   156  // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
   157  // and ed25519.PublicKey. Unsupported key types result in an error.
   158  //
   159  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
   160  func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
   161  	var publicKeyBytes []byte
   162  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
   163  	var err error
   164  
   165  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
   166  		return nil, err
   167  	}
   168  
   169  	pkix := pkixPublicKey{
   170  		Algo: publicKeyAlgorithm,
   171  		BitString: asn1.BitString{
   172  			Bytes:     publicKeyBytes,
   173  			BitLength: 8 * len(publicKeyBytes),
   174  		},
   175  	}
   176  
   177  	ret, _ := asn1.Marshal(pkix)
   178  	return ret, nil
   179  }
   180  
   181  // These structures reflect the ASN.1 structure of X.509 certificates.:
   182  
   183  type certificate struct {
   184  	Raw                asn1.RawContent
   185  	TBSCertificate     tbsCertificate
   186  	SignatureAlgorithm pkix.AlgorithmIdentifier
   187  	SignatureValue     asn1.BitString
   188  }
   189  
   190  type tbsCertificate struct {
   191  	Raw                asn1.RawContent
   192  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
   193  	SerialNumber       *big.Int
   194  	SignatureAlgorithm pkix.AlgorithmIdentifier
   195  	Issuer             asn1.RawValue
   196  	Validity           validity
   197  	Subject            asn1.RawValue
   198  	PublicKey          publicKeyInfo
   199  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   200  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   201  	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
   202  }
   203  
   204  // RFC 4055,  4.1
   205  // The current ASN.1 parser does not support non-integer defaults so
   206  // the 'default:' tags here do nothing.
   207  type rsaesoaepAlgorithmParameters struct {
   208  	HashFunc    pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:0,default:sha1Identifier"`
   209  	MaskgenFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:1,default:mgf1SHA1Identifier"`
   210  	PSourceFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:2,default:pSpecifiedEmptyIdentifier"`
   211  }
   212  
   213  type dsaAlgorithmParameters struct {
   214  	P, Q, G *big.Int
   215  }
   216  
   217  type dsaSignature struct {
   218  	R, S *big.Int
   219  }
   220  
   221  type ecdsaSignature dsaSignature
   222  
   223  type validity struct {
   224  	NotBefore, NotAfter time.Time
   225  }
   226  
   227  type publicKeyInfo struct {
   228  	Raw       asn1.RawContent
   229  	Algorithm pkix.AlgorithmIdentifier
   230  	PublicKey asn1.BitString
   231  }
   232  
   233  // RFC 5280,  4.2.1.1
   234  type authKeyId struct {
   235  	Id []byte `asn1:"optional,tag:0"`
   236  }
   237  
   238  // SignatureAlgorithm indicates the algorithm used to sign a certificate.
   239  type SignatureAlgorithm int
   240  
   241  // SignatureAlgorithm values:
   242  const (
   243  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   244  	MD2WithRSA
   245  	MD5WithRSA
   246  	SHA1WithRSA
   247  	SHA256WithRSA
   248  	SHA384WithRSA
   249  	SHA512WithRSA
   250  	DSAWithSHA1
   251  	DSAWithSHA256
   252  	ECDSAWithSHA1
   253  	ECDSAWithSHA256
   254  	ECDSAWithSHA384
   255  	ECDSAWithSHA512
   256  	SHA256WithRSAPSS
   257  	SHA384WithRSAPSS
   258  	SHA512WithRSAPSS
   259  	PureEd25519
   260  )
   261  
   262  // RFC 4055,  6. Basic object identifiers
   263  var oidpSpecified = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 9}
   264  
   265  // These are the default parameters for an RSAES-OAEP pubkey.
   266  // The current ASN.1 parser does not support non-integer defaults so
   267  // these currently do nothing.
   268  var (
   269  	sha1Identifier = pkix.AlgorithmIdentifier{
   270  		Algorithm:  oidSHA1,
   271  		Parameters: asn1.NullRawValue,
   272  	}
   273  	mgf1SHA1Identifier = pkix.AlgorithmIdentifier{
   274  		Algorithm: oidMGF1,
   275  		// RFC 4055, 2.1 sha1Identifier
   276  		Parameters: asn1.RawValue{
   277  			Class:      asn1.ClassUniversal,
   278  			Tag:        asn1.TagSequence,
   279  			IsCompound: false,
   280  			Bytes:      []byte{6, 5, 43, 14, 3, 2, 26, 5, 0},
   281  			FullBytes:  []byte{16, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0}},
   282  	}
   283  	pSpecifiedEmptyIdentifier = pkix.AlgorithmIdentifier{
   284  		Algorithm: oidpSpecified,
   285  		// RFC 4055, 4.1 nullOctetString
   286  		Parameters: asn1.RawValue{
   287  			Class:      asn1.ClassUniversal,
   288  			Tag:        asn1.TagOctetString,
   289  			IsCompound: false,
   290  			Bytes:      []byte{},
   291  			FullBytes:  []byte{4, 0}},
   292  	}
   293  )
   294  
   295  func (algo SignatureAlgorithm) isRSAPSS() bool {
   296  	switch algo {
   297  	case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
   298  		return true
   299  	default:
   300  		return false
   301  	}
   302  }
   303  
   304  func (algo SignatureAlgorithm) String() string {
   305  	for _, details := range signatureAlgorithmDetails {
   306  		if details.algo == algo {
   307  			return details.name
   308  		}
   309  	}
   310  	return strconv.Itoa(int(algo))
   311  }
   312  
   313  // PublicKeyAlgorithm indicates the algorithm used for a certificate's public key.
   314  type PublicKeyAlgorithm int
   315  
   316  // PublicKeyAlgorithm values:
   317  const (
   318  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   319  	RSA
   320  	DSA
   321  	ECDSA
   322  	Ed25519
   323  	RSAESOAEP
   324  )
   325  
   326  var publicKeyAlgoName = [...]string{
   327  	RSA:       "RSA",
   328  	DSA:       "DSA",
   329  	ECDSA:     "ECDSA",
   330  	Ed25519:   "Ed25519",
   331  	RSAESOAEP: "RSAESOAEP",
   332  }
   333  
   334  func (algo PublicKeyAlgorithm) String() string {
   335  	if 0 < algo && int(algo) < len(publicKeyAlgoName) {
   336  		return publicKeyAlgoName[algo]
   337  	}
   338  	return strconv.Itoa(int(algo))
   339  }
   340  
   341  // OIDs for signature algorithms
   342  //
   343  // pkcs-1 OBJECT IDENTIFIER ::= {
   344  //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   345  //
   346  //
   347  // RFC 3279 2.2.1 RSA Signature Algorithms
   348  //
   349  // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   350  //
   351  // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   352  //
   353  // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   354  //
   355  // dsaWithSha1 OBJECT IDENTIFIER ::= {
   356  //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   357  //
   358  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   359  //
   360  // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   361  // 	  iso(1) member-body(2) us(840) ansi-x962(10045)
   362  //    signatures(4) ecdsa-with-SHA1(1)}
   363  //
   364  //
   365  // RFC 4055 5 PKCS #1 Version 1.5
   366  //
   367  // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   368  //
   369  // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   370  //
   371  // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   372  //
   373  //
   374  // RFC 5758 3.1 DSA Signature Algorithms
   375  //
   376  // dsaWithSha256 OBJECT IDENTIFIER ::= {
   377  //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   378  //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   379  //
   380  // RFC 5758 3.2 ECDSA Signature Algorithm
   381  //
   382  // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   383  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   384  //
   385  // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   386  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   387  //
   388  // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   389  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   390  //
   391  //
   392  // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
   393  //
   394  // id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   395  
   396  var (
   397  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   398  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   399  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   400  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   401  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   402  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   403  	oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
   404  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   405  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
   406  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   407  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   408  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   409  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   410  	oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
   411  
   412  	oidSHA1   = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26}
   413  	oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
   414  	oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
   415  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
   416  
   417  	oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
   418  
   419  	// oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
   420  	// but it's specified by ISO. Microsoft's makecert.exe has been known
   421  	// to produce certificates with this OID.
   422  	oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
   423  )
   424  
   425  var signatureAlgorithmDetails = []struct {
   426  	algo       SignatureAlgorithm
   427  	name       string
   428  	oid        asn1.ObjectIdentifier
   429  	pubKeyAlgo PublicKeyAlgorithm
   430  	hash       crypto.Hash
   431  }{
   432  	{MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
   433  	{MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
   434  	{SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
   435  	{SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
   436  	{SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
   437  	{SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
   438  	{SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
   439  	{SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
   440  	{SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
   441  	{SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
   442  	{DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
   443  	{DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
   444  	{ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
   445  	{ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
   446  	{ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
   447  	{ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
   448  	{PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
   449  }
   450  
   451  // pssParameters reflects the parameters in an AlgorithmIdentifier that
   452  // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
   453  type pssParameters struct {
   454  	// The following three fields are not marked as
   455  	// optional because the default values specify SHA-1,
   456  	// which is no longer suitable for use in signatures.
   457  	Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
   458  	MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
   459  	SaltLength   int                      `asn1:"explicit,tag:2"`
   460  	TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
   461  }
   462  
   463  // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
   464  // in an AlgorithmIdentifier that specifies RSA PSS.
   465  func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
   466  	var hashOID asn1.ObjectIdentifier
   467  
   468  	switch hashFunc {
   469  	case crypto.SHA256:
   470  		hashOID = oidSHA256
   471  	case crypto.SHA384:
   472  		hashOID = oidSHA384
   473  	case crypto.SHA512:
   474  		hashOID = oidSHA512
   475  	}
   476  
   477  	params := pssParameters{
   478  		Hash: pkix.AlgorithmIdentifier{
   479  			Algorithm:  hashOID,
   480  			Parameters: asn1.NullRawValue,
   481  		},
   482  		MGF: pkix.AlgorithmIdentifier{
   483  			Algorithm: oidMGF1,
   484  		},
   485  		SaltLength:   hashFunc.Size(),
   486  		TrailerField: 1,
   487  	}
   488  
   489  	mgf1Params := pkix.AlgorithmIdentifier{
   490  		Algorithm:  hashOID,
   491  		Parameters: asn1.NullRawValue,
   492  	}
   493  
   494  	var err error
   495  	params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
   496  	if err != nil {
   497  		panic(err)
   498  	}
   499  
   500  	serialized, err := asn1.Marshal(params)
   501  	if err != nil {
   502  		panic(err)
   503  	}
   504  
   505  	return asn1.RawValue{FullBytes: serialized}
   506  }
   507  
   508  // SignatureAlgorithmFromAI converts an PKIX algorithm identifier to the
   509  // equivalent local constant.
   510  func SignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
   511  	if ai.Algorithm.Equal(oidSignatureEd25519) {
   512  		// RFC 8410, Section 3
   513  		// > For all of the OIDs, the parameters MUST be absent.
   514  		if len(ai.Parameters.FullBytes) != 0 {
   515  			return UnknownSignatureAlgorithm
   516  		}
   517  	}
   518  
   519  	if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
   520  		for _, details := range signatureAlgorithmDetails {
   521  			if ai.Algorithm.Equal(details.oid) {
   522  				return details.algo
   523  			}
   524  		}
   525  		return UnknownSignatureAlgorithm
   526  	}
   527  
   528  	// RSA PSS is special because it encodes important parameters
   529  	// in the Parameters.
   530  
   531  	var params pssParameters
   532  	if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
   533  		return UnknownSignatureAlgorithm
   534  	}
   535  
   536  	var mgf1HashFunc pkix.AlgorithmIdentifier
   537  	if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
   538  		return UnknownSignatureAlgorithm
   539  	}
   540  
   541  	// PSS is greatly overburdened with options. This code forces them into
   542  	// three buckets by requiring that the MGF1 hash function always match the
   543  	// message hash function (as recommended in RFC 3447, Section 8.1), that the
   544  	// salt length matches the hash length, and that the trailer field has the
   545  	// default value.
   546  	if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
   547  		!params.MGF.Algorithm.Equal(oidMGF1) ||
   548  		!mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
   549  		(len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
   550  		params.TrailerField != 1 {
   551  		return UnknownSignatureAlgorithm
   552  	}
   553  
   554  	switch {
   555  	case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
   556  		return SHA256WithRSAPSS
   557  	case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
   558  		return SHA384WithRSAPSS
   559  	case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
   560  		return SHA512WithRSAPSS
   561  	}
   562  
   563  	return UnknownSignatureAlgorithm
   564  }
   565  
   566  // RFC 3279, 2.3 Public Key Algorithms
   567  //
   568  // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   569  //
   570  //	rsadsi(113549) pkcs(1) 1 }
   571  //
   572  // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   573  //
   574  // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   575  //
   576  //	x9-57(10040) x9cm(4) 1 }
   577  //
   578  // # RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   579  //
   580  //	id-ecPublicKey OBJECT IDENTIFIER ::= {
   581  //	      iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   582  var (
   583  	OIDPublicKeyRSA         = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   584  	OIDPublicKeyRSAESOAEP   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 7}
   585  	OIDPublicKeyDSA         = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   586  	OIDPublicKeyECDSA       = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   587  	OIDPublicKeyRSAObsolete = asn1.ObjectIdentifier{2, 5, 8, 1, 1}
   588  	OIDPublicKeyEd25519     = oidSignatureEd25519
   589  )
   590  
   591  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   592  	switch {
   593  	case oid.Equal(OIDPublicKeyRSA):
   594  		return RSA
   595  	case oid.Equal(OIDPublicKeyDSA):
   596  		return DSA
   597  	case oid.Equal(OIDPublicKeyECDSA):
   598  		return ECDSA
   599  	case oid.Equal(OIDPublicKeyRSAESOAEP):
   600  		return RSAESOAEP
   601  	case oid.Equal(OIDPublicKeyEd25519):
   602  		return Ed25519
   603  	}
   604  	return UnknownPublicKeyAlgorithm
   605  }
   606  
   607  // RFC 5480, 2.1.1.1. Named Curve
   608  //
   609  //	secp224r1 OBJECT IDENTIFIER ::= {
   610  //	  iso(1) identified-organization(3) certicom(132) curve(0) 33 }
   611  //
   612  //	secp256r1 OBJECT IDENTIFIER ::= {
   613  //	  iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   614  //	  prime(1) 7 }
   615  //
   616  //	secp384r1 OBJECT IDENTIFIER ::= {
   617  //	  iso(1) identified-organization(3) certicom(132) curve(0) 34 }
   618  //
   619  //	secp521r1 OBJECT IDENTIFIER ::= {
   620  //	  iso(1) identified-organization(3) certicom(132) curve(0) 35 }
   621  //
   622  //	secp192r1 OBJECT IDENTIFIER ::= {
   623  //	    iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   624  //	    prime(1) 1 }
   625  //
   626  // NB: secp256r1 is equivalent to prime256v1,
   627  // secp192r1 is equivalent to ansix9p192r and prime192v1
   628  var (
   629  	OIDNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   630  	OIDNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   631  	OIDNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   632  	OIDNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   633  	OIDNamedCurveP192 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 1}
   634  )
   635  
   636  func namedCurveFromOID(oid asn1.ObjectIdentifier, nfe *NonFatalErrors) elliptic.Curve {
   637  	switch {
   638  	case oid.Equal(OIDNamedCurveP224):
   639  		return elliptic.P224()
   640  	case oid.Equal(OIDNamedCurveP256):
   641  		return elliptic.P256()
   642  	case oid.Equal(OIDNamedCurveP384):
   643  		return elliptic.P384()
   644  	case oid.Equal(OIDNamedCurveP521):
   645  		return elliptic.P521()
   646  	case oid.Equal(OIDNamedCurveP192):
   647  		nfe.AddError(errors.New("insecure curve (secp192r1) specified"))
   648  		return secp192r1()
   649  	}
   650  	return nil
   651  }
   652  
   653  // OIDFromNamedCurve returns the OID used to specify the use of the given
   654  // elliptic curve.
   655  func OIDFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   656  	switch curve {
   657  	case elliptic.P224():
   658  		return OIDNamedCurveP224, true
   659  	case elliptic.P256():
   660  		return OIDNamedCurveP256, true
   661  	case elliptic.P384():
   662  		return OIDNamedCurveP384, true
   663  	case elliptic.P521():
   664  		return OIDNamedCurveP521, true
   665  	case secp192r1():
   666  		return OIDNamedCurveP192, true
   667  	}
   668  
   669  	return nil, false
   670  }
   671  
   672  // KeyUsage represents the set of actions that are valid for a given key. It's
   673  // a bitmap of the KeyUsage* constants.
   674  type KeyUsage int
   675  
   676  // KeyUsage values:
   677  const (
   678  	KeyUsageDigitalSignature KeyUsage = 1 << iota
   679  	KeyUsageContentCommitment
   680  	KeyUsageKeyEncipherment
   681  	KeyUsageDataEncipherment
   682  	KeyUsageKeyAgreement
   683  	KeyUsageCertSign
   684  	KeyUsageCRLSign
   685  	KeyUsageEncipherOnly
   686  	KeyUsageDecipherOnly
   687  )
   688  
   689  // RFC 5280, 4.2.1.12  Extended Key Usage
   690  //
   691  // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   692  //
   693  // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   694  //
   695  // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   696  // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   697  // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   698  // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   699  // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   700  // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   701  var (
   702  	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   703  	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   704  	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   705  	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   706  	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   707  	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   708  	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   709  	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   710  	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   711  	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   712  	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   713  	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   714  	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
   715  	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
   716  	// RFC 6962 s3.1
   717  	oidExtKeyUsageCertificateTransparency = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 4}
   718  )
   719  
   720  // ExtKeyUsage represents an extended set of actions that are valid for a given key.
   721  // Each of the ExtKeyUsage* constants define a unique action.
   722  type ExtKeyUsage int
   723  
   724  // ExtKeyUsage values:
   725  const (
   726  	ExtKeyUsageAny ExtKeyUsage = iota
   727  	ExtKeyUsageServerAuth
   728  	ExtKeyUsageClientAuth
   729  	ExtKeyUsageCodeSigning
   730  	ExtKeyUsageEmailProtection
   731  	ExtKeyUsageIPSECEndSystem
   732  	ExtKeyUsageIPSECTunnel
   733  	ExtKeyUsageIPSECUser
   734  	ExtKeyUsageTimeStamping
   735  	ExtKeyUsageOCSPSigning
   736  	ExtKeyUsageMicrosoftServerGatedCrypto
   737  	ExtKeyUsageNetscapeServerGatedCrypto
   738  	ExtKeyUsageMicrosoftCommercialCodeSigning
   739  	ExtKeyUsageMicrosoftKernelCodeSigning
   740  	ExtKeyUsageCertificateTransparency
   741  )
   742  
   743  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   744  var extKeyUsageOIDs = []struct {
   745  	extKeyUsage ExtKeyUsage
   746  	oid         asn1.ObjectIdentifier
   747  }{
   748  	{ExtKeyUsageAny, oidExtKeyUsageAny},
   749  	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   750  	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   751  	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   752  	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   753  	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   754  	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   755  	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   756  	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   757  	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   758  	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   759  	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   760  	{ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
   761  	{ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
   762  	{ExtKeyUsageCertificateTransparency, oidExtKeyUsageCertificateTransparency},
   763  }
   764  
   765  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
   766  	for _, pair := range extKeyUsageOIDs {
   767  		if oid.Equal(pair.oid) {
   768  			return pair.extKeyUsage, true
   769  		}
   770  	}
   771  	return
   772  }
   773  
   774  func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   775  	for _, pair := range extKeyUsageOIDs {
   776  		if eku == pair.extKeyUsage {
   777  			return pair.oid, true
   778  		}
   779  	}
   780  	return
   781  }
   782  
   783  // SerializedSCT represents a single TLS-encoded signed certificate timestamp, from RFC6962 s3.3.
   784  type SerializedSCT struct {
   785  	Val []byte `tls:"minlen:1,maxlen:65535"`
   786  }
   787  
   788  // SignedCertificateTimestampList is a list of signed certificate timestamps, from RFC6962 s3.3.
   789  type SignedCertificateTimestampList struct {
   790  	SCTList []SerializedSCT `tls:"minlen:1,maxlen:65335"`
   791  }
   792  
   793  // A Certificate represents an X.509 certificate.
   794  type Certificate struct {
   795  	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
   796  	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
   797  	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
   798  	RawSubject              []byte // DER encoded Subject
   799  	RawIssuer               []byte // DER encoded Issuer
   800  
   801  	Signature          []byte
   802  	SignatureAlgorithm SignatureAlgorithm
   803  
   804  	PublicKeyAlgorithm PublicKeyAlgorithm
   805  	PublicKey          interface{}
   806  
   807  	Version             int
   808  	SerialNumber        *big.Int
   809  	Issuer              pkix.Name
   810  	Subject             pkix.Name
   811  	NotBefore, NotAfter time.Time // Validity bounds.
   812  	KeyUsage            KeyUsage
   813  
   814  	// Extensions contains raw X.509 extensions. When parsing certificates,
   815  	// this can be used to extract non-critical extensions that are not
   816  	// parsed by this package. When marshaling certificates, the Extensions
   817  	// field is ignored, see ExtraExtensions.
   818  	Extensions []pkix.Extension
   819  
   820  	// ExtraExtensions contains extensions to be copied, raw, into any
   821  	// marshaled certificates. Values override any extensions that would
   822  	// otherwise be produced based on the other fields. The ExtraExtensions
   823  	// field is not populated when parsing certificates, see Extensions.
   824  	ExtraExtensions []pkix.Extension
   825  
   826  	// UnhandledCriticalExtensions contains a list of extension IDs that
   827  	// were not (fully) processed when parsing. Verify will fail if this
   828  	// slice is non-empty, unless verification is delegated to an OS
   829  	// library which understands all the critical extensions.
   830  	//
   831  	// Users can access these extensions using Extensions and can remove
   832  	// elements from this slice if they believe that they have been
   833  	// handled.
   834  	UnhandledCriticalExtensions []asn1.ObjectIdentifier
   835  
   836  	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
   837  	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
   838  
   839  	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
   840  	// and MaxPathLenZero are valid.
   841  	BasicConstraintsValid bool
   842  	IsCA                  bool
   843  
   844  	// MaxPathLen and MaxPathLenZero indicate the presence and
   845  	// value of the BasicConstraints' "pathLenConstraint".
   846  	//
   847  	// When parsing a certificate, a positive non-zero MaxPathLen
   848  	// means that the field was specified, -1 means it was unset,
   849  	// and MaxPathLenZero being true mean that the field was
   850  	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
   851  	// should be treated equivalent to -1 (unset).
   852  	//
   853  	// When generating a certificate, an unset pathLenConstraint
   854  	// can be requested with either MaxPathLen == -1 or using the
   855  	// zero value for both MaxPathLen and MaxPathLenZero.
   856  	MaxPathLen int
   857  	// MaxPathLenZero indicates that BasicConstraintsValid==true
   858  	// and MaxPathLen==0 should be interpreted as an actual
   859  	// maximum path length of zero. Otherwise, that combination is
   860  	// interpreted as MaxPathLen not being set.
   861  	MaxPathLenZero bool
   862  
   863  	SubjectKeyId   []byte
   864  	AuthorityKeyId []byte
   865  
   866  	// RFC 5280, 4.2.2.1 (Authority Information Access)
   867  	OCSPServer            []string
   868  	IssuingCertificateURL []string
   869  
   870  	// Subject Information Access
   871  	SubjectTimestamps     []string
   872  	SubjectCARepositories []string
   873  
   874  	// Subject Alternate Name values. (Note that these values may not be valid
   875  	// if invalid values were contained within a parsed certificate. For
   876  	// example, an element of DNSNames may not be a valid DNS domain name.)
   877  	DNSNames       []string
   878  	EmailAddresses []string
   879  	IPAddresses    []net.IP
   880  	URIs           []*url.URL
   881  
   882  	// Name constraints
   883  	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   884  	PermittedDNSDomains         []string
   885  	ExcludedDNSDomains          []string
   886  	PermittedIPRanges           []*net.IPNet
   887  	ExcludedIPRanges            []*net.IPNet
   888  	PermittedEmailAddresses     []string
   889  	ExcludedEmailAddresses      []string
   890  	PermittedURIDomains         []string
   891  	ExcludedURIDomains          []string
   892  
   893  	// CRL Distribution Points
   894  	CRLDistributionPoints []string
   895  
   896  	PolicyIdentifiers []asn1.ObjectIdentifier
   897  
   898  	RPKIAddressRanges                   []*IPAddressFamilyBlocks
   899  	RPKIASNumbers, RPKIRoutingDomainIDs *ASIdentifiers
   900  
   901  	// Certificate Transparency SCT extension contents; this is a TLS-encoded
   902  	// SignedCertificateTimestampList (RFC 6962 s3.3).
   903  	RawSCT  []byte
   904  	SCTList SignedCertificateTimestampList
   905  }
   906  
   907  // ErrUnsupportedAlgorithm results from attempting to perform an operation that
   908  // involves algorithms that are not currently implemented.
   909  var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
   910  
   911  // InsecureAlgorithmError results when the signature algorithm for a certificate
   912  // is known to be insecure.
   913  type InsecureAlgorithmError SignatureAlgorithm
   914  
   915  func (e InsecureAlgorithmError) Error() string {
   916  	return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
   917  }
   918  
   919  // ConstraintViolationError results when a requested usage is not permitted by
   920  // a certificate. For example: checking a signature when the public key isn't a
   921  // certificate signing key.
   922  type ConstraintViolationError struct{}
   923  
   924  func (ConstraintViolationError) Error() string {
   925  	return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
   926  }
   927  
   928  // Equal indicates whether two Certificate objects are equal (by comparing their
   929  // DER-encoded values).
   930  func (c *Certificate) Equal(other *Certificate) bool {
   931  	if c == nil || other == nil {
   932  		return c == other
   933  	}
   934  	return bytes.Equal(c.Raw, other.Raw)
   935  }
   936  
   937  // IsPrecertificate checks whether the certificate is a precertificate, by
   938  // checking for the presence of the CT Poison extension.
   939  func (c *Certificate) IsPrecertificate() bool {
   940  	if c == nil {
   941  		return false
   942  	}
   943  	for _, ext := range c.Extensions {
   944  		if ext.Id.Equal(OIDExtensionCTPoison) {
   945  			return true
   946  		}
   947  	}
   948  	return false
   949  }
   950  
   951  func (c *Certificate) hasSANExtension() bool {
   952  	return oidInExtensions(OIDExtensionSubjectAltName, c.Extensions)
   953  }
   954  
   955  // Entrust have a broken root certificate (CN=Entrust.net Certification
   956  // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
   957  // according to PKIX.
   958  // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
   959  // from the Basic Constraints requirement.
   960  // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
   961  //
   962  // TODO(agl): remove this hack once their reissued root is sufficiently
   963  // widespread.
   964  var entrustBrokenSPKI = []byte{
   965  	0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
   966  	0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
   967  	0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
   968  	0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
   969  	0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
   970  	0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
   971  	0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
   972  	0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
   973  	0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
   974  	0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
   975  	0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
   976  	0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
   977  	0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
   978  	0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
   979  	0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
   980  	0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
   981  	0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
   982  	0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
   983  	0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
   984  	0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
   985  	0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
   986  	0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
   987  	0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
   988  	0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
   989  	0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
   990  	0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
   991  	0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
   992  	0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
   993  	0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
   994  	0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
   995  	0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
   996  	0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
   997  	0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
   998  	0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
   999  	0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
  1000  	0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
  1001  	0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
  1002  }
  1003  
  1004  // CheckSignatureFrom verifies that the signature on c is a valid signature
  1005  // from parent.
  1006  func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
  1007  	// RFC 5280, 4.2.1.9:
  1008  	// "If the basic constraints extension is not present in a version 3
  1009  	// certificate, or the extension is present but the cA boolean is not
  1010  	// asserted, then the certified public key MUST NOT be used to verify
  1011  	// certificate signatures."
  1012  	// (except for Entrust, see comment above entrustBrokenSPKI)
  1013  	if (parent.Version == 3 && !parent.BasicConstraintsValid ||
  1014  		parent.BasicConstraintsValid && !parent.IsCA) &&
  1015  		!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
  1016  		return ConstraintViolationError{}
  1017  	}
  1018  
  1019  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
  1020  		return ConstraintViolationError{}
  1021  	}
  1022  
  1023  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
  1024  		return ErrUnsupportedAlgorithm
  1025  	}
  1026  
  1027  	// TODO(agl): don't ignore the path length constraint.
  1028  
  1029  	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
  1030  }
  1031  
  1032  // CheckSignature verifies that signature is a valid signature over signed from
  1033  // c's public key.
  1034  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
  1035  	return checkSignature(algo, signed, signature, c.PublicKey)
  1036  }
  1037  
  1038  func (c *Certificate) hasNameConstraints() bool {
  1039  	return oidInExtensions(OIDExtensionNameConstraints, c.Extensions)
  1040  }
  1041  
  1042  func (c *Certificate) getSANExtension() []byte {
  1043  	for _, e := range c.Extensions {
  1044  		if e.Id.Equal(OIDExtensionSubjectAltName) {
  1045  			return e.Value
  1046  		}
  1047  	}
  1048  
  1049  	return nil
  1050  }
  1051  
  1052  func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
  1053  	return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
  1054  }
  1055  
  1056  // CheckSignature verifies that signature is a valid signature over signed from
  1057  // a crypto.PublicKey.
  1058  func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
  1059  	var hashType crypto.Hash
  1060  	var pubKeyAlgo PublicKeyAlgorithm
  1061  
  1062  	for _, details := range signatureAlgorithmDetails {
  1063  		if details.algo == algo {
  1064  			hashType = details.hash
  1065  			pubKeyAlgo = details.pubKeyAlgo
  1066  		}
  1067  	}
  1068  
  1069  	switch hashType {
  1070  	case crypto.Hash(0):
  1071  		if pubKeyAlgo != Ed25519 {
  1072  			return ErrUnsupportedAlgorithm
  1073  		}
  1074  	case crypto.MD5:
  1075  		return InsecureAlgorithmError(algo)
  1076  	default:
  1077  		if !hashType.Available() {
  1078  			return ErrUnsupportedAlgorithm
  1079  		}
  1080  		h := hashType.New()
  1081  		h.Write(signed)
  1082  		signed = h.Sum(nil)
  1083  	}
  1084  
  1085  	switch pub := publicKey.(type) {
  1086  	case *rsa.PublicKey:
  1087  		if pubKeyAlgo != RSA {
  1088  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1089  		}
  1090  		if algo.isRSAPSS() {
  1091  			return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
  1092  		} else {
  1093  			return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
  1094  		}
  1095  	case *dsa.PublicKey:
  1096  		if pubKeyAlgo != DSA {
  1097  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1098  		}
  1099  		dsaSig := new(dsaSignature)
  1100  		if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
  1101  			return err
  1102  		} else if len(rest) != 0 {
  1103  			return errors.New("x509: trailing data after DSA signature")
  1104  		}
  1105  		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
  1106  			return errors.New("x509: DSA signature contained zero or negative values")
  1107  		}
  1108  		// According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
  1109  		// than the key length, but crypto/dsa doesn't do it automatically.
  1110  		if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
  1111  			signed = signed[:maxHashLen]
  1112  		}
  1113  		if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
  1114  			return errors.New("x509: DSA verification failure")
  1115  		}
  1116  		return
  1117  	case *ecdsa.PublicKey:
  1118  		if pubKeyAlgo != ECDSA {
  1119  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1120  		}
  1121  		ecdsaSig := new(ecdsaSignature)
  1122  		if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
  1123  			return err
  1124  		} else if len(rest) != 0 {
  1125  			return errors.New("x509: trailing data after ECDSA signature")
  1126  		}
  1127  		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  1128  			return errors.New("x509: ECDSA signature contained zero or negative values")
  1129  		}
  1130  		if !ecdsa.Verify(pub, signed, ecdsaSig.R, ecdsaSig.S) {
  1131  			return errors.New("x509: ECDSA verification failure")
  1132  		}
  1133  		return
  1134  	case ed25519.PublicKey:
  1135  		if pubKeyAlgo != Ed25519 {
  1136  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1137  		}
  1138  		if !ed25519.Verify(pub, signed, signature) {
  1139  			return errors.New("x509: Ed25519 verification failure")
  1140  		}
  1141  		return
  1142  	}
  1143  	return ErrUnsupportedAlgorithm
  1144  }
  1145  
  1146  // CheckCRLSignature checks that the signature in crl is from c.
  1147  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
  1148  	algo := SignatureAlgorithmFromAI(crl.SignatureAlgorithm)
  1149  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
  1150  }
  1151  
  1152  // UnhandledCriticalExtension results when the certificate contains an extension
  1153  // that is marked as critical but which is not handled by this library.
  1154  type UnhandledCriticalExtension struct {
  1155  	ID asn1.ObjectIdentifier
  1156  }
  1157  
  1158  func (h UnhandledCriticalExtension) Error() string {
  1159  	return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID)
  1160  }
  1161  
  1162  // removeExtension takes a DER-encoded TBSCertificate, removes the extension
  1163  // specified by oid (preserving the order of other extensions), and returns the
  1164  // result still as a DER-encoded TBSCertificate.  This function will fail if
  1165  // there is not exactly 1 extension of the type specified by the oid present.
  1166  func removeExtension(tbsData []byte, oid asn1.ObjectIdentifier) ([]byte, error) {
  1167  	var tbs tbsCertificate
  1168  	rest, err := asn1.Unmarshal(tbsData, &tbs)
  1169  	if err != nil {
  1170  		return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err)
  1171  	} else if rLen := len(rest); rLen > 0 {
  1172  		return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen)
  1173  	}
  1174  	extAt := -1
  1175  	for i, ext := range tbs.Extensions {
  1176  		if ext.Id.Equal(oid) {
  1177  			if extAt != -1 {
  1178  				return nil, errors.New("multiple extensions of specified type present")
  1179  			}
  1180  			extAt = i
  1181  		}
  1182  	}
  1183  	if extAt == -1 {
  1184  		return nil, errors.New("no extension of specified type present")
  1185  	}
  1186  	tbs.Extensions = append(tbs.Extensions[:extAt], tbs.Extensions[extAt+1:]...)
  1187  	// Clear out the asn1.RawContent so the re-marshal operation sees the
  1188  	// updated structure (rather than just copying the out-of-date DER data).
  1189  	tbs.Raw = nil
  1190  
  1191  	data, err := asn1.Marshal(tbs)
  1192  	if err != nil {
  1193  		return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err)
  1194  	}
  1195  	return data, nil
  1196  }
  1197  
  1198  // RemoveSCTList takes a DER-encoded TBSCertificate and removes the CT SCT
  1199  // extension that contains the SCT list (preserving the order of other
  1200  // extensions), and returns the result still as a DER-encoded TBSCertificate.
  1201  // This function will fail if there is not exactly 1 CT SCT extension present.
  1202  func RemoveSCTList(tbsData []byte) ([]byte, error) {
  1203  	return removeExtension(tbsData, OIDExtensionCTSCT)
  1204  }
  1205  
  1206  // RemoveCTPoison takes a DER-encoded TBSCertificate and removes the CT poison
  1207  // extension (preserving the order of other extensions), and returns the result
  1208  // still as a DER-encoded TBSCertificate.  This function will fail if there is
  1209  // not exactly 1 CT poison extension present.
  1210  func RemoveCTPoison(tbsData []byte) ([]byte, error) {
  1211  	return BuildPrecertTBS(tbsData, nil)
  1212  }
  1213  
  1214  // BuildPrecertTBS builds a Certificate Transparency pre-certificate (RFC 6962
  1215  // s3.1) from the given DER-encoded TBSCertificate, returning a DER-encoded
  1216  // TBSCertificate.
  1217  //
  1218  // This function removes the CT poison extension (there must be exactly 1 of
  1219  // these), preserving the order of other extensions.
  1220  //
  1221  // If preIssuer is provided, this should be a special intermediate certificate
  1222  // that was used to sign the precert (indicated by having the special
  1223  // CertificateTransparency extended key usage).  In this case, the issuance
  1224  // information of the pre-cert is updated to reflect the next issuer in the
  1225  // chain, i.e. the issuer of this special intermediate:
  1226  //   - The precert's Issuer is changed to the Issuer of the intermediate
  1227  //   - The precert's AuthorityKeyId is changed to the AuthorityKeyId of the
  1228  //     intermediate.
  1229  func BuildPrecertTBS(tbsData []byte, preIssuer *Certificate) ([]byte, error) {
  1230  	data, err := removeExtension(tbsData, OIDExtensionCTPoison)
  1231  	if err != nil {
  1232  		return nil, err
  1233  	}
  1234  
  1235  	var tbs tbsCertificate
  1236  	rest, err := asn1.Unmarshal(data, &tbs)
  1237  	if err != nil {
  1238  		return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err)
  1239  	} else if rLen := len(rest); rLen > 0 {
  1240  		return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen)
  1241  	}
  1242  
  1243  	if preIssuer != nil {
  1244  		// Update the precert's Issuer field.  Use the RawIssuer rather than the
  1245  		// parsed Issuer to avoid any chance of ASN.1 differences (e.g. switching
  1246  		// from UTF8String to PrintableString).
  1247  		tbs.Issuer.FullBytes = preIssuer.RawIssuer
  1248  
  1249  		// Also need to update the cert's AuthorityKeyID extension
  1250  		// to that of the preIssuer.
  1251  		var issuerKeyID []byte
  1252  		for _, ext := range preIssuer.Extensions {
  1253  			if ext.Id.Equal(OIDExtensionAuthorityKeyId) {
  1254  				issuerKeyID = ext.Value
  1255  				break
  1256  			}
  1257  		}
  1258  
  1259  		// Check the preIssuer has the CT EKU.
  1260  		seenCTEKU := false
  1261  		for _, eku := range preIssuer.ExtKeyUsage {
  1262  			if eku == ExtKeyUsageCertificateTransparency {
  1263  				seenCTEKU = true
  1264  				break
  1265  			}
  1266  		}
  1267  		if !seenCTEKU {
  1268  			return nil, fmt.Errorf("issuer does not have CertificateTransparency extended key usage")
  1269  		}
  1270  
  1271  		keyAt := -1
  1272  		for i, ext := range tbs.Extensions {
  1273  			if ext.Id.Equal(OIDExtensionAuthorityKeyId) {
  1274  				keyAt = i
  1275  				break
  1276  			}
  1277  		}
  1278  		if keyAt >= 0 {
  1279  			// PreCert has an auth-key-id; replace it with the value from the preIssuer
  1280  			if issuerKeyID != nil {
  1281  				tbs.Extensions[keyAt].Value = issuerKeyID
  1282  			} else {
  1283  				tbs.Extensions = append(tbs.Extensions[:keyAt], tbs.Extensions[keyAt+1:]...)
  1284  			}
  1285  		} else if issuerKeyID != nil {
  1286  			// PreCert did not have an auth-key-id, but the preIssuer does, so add it at the end.
  1287  			authKeyIDExt := pkix.Extension{
  1288  				Id:       OIDExtensionAuthorityKeyId,
  1289  				Critical: false,
  1290  				Value:    issuerKeyID,
  1291  			}
  1292  			tbs.Extensions = append(tbs.Extensions, authKeyIDExt)
  1293  		}
  1294  
  1295  		// Clear out the asn1.RawContent so the re-marshal operation sees the
  1296  		// updated structure (rather than just copying the out-of-date DER data).
  1297  		tbs.Raw = nil
  1298  	}
  1299  
  1300  	data, err = asn1.Marshal(tbs)
  1301  	if err != nil {
  1302  		return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err)
  1303  	}
  1304  	return data, nil
  1305  }
  1306  
  1307  type basicConstraints struct {
  1308  	IsCA       bool `asn1:"optional"`
  1309  	MaxPathLen int  `asn1:"optional,default:-1"`
  1310  }
  1311  
  1312  // RFC 5280, 4.2.1.4
  1313  type policyInformation struct {
  1314  	Policy asn1.ObjectIdentifier
  1315  	// policyQualifiers omitted
  1316  }
  1317  
  1318  const (
  1319  	nameTypeEmail = 1
  1320  	nameTypeDNS   = 2
  1321  	nameTypeURI   = 6
  1322  	nameTypeIP    = 7
  1323  )
  1324  
  1325  // RFC 5280, 4.2.2.1
  1326  type accessDescription struct {
  1327  	Method   asn1.ObjectIdentifier
  1328  	Location asn1.RawValue
  1329  }
  1330  
  1331  // RFC 5280, 4.2.1.14
  1332  type distributionPoint struct {
  1333  	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  1334  	Reason            asn1.BitString        `asn1:"optional,tag:1"`
  1335  	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
  1336  }
  1337  
  1338  type distributionPointName struct {
  1339  	FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
  1340  	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  1341  }
  1342  
  1343  func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo, nfe *NonFatalErrors) (interface{}, error) {
  1344  	asn1Data := keyData.PublicKey.RightAlign()
  1345  	switch algo {
  1346  	case RSA, RSAESOAEP:
  1347  		// RSA public keys must have a NULL in the parameters.
  1348  		// See RFC 3279, Section 2.3.1.
  1349  		if algo == RSA && !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
  1350  			nfe.AddError(errors.New("x509: RSA key missing NULL parameters"))
  1351  		}
  1352  		if algo == RSAESOAEP {
  1353  			// We only parse the parameters to ensure it is a valid encoding, we throw out the actual values
  1354  			paramsData := keyData.Algorithm.Parameters.FullBytes
  1355  			params := new(rsaesoaepAlgorithmParameters)
  1356  			params.HashFunc = sha1Identifier
  1357  			params.MaskgenFunc = mgf1SHA1Identifier
  1358  			params.PSourceFunc = pSpecifiedEmptyIdentifier
  1359  			rest, err := asn1.Unmarshal(paramsData, params)
  1360  			if err != nil {
  1361  				return nil, err
  1362  			}
  1363  			if len(rest) != 0 {
  1364  				return nil, errors.New("x509: trailing data after RSAES-OAEP parameters")
  1365  			}
  1366  		}
  1367  
  1368  		p := new(pkcs1PublicKey)
  1369  		rest, err := asn1.Unmarshal(asn1Data, p)
  1370  		if err != nil {
  1371  			var laxErr error
  1372  			rest, laxErr = asn1.UnmarshalWithParams(asn1Data, p, "lax")
  1373  			if laxErr != nil {
  1374  				return nil, laxErr
  1375  			}
  1376  			nfe.AddError(err)
  1377  		}
  1378  		if len(rest) != 0 {
  1379  			return nil, errors.New("x509: trailing data after RSA public key")
  1380  		}
  1381  
  1382  		if p.N.Sign() <= 0 {
  1383  			nfe.AddError(errors.New("x509: RSA modulus is not a positive number"))
  1384  		}
  1385  		if p.E <= 0 {
  1386  			return nil, errors.New("x509: RSA public exponent is not a positive number")
  1387  		}
  1388  
  1389  		// TODO(dkarch): Update to return the parameters once crypto/x509 has come up with permanent solution (https://github.com/golang/go/issues/30416)
  1390  		pub := &rsa.PublicKey{
  1391  			E: p.E,
  1392  			N: p.N,
  1393  		}
  1394  		return pub, nil
  1395  	case DSA:
  1396  		var p *big.Int
  1397  		rest, err := asn1.Unmarshal(asn1Data, &p)
  1398  		if err != nil {
  1399  			var laxErr error
  1400  			rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &p, "lax")
  1401  			if laxErr != nil {
  1402  				return nil, laxErr
  1403  			}
  1404  			nfe.AddError(err)
  1405  		}
  1406  		if len(rest) != 0 {
  1407  			return nil, errors.New("x509: trailing data after DSA public key")
  1408  		}
  1409  		paramsData := keyData.Algorithm.Parameters.FullBytes
  1410  		params := new(dsaAlgorithmParameters)
  1411  		rest, err = asn1.Unmarshal(paramsData, params)
  1412  		if err != nil {
  1413  			return nil, err
  1414  		}
  1415  		if len(rest) != 0 {
  1416  			return nil, errors.New("x509: trailing data after DSA parameters")
  1417  		}
  1418  		if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
  1419  			return nil, errors.New("x509: zero or negative DSA parameter")
  1420  		}
  1421  		pub := &dsa.PublicKey{
  1422  			Parameters: dsa.Parameters{
  1423  				P: params.P,
  1424  				Q: params.Q,
  1425  				G: params.G,
  1426  			},
  1427  			Y: p,
  1428  		}
  1429  		return pub, nil
  1430  	case ECDSA:
  1431  		paramsData := keyData.Algorithm.Parameters.FullBytes
  1432  		namedCurveOID := new(asn1.ObjectIdentifier)
  1433  		rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
  1434  		if err != nil {
  1435  			return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
  1436  		}
  1437  		if len(rest) != 0 {
  1438  			return nil, errors.New("x509: trailing data after ECDSA parameters")
  1439  		}
  1440  		namedCurve := namedCurveFromOID(*namedCurveOID, nfe)
  1441  		if namedCurve == nil {
  1442  			return nil, fmt.Errorf("x509: unsupported elliptic curve %v", namedCurveOID)
  1443  		}
  1444  		x, y := elliptic.Unmarshal(namedCurve, asn1Data)
  1445  		if x == nil {
  1446  			return nil, errors.New("x509: failed to unmarshal elliptic curve point")
  1447  		}
  1448  		pub := &ecdsa.PublicKey{
  1449  			Curve: namedCurve,
  1450  			X:     x,
  1451  			Y:     y,
  1452  		}
  1453  		return pub, nil
  1454  	case Ed25519:
  1455  		return ed25519.PublicKey(asn1Data), nil
  1456  	default:
  1457  		return nil, nil
  1458  	}
  1459  }
  1460  
  1461  // NonFatalErrors is an error type which can hold a number of other errors.
  1462  // It's used to collect a range of non-fatal errors which occur while parsing
  1463  // a certificate, that way we can still match on certs which technically are
  1464  // invalid.
  1465  type NonFatalErrors struct {
  1466  	Errors []error
  1467  }
  1468  
  1469  // AddError adds an error to the list of errors contained by NonFatalErrors.
  1470  func (e *NonFatalErrors) AddError(err error) {
  1471  	e.Errors = append(e.Errors, err)
  1472  }
  1473  
  1474  // Returns a string consisting of the values of Error() from all of the errors
  1475  // contained in |e|
  1476  func (e NonFatalErrors) Error() string {
  1477  	r := "NonFatalErrors: "
  1478  	for _, err := range e.Errors {
  1479  		r += err.Error() + "; "
  1480  	}
  1481  	return r
  1482  }
  1483  
  1484  // HasError returns true if |e| contains at least one error
  1485  func (e *NonFatalErrors) HasError() bool {
  1486  	if e == nil {
  1487  		return false
  1488  	}
  1489  	return len(e.Errors) > 0
  1490  }
  1491  
  1492  // Append combines the contents of two NonFatalErrors instances.
  1493  func (e *NonFatalErrors) Append(more *NonFatalErrors) *NonFatalErrors {
  1494  	if e == nil {
  1495  		return more
  1496  	}
  1497  	if more == nil {
  1498  		return e
  1499  	}
  1500  	combined := NonFatalErrors{Errors: make([]error, 0, len(e.Errors)+len(more.Errors))}
  1501  	combined.Errors = append(combined.Errors, e.Errors...)
  1502  	combined.Errors = append(combined.Errors, more.Errors...)
  1503  	return &combined
  1504  }
  1505  
  1506  // IsFatal indicates whether an error is fatal.
  1507  func IsFatal(err error) bool {
  1508  	if err == nil {
  1509  		return false
  1510  	}
  1511  	if _, ok := err.(NonFatalErrors); ok {
  1512  		return false
  1513  	}
  1514  	if errs, ok := err.(*Errors); ok {
  1515  		return errs.Fatal()
  1516  	}
  1517  	return true
  1518  }
  1519  
  1520  func parseDistributionPoints(data []byte, crldp *[]string) error {
  1521  	// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
  1522  	//
  1523  	// DistributionPoint ::= SEQUENCE {
  1524  	//     distributionPoint       [0]     DistributionPointName OPTIONAL,
  1525  	//     reasons                 [1]     ReasonFlags OPTIONAL,
  1526  	//     cRLIssuer               [2]     GeneralNames OPTIONAL }
  1527  	//
  1528  	// DistributionPointName ::= CHOICE {
  1529  	//     fullName                [0]     GeneralNames,
  1530  	//     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
  1531  
  1532  	var cdp []distributionPoint
  1533  	if rest, err := asn1.Unmarshal(data, &cdp); err != nil {
  1534  		return err
  1535  	} else if len(rest) != 0 {
  1536  		return errors.New("x509: trailing data after X.509 CRL distribution point")
  1537  	}
  1538  
  1539  	for _, dp := range cdp {
  1540  		// Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
  1541  		if len(dp.DistributionPoint.FullName) == 0 {
  1542  			continue
  1543  		}
  1544  
  1545  		for _, fullName := range dp.DistributionPoint.FullName {
  1546  			if fullName.Tag == 6 {
  1547  				*crldp = append(*crldp, string(fullName.Bytes))
  1548  			}
  1549  		}
  1550  	}
  1551  	return nil
  1552  }
  1553  
  1554  func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
  1555  	// RFC 5280, 4.2.1.6
  1556  
  1557  	// SubjectAltName ::= GeneralNames
  1558  	//
  1559  	// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  1560  	//
  1561  	// GeneralName ::= CHOICE {
  1562  	//      otherName                       [0]     OtherName,
  1563  	//      rfc822Name                      [1]     IA5String,
  1564  	//      dNSName                         [2]     IA5String,
  1565  	//      x400Address                     [3]     ORAddress,
  1566  	//      directoryName                   [4]     Name,
  1567  	//      ediPartyName                    [5]     EDIPartyName,
  1568  	//      uniformResourceIdentifier       [6]     IA5String,
  1569  	//      iPAddress                       [7]     OCTET STRING,
  1570  	//      registeredID                    [8]     OBJECT IDENTIFIER }
  1571  	var seq asn1.RawValue
  1572  	rest, err := asn1.Unmarshal(extension, &seq)
  1573  	if err != nil {
  1574  		return err
  1575  	} else if len(rest) != 0 {
  1576  		return errors.New("x509: trailing data after X.509 extension")
  1577  	}
  1578  	if !seq.IsCompound || seq.Tag != asn1.TagSequence || seq.Class != asn1.ClassUniversal {
  1579  		return asn1.StructuralError{Msg: "bad SAN sequence"}
  1580  	}
  1581  
  1582  	rest = seq.Bytes
  1583  	for len(rest) > 0 {
  1584  		var v asn1.RawValue
  1585  		rest, err = asn1.Unmarshal(rest, &v)
  1586  		if err != nil {
  1587  			return err
  1588  		}
  1589  
  1590  		if err := callback(v.Tag, v.Bytes); err != nil {
  1591  			return err
  1592  		}
  1593  	}
  1594  
  1595  	return nil
  1596  }
  1597  
  1598  func parseSANExtension(value []byte, nfe *NonFatalErrors) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
  1599  	err = forEachSAN(value, func(tag int, data []byte) error {
  1600  		switch tag {
  1601  		case nameTypeEmail:
  1602  			emailAddresses = append(emailAddresses, string(data))
  1603  		case nameTypeDNS:
  1604  			dnsNames = append(dnsNames, string(data))
  1605  		case nameTypeURI:
  1606  			uri, err := url.Parse(string(data))
  1607  			if err != nil {
  1608  				return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
  1609  			}
  1610  			if len(uri.Host) > 0 {
  1611  				if _, ok := domainToReverseLabels(uri.Host); !ok {
  1612  					return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
  1613  				}
  1614  			}
  1615  			uris = append(uris, uri)
  1616  		case nameTypeIP:
  1617  			switch len(data) {
  1618  			case net.IPv4len, net.IPv6len:
  1619  				ipAddresses = append(ipAddresses, data)
  1620  			default:
  1621  				nfe.AddError(errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data))))
  1622  			}
  1623  		}
  1624  
  1625  		return nil
  1626  	})
  1627  
  1628  	return
  1629  }
  1630  
  1631  // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
  1632  func isValidIPMask(mask []byte) bool {
  1633  	seenZero := false
  1634  
  1635  	for _, b := range mask {
  1636  		if seenZero {
  1637  			if b != 0 {
  1638  				return false
  1639  			}
  1640  
  1641  			continue
  1642  		}
  1643  
  1644  		switch b {
  1645  		case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
  1646  			seenZero = true
  1647  		case 0xff:
  1648  		default:
  1649  			return false
  1650  		}
  1651  	}
  1652  
  1653  	return true
  1654  }
  1655  
  1656  func parseNameConstraintsExtension(out *Certificate, e pkix.Extension, nfe *NonFatalErrors) (unhandled bool, err error) {
  1657  	// RFC 5280, 4.2.1.10
  1658  
  1659  	// NameConstraints ::= SEQUENCE {
  1660  	//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
  1661  	//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
  1662  	//
  1663  	// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  1664  	//
  1665  	// GeneralSubtree ::= SEQUENCE {
  1666  	//      base                    GeneralName,
  1667  	//      minimum         [0]     BaseDistance DEFAULT 0,
  1668  	//      maximum         [1]     BaseDistance OPTIONAL }
  1669  	//
  1670  	// BaseDistance ::= INTEGER (0..MAX)
  1671  
  1672  	outer := cryptobyte.String(e.Value)
  1673  	var toplevel, permitted, excluded cryptobyte.String
  1674  	var havePermitted, haveExcluded bool
  1675  	if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
  1676  		!outer.Empty() ||
  1677  		!toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
  1678  		!toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
  1679  		!toplevel.Empty() {
  1680  		return false, errors.New("x509: invalid NameConstraints extension")
  1681  	}
  1682  
  1683  	if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
  1684  		// From RFC 5280, Section 4.2.1.10:
  1685  		//   “either the permittedSubtrees field
  1686  		//   or the excludedSubtrees MUST be
  1687  		//   present”
  1688  		return false, errors.New("x509: empty name constraints extension")
  1689  	}
  1690  
  1691  	getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
  1692  		for !subtrees.Empty() {
  1693  			var seq, value cryptobyte.String
  1694  			var tag cryptobyte_asn1.Tag
  1695  			if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
  1696  				!seq.ReadAnyASN1(&value, &tag) {
  1697  				return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
  1698  			}
  1699  
  1700  			var (
  1701  				dnsTag   = cryptobyte_asn1.Tag(2).ContextSpecific()
  1702  				emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
  1703  				ipTag    = cryptobyte_asn1.Tag(7).ContextSpecific()
  1704  				uriTag   = cryptobyte_asn1.Tag(6).ContextSpecific()
  1705  			)
  1706  
  1707  			switch tag {
  1708  			case dnsTag:
  1709  				domain := string(value)
  1710  				if err := isIA5String(domain); err != nil {
  1711  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1712  				}
  1713  
  1714  				trimmedDomain := domain
  1715  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
  1716  					// constraints can have a leading
  1717  					// period to exclude the domain
  1718  					// itself, but that's not valid in a
  1719  					// normal domain name.
  1720  					trimmedDomain = trimmedDomain[1:]
  1721  				}
  1722  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
  1723  					nfe.AddError(fmt.Errorf("x509: failed to parse dnsName constraint %q", domain))
  1724  				}
  1725  				dnsNames = append(dnsNames, domain)
  1726  
  1727  			case ipTag:
  1728  				l := len(value)
  1729  				var ip, mask []byte
  1730  
  1731  				switch l {
  1732  				case 8:
  1733  					ip = value[:4]
  1734  					mask = value[4:]
  1735  
  1736  				case 32:
  1737  					ip = value[:16]
  1738  					mask = value[16:]
  1739  
  1740  				default:
  1741  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
  1742  				}
  1743  
  1744  				if !isValidIPMask(mask) {
  1745  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
  1746  				}
  1747  
  1748  				ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
  1749  
  1750  			case emailTag:
  1751  				constraint := string(value)
  1752  				if err := isIA5String(constraint); err != nil {
  1753  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1754  				}
  1755  
  1756  				// If the constraint contains an @ then
  1757  				// it specifies an exact mailbox name.
  1758  				if strings.Contains(constraint, "@") {
  1759  					if _, ok := parseRFC2821Mailbox(constraint); !ok {
  1760  						nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint))
  1761  					}
  1762  				} else {
  1763  					// Otherwise it's a domain name.
  1764  					domain := constraint
  1765  					if len(domain) > 0 && domain[0] == '.' {
  1766  						domain = domain[1:]
  1767  					}
  1768  					if _, ok := domainToReverseLabels(domain); !ok {
  1769  						nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint))
  1770  					}
  1771  				}
  1772  				emails = append(emails, constraint)
  1773  
  1774  			case uriTag:
  1775  				domain := string(value)
  1776  				if err := isIA5String(domain); err != nil {
  1777  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1778  				}
  1779  
  1780  				if net.ParseIP(domain) != nil {
  1781  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
  1782  				}
  1783  
  1784  				trimmedDomain := domain
  1785  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
  1786  					// constraints can have a leading
  1787  					// period to exclude the domain itself,
  1788  					// but that's not valid in a normal
  1789  					// domain name.
  1790  					trimmedDomain = trimmedDomain[1:]
  1791  				}
  1792  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
  1793  					nfe.AddError(fmt.Errorf("x509: failed to parse URI constraint %q", domain))
  1794  				}
  1795  				uriDomains = append(uriDomains, domain)
  1796  
  1797  			default:
  1798  				unhandled = true
  1799  			}
  1800  		}
  1801  
  1802  		return dnsNames, ips, emails, uriDomains, nil
  1803  	}
  1804  
  1805  	if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
  1806  		return false, err
  1807  	}
  1808  	if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
  1809  		return false, err
  1810  	}
  1811  	out.PermittedDNSDomainsCritical = e.Critical
  1812  
  1813  	return unhandled, nil
  1814  }
  1815  
  1816  func parseCertificate(in *certificate) (*Certificate, error) {
  1817  	var nfe NonFatalErrors
  1818  
  1819  	out := new(Certificate)
  1820  	out.Raw = in.Raw
  1821  	out.RawTBSCertificate = in.TBSCertificate.Raw
  1822  	out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
  1823  	out.RawSubject = in.TBSCertificate.Subject.FullBytes
  1824  	out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
  1825  
  1826  	out.Signature = in.SignatureValue.RightAlign()
  1827  	out.SignatureAlgorithm = SignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
  1828  
  1829  	out.PublicKeyAlgorithm =
  1830  		getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
  1831  	var err error
  1832  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey, &nfe)
  1833  	if err != nil {
  1834  		return nil, err
  1835  	}
  1836  
  1837  	out.Version = in.TBSCertificate.Version + 1
  1838  	out.SerialNumber = in.TBSCertificate.SerialNumber
  1839  
  1840  	var issuer, subject pkix.RDNSequence
  1841  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
  1842  		var laxErr error
  1843  		rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Subject.FullBytes, &subject, "lax")
  1844  		if laxErr != nil {
  1845  			return nil, laxErr
  1846  		}
  1847  		nfe.AddError(err)
  1848  	} else if len(rest) != 0 {
  1849  		return nil, errors.New("x509: trailing data after X.509 subject")
  1850  	}
  1851  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
  1852  		var laxErr error
  1853  		rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Issuer.FullBytes, &issuer, "lax")
  1854  		if laxErr != nil {
  1855  			return nil, laxErr
  1856  		}
  1857  		nfe.AddError(err)
  1858  	} else if len(rest) != 0 {
  1859  		return nil, errors.New("x509: trailing data after X.509 subject")
  1860  	}
  1861  
  1862  	out.Issuer.FillFromRDNSequence(&issuer)
  1863  	out.Subject.FillFromRDNSequence(&subject)
  1864  
  1865  	out.NotBefore = in.TBSCertificate.Validity.NotBefore
  1866  	out.NotAfter = in.TBSCertificate.Validity.NotAfter
  1867  
  1868  	for _, e := range in.TBSCertificate.Extensions {
  1869  		out.Extensions = append(out.Extensions, e)
  1870  		unhandled := false
  1871  
  1872  		if len(e.Id) == 4 && e.Id[0] == OIDExtensionArc[0] && e.Id[1] == OIDExtensionArc[1] && e.Id[2] == OIDExtensionArc[2] {
  1873  			switch e.Id[3] {
  1874  			case OIDExtensionKeyUsage[3]:
  1875  				// RFC 5280, 4.2.1.3
  1876  				var usageBits asn1.BitString
  1877  				if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
  1878  					return nil, err
  1879  				} else if len(rest) != 0 {
  1880  					return nil, errors.New("x509: trailing data after X.509 KeyUsage")
  1881  				}
  1882  
  1883  				var usage int
  1884  				for i := 0; i < 9; i++ {
  1885  					if usageBits.At(i) != 0 {
  1886  						usage |= 1 << uint(i)
  1887  					}
  1888  				}
  1889  				out.KeyUsage = KeyUsage(usage)
  1890  
  1891  			case OIDExtensionBasicConstraints[3]:
  1892  				// RFC 5280, 4.2.1.9
  1893  				var constraints basicConstraints
  1894  				if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
  1895  					return nil, err
  1896  				} else if len(rest) != 0 {
  1897  					return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
  1898  				}
  1899  
  1900  				out.BasicConstraintsValid = true
  1901  				out.IsCA = constraints.IsCA
  1902  				out.MaxPathLen = constraints.MaxPathLen
  1903  				out.MaxPathLenZero = out.MaxPathLen == 0
  1904  				// TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
  1905  
  1906  			case OIDExtensionSubjectAltName[3]:
  1907  				out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value, &nfe)
  1908  				if err != nil {
  1909  					return nil, err
  1910  				}
  1911  
  1912  				if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
  1913  					// If we didn't parse anything then we do the critical check, below.
  1914  					unhandled = true
  1915  				}
  1916  
  1917  			case OIDExtensionNameConstraints[3]:
  1918  				unhandled, err = parseNameConstraintsExtension(out, e, &nfe)
  1919  				if err != nil {
  1920  					return nil, err
  1921  				}
  1922  
  1923  			case OIDExtensionCRLDistributionPoints[3]:
  1924  				// RFC 5280, 4.2.1.13
  1925  				if err := parseDistributionPoints(e.Value, &out.CRLDistributionPoints); err != nil {
  1926  					return nil, err
  1927  				}
  1928  
  1929  			case OIDExtensionAuthorityKeyId[3]:
  1930  				// RFC 5280, 4.2.1.1
  1931  				var a authKeyId
  1932  				if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
  1933  					return nil, err
  1934  				} else if len(rest) != 0 {
  1935  					return nil, errors.New("x509: trailing data after X.509 authority key-id")
  1936  				}
  1937  				out.AuthorityKeyId = a.Id
  1938  
  1939  			case OIDExtensionExtendedKeyUsage[3]:
  1940  				// RFC 5280, 4.2.1.12.  Extended Key Usage
  1941  
  1942  				// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
  1943  				//
  1944  				// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  1945  				//
  1946  				// KeyPurposeId ::= OBJECT IDENTIFIER
  1947  
  1948  				var keyUsage []asn1.ObjectIdentifier
  1949  				if len(e.Value) == 0 {
  1950  					nfe.AddError(errors.New("x509: empty ExtendedKeyUsage"))
  1951  				} else {
  1952  					rest, err := asn1.Unmarshal(e.Value, &keyUsage)
  1953  					if err != nil {
  1954  						var laxErr error
  1955  						rest, laxErr = asn1.UnmarshalWithParams(e.Value, &keyUsage, "lax")
  1956  						if laxErr != nil {
  1957  							return nil, laxErr
  1958  						}
  1959  						nfe.AddError(err)
  1960  					}
  1961  					if len(rest) != 0 {
  1962  						return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
  1963  					}
  1964  				}
  1965  
  1966  				for _, u := range keyUsage {
  1967  					if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
  1968  						out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
  1969  					} else {
  1970  						out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
  1971  					}
  1972  				}
  1973  
  1974  			case OIDExtensionSubjectKeyId[3]:
  1975  				// RFC 5280, 4.2.1.2
  1976  				var keyid []byte
  1977  				if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
  1978  					return nil, err
  1979  				} else if len(rest) != 0 {
  1980  					return nil, errors.New("x509: trailing data after X.509 key-id")
  1981  				}
  1982  				out.SubjectKeyId = keyid
  1983  
  1984  			case OIDExtensionCertificatePolicies[3]:
  1985  				// RFC 5280 4.2.1.4: Certificate Policies
  1986  				var policies []policyInformation
  1987  				if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
  1988  					return nil, err
  1989  				} else if len(rest) != 0 {
  1990  					return nil, errors.New("x509: trailing data after X.509 certificate policies")
  1991  				}
  1992  				out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
  1993  				for i, policy := range policies {
  1994  					out.PolicyIdentifiers[i] = policy.Policy
  1995  				}
  1996  
  1997  			default:
  1998  				// Unknown extensions are recorded if critical.
  1999  				unhandled = true
  2000  			}
  2001  		} else if e.Id.Equal(OIDExtensionAuthorityInfoAccess) {
  2002  			// RFC 5280 4.2.2.1: Authority Information Access
  2003  			var aia []accessDescription
  2004  			if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
  2005  				return nil, err
  2006  			} else if len(rest) != 0 {
  2007  				return nil, errors.New("x509: trailing data after X.509 authority information")
  2008  			}
  2009  			if len(aia) == 0 {
  2010  				nfe.AddError(errors.New("x509: empty AuthorityInfoAccess extension"))
  2011  			}
  2012  
  2013  			for _, v := range aia {
  2014  				// GeneralName: uniformResourceIdentifier [6] IA5String
  2015  				if v.Location.Tag != 6 {
  2016  					continue
  2017  				}
  2018  				if v.Method.Equal(OIDAuthorityInfoAccessOCSP) {
  2019  					out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
  2020  				} else if v.Method.Equal(OIDAuthorityInfoAccessIssuers) {
  2021  					out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
  2022  				}
  2023  			}
  2024  		} else if e.Id.Equal(OIDExtensionSubjectInfoAccess) {
  2025  			// RFC 5280 4.2.2.2: Subject Information Access
  2026  			var sia []accessDescription
  2027  			if rest, err := asn1.Unmarshal(e.Value, &sia); err != nil {
  2028  				return nil, err
  2029  			} else if len(rest) != 0 {
  2030  				return nil, errors.New("x509: trailing data after X.509 subject information")
  2031  			}
  2032  			if len(sia) == 0 {
  2033  				nfe.AddError(errors.New("x509: empty SubjectInfoAccess extension"))
  2034  			}
  2035  
  2036  			for _, v := range sia {
  2037  				// TODO(drysdale): cope with non-URI types of GeneralName
  2038  				// GeneralName: uniformResourceIdentifier [6] IA5String
  2039  				if v.Location.Tag != 6 {
  2040  					continue
  2041  				}
  2042  				if v.Method.Equal(OIDSubjectInfoAccessTimestamp) {
  2043  					out.SubjectTimestamps = append(out.SubjectTimestamps, string(v.Location.Bytes))
  2044  				} else if v.Method.Equal(OIDSubjectInfoAccessCARepo) {
  2045  					out.SubjectCARepositories = append(out.SubjectCARepositories, string(v.Location.Bytes))
  2046  				}
  2047  			}
  2048  		} else if e.Id.Equal(OIDExtensionIPPrefixList) {
  2049  			out.RPKIAddressRanges = parseRPKIAddrBlocks(e.Value, &nfe)
  2050  		} else if e.Id.Equal(OIDExtensionASList) {
  2051  			out.RPKIASNumbers, out.RPKIRoutingDomainIDs = parseRPKIASIdentifiers(e.Value, &nfe)
  2052  		} else if e.Id.Equal(OIDExtensionCTSCT) {
  2053  			if rest, err := asn1.Unmarshal(e.Value, &out.RawSCT); err != nil {
  2054  				nfe.AddError(fmt.Errorf("failed to asn1.Unmarshal SCT list extension: %v", err))
  2055  			} else if len(rest) != 0 {
  2056  				nfe.AddError(errors.New("trailing data after ASN1-encoded SCT list"))
  2057  			} else {
  2058  				if rest, err := tls.Unmarshal(out.RawSCT, &out.SCTList); err != nil {
  2059  					nfe.AddError(fmt.Errorf("failed to tls.Unmarshal SCT list: %v", err))
  2060  				} else if len(rest) != 0 {
  2061  					nfe.AddError(errors.New("trailing data after TLS-encoded SCT list"))
  2062  				}
  2063  			}
  2064  		} else {
  2065  			// Unknown extensions are recorded if critical.
  2066  			unhandled = true
  2067  		}
  2068  
  2069  		if e.Critical && unhandled {
  2070  			out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
  2071  		}
  2072  	}
  2073  	if nfe.HasError() {
  2074  		return out, nfe
  2075  	}
  2076  	return out, nil
  2077  }
  2078  
  2079  // ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data.
  2080  // The parsed data is returned in a Certificate struct for ease of access.
  2081  func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) {
  2082  	var tbsCert tbsCertificate
  2083  	var nfe NonFatalErrors
  2084  	rest, err := asn1.Unmarshal(asn1Data, &tbsCert)
  2085  	if err != nil {
  2086  		var laxErr error
  2087  		rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &tbsCert, "lax")
  2088  		if laxErr != nil {
  2089  			return nil, laxErr
  2090  		}
  2091  		nfe.AddError(err)
  2092  	}
  2093  	if len(rest) > 0 {
  2094  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  2095  	}
  2096  	ret, err := parseCertificate(&certificate{
  2097  		Raw:            tbsCert.Raw,
  2098  		TBSCertificate: tbsCert})
  2099  	if err != nil {
  2100  		errs, ok := err.(NonFatalErrors)
  2101  		if !ok {
  2102  			return nil, err
  2103  		}
  2104  		nfe.Errors = append(nfe.Errors, errs.Errors...)
  2105  	}
  2106  	if nfe.HasError() {
  2107  		return ret, nfe
  2108  	}
  2109  	return ret, nil
  2110  }
  2111  
  2112  // ParseCertificate parses a single certificate from the given ASN.1 DER data.
  2113  // This function can return both a Certificate and an error (in which case the
  2114  // error will be of type NonFatalErrors).
  2115  func ParseCertificate(asn1Data []byte) (*Certificate, error) {
  2116  	var cert certificate
  2117  	var nfe NonFatalErrors
  2118  	rest, err := asn1.Unmarshal(asn1Data, &cert)
  2119  	if err != nil {
  2120  		var laxErr error
  2121  		rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax")
  2122  		if laxErr != nil {
  2123  			return nil, laxErr
  2124  		}
  2125  		nfe.AddError(err)
  2126  	}
  2127  	if len(rest) > 0 {
  2128  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  2129  	}
  2130  	ret, err := parseCertificate(&cert)
  2131  	if err != nil {
  2132  		errs, ok := err.(NonFatalErrors)
  2133  		if !ok {
  2134  			return nil, err
  2135  		}
  2136  		nfe.Errors = append(nfe.Errors, errs.Errors...)
  2137  	}
  2138  	if nfe.HasError() {
  2139  		return ret, nfe
  2140  	}
  2141  	return ret, nil
  2142  }
  2143  
  2144  // ParseCertificates parses one or more certificates from the given ASN.1 DER
  2145  // data. The certificates must be concatenated with no intermediate padding.
  2146  // This function can return both a slice of Certificate and an error (in which
  2147  // case the error will be of type NonFatalErrors).
  2148  func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
  2149  	var v []*certificate
  2150  	var nfe NonFatalErrors
  2151  
  2152  	for len(asn1Data) > 0 {
  2153  		cert := new(certificate)
  2154  		var err error
  2155  		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
  2156  		if err != nil {
  2157  			var laxErr error
  2158  			asn1Data, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax")
  2159  			if laxErr != nil {
  2160  				return nil, laxErr
  2161  			}
  2162  			nfe.AddError(err)
  2163  		}
  2164  		v = append(v, cert)
  2165  	}
  2166  
  2167  	ret := make([]*Certificate, len(v))
  2168  	for i, ci := range v {
  2169  		cert, err := parseCertificate(ci)
  2170  		if err != nil {
  2171  			errs, ok := err.(NonFatalErrors)
  2172  			if !ok {
  2173  				return nil, err
  2174  			}
  2175  			nfe.Errors = append(nfe.Errors, errs.Errors...)
  2176  		}
  2177  		ret[i] = cert
  2178  	}
  2179  
  2180  	if nfe.HasError() {
  2181  		return ret, nfe
  2182  	}
  2183  	return ret, nil
  2184  }
  2185  
  2186  func reverseBitsInAByte(in byte) byte {
  2187  	b1 := in>>4 | in<<4
  2188  	b2 := b1>>2&0x33 | b1<<2&0xcc
  2189  	b3 := b2>>1&0x55 | b2<<1&0xaa
  2190  	return b3
  2191  }
  2192  
  2193  // asn1BitLength returns the bit-length of bitString by considering the
  2194  // most-significant bit in a byte to be the "first" bit. This convention
  2195  // matches ASN.1, but differs from almost everything else.
  2196  func asn1BitLength(bitString []byte) int {
  2197  	bitLen := len(bitString) * 8
  2198  
  2199  	for i := range bitString {
  2200  		b := bitString[len(bitString)-i-1]
  2201  
  2202  		for bit := uint(0); bit < 8; bit++ {
  2203  			if (b>>bit)&1 == 1 {
  2204  				return bitLen
  2205  			}
  2206  			bitLen--
  2207  		}
  2208  	}
  2209  
  2210  	return 0
  2211  }
  2212  
  2213  // OID values for standard extensions from RFC 5280.
  2214  var (
  2215  	OIDExtensionArc                        = asn1.ObjectIdentifier{2, 5, 29} // id-ce RFC5280 s4.2.1
  2216  	OIDExtensionSubjectKeyId               = asn1.ObjectIdentifier{2, 5, 29, 14}
  2217  	OIDExtensionKeyUsage                   = asn1.ObjectIdentifier{2, 5, 29, 15}
  2218  	OIDExtensionExtendedKeyUsage           = asn1.ObjectIdentifier{2, 5, 29, 37}
  2219  	OIDExtensionAuthorityKeyId             = asn1.ObjectIdentifier{2, 5, 29, 35}
  2220  	OIDExtensionBasicConstraints           = asn1.ObjectIdentifier{2, 5, 29, 19}
  2221  	OIDExtensionSubjectAltName             = asn1.ObjectIdentifier{2, 5, 29, 17}
  2222  	OIDExtensionCertificatePolicies        = asn1.ObjectIdentifier{2, 5, 29, 32}
  2223  	OIDExtensionNameConstraints            = asn1.ObjectIdentifier{2, 5, 29, 30}
  2224  	OIDExtensionCRLDistributionPoints      = asn1.ObjectIdentifier{2, 5, 29, 31}
  2225  	OIDExtensionIssuerAltName              = asn1.ObjectIdentifier{2, 5, 29, 18}
  2226  	OIDExtensionSubjectDirectoryAttributes = asn1.ObjectIdentifier{2, 5, 29, 9}
  2227  	OIDExtensionInhibitAnyPolicy           = asn1.ObjectIdentifier{2, 5, 29, 54}
  2228  	OIDExtensionPolicyConstraints          = asn1.ObjectIdentifier{2, 5, 29, 36}
  2229  	OIDExtensionPolicyMappings             = asn1.ObjectIdentifier{2, 5, 29, 33}
  2230  	OIDExtensionFreshestCRL                = asn1.ObjectIdentifier{2, 5, 29, 46}
  2231  
  2232  	OIDExtensionAuthorityInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1}
  2233  	OIDExtensionSubjectInfoAccess   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 11}
  2234  
  2235  	// OIDExtensionCTPoison is defined in RFC 6962 s3.1.
  2236  	OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
  2237  	// OIDExtensionCTSCT is defined in RFC 6962 s3.3.
  2238  	OIDExtensionCTSCT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
  2239  	// OIDExtensionIPPrefixList is defined in RFC 3779 s2.
  2240  	OIDExtensionIPPrefixList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 7}
  2241  	// OIDExtensionASList is defined in RFC 3779 s3.
  2242  	OIDExtensionASList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 8}
  2243  )
  2244  
  2245  var (
  2246  	OIDAuthorityInfoAccessOCSP    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  2247  	OIDAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  2248  	OIDSubjectInfoAccessTimestamp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 3}
  2249  	OIDSubjectInfoAccessCARepo    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 5}
  2250  	OIDAnyPolicy                  = asn1.ObjectIdentifier{2, 5, 29, 32, 0}
  2251  )
  2252  
  2253  // oidInExtensions reports whether an extension with the given oid exists in
  2254  // extensions.
  2255  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  2256  	for _, e := range extensions {
  2257  		if e.Id.Equal(oid) {
  2258  			return true
  2259  		}
  2260  	}
  2261  	return false
  2262  }
  2263  
  2264  // marshalSANs marshals a list of addresses into a the contents of an X.509
  2265  // SubjectAlternativeName extension.
  2266  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
  2267  	var rawValues []asn1.RawValue
  2268  	for _, name := range dnsNames {
  2269  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: asn1.ClassContextSpecific, Bytes: []byte(name)})
  2270  	}
  2271  	for _, email := range emailAddresses {
  2272  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: asn1.ClassContextSpecific, Bytes: []byte(email)})
  2273  	}
  2274  	for _, rawIP := range ipAddresses {
  2275  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
  2276  		ip := rawIP.To4()
  2277  		if ip == nil {
  2278  			ip = rawIP
  2279  		}
  2280  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: asn1.ClassContextSpecific, Bytes: ip})
  2281  	}
  2282  	for _, uri := range uris {
  2283  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: asn1.ClassContextSpecific, Bytes: []byte(uri.String())})
  2284  	}
  2285  	return asn1.Marshal(rawValues)
  2286  }
  2287  
  2288  func isIA5String(s string) error {
  2289  	for _, r := range s {
  2290  		if r >= utf8.RuneSelf {
  2291  			return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
  2292  		}
  2293  	}
  2294  
  2295  	return nil
  2296  }
  2297  
  2298  func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte) (ret []pkix.Extension, err error) {
  2299  	ret = make([]pkix.Extension, 12 /* maximum number of elements. */)
  2300  	n := 0
  2301  
  2302  	if template.KeyUsage != 0 &&
  2303  		!oidInExtensions(OIDExtensionKeyUsage, template.ExtraExtensions) {
  2304  		ret[n].Id = OIDExtensionKeyUsage
  2305  		ret[n].Critical = true
  2306  
  2307  		var a [2]byte
  2308  		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  2309  		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  2310  
  2311  		l := 1
  2312  		if a[1] != 0 {
  2313  			l = 2
  2314  		}
  2315  
  2316  		bitString := a[:l]
  2317  		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  2318  		if err != nil {
  2319  			return
  2320  		}
  2321  		n++
  2322  	}
  2323  
  2324  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  2325  		!oidInExtensions(OIDExtensionExtendedKeyUsage, template.ExtraExtensions) {
  2326  		ret[n].Id = OIDExtensionExtendedKeyUsage
  2327  
  2328  		var oids []asn1.ObjectIdentifier
  2329  		for _, u := range template.ExtKeyUsage {
  2330  			if oid, ok := oidFromExtKeyUsage(u); ok {
  2331  				oids = append(oids, oid)
  2332  			} else {
  2333  				panic("internal error")
  2334  			}
  2335  		}
  2336  
  2337  		oids = append(oids, template.UnknownExtKeyUsage...)
  2338  
  2339  		ret[n].Value, err = asn1.Marshal(oids)
  2340  		if err != nil {
  2341  			return
  2342  		}
  2343  		n++
  2344  	}
  2345  
  2346  	if template.BasicConstraintsValid && !oidInExtensions(OIDExtensionBasicConstraints, template.ExtraExtensions) {
  2347  		// Leaving MaxPathLen as zero indicates that no maximum path
  2348  		// length is desired, unless MaxPathLenZero is set. A value of
  2349  		// -1 causes encoding/asn1 to omit the value as desired.
  2350  		maxPathLen := template.MaxPathLen
  2351  		if maxPathLen == 0 && !template.MaxPathLenZero {
  2352  			maxPathLen = -1
  2353  		}
  2354  		ret[n].Id = OIDExtensionBasicConstraints
  2355  		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
  2356  		ret[n].Critical = true
  2357  		if err != nil {
  2358  			return
  2359  		}
  2360  		n++
  2361  	}
  2362  
  2363  	if len(template.SubjectKeyId) > 0 && !oidInExtensions(OIDExtensionSubjectKeyId, template.ExtraExtensions) {
  2364  		ret[n].Id = OIDExtensionSubjectKeyId
  2365  		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  2366  		if err != nil {
  2367  			return
  2368  		}
  2369  		n++
  2370  	}
  2371  
  2372  	if len(authorityKeyId) > 0 && !oidInExtensions(OIDExtensionAuthorityKeyId, template.ExtraExtensions) {
  2373  		ret[n].Id = OIDExtensionAuthorityKeyId
  2374  		ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
  2375  		if err != nil {
  2376  			return
  2377  		}
  2378  		n++
  2379  	}
  2380  
  2381  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  2382  		!oidInExtensions(OIDExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  2383  		ret[n].Id = OIDExtensionAuthorityInfoAccess
  2384  		var aiaValues []accessDescription
  2385  		for _, name := range template.OCSPServer {
  2386  			aiaValues = append(aiaValues, accessDescription{
  2387  				Method:   OIDAuthorityInfoAccessOCSP,
  2388  				Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
  2389  			})
  2390  		}
  2391  		for _, name := range template.IssuingCertificateURL {
  2392  			aiaValues = append(aiaValues, accessDescription{
  2393  				Method:   OIDAuthorityInfoAccessIssuers,
  2394  				Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
  2395  			})
  2396  		}
  2397  		ret[n].Value, err = asn1.Marshal(aiaValues)
  2398  		if err != nil {
  2399  			return
  2400  		}
  2401  		n++
  2402  	}
  2403  
  2404  	if len(template.SubjectTimestamps) > 0 || len(template.SubjectCARepositories) > 0 &&
  2405  		!oidInExtensions(OIDExtensionSubjectInfoAccess, template.ExtraExtensions) {
  2406  		ret[n].Id = OIDExtensionSubjectInfoAccess
  2407  		var siaValues []accessDescription
  2408  		for _, ts := range template.SubjectTimestamps {
  2409  			siaValues = append(siaValues, accessDescription{
  2410  				Method:   OIDSubjectInfoAccessTimestamp,
  2411  				Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(ts)},
  2412  			})
  2413  		}
  2414  		for _, repo := range template.SubjectCARepositories {
  2415  			siaValues = append(siaValues, accessDescription{
  2416  				Method:   OIDSubjectInfoAccessCARepo,
  2417  				Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(repo)},
  2418  			})
  2419  		}
  2420  		ret[n].Value, err = asn1.Marshal(siaValues)
  2421  		if err != nil {
  2422  			return
  2423  		}
  2424  		n++
  2425  	}
  2426  
  2427  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  2428  		!oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) {
  2429  		ret[n].Id = OIDExtensionSubjectAltName
  2430  		// From RFC 5280, Section 4.2.1.6:
  2431  		// “If the subject field contains an empty sequence ... then
  2432  		// subjectAltName extension ... is marked as critical”
  2433  		ret[n].Critical = subjectIsEmpty
  2434  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  2435  		if err != nil {
  2436  			return
  2437  		}
  2438  		n++
  2439  	}
  2440  
  2441  	if len(template.PolicyIdentifiers) > 0 &&
  2442  		!oidInExtensions(OIDExtensionCertificatePolicies, template.ExtraExtensions) {
  2443  		ret[n].Id = OIDExtensionCertificatePolicies
  2444  		policies := make([]policyInformation, len(template.PolicyIdentifiers))
  2445  		for i, policy := range template.PolicyIdentifiers {
  2446  			policies[i].Policy = policy
  2447  		}
  2448  		ret[n].Value, err = asn1.Marshal(policies)
  2449  		if err != nil {
  2450  			return
  2451  		}
  2452  		n++
  2453  	}
  2454  
  2455  	if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
  2456  		len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
  2457  		len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
  2458  		len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
  2459  		!oidInExtensions(OIDExtensionNameConstraints, template.ExtraExtensions) {
  2460  		ret[n].Id = OIDExtensionNameConstraints
  2461  		ret[n].Critical = template.PermittedDNSDomainsCritical
  2462  
  2463  		ipAndMask := func(ipNet *net.IPNet) []byte {
  2464  			maskedIP := ipNet.IP.Mask(ipNet.Mask)
  2465  			ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
  2466  			ipAndMask = append(ipAndMask, maskedIP...)
  2467  			ipAndMask = append(ipAndMask, ipNet.Mask...)
  2468  			return ipAndMask
  2469  		}
  2470  
  2471  		serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
  2472  			var b cryptobyte.Builder
  2473  
  2474  			for _, name := range dns {
  2475  				if err = isIA5String(name); err != nil {
  2476  					return nil, err
  2477  				}
  2478  
  2479  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  2480  					b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
  2481  						b.AddBytes([]byte(name))
  2482  					})
  2483  				})
  2484  			}
  2485  
  2486  			for _, ipNet := range ips {
  2487  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  2488  					b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
  2489  						b.AddBytes(ipAndMask(ipNet))
  2490  					})
  2491  				})
  2492  			}
  2493  
  2494  			for _, email := range emails {
  2495  				if err = isIA5String(email); err != nil {
  2496  					return nil, err
  2497  				}
  2498  
  2499  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  2500  					b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
  2501  						b.AddBytes([]byte(email))
  2502  					})
  2503  				})
  2504  			}
  2505  
  2506  			for _, uriDomain := range uriDomains {
  2507  				if err = isIA5String(uriDomain); err != nil {
  2508  					return nil, err
  2509  				}
  2510  
  2511  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  2512  					b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
  2513  						b.AddBytes([]byte(uriDomain))
  2514  					})
  2515  				})
  2516  			}
  2517  
  2518  			return b.Bytes()
  2519  		}
  2520  
  2521  		permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
  2522  		if err != nil {
  2523  			return nil, err
  2524  		}
  2525  
  2526  		excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
  2527  		if err != nil {
  2528  			return nil, err
  2529  		}
  2530  
  2531  		var b cryptobyte.Builder
  2532  		b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  2533  			if len(permitted) > 0 {
  2534  				b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  2535  					b.AddBytes(permitted)
  2536  				})
  2537  			}
  2538  
  2539  			if len(excluded) > 0 {
  2540  				b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  2541  					b.AddBytes(excluded)
  2542  				})
  2543  			}
  2544  		})
  2545  
  2546  		ret[n].Value, err = b.Bytes()
  2547  		if err != nil {
  2548  			return nil, err
  2549  		}
  2550  		n++
  2551  	}
  2552  
  2553  	if len(template.CRLDistributionPoints) > 0 &&
  2554  		!oidInExtensions(OIDExtensionCRLDistributionPoints, template.ExtraExtensions) {
  2555  		ret[n].Id = OIDExtensionCRLDistributionPoints
  2556  
  2557  		var crlDp []distributionPoint
  2558  		for _, name := range template.CRLDistributionPoints {
  2559  			dp := distributionPoint{
  2560  				DistributionPoint: distributionPointName{
  2561  					FullName: []asn1.RawValue{
  2562  						{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)},
  2563  					},
  2564  				},
  2565  			}
  2566  			crlDp = append(crlDp, dp)
  2567  		}
  2568  
  2569  		ret[n].Value, err = asn1.Marshal(crlDp)
  2570  		if err != nil {
  2571  			return
  2572  		}
  2573  		n++
  2574  	}
  2575  
  2576  	if (len(template.RawSCT) > 0 || len(template.SCTList.SCTList) > 0) && !oidInExtensions(OIDExtensionCTSCT, template.ExtraExtensions) {
  2577  		rawSCT := template.RawSCT
  2578  		if len(template.SCTList.SCTList) > 0 {
  2579  			rawSCT, err = tls.Marshal(template.SCTList)
  2580  			if err != nil {
  2581  				return
  2582  			}
  2583  		}
  2584  		ret[n].Id = OIDExtensionCTSCT
  2585  		ret[n].Value, err = asn1.Marshal(rawSCT)
  2586  		if err != nil {
  2587  			return
  2588  		}
  2589  		n++
  2590  	}
  2591  
  2592  	// Adding another extension here? Remember to update the maximum number
  2593  	// of elements in the make() at the top of the function and the list of
  2594  	// template fields used in CreateCertificate documentation.
  2595  
  2596  	return append(ret[:n], template.ExtraExtensions...), nil
  2597  }
  2598  
  2599  func subjectBytes(cert *Certificate) ([]byte, error) {
  2600  	if len(cert.RawSubject) > 0 {
  2601  		return cert.RawSubject, nil
  2602  	}
  2603  
  2604  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  2605  }
  2606  
  2607  // signingParamsForPublicKey returns the parameters to use for signing with
  2608  // priv. If requestedSigAlgo is not zero then it overrides the default
  2609  // signature algorithm.
  2610  func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
  2611  	var pubType PublicKeyAlgorithm
  2612  
  2613  	switch pub := pub.(type) {
  2614  	case *rsa.PublicKey:
  2615  		pubType = RSA
  2616  		hashFunc = crypto.SHA256
  2617  		sigAlgo.Algorithm = oidSignatureSHA256WithRSA
  2618  		sigAlgo.Parameters = asn1.NullRawValue
  2619  
  2620  	case *ecdsa.PublicKey:
  2621  		pubType = ECDSA
  2622  
  2623  		switch pub.Curve {
  2624  		case elliptic.P224(), elliptic.P256():
  2625  			hashFunc = crypto.SHA256
  2626  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  2627  		case elliptic.P384():
  2628  			hashFunc = crypto.SHA384
  2629  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  2630  		case elliptic.P521():
  2631  			hashFunc = crypto.SHA512
  2632  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  2633  		default:
  2634  			err = errors.New("x509: unknown elliptic curve")
  2635  		}
  2636  
  2637  	case ed25519.PublicKey:
  2638  		pubType = Ed25519
  2639  		sigAlgo.Algorithm = oidSignatureEd25519
  2640  
  2641  	default:
  2642  		err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
  2643  	}
  2644  
  2645  	if err != nil {
  2646  		return
  2647  	}
  2648  
  2649  	if requestedSigAlgo == 0 {
  2650  		return
  2651  	}
  2652  
  2653  	found := false
  2654  	for _, details := range signatureAlgorithmDetails {
  2655  		if details.algo == requestedSigAlgo {
  2656  			if details.pubKeyAlgo != pubType {
  2657  				err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
  2658  				return
  2659  			}
  2660  			sigAlgo.Algorithm, hashFunc = details.oid, details.hash
  2661  			if hashFunc == 0 && pubType != Ed25519 {
  2662  				err = errors.New("x509: cannot sign with hash function requested")
  2663  				return
  2664  			}
  2665  			if requestedSigAlgo.isRSAPSS() {
  2666  				sigAlgo.Parameters = rsaPSSParameters(hashFunc)
  2667  			}
  2668  			found = true
  2669  			break
  2670  		}
  2671  	}
  2672  
  2673  	if !found {
  2674  		err = errors.New("x509: unknown SignatureAlgorithm")
  2675  	}
  2676  
  2677  	return
  2678  }
  2679  
  2680  // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
  2681  // just an empty SEQUENCE.
  2682  var emptyASN1Subject = []byte{0x30, 0}
  2683  
  2684  // CreateCertificate creates a new X.509v3 certificate based on a template.
  2685  // The following members of template are used:
  2686  //   - SerialNumber
  2687  //   - Subject
  2688  //   - NotBefore, NotAfter
  2689  //   - SignatureAlgorithm
  2690  //   - For extensions:
  2691  //   - KeyUsage
  2692  //   - ExtKeyUsage, UnknownExtKeyUsage
  2693  //   - BasicConstraintsValid, IsCA, MaxPathLen, MaxPathLenZero
  2694  //   - SubjectKeyId
  2695  //   - AuthorityKeyId
  2696  //   - OCSPServer, IssuingCertificateURL
  2697  //   - SubjectTimestamps, SubjectCARepositories
  2698  //   - DNSNames, EmailAddresses, IPAddresses, URIs
  2699  //   - PolicyIdentifiers
  2700  //   - ExcludedDNSDomains, ExcludedIPRanges, ExcludedEmailAddresses, ExcludedURIDomains, PermittedDNSDomainsCritical,
  2701  //     PermittedDNSDomains, PermittedIPRanges, PermittedEmailAddresses, PermittedURIDomains
  2702  //   - CRLDistributionPoints
  2703  //   - RawSCT, SCTList
  2704  //   - ExtraExtensions
  2705  //
  2706  // The certificate is signed by parent. If parent is equal to template then the
  2707  // certificate is self-signed. The parameter pub is the public key of the
  2708  // signee and priv is the private key of the signer.
  2709  //
  2710  // The returned slice is the certificate in DER encoding.
  2711  //
  2712  // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
  2713  // ed25519.PublicKey. pub must be a supported key type, and priv must be a
  2714  // crypto.Signer with a supported public key.
  2715  //
  2716  // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
  2717  // unless the resulting certificate is self-signed. Otherwise the value from
  2718  // template will be used.
  2719  func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
  2720  	key, ok := priv.(crypto.Signer)
  2721  	if !ok {
  2722  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2723  	}
  2724  
  2725  	if template.SerialNumber == nil {
  2726  		return nil, errors.New("x509: no SerialNumber given")
  2727  	}
  2728  
  2729  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  2730  	if err != nil {
  2731  		return nil, err
  2732  	}
  2733  
  2734  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  2735  	if err != nil {
  2736  		return nil, err
  2737  	}
  2738  
  2739  	asn1Issuer, err := subjectBytes(parent)
  2740  	if err != nil {
  2741  		return
  2742  	}
  2743  
  2744  	asn1Subject, err := subjectBytes(template)
  2745  	if err != nil {
  2746  		return
  2747  	}
  2748  
  2749  	authorityKeyId := template.AuthorityKeyId
  2750  	if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
  2751  		authorityKeyId = parent.SubjectKeyId
  2752  	}
  2753  
  2754  	extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId)
  2755  	if err != nil {
  2756  		return
  2757  	}
  2758  
  2759  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  2760  	c := tbsCertificate{
  2761  		Version:            2,
  2762  		SerialNumber:       template.SerialNumber,
  2763  		SignatureAlgorithm: signatureAlgorithm,
  2764  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  2765  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  2766  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  2767  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  2768  		Extensions:         extensions,
  2769  	}
  2770  
  2771  	tbsCertContents, err := asn1.Marshal(c)
  2772  	if err != nil {
  2773  		return
  2774  	}
  2775  	c.Raw = tbsCertContents
  2776  
  2777  	signed := tbsCertContents
  2778  	if hashFunc != 0 {
  2779  		h := hashFunc.New()
  2780  		h.Write(signed)
  2781  		signed = h.Sum(nil)
  2782  	}
  2783  
  2784  	var signerOpts crypto.SignerOpts = hashFunc
  2785  	if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
  2786  		signerOpts = &rsa.PSSOptions{
  2787  			SaltLength: rsa.PSSSaltLengthEqualsHash,
  2788  			Hash:       hashFunc,
  2789  		}
  2790  	}
  2791  
  2792  	var signature []byte
  2793  	signature, err = key.Sign(rand, signed, signerOpts)
  2794  	if err != nil {
  2795  		return
  2796  	}
  2797  
  2798  	return asn1.Marshal(certificate{
  2799  		nil,
  2800  		c,
  2801  		signatureAlgorithm,
  2802  		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2803  	})
  2804  }
  2805  
  2806  // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  2807  // CRL.
  2808  var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  2809  
  2810  // pemType is the type of a PEM encoded CRL.
  2811  var pemType = "X509 CRL"
  2812  
  2813  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  2814  // encoded CRLs will appear where they should be DER encoded, so this function
  2815  // will transparently handle PEM encoding as long as there isn't any leading
  2816  // garbage.
  2817  func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
  2818  	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  2819  		block, _ := pem.Decode(crlBytes)
  2820  		if block != nil && block.Type == pemType {
  2821  			crlBytes = block.Bytes
  2822  		}
  2823  	}
  2824  	return ParseDERCRL(crlBytes)
  2825  }
  2826  
  2827  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  2828  func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
  2829  	certList := new(pkix.CertificateList)
  2830  	if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
  2831  		return nil, err
  2832  	} else if len(rest) != 0 {
  2833  		return nil, errors.New("x509: trailing data after CRL")
  2834  	}
  2835  	return certList, nil
  2836  }
  2837  
  2838  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  2839  // contains the given list of revoked certificates.
  2840  func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  2841  	key, ok := priv.(crypto.Signer)
  2842  	if !ok {
  2843  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2844  	}
  2845  
  2846  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
  2847  	if err != nil {
  2848  		return nil, err
  2849  	}
  2850  
  2851  	// Force revocation times to UTC per RFC 5280.
  2852  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  2853  	for i, rc := range revokedCerts {
  2854  		rc.RevocationTime = rc.RevocationTime.UTC()
  2855  		revokedCertsUTC[i] = rc
  2856  	}
  2857  
  2858  	tbsCertList := pkix.TBSCertificateList{
  2859  		Version:             1,
  2860  		Signature:           signatureAlgorithm,
  2861  		Issuer:              c.Subject.ToRDNSequence(),
  2862  		ThisUpdate:          now.UTC(),
  2863  		NextUpdate:          expiry.UTC(),
  2864  		RevokedCertificates: revokedCertsUTC,
  2865  	}
  2866  
  2867  	// Authority Key Id
  2868  	if len(c.SubjectKeyId) > 0 {
  2869  		var aki pkix.Extension
  2870  		aki.Id = OIDExtensionAuthorityKeyId
  2871  		aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  2872  		if err != nil {
  2873  			return
  2874  		}
  2875  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  2876  	}
  2877  
  2878  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2879  	if err != nil {
  2880  		return
  2881  	}
  2882  
  2883  	signed := tbsCertListContents
  2884  	if hashFunc != 0 {
  2885  		h := hashFunc.New()
  2886  		h.Write(signed)
  2887  		signed = h.Sum(nil)
  2888  	}
  2889  
  2890  	var signature []byte
  2891  	signature, err = key.Sign(rand, signed, hashFunc)
  2892  	if err != nil {
  2893  		return
  2894  	}
  2895  
  2896  	return asn1.Marshal(pkix.CertificateList{
  2897  		TBSCertList:        tbsCertList,
  2898  		SignatureAlgorithm: signatureAlgorithm,
  2899  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2900  	})
  2901  }
  2902  
  2903  // CertificateRequest represents a PKCS #10, certificate signature request.
  2904  type CertificateRequest struct {
  2905  	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  2906  	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  2907  	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
  2908  	RawSubject               []byte // DER encoded Subject.
  2909  
  2910  	Version            int
  2911  	Signature          []byte
  2912  	SignatureAlgorithm SignatureAlgorithm
  2913  
  2914  	PublicKeyAlgorithm PublicKeyAlgorithm
  2915  	PublicKey          interface{}
  2916  
  2917  	Subject pkix.Name
  2918  
  2919  	// Attributes contains the CSR attributes that can parse as
  2920  	// pkix.AttributeTypeAndValueSET.
  2921  	//
  2922  	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
  2923  	// generating the requestedExtensions attribute.
  2924  	Attributes []pkix.AttributeTypeAndValueSET
  2925  
  2926  	// Extensions contains all requested extensions, in raw form. When parsing
  2927  	// CSRs, this can be used to extract extensions that are not parsed by this
  2928  	// package.
  2929  	Extensions []pkix.Extension
  2930  
  2931  	// ExtraExtensions contains extensions to be copied, raw, into any CSR
  2932  	// marshaled by CreateCertificateRequest. Values override any extensions
  2933  	// that would otherwise be produced based on the other fields but are
  2934  	// overridden by any extensions specified in Attributes.
  2935  	//
  2936  	// The ExtraExtensions field is not populated by ParseCertificateRequest,
  2937  	// see Extensions instead.
  2938  	ExtraExtensions []pkix.Extension
  2939  
  2940  	// Subject Alternate Name values.
  2941  	DNSNames       []string
  2942  	EmailAddresses []string
  2943  	IPAddresses    []net.IP
  2944  	URIs           []*url.URL
  2945  }
  2946  
  2947  // These structures reflect the ASN.1 structure of X.509 certificate
  2948  // signature requests (see RFC 2986):
  2949  
  2950  type tbsCertificateRequest struct {
  2951  	Raw           asn1.RawContent
  2952  	Version       int
  2953  	Subject       asn1.RawValue
  2954  	PublicKey     publicKeyInfo
  2955  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  2956  }
  2957  
  2958  type certificateRequest struct {
  2959  	Raw                asn1.RawContent
  2960  	TBSCSR             tbsCertificateRequest
  2961  	SignatureAlgorithm pkix.AlgorithmIdentifier
  2962  	SignatureValue     asn1.BitString
  2963  }
  2964  
  2965  // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
  2966  // extensions in a CSR.
  2967  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  2968  
  2969  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  2970  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  2971  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  2972  	var rawAttributes []asn1.RawValue
  2973  	b, err := asn1.Marshal(attributes)
  2974  	if err != nil {
  2975  		return nil, err
  2976  	}
  2977  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  2978  	if err != nil {
  2979  		return nil, err
  2980  	}
  2981  	if len(rest) != 0 {
  2982  		return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  2983  	}
  2984  	return rawAttributes, nil
  2985  }
  2986  
  2987  // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
  2988  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  2989  	var attributes []pkix.AttributeTypeAndValueSET
  2990  	for _, rawAttr := range rawAttributes {
  2991  		var attr pkix.AttributeTypeAndValueSET
  2992  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  2993  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  2994  		// (i.e.: challengePassword or unstructuredName).
  2995  		if err == nil && len(rest) == 0 {
  2996  			attributes = append(attributes, attr)
  2997  		}
  2998  	}
  2999  	return attributes
  3000  }
  3001  
  3002  // parseCSRExtensions parses the attributes from a CSR and extracts any
  3003  // requested extensions.
  3004  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  3005  	// pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
  3006  	type pkcs10Attribute struct {
  3007  		Id     asn1.ObjectIdentifier
  3008  		Values []asn1.RawValue `asn1:"set"`
  3009  	}
  3010  
  3011  	var ret []pkix.Extension
  3012  	for _, rawAttr := range rawAttributes {
  3013  		var attr pkcs10Attribute
  3014  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  3015  			// Ignore attributes that don't parse.
  3016  			continue
  3017  		}
  3018  
  3019  		if !attr.Id.Equal(oidExtensionRequest) {
  3020  			continue
  3021  		}
  3022  
  3023  		var extensions []pkix.Extension
  3024  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  3025  			return nil, err
  3026  		}
  3027  		ret = append(ret, extensions...)
  3028  	}
  3029  
  3030  	return ret, nil
  3031  }
  3032  
  3033  // CreateCertificateRequest creates a new certificate request based on a
  3034  // template. The following members of template are used:
  3035  //
  3036  //   - SignatureAlgorithm
  3037  //   - Subject
  3038  //   - DNSNames
  3039  //   - EmailAddresses
  3040  //   - IPAddresses
  3041  //   - URIs
  3042  //   - ExtraExtensions
  3043  //   - Attributes (deprecated)
  3044  //
  3045  // priv is the private key to sign the CSR with, and the corresponding public
  3046  // key will be included in the CSR. It must implement crypto.Signer and its
  3047  // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
  3048  // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
  3049  // ed25519.PrivateKey satisfies this.)
  3050  //
  3051  // The returned slice is the certificate request in DER encoding.
  3052  func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
  3053  	key, ok := priv.(crypto.Signer)
  3054  	if !ok {
  3055  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  3056  	}
  3057  
  3058  	var hashFunc crypto.Hash
  3059  	var sigAlgo pkix.AlgorithmIdentifier
  3060  	hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  3061  	if err != nil {
  3062  		return nil, err
  3063  	}
  3064  
  3065  	var publicKeyBytes []byte
  3066  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  3067  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  3068  	if err != nil {
  3069  		return nil, err
  3070  	}
  3071  
  3072  	var extensions []pkix.Extension
  3073  
  3074  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  3075  		!oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) {
  3076  		sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  3077  		if err != nil {
  3078  			return nil, err
  3079  		}
  3080  
  3081  		extensions = append(extensions, pkix.Extension{
  3082  			Id:    OIDExtensionSubjectAltName,
  3083  			Value: sanBytes,
  3084  		})
  3085  	}
  3086  
  3087  	extensions = append(extensions, template.ExtraExtensions...)
  3088  
  3089  	// Make a copy of template.Attributes because we may alter it below.
  3090  	attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
  3091  	for _, attr := range template.Attributes {
  3092  		values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
  3093  		copy(values, attr.Value)
  3094  		attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  3095  			Type:  attr.Type,
  3096  			Value: values,
  3097  		})
  3098  	}
  3099  
  3100  	extensionsAppended := false
  3101  	if len(extensions) > 0 {
  3102  		// Append the extensions to an existing attribute if possible.
  3103  		for _, atvSet := range attributes {
  3104  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  3105  				continue
  3106  			}
  3107  
  3108  			// specifiedExtensions contains all the extensions that we
  3109  			// found specified via template.Attributes.
  3110  			specifiedExtensions := make(map[string]bool)
  3111  
  3112  			for _, atvs := range atvSet.Value {
  3113  				for _, atv := range atvs {
  3114  					specifiedExtensions[atv.Type.String()] = true
  3115  				}
  3116  			}
  3117  
  3118  			newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
  3119  			newValue = append(newValue, atvSet.Value[0]...)
  3120  
  3121  			for _, e := range extensions {
  3122  				if specifiedExtensions[e.Id.String()] {
  3123  					// Attributes already contained a value for
  3124  					// this extension and it takes priority.
  3125  					continue
  3126  				}
  3127  
  3128  				newValue = append(newValue, pkix.AttributeTypeAndValue{
  3129  					// There is no place for the critical
  3130  					// flag in an AttributeTypeAndValue.
  3131  					Type:  e.Id,
  3132  					Value: e.Value,
  3133  				})
  3134  			}
  3135  
  3136  			atvSet.Value[0] = newValue
  3137  			extensionsAppended = true
  3138  			break
  3139  		}
  3140  	}
  3141  
  3142  	rawAttributes, err := newRawAttributes(attributes)
  3143  	if err != nil {
  3144  		return
  3145  	}
  3146  
  3147  	// If not included in attributes, add a new attribute for the
  3148  	// extensions.
  3149  	if len(extensions) > 0 && !extensionsAppended {
  3150  		attr := struct {
  3151  			Type  asn1.ObjectIdentifier
  3152  			Value [][]pkix.Extension `asn1:"set"`
  3153  		}{
  3154  			Type:  oidExtensionRequest,
  3155  			Value: [][]pkix.Extension{extensions},
  3156  		}
  3157  
  3158  		b, err := asn1.Marshal(attr)
  3159  		if err != nil {
  3160  			return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
  3161  		}
  3162  
  3163  		var rawValue asn1.RawValue
  3164  		if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
  3165  			return nil, err
  3166  		}
  3167  
  3168  		rawAttributes = append(rawAttributes, rawValue)
  3169  	}
  3170  
  3171  	asn1Subject := template.RawSubject
  3172  	if len(asn1Subject) == 0 {
  3173  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  3174  		if err != nil {
  3175  			return nil, err
  3176  		}
  3177  	}
  3178  
  3179  	tbsCSR := tbsCertificateRequest{
  3180  		Version: 0, // PKCS #10, RFC 2986
  3181  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  3182  		PublicKey: publicKeyInfo{
  3183  			Algorithm: publicKeyAlgorithm,
  3184  			PublicKey: asn1.BitString{
  3185  				Bytes:     publicKeyBytes,
  3186  				BitLength: len(publicKeyBytes) * 8,
  3187  			},
  3188  		},
  3189  		RawAttributes: rawAttributes,
  3190  	}
  3191  
  3192  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  3193  	if err != nil {
  3194  		return
  3195  	}
  3196  	tbsCSR.Raw = tbsCSRContents
  3197  
  3198  	signed := tbsCSRContents
  3199  	if hashFunc != 0 {
  3200  		h := hashFunc.New()
  3201  		h.Write(signed)
  3202  		signed = h.Sum(nil)
  3203  	}
  3204  
  3205  	var signature []byte
  3206  	signature, err = key.Sign(rand, signed, hashFunc)
  3207  	if err != nil {
  3208  		return
  3209  	}
  3210  
  3211  	return asn1.Marshal(certificateRequest{
  3212  		TBSCSR:             tbsCSR,
  3213  		SignatureAlgorithm: sigAlgo,
  3214  		SignatureValue: asn1.BitString{
  3215  			Bytes:     signature,
  3216  			BitLength: len(signature) * 8,
  3217  		},
  3218  	})
  3219  }
  3220  
  3221  // ParseCertificateRequest parses a single certificate request from the
  3222  // given ASN.1 DER data.
  3223  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  3224  	var csr certificateRequest
  3225  
  3226  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  3227  	if err != nil {
  3228  		return nil, err
  3229  	} else if len(rest) != 0 {
  3230  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  3231  	}
  3232  
  3233  	return parseCertificateRequest(&csr)
  3234  }
  3235  
  3236  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  3237  	out := &CertificateRequest{
  3238  		Raw:                      in.Raw,
  3239  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  3240  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  3241  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  3242  
  3243  		Signature:          in.SignatureValue.RightAlign(),
  3244  		SignatureAlgorithm: SignatureAlgorithmFromAI(in.SignatureAlgorithm),
  3245  
  3246  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  3247  
  3248  		Version:    in.TBSCSR.Version,
  3249  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  3250  	}
  3251  
  3252  	var err error
  3253  	var nfe NonFatalErrors
  3254  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey, &nfe)
  3255  	if err != nil {
  3256  		return nil, err
  3257  	}
  3258  	// Treat non-fatal errors as fatal here.
  3259  	if len(nfe.Errors) > 0 {
  3260  		return nil, nfe.Errors[0]
  3261  	}
  3262  
  3263  	var subject pkix.RDNSequence
  3264  	if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  3265  		return nil, err
  3266  	} else if len(rest) != 0 {
  3267  		return nil, errors.New("x509: trailing data after X.509 Subject")
  3268  	}
  3269  
  3270  	out.Subject.FillFromRDNSequence(&subject)
  3271  
  3272  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  3273  		return nil, err
  3274  	}
  3275  
  3276  	for _, extension := range out.Extensions {
  3277  		if extension.Id.Equal(OIDExtensionSubjectAltName) {
  3278  			out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value, &nfe)
  3279  			if err != nil {
  3280  				return nil, err
  3281  			}
  3282  		}
  3283  	}
  3284  
  3285  	return out, nil
  3286  }
  3287  
  3288  // CheckSignature reports whether the signature on c is valid.
  3289  func (c *CertificateRequest) CheckSignature() error {
  3290  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
  3291  }
  3292  

View as plain text