github.com/euank/go@v0.0.0-20160829210321-495514729181/src/crypto/x509/x509.go (about)

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