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