...

Source file src/crypto/x509/x509.go

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

View as plain text