github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/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  	out.Version = in.TBSCertificate.Version + 1
   913  	out.SerialNumber = in.TBSCertificate.SerialNumber
   914  
   915  	var issuer, subject pkix.RDNSequence
   916  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
   917  		return nil, err
   918  	} else if len(rest) != 0 {
   919  		return nil, errors.New("x509: trailing data after X.509 subject")
   920  	}
   921  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
   922  		return nil, err
   923  	} else if len(rest) != 0 {
   924  		return nil, errors.New("x509: trailing data after X.509 subject")
   925  	}
   926  
   927  	out.Issuer.FillFromRDNSequence(&issuer)
   928  	out.Subject.FillFromRDNSequence(&subject)
   929  
   930  	out.NotBefore = in.TBSCertificate.Validity.NotBefore
   931  	out.NotAfter = in.TBSCertificate.Validity.NotAfter
   932  
   933  	for _, e := range in.TBSCertificate.Extensions {
   934  		out.Extensions = append(out.Extensions, e)
   935  		unhandled := false
   936  
   937  		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
   938  			switch e.Id[3] {
   939  			case 15:
   940  				// RFC 5280, 4.2.1.3
   941  				var usageBits asn1.BitString
   942  				if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
   943  					return nil, err
   944  				} else if len(rest) != 0 {
   945  					return nil, errors.New("x509: trailing data after X.509 KeyUsage")
   946  				}
   947  
   948  				var usage int
   949  				for i := 0; i < 9; i++ {
   950  					if usageBits.At(i) != 0 {
   951  						usage |= 1 << uint(i)
   952  					}
   953  				}
   954  				out.KeyUsage = KeyUsage(usage)
   955  
   956  			case 19:
   957  				// RFC 5280, 4.2.1.9
   958  				var constraints basicConstraints
   959  				if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
   960  					return nil, err
   961  				} else if len(rest) != 0 {
   962  					return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
   963  				}
   964  
   965  				out.BasicConstraintsValid = true
   966  				out.IsCA = constraints.IsCA
   967  				out.MaxPathLen = constraints.MaxPathLen
   968  				out.MaxPathLenZero = out.MaxPathLen == 0
   969  
   970  			case 17:
   971  				out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value)
   972  				if err != nil {
   973  					return nil, err
   974  				}
   975  
   976  				if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 {
   977  					// If we didn't parse anything then we do the critical check, below.
   978  					unhandled = true
   979  				}
   980  
   981  			case 30:
   982  				// RFC 5280, 4.2.1.10
   983  
   984  				// NameConstraints ::= SEQUENCE {
   985  				//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
   986  				//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
   987  				//
   988  				// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
   989  				//
   990  				// GeneralSubtree ::= SEQUENCE {
   991  				//      base                    GeneralName,
   992  				//      minimum         [0]     BaseDistance DEFAULT 0,
   993  				//      maximum         [1]     BaseDistance OPTIONAL }
   994  				//
   995  				// BaseDistance ::= INTEGER (0..MAX)
   996  
   997  				var constraints nameConstraints
   998  				if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
   999  					return nil, err
  1000  				} else if len(rest) != 0 {
  1001  					return nil, errors.New("x509: trailing data after X.509 NameConstraints")
  1002  				}
  1003  
  1004  				if len(constraints.Excluded) > 0 && e.Critical {
  1005  					return out, UnhandledCriticalExtension{}
  1006  				}
  1007  
  1008  				for _, subtree := range constraints.Permitted {
  1009  					if len(subtree.Name) == 0 {
  1010  						if e.Critical {
  1011  							return out, UnhandledCriticalExtension{}
  1012  						}
  1013  						continue
  1014  					}
  1015  					out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
  1016  				}
  1017  
  1018  			case 31:
  1019  				// RFC 5280, 4.2.1.14
  1020  
  1021  				// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
  1022  				//
  1023  				// DistributionPoint ::= SEQUENCE {
  1024  				//     distributionPoint       [0]     DistributionPointName OPTIONAL,
  1025  				//     reasons                 [1]     ReasonFlags OPTIONAL,
  1026  				//     cRLIssuer               [2]     GeneralNames OPTIONAL }
  1027  				//
  1028  				// DistributionPointName ::= CHOICE {
  1029  				//     fullName                [0]     GeneralNames,
  1030  				//     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
  1031  
  1032  				var cdp []distributionPoint
  1033  				if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
  1034  					return nil, err
  1035  				} else if len(rest) != 0 {
  1036  					return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
  1037  				}
  1038  
  1039  				for _, dp := range cdp {
  1040  					var n asn1.RawValue
  1041  					if _, err := asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n); err != nil {
  1042  						return nil, err
  1043  					}
  1044  					// Trailing data after the fullName is
  1045  					// allowed because other elements of
  1046  					// the SEQUENCE can appear.
  1047  
  1048  					if n.Tag == 6 {
  1049  						out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
  1050  					}
  1051  				}
  1052  
  1053  			case 35:
  1054  				// RFC 5280, 4.2.1.1
  1055  				var a authKeyId
  1056  				if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
  1057  					return nil, err
  1058  				} else if len(rest) != 0 {
  1059  					return nil, errors.New("x509: trailing data after X.509 authority key-id")
  1060  				}
  1061  				out.AuthorityKeyId = a.Id
  1062  
  1063  			case 37:
  1064  				// RFC 5280, 4.2.1.12.  Extended Key Usage
  1065  
  1066  				// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
  1067  				//
  1068  				// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  1069  				//
  1070  				// KeyPurposeId ::= OBJECT IDENTIFIER
  1071  
  1072  				var keyUsage []asn1.ObjectIdentifier
  1073  				if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
  1074  					return nil, err
  1075  				} else if len(rest) != 0 {
  1076  					return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
  1077  				}
  1078  
  1079  				for _, u := range keyUsage {
  1080  					if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
  1081  						out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
  1082  					} else {
  1083  						out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
  1084  					}
  1085  				}
  1086  
  1087  			case 14:
  1088  				// RFC 5280, 4.2.1.2
  1089  				var keyid []byte
  1090  				if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
  1091  					return nil, err
  1092  				} else if len(rest) != 0 {
  1093  					return nil, errors.New("x509: trailing data after X.509 authority key-id")
  1094  				}
  1095  				out.SubjectKeyId = keyid
  1096  
  1097  			case 32:
  1098  				// RFC 5280 4.2.1.4: Certificate Policies
  1099  				var policies []policyInformation
  1100  				if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
  1101  					return nil, err
  1102  				} else if len(rest) != 0 {
  1103  					return nil, errors.New("x509: trailing data after X.509 certificate policies")
  1104  				}
  1105  				out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
  1106  				for i, policy := range policies {
  1107  					out.PolicyIdentifiers[i] = policy.Policy
  1108  				}
  1109  
  1110  			default:
  1111  				// Unknown extensions are recorded if critical.
  1112  				unhandled = true
  1113  			}
  1114  		} else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
  1115  			// RFC 5280 4.2.2.1: Authority Information Access
  1116  			var aia []authorityInfoAccess
  1117  			if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
  1118  				return nil, err
  1119  			} else if len(rest) != 0 {
  1120  				return nil, errors.New("x509: trailing data after X.509 authority information")
  1121  			}
  1122  
  1123  			for _, v := range aia {
  1124  				// GeneralName: uniformResourceIdentifier [6] IA5String
  1125  				if v.Location.Tag != 6 {
  1126  					continue
  1127  				}
  1128  				if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
  1129  					out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
  1130  				} else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
  1131  					out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
  1132  				}
  1133  			}
  1134  		} else {
  1135  			// Unknown extensions are recorded if critical.
  1136  			unhandled = true
  1137  		}
  1138  
  1139  		if e.Critical && unhandled {
  1140  			out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
  1141  		}
  1142  	}
  1143  
  1144  	return out, nil
  1145  }
  1146  
  1147  // ParseCertificate parses a single certificate from the given ASN.1 DER data.
  1148  func ParseCertificate(asn1Data []byte) (*Certificate, error) {
  1149  	var cert certificate
  1150  	rest, err := asn1.Unmarshal(asn1Data, &cert)
  1151  	if err != nil {
  1152  		return nil, err
  1153  	}
  1154  	if len(rest) > 0 {
  1155  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  1156  	}
  1157  
  1158  	return parseCertificate(&cert)
  1159  }
  1160  
  1161  // ParseCertificates parses one or more certificates from the given ASN.1 DER
  1162  // data. The certificates must be concatenated with no intermediate padding.
  1163  func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
  1164  	var v []*certificate
  1165  
  1166  	for len(asn1Data) > 0 {
  1167  		cert := new(certificate)
  1168  		var err error
  1169  		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
  1170  		if err != nil {
  1171  			return nil, err
  1172  		}
  1173  		v = append(v, cert)
  1174  	}
  1175  
  1176  	ret := make([]*Certificate, len(v))
  1177  	for i, ci := range v {
  1178  		cert, err := parseCertificate(ci)
  1179  		if err != nil {
  1180  			return nil, err
  1181  		}
  1182  		ret[i] = cert
  1183  	}
  1184  
  1185  	return ret, nil
  1186  }
  1187  
  1188  func reverseBitsInAByte(in byte) byte {
  1189  	b1 := in>>4 | in<<4
  1190  	b2 := b1>>2&0x33 | b1<<2&0xcc
  1191  	b3 := b2>>1&0x55 | b2<<1&0xaa
  1192  	return b3
  1193  }
  1194  
  1195  // asn1BitLength returns the bit-length of bitString by considering the
  1196  // most-significant bit in a byte to be the "first" bit. This convention
  1197  // matches ASN.1, but differs from almost everything else.
  1198  func asn1BitLength(bitString []byte) int {
  1199  	bitLen := len(bitString) * 8
  1200  
  1201  	for i := range bitString {
  1202  		b := bitString[len(bitString)-i-1]
  1203  
  1204  		for bit := uint(0); bit < 8; bit++ {
  1205  			if (b>>bit)&1 == 1 {
  1206  				return bitLen
  1207  			}
  1208  			bitLen--
  1209  		}
  1210  	}
  1211  
  1212  	return 0
  1213  }
  1214  
  1215  var (
  1216  	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
  1217  	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
  1218  	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
  1219  	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
  1220  	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
  1221  	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
  1222  	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
  1223  	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
  1224  	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  1225  	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  1226  )
  1227  
  1228  var (
  1229  	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  1230  	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  1231  )
  1232  
  1233  // oidNotInExtensions returns whether an extension with the given oid exists in
  1234  // extensions.
  1235  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  1236  	for _, e := range extensions {
  1237  		if e.Id.Equal(oid) {
  1238  			return true
  1239  		}
  1240  	}
  1241  	return false
  1242  }
  1243  
  1244  // marshalSANs marshals a list of addresses into a the contents of an X.509
  1245  // SubjectAlternativeName extension.
  1246  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
  1247  	var rawValues []asn1.RawValue
  1248  	for _, name := range dnsNames {
  1249  		rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
  1250  	}
  1251  	for _, email := range emailAddresses {
  1252  		rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
  1253  	}
  1254  	for _, rawIP := range ipAddresses {
  1255  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
  1256  		ip := rawIP.To4()
  1257  		if ip == nil {
  1258  			ip = rawIP
  1259  		}
  1260  		rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
  1261  	}
  1262  	return asn1.Marshal(rawValues)
  1263  }
  1264  
  1265  func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
  1266  	ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
  1267  	n := 0
  1268  
  1269  	if template.KeyUsage != 0 &&
  1270  		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1271  		ret[n].Id = oidExtensionKeyUsage
  1272  		ret[n].Critical = true
  1273  
  1274  		var a [2]byte
  1275  		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  1276  		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  1277  
  1278  		l := 1
  1279  		if a[1] != 0 {
  1280  			l = 2
  1281  		}
  1282  
  1283  		bitString := a[:l]
  1284  		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1285  		if err != nil {
  1286  			return
  1287  		}
  1288  		n++
  1289  	}
  1290  
  1291  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1292  		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1293  		ret[n].Id = oidExtensionExtendedKeyUsage
  1294  
  1295  		var oids []asn1.ObjectIdentifier
  1296  		for _, u := range template.ExtKeyUsage {
  1297  			if oid, ok := oidFromExtKeyUsage(u); ok {
  1298  				oids = append(oids, oid)
  1299  			} else {
  1300  				panic("internal error")
  1301  			}
  1302  		}
  1303  
  1304  		oids = append(oids, template.UnknownExtKeyUsage...)
  1305  
  1306  		ret[n].Value, err = asn1.Marshal(oids)
  1307  		if err != nil {
  1308  			return
  1309  		}
  1310  		n++
  1311  	}
  1312  
  1313  	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1314  		// Leaving MaxPathLen as zero indicates that no maximum path
  1315  		// length is desired, unless MaxPathLenZero is set. A value of
  1316  		// -1 causes encoding/asn1 to omit the value as desired.
  1317  		maxPathLen := template.MaxPathLen
  1318  		if maxPathLen == 0 && !template.MaxPathLenZero {
  1319  			maxPathLen = -1
  1320  		}
  1321  		ret[n].Id = oidExtensionBasicConstraints
  1322  		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
  1323  		ret[n].Critical = true
  1324  		if err != nil {
  1325  			return
  1326  		}
  1327  		n++
  1328  	}
  1329  
  1330  	if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1331  		ret[n].Id = oidExtensionSubjectKeyId
  1332  		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  1333  		if err != nil {
  1334  			return
  1335  		}
  1336  		n++
  1337  	}
  1338  
  1339  	if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1340  		ret[n].Id = oidExtensionAuthorityKeyId
  1341  		ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
  1342  		if err != nil {
  1343  			return
  1344  		}
  1345  		n++
  1346  	}
  1347  
  1348  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1349  		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1350  		ret[n].Id = oidExtensionAuthorityInfoAccess
  1351  		var aiaValues []authorityInfoAccess
  1352  		for _, name := range template.OCSPServer {
  1353  			aiaValues = append(aiaValues, authorityInfoAccess{
  1354  				Method:   oidAuthorityInfoAccessOcsp,
  1355  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1356  			})
  1357  		}
  1358  		for _, name := range template.IssuingCertificateURL {
  1359  			aiaValues = append(aiaValues, authorityInfoAccess{
  1360  				Method:   oidAuthorityInfoAccessIssuers,
  1361  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1362  			})
  1363  		}
  1364  		ret[n].Value, err = asn1.Marshal(aiaValues)
  1365  		if err != nil {
  1366  			return
  1367  		}
  1368  		n++
  1369  	}
  1370  
  1371  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1372  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1373  		ret[n].Id = oidExtensionSubjectAltName
  1374  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  1375  		if err != nil {
  1376  			return
  1377  		}
  1378  		n++
  1379  	}
  1380  
  1381  	if len(template.PolicyIdentifiers) > 0 &&
  1382  		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1383  		ret[n].Id = oidExtensionCertificatePolicies
  1384  		policies := make([]policyInformation, len(template.PolicyIdentifiers))
  1385  		for i, policy := range template.PolicyIdentifiers {
  1386  			policies[i].Policy = policy
  1387  		}
  1388  		ret[n].Value, err = asn1.Marshal(policies)
  1389  		if err != nil {
  1390  			return
  1391  		}
  1392  		n++
  1393  	}
  1394  
  1395  	if len(template.PermittedDNSDomains) > 0 &&
  1396  		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1397  		ret[n].Id = oidExtensionNameConstraints
  1398  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1399  
  1400  		var out nameConstraints
  1401  		out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
  1402  		for i, permitted := range template.PermittedDNSDomains {
  1403  			out.Permitted[i] = generalSubtree{Name: permitted}
  1404  		}
  1405  		ret[n].Value, err = asn1.Marshal(out)
  1406  		if err != nil {
  1407  			return
  1408  		}
  1409  		n++
  1410  	}
  1411  
  1412  	if len(template.CRLDistributionPoints) > 0 &&
  1413  		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1414  		ret[n].Id = oidExtensionCRLDistributionPoints
  1415  
  1416  		var crlDp []distributionPoint
  1417  		for _, name := range template.CRLDistributionPoints {
  1418  			rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
  1419  
  1420  			dp := distributionPoint{
  1421  				DistributionPoint: distributionPointName{
  1422  					FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName},
  1423  				},
  1424  			}
  1425  			crlDp = append(crlDp, dp)
  1426  		}
  1427  
  1428  		ret[n].Value, err = asn1.Marshal(crlDp)
  1429  		if err != nil {
  1430  			return
  1431  		}
  1432  		n++
  1433  	}
  1434  
  1435  	// Adding another extension here? Remember to update the maximum number
  1436  	// of elements in the make() at the top of the function.
  1437  
  1438  	return append(ret[:n], template.ExtraExtensions...), nil
  1439  }
  1440  
  1441  func subjectBytes(cert *Certificate) ([]byte, error) {
  1442  	if len(cert.RawSubject) > 0 {
  1443  		return cert.RawSubject, nil
  1444  	}
  1445  
  1446  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1447  }
  1448  
  1449  // signingParamsForPublicKey returns the parameters to use for signing with
  1450  // priv. If requestedSigAlgo is not zero then it overrides the default
  1451  // signature algorithm.
  1452  func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
  1453  	var pubType PublicKeyAlgorithm
  1454  
  1455  	switch pub := pub.(type) {
  1456  	case *rsa.PublicKey:
  1457  		pubType = RSA
  1458  		hashFunc = crypto.SHA256
  1459  		sigAlgo.Algorithm = oidSignatureSHA256WithRSA
  1460  		sigAlgo.Parameters = asn1.RawValue{
  1461  			Tag: 5,
  1462  		}
  1463  
  1464  	case *ecdsa.PublicKey:
  1465  		pubType = ECDSA
  1466  
  1467  		switch pub.Curve {
  1468  		case elliptic.P224(), elliptic.P256():
  1469  			hashFunc = crypto.SHA256
  1470  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  1471  		case elliptic.P384():
  1472  			hashFunc = crypto.SHA384
  1473  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  1474  		case elliptic.P521():
  1475  			hashFunc = crypto.SHA512
  1476  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  1477  		default:
  1478  			err = errors.New("x509: unknown elliptic curve")
  1479  		}
  1480  
  1481  	default:
  1482  		err = errors.New("x509: only RSA and ECDSA keys supported")
  1483  	}
  1484  
  1485  	if err != nil {
  1486  		return
  1487  	}
  1488  
  1489  	if requestedSigAlgo == 0 {
  1490  		return
  1491  	}
  1492  
  1493  	found := false
  1494  	for _, details := range signatureAlgorithmDetails {
  1495  		if details.algo == requestedSigAlgo {
  1496  			if details.pubKeyAlgo != pubType {
  1497  				err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1498  				return
  1499  			}
  1500  			sigAlgo.Algorithm, hashFunc = details.oid, details.hash
  1501  			if hashFunc == 0 {
  1502  				err = errors.New("x509: cannot sign with hash function requested")
  1503  				return
  1504  			}
  1505  			found = true
  1506  			break
  1507  		}
  1508  	}
  1509  
  1510  	if !found {
  1511  		err = errors.New("x509: unknown SignatureAlgorithm")
  1512  	}
  1513  
  1514  	return
  1515  }
  1516  
  1517  // CreateCertificate creates a new certificate based on a template. The
  1518  // following members of template are used: SerialNumber, Subject, NotBefore,
  1519  // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
  1520  // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
  1521  // PermittedDNSDomains, SignatureAlgorithm.
  1522  //
  1523  // The certificate is signed by parent. If parent is equal to template then the
  1524  // certificate is self-signed. The parameter pub is the public key of the
  1525  // signee and priv is the private key of the signer.
  1526  //
  1527  // The returned slice is the certificate in DER encoding.
  1528  //
  1529  // All keys types that are implemented via crypto.Signer are supported (This
  1530  // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  1531  func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
  1532  	key, ok := priv.(crypto.Signer)
  1533  	if !ok {
  1534  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1535  	}
  1536  
  1537  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  1538  	if err != nil {
  1539  		return nil, err
  1540  	}
  1541  
  1542  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  1543  	if err != nil {
  1544  		return nil, err
  1545  	}
  1546  
  1547  	if len(parent.SubjectKeyId) > 0 {
  1548  		template.AuthorityKeyId = parent.SubjectKeyId
  1549  	}
  1550  
  1551  	extensions, err := buildExtensions(template)
  1552  	if err != nil {
  1553  		return
  1554  	}
  1555  
  1556  	asn1Issuer, err := subjectBytes(parent)
  1557  	if err != nil {
  1558  		return
  1559  	}
  1560  
  1561  	asn1Subject, err := subjectBytes(template)
  1562  	if err != nil {
  1563  		return
  1564  	}
  1565  
  1566  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1567  	c := tbsCertificate{
  1568  		Version:            2,
  1569  		SerialNumber:       template.SerialNumber,
  1570  		SignatureAlgorithm: signatureAlgorithm,
  1571  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  1572  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1573  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  1574  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1575  		Extensions:         extensions,
  1576  	}
  1577  
  1578  	tbsCertContents, err := asn1.Marshal(c)
  1579  	if err != nil {
  1580  		return
  1581  	}
  1582  
  1583  	c.Raw = tbsCertContents
  1584  
  1585  	h := hashFunc.New()
  1586  	h.Write(tbsCertContents)
  1587  	digest := h.Sum(nil)
  1588  
  1589  	var signature []byte
  1590  	signature, err = key.Sign(rand, digest, hashFunc)
  1591  	if err != nil {
  1592  		return
  1593  	}
  1594  
  1595  	return asn1.Marshal(certificate{
  1596  		nil,
  1597  		c,
  1598  		signatureAlgorithm,
  1599  		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1600  	})
  1601  }
  1602  
  1603  // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  1604  // CRL.
  1605  var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  1606  
  1607  // pemType is the type of a PEM encoded CRL.
  1608  var pemType = "X509 CRL"
  1609  
  1610  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1611  // encoded CRLs will appear where they should be DER encoded, so this function
  1612  // will transparently handle PEM encoding as long as there isn't any leading
  1613  // garbage.
  1614  func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
  1615  	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1616  		block, _ := pem.Decode(crlBytes)
  1617  		if block != nil && block.Type == pemType {
  1618  			crlBytes = block.Bytes
  1619  		}
  1620  	}
  1621  	return ParseDERCRL(crlBytes)
  1622  }
  1623  
  1624  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1625  func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
  1626  	certList = new(pkix.CertificateList)
  1627  	if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
  1628  		return nil, err
  1629  	} else if len(rest) != 0 {
  1630  		return nil, errors.New("x509: trailing data after CRL")
  1631  	}
  1632  	return certList, nil
  1633  }
  1634  
  1635  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1636  // contains the given list of revoked certificates.
  1637  func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1638  	key, ok := priv.(crypto.Signer)
  1639  	if !ok {
  1640  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1641  	}
  1642  
  1643  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
  1644  	if err != nil {
  1645  		return nil, err
  1646  	}
  1647  
  1648  	tbsCertList := pkix.TBSCertificateList{
  1649  		Version:             1,
  1650  		Signature:           signatureAlgorithm,
  1651  		Issuer:              c.Subject.ToRDNSequence(),
  1652  		ThisUpdate:          now.UTC(),
  1653  		NextUpdate:          expiry.UTC(),
  1654  		RevokedCertificates: revokedCerts,
  1655  	}
  1656  
  1657  	// Authority Key Id
  1658  	if len(c.SubjectKeyId) > 0 {
  1659  		var aki pkix.Extension
  1660  		aki.Id = oidExtensionAuthorityKeyId
  1661  		aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  1662  		if err != nil {
  1663  			return
  1664  		}
  1665  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  1666  	}
  1667  
  1668  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1669  	if err != nil {
  1670  		return
  1671  	}
  1672  
  1673  	h := hashFunc.New()
  1674  	h.Write(tbsCertListContents)
  1675  	digest := h.Sum(nil)
  1676  
  1677  	var signature []byte
  1678  	signature, err = key.Sign(rand, digest, hashFunc)
  1679  	if err != nil {
  1680  		return
  1681  	}
  1682  
  1683  	return asn1.Marshal(pkix.CertificateList{
  1684  		TBSCertList:        tbsCertList,
  1685  		SignatureAlgorithm: signatureAlgorithm,
  1686  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1687  	})
  1688  }
  1689  
  1690  // CertificateRequest represents a PKCS #10, certificate signature request.
  1691  type CertificateRequest struct {
  1692  	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  1693  	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  1694  	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
  1695  	RawSubject               []byte // DER encoded Subject.
  1696  
  1697  	Version            int
  1698  	Signature          []byte
  1699  	SignatureAlgorithm SignatureAlgorithm
  1700  
  1701  	PublicKeyAlgorithm PublicKeyAlgorithm
  1702  	PublicKey          interface{}
  1703  
  1704  	Subject pkix.Name
  1705  
  1706  	// Attributes is the dried husk of a bug and shouldn't be used.
  1707  	Attributes []pkix.AttributeTypeAndValueSET
  1708  
  1709  	// Extensions contains raw X.509 extensions. When parsing CSRs, this
  1710  	// can be used to extract extensions that are not parsed by this
  1711  	// package.
  1712  	Extensions []pkix.Extension
  1713  
  1714  	// ExtraExtensions contains extensions to be copied, raw, into any
  1715  	// marshaled CSR. Values override any extensions that would otherwise
  1716  	// be produced based on the other fields but are overridden by any
  1717  	// extensions specified in Attributes.
  1718  	//
  1719  	// The ExtraExtensions field is not populated when parsing CSRs, see
  1720  	// Extensions.
  1721  	ExtraExtensions []pkix.Extension
  1722  
  1723  	// Subject Alternate Name values.
  1724  	DNSNames       []string
  1725  	EmailAddresses []string
  1726  	IPAddresses    []net.IP
  1727  }
  1728  
  1729  // These structures reflect the ASN.1 structure of X.509 certificate
  1730  // signature requests (see RFC 2986):
  1731  
  1732  type tbsCertificateRequest struct {
  1733  	Raw           asn1.RawContent
  1734  	Version       int
  1735  	Subject       asn1.RawValue
  1736  	PublicKey     publicKeyInfo
  1737  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  1738  }
  1739  
  1740  type certificateRequest struct {
  1741  	Raw                asn1.RawContent
  1742  	TBSCSR             tbsCertificateRequest
  1743  	SignatureAlgorithm pkix.AlgorithmIdentifier
  1744  	SignatureValue     asn1.BitString
  1745  }
  1746  
  1747  // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
  1748  // extensions in a CSR.
  1749  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  1750  
  1751  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  1752  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  1753  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  1754  	var rawAttributes []asn1.RawValue
  1755  	b, err := asn1.Marshal(attributes)
  1756  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  1757  	if err != nil {
  1758  		return nil, err
  1759  	}
  1760  	if len(rest) != 0 {
  1761  		return nil, errors.New("x509: failed to unmarshall raw CSR Attributes")
  1762  	}
  1763  	return rawAttributes, nil
  1764  }
  1765  
  1766  // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
  1767  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  1768  	var attributes []pkix.AttributeTypeAndValueSET
  1769  	for _, rawAttr := range rawAttributes {
  1770  		var attr pkix.AttributeTypeAndValueSET
  1771  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  1772  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  1773  		// (i.e.: challengePassword or unstructuredName).
  1774  		if err == nil && len(rest) == 0 {
  1775  			attributes = append(attributes, attr)
  1776  		}
  1777  	}
  1778  	return attributes
  1779  }
  1780  
  1781  // parseCSRExtensions parses the attributes from a CSR and extracts any
  1782  // requested extensions.
  1783  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  1784  	// pkcs10Attribute reflects the Attribute structure from section 4.1 of
  1785  	// https://tools.ietf.org/html/rfc2986.
  1786  	type pkcs10Attribute struct {
  1787  		Id     asn1.ObjectIdentifier
  1788  		Values []asn1.RawValue `asn1:"set"`
  1789  	}
  1790  
  1791  	var ret []pkix.Extension
  1792  	for _, rawAttr := range rawAttributes {
  1793  		var attr pkcs10Attribute
  1794  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  1795  			// Ignore attributes that don't parse.
  1796  			continue
  1797  		}
  1798  
  1799  		if !attr.Id.Equal(oidExtensionRequest) {
  1800  			continue
  1801  		}
  1802  
  1803  		var extensions []pkix.Extension
  1804  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  1805  			return nil, err
  1806  		}
  1807  		ret = append(ret, extensions...)
  1808  	}
  1809  
  1810  	return ret, nil
  1811  }
  1812  
  1813  // CreateCertificateRequest creates a new certificate based on a template. The
  1814  // following members of template are used: Subject, Attributes,
  1815  // SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses.
  1816  // The private key is the private key of the signer.
  1817  //
  1818  // The returned slice is the certificate request in DER encoding.
  1819  //
  1820  // All keys types that are implemented via crypto.Signer are supported (This
  1821  // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  1822  func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
  1823  	key, ok := priv.(crypto.Signer)
  1824  	if !ok {
  1825  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1826  	}
  1827  
  1828  	var hashFunc crypto.Hash
  1829  	var sigAlgo pkix.AlgorithmIdentifier
  1830  	hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  1831  	if err != nil {
  1832  		return nil, err
  1833  	}
  1834  
  1835  	var publicKeyBytes []byte
  1836  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1837  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  1838  	if err != nil {
  1839  		return nil, err
  1840  	}
  1841  
  1842  	var extensions []pkix.Extension
  1843  
  1844  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1845  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1846  		sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  1847  		if err != nil {
  1848  			return nil, err
  1849  		}
  1850  
  1851  		extensions = append(extensions, pkix.Extension{
  1852  			Id:    oidExtensionSubjectAltName,
  1853  			Value: sanBytes,
  1854  		})
  1855  	}
  1856  
  1857  	extensions = append(extensions, template.ExtraExtensions...)
  1858  
  1859  	var attributes []pkix.AttributeTypeAndValueSET
  1860  	attributes = append(attributes, template.Attributes...)
  1861  
  1862  	if len(extensions) > 0 {
  1863  		// specifiedExtensions contains all the extensions that we
  1864  		// found specified via template.Attributes.
  1865  		specifiedExtensions := make(map[string]bool)
  1866  
  1867  		for _, atvSet := range template.Attributes {
  1868  			if !atvSet.Type.Equal(oidExtensionRequest) {
  1869  				continue
  1870  			}
  1871  
  1872  			for _, atvs := range atvSet.Value {
  1873  				for _, atv := range atvs {
  1874  					specifiedExtensions[atv.Type.String()] = true
  1875  				}
  1876  			}
  1877  		}
  1878  
  1879  		atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions))
  1880  		for _, e := range extensions {
  1881  			if specifiedExtensions[e.Id.String()] {
  1882  				// Attributes already contained a value for
  1883  				// this extension and it takes priority.
  1884  				continue
  1885  			}
  1886  
  1887  			atvs = append(atvs, pkix.AttributeTypeAndValue{
  1888  				// There is no place for the critical flag in a CSR.
  1889  				Type:  e.Id,
  1890  				Value: e.Value,
  1891  			})
  1892  		}
  1893  
  1894  		// Append the extensions to an existing attribute if possible.
  1895  		appended := false
  1896  		for _, atvSet := range attributes {
  1897  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  1898  				continue
  1899  			}
  1900  
  1901  			atvSet.Value[0] = append(atvSet.Value[0], atvs...)
  1902  			appended = true
  1903  			break
  1904  		}
  1905  
  1906  		// Otherwise, add a new attribute for the extensions.
  1907  		if !appended {
  1908  			attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  1909  				Type: oidExtensionRequest,
  1910  				Value: [][]pkix.AttributeTypeAndValue{
  1911  					atvs,
  1912  				},
  1913  			})
  1914  		}
  1915  	}
  1916  
  1917  	asn1Subject := template.RawSubject
  1918  	if len(asn1Subject) == 0 {
  1919  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  1920  		if err != nil {
  1921  			return
  1922  		}
  1923  	}
  1924  
  1925  	rawAttributes, err := newRawAttributes(attributes)
  1926  	if err != nil {
  1927  		return
  1928  	}
  1929  
  1930  	tbsCSR := tbsCertificateRequest{
  1931  		Version: 0, // PKCS #10, RFC 2986
  1932  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  1933  		PublicKey: publicKeyInfo{
  1934  			Algorithm: publicKeyAlgorithm,
  1935  			PublicKey: asn1.BitString{
  1936  				Bytes:     publicKeyBytes,
  1937  				BitLength: len(publicKeyBytes) * 8,
  1938  			},
  1939  		},
  1940  		RawAttributes: rawAttributes,
  1941  	}
  1942  
  1943  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  1944  	if err != nil {
  1945  		return
  1946  	}
  1947  	tbsCSR.Raw = tbsCSRContents
  1948  
  1949  	h := hashFunc.New()
  1950  	h.Write(tbsCSRContents)
  1951  	digest := h.Sum(nil)
  1952  
  1953  	var signature []byte
  1954  	signature, err = key.Sign(rand, digest, hashFunc)
  1955  	if err != nil {
  1956  		return
  1957  	}
  1958  
  1959  	return asn1.Marshal(certificateRequest{
  1960  		TBSCSR:             tbsCSR,
  1961  		SignatureAlgorithm: sigAlgo,
  1962  		SignatureValue: asn1.BitString{
  1963  			Bytes:     signature,
  1964  			BitLength: len(signature) * 8,
  1965  		},
  1966  	})
  1967  }
  1968  
  1969  // ParseCertificateRequest parses a single certificate request from the
  1970  // given ASN.1 DER data.
  1971  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  1972  	var csr certificateRequest
  1973  
  1974  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  1975  	if err != nil {
  1976  		return nil, err
  1977  	} else if len(rest) != 0 {
  1978  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  1979  	}
  1980  
  1981  	return parseCertificateRequest(&csr)
  1982  }
  1983  
  1984  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  1985  	out := &CertificateRequest{
  1986  		Raw: in.Raw,
  1987  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  1988  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  1989  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  1990  
  1991  		Signature:          in.SignatureValue.RightAlign(),
  1992  		SignatureAlgorithm: getSignatureAlgorithmFromOID(in.SignatureAlgorithm.Algorithm),
  1993  
  1994  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  1995  
  1996  		Version:    in.TBSCSR.Version,
  1997  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  1998  	}
  1999  
  2000  	var err error
  2001  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
  2002  	if err != nil {
  2003  		return nil, err
  2004  	}
  2005  
  2006  	var subject pkix.RDNSequence
  2007  	if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  2008  		return nil, err
  2009  	} else if len(rest) != 0 {
  2010  		return nil, errors.New("x509: trailing data after X.509 Subject")
  2011  	}
  2012  
  2013  	out.Subject.FillFromRDNSequence(&subject)
  2014  
  2015  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  2016  		return nil, err
  2017  	}
  2018  
  2019  	for _, extension := range out.Extensions {
  2020  		if extension.Id.Equal(oidExtensionSubjectAltName) {
  2021  			out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(extension.Value)
  2022  			if err != nil {
  2023  				return nil, err
  2024  			}
  2025  		}
  2026  	}
  2027  
  2028  	return out, nil
  2029  }
  2030  
  2031  // CheckSignature verifies that the signature on c is a valid signature
  2032  func (c *CertificateRequest) CheckSignature() (err error) {
  2033  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
  2034  }