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