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