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