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