github.com/fisco-bcos/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/x509/x509.go (about)

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