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