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