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