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