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