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