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