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