...
Run Format

Source file src/crypto/x509/x509.go

Documentation: crypto/x509

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

View as plain text