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