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/x509/pkix"
17	"encoding/asn1"
18	"encoding/pem"
19	"errors"
20	"io"
21	"math/big"
22	"net"
23	"strconv"
24	"time"
25)
26
27// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
28// in RFC 3280.
29type pkixPublicKey struct {
30	Algo      pkix.AlgorithmIdentifier
31	BitString asn1.BitString
32}
33
34// ParsePKIXPublicKey parses a DER encoded public key. These values are
35// typically found in PEM blocks with "BEGIN PUBLIC KEY".
36func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
37	var pki publicKeyInfo
38	if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
39		return
40	}
41	algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
42	if algo == UnknownPublicKeyAlgorithm {
43		return nil, errors.New("x509: unknown public key algorithm")
44	}
45	return parsePublicKey(algo, &pki)
46}
47
48func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
49	switch pub := pub.(type) {
50	case *rsa.PublicKey:
51		publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
52			N: pub.N,
53			E: pub.E,
54		})
55		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
56		// This is a NULL parameters value which is technically
57		// superfluous, but most other code includes it and, by
58		// doing this, we match their public key hashes.
59		publicKeyAlgorithm.Parameters = asn1.RawValue{
60			Tag: 5,
61		}
62	case *ecdsa.PublicKey:
63		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
64		oid, ok := oidFromNamedCurve(pub.Curve)
65		if !ok {
66			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
67		}
68		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
69		var paramBytes []byte
70		paramBytes, err = asn1.Marshal(oid)
71		if err != nil {
72			return
73		}
74		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
75	default:
76		return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
77	}
78
79	return publicKeyBytes, publicKeyAlgorithm, nil
80}
81
82// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
83func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
84	var publicKeyBytes []byte
85	var publicKeyAlgorithm pkix.AlgorithmIdentifier
86	var err error
87
88	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
89		return nil, err
90	}
91
92	pkix := pkixPublicKey{
93		Algo: publicKeyAlgorithm,
94		BitString: asn1.BitString{
95			Bytes:     publicKeyBytes,
96			BitLength: 8 * len(publicKeyBytes),
97		},
98	}
99
100	ret, _ := asn1.Marshal(pkix)
101	return ret, nil
102}
103
104// These structures reflect the ASN.1 structure of X.509 certificates.:
105
106type certificate struct {
107	Raw                asn1.RawContent
108	TBSCertificate     tbsCertificate
109	SignatureAlgorithm pkix.AlgorithmIdentifier
110	SignatureValue     asn1.BitString
111}
112
113type tbsCertificate struct {
114	Raw                asn1.RawContent
115	Version            int `asn1:"optional,explicit,default:1,tag:0"`
116	SerialNumber       *big.Int
117	SignatureAlgorithm pkix.AlgorithmIdentifier
118	Issuer             asn1.RawValue
119	Validity           validity
120	Subject            asn1.RawValue
121	PublicKey          publicKeyInfo
122	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
123	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
124	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
125}
126
127type dsaAlgorithmParameters struct {
128	P, Q, G *big.Int
129}
130
131type dsaSignature struct {
132	R, S *big.Int
133}
134
135type ecdsaSignature dsaSignature
136
137type validity struct {
138	NotBefore, NotAfter time.Time
139}
140
141type publicKeyInfo struct {
142	Raw       asn1.RawContent
143	Algorithm pkix.AlgorithmIdentifier
144	PublicKey asn1.BitString
145}
146
147// RFC 5280,  4.2.1.1
148type authKeyId struct {
149	Id []byte `asn1:"optional,tag:0"`
150}
151
152type SignatureAlgorithm int
153
154const (
155	UnknownSignatureAlgorithm SignatureAlgorithm = iota
156	MD2WithRSA
157	MD5WithRSA
158	SHA1WithRSA
159	SHA256WithRSA
160	SHA384WithRSA
161	SHA512WithRSA
162	DSAWithSHA1
163	DSAWithSHA256
164	ECDSAWithSHA1
165	ECDSAWithSHA256
166	ECDSAWithSHA384
167	ECDSAWithSHA512
168)
169
170type PublicKeyAlgorithm int
171
172const (
173	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
174	RSA
175	DSA
176	ECDSA
177)
178
179// OIDs for signature algorithms
180//
181// pkcs-1 OBJECT IDENTIFIER ::= {
182//    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
183//
184//
185// RFC 3279 2.2.1 RSA Signature Algorithms
186//
187// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
188//
189// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
190//
191// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
192//
193// dsaWithSha1 OBJECT IDENTIFIER ::= {
194//    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
195//
196// RFC 3279 2.2.3 ECDSA Signature Algorithm
197//
198// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
199// 	  iso(1) member-body(2) us(840) ansi-x962(10045)
200//    signatures(4) ecdsa-with-SHA1(1)}
201//
202//
203// RFC 4055 5 PKCS #1 Version 1.5
204//
205// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
206//
207// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
208//
209// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
210//
211//
212// RFC 5758 3.1 DSA Signature Algorithms
213//
214// dsaWithSha256 OBJECT IDENTIFIER ::= {
215//    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
216//    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
217//
218// RFC 5758 3.2 ECDSA Signature Algorithm
219//
220// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
221//    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
222//
223// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
224//    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
225//
226// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
227//    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
228
229var (
230	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
231	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
232	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
233	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
234	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
235	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
236	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
237	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
238	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
239	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
240	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
241	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
242)
243
244func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
245	switch {
246	case oid.Equal(oidSignatureMD2WithRSA):
247		return MD2WithRSA
248	case oid.Equal(oidSignatureMD5WithRSA):
249		return MD5WithRSA
250	case oid.Equal(oidSignatureSHA1WithRSA):
251		return SHA1WithRSA
252	case oid.Equal(oidSignatureSHA256WithRSA):
253		return SHA256WithRSA
254	case oid.Equal(oidSignatureSHA384WithRSA):
255		return SHA384WithRSA
256	case oid.Equal(oidSignatureSHA512WithRSA):
257		return SHA512WithRSA
258	case oid.Equal(oidSignatureDSAWithSHA1):
259		return DSAWithSHA1
260	case oid.Equal(oidSignatureDSAWithSHA256):
261		return DSAWithSHA256
262	case oid.Equal(oidSignatureECDSAWithSHA1):
263		return ECDSAWithSHA1
264	case oid.Equal(oidSignatureECDSAWithSHA256):
265		return ECDSAWithSHA256
266	case oid.Equal(oidSignatureECDSAWithSHA384):
267		return ECDSAWithSHA384
268	case oid.Equal(oidSignatureECDSAWithSHA512):
269		return ECDSAWithSHA512
270	}
271	return UnknownSignatureAlgorithm
272}
273
274// RFC 3279, 2.3 Public Key Algorithms
275//
276// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
277//    rsadsi(113549) pkcs(1) 1 }
278//
279// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
280//
281// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
282//    x9-57(10040) x9cm(4) 1 }
283//
284// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
285//
286// id-ecPublicKey OBJECT IDENTIFIER ::= {
287//       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
288var (
289	oidPublicKeyRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
290	oidPublicKeyDSA   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
291	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
292)
293
294func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
295	switch {
296	case oid.Equal(oidPublicKeyRSA):
297		return RSA
298	case oid.Equal(oidPublicKeyDSA):
299		return DSA
300	case oid.Equal(oidPublicKeyECDSA):
301		return ECDSA
302	}
303	return UnknownPublicKeyAlgorithm
304}
305
306// RFC 5480, 2.1.1.1. Named Curve
307//
308// secp224r1 OBJECT IDENTIFIER ::= {
309//   iso(1) identified-organization(3) certicom(132) curve(0) 33 }
310//
311// secp256r1 OBJECT IDENTIFIER ::= {
312//   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
313//   prime(1) 7 }
314//
315// secp384r1 OBJECT IDENTIFIER ::= {
316//   iso(1) identified-organization(3) certicom(132) curve(0) 34 }
317//
318// secp521r1 OBJECT IDENTIFIER ::= {
319//   iso(1) identified-organization(3) certicom(132) curve(0) 35 }
320//
321// NB: secp256r1 is equivalent to prime256v1
322var (
323	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
324	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
325	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
326	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
327)
328
329func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
330	switch {
331	case oid.Equal(oidNamedCurveP224):
332		return elliptic.P224()
333	case oid.Equal(oidNamedCurveP256):
334		return elliptic.P256()
335	case oid.Equal(oidNamedCurveP384):
336		return elliptic.P384()
337	case oid.Equal(oidNamedCurveP521):
338		return elliptic.P521()
339	}
340	return nil
341}
342
343func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
344	switch curve {
345	case elliptic.P224():
346		return oidNamedCurveP224, true
347	case elliptic.P256():
348		return oidNamedCurveP256, true
349	case elliptic.P384():
350		return oidNamedCurveP384, true
351	case elliptic.P521():
352		return oidNamedCurveP521, true
353	}
354
355	return nil, false
356}
357
358// KeyUsage represents the set of actions that are valid for a given key. It's
359// a bitmap of the KeyUsage* constants.
360type KeyUsage int
361
362const (
363	KeyUsageDigitalSignature KeyUsage = 1 << iota
364	KeyUsageContentCommitment
365	KeyUsageKeyEncipherment
366	KeyUsageDataEncipherment
367	KeyUsageKeyAgreement
368	KeyUsageCertSign
369	KeyUsageCRLSign
370	KeyUsageEncipherOnly
371	KeyUsageDecipherOnly
372)
373
374// RFC 5280, 4.2.1.12  Extended Key Usage
375//
376// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
377//
378// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
379//
380// id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
381// id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
382// id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
383// id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
384// id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
385// id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
386var (
387	oidExtKeyUsageAny                        = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
388	oidExtKeyUsageServerAuth                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
389	oidExtKeyUsageClientAuth                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
390	oidExtKeyUsageCodeSigning                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
391	oidExtKeyUsageEmailProtection            = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
392	oidExtKeyUsageIPSECEndSystem             = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
393	oidExtKeyUsageIPSECTunnel                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
394	oidExtKeyUsageIPSECUser                  = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
395	oidExtKeyUsageTimeStamping               = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
396	oidExtKeyUsageOCSPSigning                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
397	oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
398	oidExtKeyUsageNetscapeServerGatedCrypto  = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
399)
400
401// ExtKeyUsage represents an extended set of actions that are valid for a given key.
402// Each of the ExtKeyUsage* constants define a unique action.
403type ExtKeyUsage int
404
405const (
406	ExtKeyUsageAny ExtKeyUsage = iota
407	ExtKeyUsageServerAuth
408	ExtKeyUsageClientAuth
409	ExtKeyUsageCodeSigning
410	ExtKeyUsageEmailProtection
411	ExtKeyUsageIPSECEndSystem
412	ExtKeyUsageIPSECTunnel
413	ExtKeyUsageIPSECUser
414	ExtKeyUsageTimeStamping
415	ExtKeyUsageOCSPSigning
416	ExtKeyUsageMicrosoftServerGatedCrypto
417	ExtKeyUsageNetscapeServerGatedCrypto
418)
419
420// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
421var extKeyUsageOIDs = []struct {
422	extKeyUsage ExtKeyUsage
423	oid         asn1.ObjectIdentifier
424}{
425	{ExtKeyUsageAny, oidExtKeyUsageAny},
426	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
427	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
428	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
429	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
430	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
431	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
432	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
433	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
434	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
435	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
436	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
437}
438
439func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
440	for _, pair := range extKeyUsageOIDs {
441		if oid.Equal(pair.oid) {
442			return pair.extKeyUsage, true
443		}
444	}
445	return
446}
447
448func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
449	for _, pair := range extKeyUsageOIDs {
450		if eku == pair.extKeyUsage {
451			return pair.oid, true
452		}
453	}
454	return
455}
456
457// A Certificate represents an X.509 certificate.
458type Certificate struct {
459	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
460	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
461	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
462	RawSubject              []byte // DER encoded Subject
463	RawIssuer               []byte // DER encoded Issuer
464
465	Signature          []byte
466	SignatureAlgorithm SignatureAlgorithm
467
468	PublicKeyAlgorithm PublicKeyAlgorithm
469	PublicKey          interface{}
470
471	Version             int
472	SerialNumber        *big.Int
473	Issuer              pkix.Name
474	Subject             pkix.Name
475	NotBefore, NotAfter time.Time // Validity bounds.
476	KeyUsage            KeyUsage
477
478	// Extensions contains raw X.509 extensions. When parsing certificates,
479	// this can be used to extract non-critical extensions that are not
480	// parsed by this package. When marshaling certificates, the Extensions
481	// field is ignored, see ExtraExtensions.
482	Extensions []pkix.Extension
483
484	// ExtraExtensions contains extensions to be copied, raw, into any
485	// marshaled certificates. Values override any extensions that would
486	// otherwise be produced based on the other fields. The ExtraExtensions
487	// field is not populated when parsing certificates, see Extensions.
488	ExtraExtensions []pkix.Extension
489
490	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
491	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
492
493	BasicConstraintsValid bool // if true then the next two fields are valid.
494	IsCA                  bool
495	MaxPathLen            int
496
497	SubjectKeyId   []byte
498	AuthorityKeyId []byte
499
500	// RFC 5280, 4.2.2.1 (Authority Information Access)
501	OCSPServer            []string
502	IssuingCertificateURL []string
503
504	// Subject Alternate Name values
505	DNSNames       []string
506	EmailAddresses []string
507	IPAddresses    []net.IP
508
509	// Name constraints
510	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
511	PermittedDNSDomains         []string
512
513	// CRL Distribution Points
514	CRLDistributionPoints []string
515
516	PolicyIdentifiers []asn1.ObjectIdentifier
517}
518
519// ErrUnsupportedAlgorithm results from attempting to perform an operation that
520// involves algorithms that are not currently implemented.
521var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
522
523// ConstraintViolationError results when a requested usage is not permitted by
524// a certificate. For example: checking a signature when the public key isn't a
525// certificate signing key.
526type ConstraintViolationError struct{}
527
528func (ConstraintViolationError) Error() string {
529	return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
530}
531
532func (c *Certificate) Equal(other *Certificate) bool {
533	return bytes.Equal(c.Raw, other.Raw)
534}
535
536// Entrust have a broken root certificate (CN=Entrust.net Certification
537// Authority (2048)) which isn't marked as a CA certificate and is thus invalid
538// according to PKIX.
539// We recognise this certificate by its SubjectPublicKeyInfo and exempt it
540// from the Basic Constraints requirement.
541// See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
542//
543// TODO(agl): remove this hack once their reissued root is sufficiently
544// widespread.
545var entrustBrokenSPKI = []byte{
546	0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
547	0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
548	0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
549	0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
550	0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
551	0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
552	0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
553	0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
554	0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
555	0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
556	0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
557	0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
558	0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
559	0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
560	0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
561	0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
562	0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
563	0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
564	0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
565	0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
566	0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
567	0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
568	0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
569	0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
570	0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
571	0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
572	0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
573	0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
574	0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
575	0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
576	0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
577	0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
578	0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
579	0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
580	0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
581	0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
582	0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
583}
584
585// CheckSignatureFrom verifies that the signature on c is a valid signature
586// from parent.
587func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
588	// RFC 5280, 4.2.1.9:
589	// "If the basic constraints extension is not present in a version 3
590	// certificate, or the extension is present but the cA boolean is not
591	// asserted, then the certified public key MUST NOT be used to verify
592	// certificate signatures."
593	// (except for Entrust, see comment above entrustBrokenSPKI)
594	if (parent.Version == 3 && !parent.BasicConstraintsValid ||
595		parent.BasicConstraintsValid && !parent.IsCA) &&
596		!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
597		return ConstraintViolationError{}
598	}
599
600	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
601		return ConstraintViolationError{}
602	}
603
604	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
605		return ErrUnsupportedAlgorithm
606	}
607
608	// TODO(agl): don't ignore the path length constraint.
609
610	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
611}
612
613// CheckSignature verifies that signature is a valid signature over signed from
614// c's public key.
615func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
616	var hashType crypto.Hash
617
618	switch algo {
619	case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
620		hashType = crypto.SHA1
621	case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
622		hashType = crypto.SHA256
623	case SHA384WithRSA, ECDSAWithSHA384:
624		hashType = crypto.SHA384
625	case SHA512WithRSA, ECDSAWithSHA512:
626		hashType = crypto.SHA512
627	default:
628		return ErrUnsupportedAlgorithm
629	}
630
631	if !hashType.Available() {
632		return ErrUnsupportedAlgorithm
633	}
634	h := hashType.New()
635
636	h.Write(signed)
637	digest := h.Sum(nil)
638
639	switch pub := c.PublicKey.(type) {
640	case *rsa.PublicKey:
641		return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
642	case *dsa.PublicKey:
643		dsaSig := new(dsaSignature)
644		if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
645			return err
646		}
647		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
648			return errors.New("x509: DSA signature contained zero or negative values")
649		}
650		if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
651			return errors.New("x509: DSA verification failure")
652		}
653		return
654	case *ecdsa.PublicKey:
655		ecdsaSig := new(ecdsaSignature)
656		if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
657			return err
658		}
659		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
660			return errors.New("x509: ECDSA signature contained zero or negative values")
661		}
662		if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
663			return errors.New("x509: ECDSA verification failure")
664		}
665		return
666	}
667	return ErrUnsupportedAlgorithm
668}
669
670// CheckCRLSignature checks that the signature in crl is from c.
671func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
672	algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
673	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
674}
675
676type UnhandledCriticalExtension struct{}
677
678func (h UnhandledCriticalExtension) Error() string {
679	return "x509: unhandled critical extension"
680}
681
682type basicConstraints struct {
683	IsCA       bool `asn1:"optional"`
684	MaxPathLen int  `asn1:"optional,default:-1"`
685}
686
687// RFC 5280 4.2.1.4
688type policyInformation struct {
689	Policy asn1.ObjectIdentifier
690	// policyQualifiers omitted
691}
692
693// RFC 5280, 4.2.1.10
694type nameConstraints struct {
695	Permitted []generalSubtree `asn1:"optional,tag:0"`
696	Excluded  []generalSubtree `asn1:"optional,tag:1"`
697}
698
699type generalSubtree struct {
700	Name string `asn1:"tag:2,optional,ia5"`
701}
702
703// RFC 5280, 4.2.2.1
704type authorityInfoAccess struct {
705	Method   asn1.ObjectIdentifier
706	Location asn1.RawValue
707}
708
709// RFC 5280, 4.2.1.14
710type distributionPoint struct {
711	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
712	Reason            asn1.BitString        `asn1:"optional,tag:1"`
713	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
714}
715
716type distributionPointName struct {
717	FullName     asn1.RawValue    `asn1:"optional,tag:0"`
718	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
719}
720
721func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
722	asn1Data := keyData.PublicKey.RightAlign()
723	switch algo {
724	case RSA:
725		p := new(rsaPublicKey)
726		_, err := asn1.Unmarshal(asn1Data, p)
727		if err != nil {
728			return nil, err
729		}
730
731		if p.N.Sign() <= 0 {
732			return nil, errors.New("x509: RSA modulus is not a positive number")
733		}
734		if p.E <= 0 {
735			return nil, errors.New("x509: RSA public exponent is not a positive number")
736		}
737
738		pub := &rsa.PublicKey{
739			E: p.E,
740			N: p.N,
741		}
742		return pub, nil
743	case DSA:
744		var p *big.Int
745		_, err := asn1.Unmarshal(asn1Data, &p)
746		if err != nil {
747			return nil, err
748		}
749		paramsData := keyData.Algorithm.Parameters.FullBytes
750		params := new(dsaAlgorithmParameters)
751		_, err = asn1.Unmarshal(paramsData, params)
752		if err != nil {
753			return nil, err
754		}
755		if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
756			return nil, errors.New("x509: zero or negative DSA parameter")
757		}
758		pub := &dsa.PublicKey{
759			Parameters: dsa.Parameters{
760				P: params.P,
761				Q: params.Q,
762				G: params.G,
763			},
764			Y: p,
765		}
766		return pub, nil
767	case ECDSA:
768		paramsData := keyData.Algorithm.Parameters.FullBytes
769		namedCurveOID := new(asn1.ObjectIdentifier)
770		_, err := asn1.Unmarshal(paramsData, namedCurveOID)
771		if err != nil {
772			return nil, err
773		}
774		namedCurve := namedCurveFromOID(*namedCurveOID)
775		if namedCurve == nil {
776			return nil, errors.New("x509: unsupported elliptic curve")
777		}
778		x, y := elliptic.Unmarshal(namedCurve, asn1Data)
779		if x == nil {
780			return nil, errors.New("x509: failed to unmarshal elliptic curve point")
781		}
782		pub := &ecdsa.PublicKey{
783			Curve: namedCurve,
784			X:     x,
785			Y:     y,
786		}
787		return pub, nil
788	default:
789		return nil, nil
790	}
791}
792
793func parseCertificate(in *certificate) (*Certificate, error) {
794	out := new(Certificate)
795	out.Raw = in.Raw
796	out.RawTBSCertificate = in.TBSCertificate.Raw
797	out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
798	out.RawSubject = in.TBSCertificate.Subject.FullBytes
799	out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
800
801	out.Signature = in.SignatureValue.RightAlign()
802	out.SignatureAlgorithm =
803		getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
804
805	out.PublicKeyAlgorithm =
806		getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
807	var err error
808	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
809	if err != nil {
810		return nil, err
811	}
812
813	if in.TBSCertificate.SerialNumber.Sign() < 0 {
814		return nil, errors.New("x509: negative serial number")
815	}
816
817	out.Version = in.TBSCertificate.Version + 1
818	out.SerialNumber = in.TBSCertificate.SerialNumber
819
820	var issuer, subject pkix.RDNSequence
821	if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
822		return nil, err
823	}
824	if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
825		return nil, err
826	}
827
828	out.Issuer.FillFromRDNSequence(&issuer)
829	out.Subject.FillFromRDNSequence(&subject)
830
831	out.NotBefore = in.TBSCertificate.Validity.NotBefore
832	out.NotAfter = in.TBSCertificate.Validity.NotAfter
833
834	for _, e := range in.TBSCertificate.Extensions {
835		out.Extensions = append(out.Extensions, e)
836
837		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
838			switch e.Id[3] {
839			case 15:
840				// RFC 5280, 4.2.1.3
841				var usageBits asn1.BitString
842				_, err := asn1.Unmarshal(e.Value, &usageBits)
843
844				if err == nil {
845					var usage int
846					for i := 0; i < 9; i++ {
847						if usageBits.At(i) != 0 {
848							usage |= 1 << uint(i)
849						}
850					}
851					out.KeyUsage = KeyUsage(usage)
852					continue
853				}
854			case 19:
855				// RFC 5280, 4.2.1.9
856				var constraints basicConstraints
857				_, err := asn1.Unmarshal(e.Value, &constraints)
858
859				if err == nil {
860					out.BasicConstraintsValid = true
861					out.IsCA = constraints.IsCA
862					out.MaxPathLen = constraints.MaxPathLen
863					continue
864				}
865			case 17:
866				// RFC 5280, 4.2.1.6
867
868				// SubjectAltName ::= GeneralNames
869				//
870				// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
871				//
872				// GeneralName ::= CHOICE {
873				//      otherName                       [0]     OtherName,
874				//      rfc822Name                      [1]     IA5String,
875				//      dNSName                         [2]     IA5String,
876				//      x400Address                     [3]     ORAddress,
877				//      directoryName                   [4]     Name,
878				//      ediPartyName                    [5]     EDIPartyName,
879				//      uniformResourceIdentifier       [6]     IA5String,
880				//      iPAddress                       [7]     OCTET STRING,
881				//      registeredID                    [8]     OBJECT IDENTIFIER }
882				var seq asn1.RawValue
883				_, err := asn1.Unmarshal(e.Value, &seq)
884				if err != nil {
885					return nil, err
886				}
887				if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
888					return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
889				}
890
891				parsedName := false
892
893				rest := seq.Bytes
894				for len(rest) > 0 {
895					var v asn1.RawValue
896					rest, err = asn1.Unmarshal(rest, &v)
897					if err != nil {
898						return nil, err
899					}
900					switch v.Tag {
901					case 1:
902						out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
903						parsedName = true
904					case 2:
905						out.DNSNames = append(out.DNSNames, string(v.Bytes))
906						parsedName = true
907					case 7:
908						switch len(v.Bytes) {
909						case net.IPv4len, net.IPv6len:
910							out.IPAddresses = append(out.IPAddresses, v.Bytes)
911						default:
912							return nil, errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
913						}
914					}
915				}
916
917				if parsedName {
918					continue
919				}
920				// If we didn't parse any of the names then we
921				// fall through to the critical check below.
922
923			case 30:
924				// RFC 5280, 4.2.1.10
925
926				// NameConstraints ::= SEQUENCE {
927				//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
928				//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
929				//
930				// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
931				//
932				// GeneralSubtree ::= SEQUENCE {
933				//      base                    GeneralName,
934				//      minimum         [0]     BaseDistance DEFAULT 0,
935				//      maximum         [1]     BaseDistance OPTIONAL }
936				//
937				// BaseDistance ::= INTEGER (0..MAX)
938
939				var constraints nameConstraints
940				_, err := asn1.Unmarshal(e.Value, &constraints)
941				if err != nil {
942					return nil, err
943				}
944
945				if len(constraints.Excluded) > 0 && e.Critical {
946					return out, UnhandledCriticalExtension{}
947				}
948
949				for _, subtree := range constraints.Permitted {
950					if len(subtree.Name) == 0 {
951						if e.Critical {
952							return out, UnhandledCriticalExtension{}
953						}
954						continue
955					}
956					out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
957				}
958				continue
959
960			case 31:
961				// RFC 5280, 4.2.1.14
962
963				// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
964				//
965				// DistributionPoint ::= SEQUENCE {
966				//     distributionPoint       [0]     DistributionPointName OPTIONAL,
967				//     reasons                 [1]     ReasonFlags OPTIONAL,
968				//     cRLIssuer               [2]     GeneralNames OPTIONAL }
969				//
970				// DistributionPointName ::= CHOICE {
971				//     fullName                [0]     GeneralNames,
972				//     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
973
974				var cdp []distributionPoint
975				_, err := asn1.Unmarshal(e.Value, &cdp)
976				if err != nil {
977					return nil, err
978				}
979
980				for _, dp := range cdp {
981					var n asn1.RawValue
982					_, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n)
983					if err != nil {
984						return nil, err
985					}
986
987					if n.Tag == 6 {
988						out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
989					}
990				}
991				continue
992
993			case 35:
994				// RFC 5280, 4.2.1.1
995				var a authKeyId
996				_, err = asn1.Unmarshal(e.Value, &a)
997				if err != nil {
998					return nil, err
999				}
1000				out.AuthorityKeyId = a.Id
1001				continue
1002
1003			case 37:
1004				// RFC 5280, 4.2.1.12.  Extended Key Usage
1005
1006				// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1007				//
1008				// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1009				//
1010				// KeyPurposeId ::= OBJECT IDENTIFIER
1011
1012				var keyUsage []asn1.ObjectIdentifier
1013				_, err = asn1.Unmarshal(e.Value, &keyUsage)
1014				if err != nil {
1015					return nil, err
1016				}
1017
1018				for _, u := range keyUsage {
1019					if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1020						out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1021					} else {
1022						out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1023					}
1024				}
1025
1026				continue
1027
1028			case 14:
1029				// RFC 5280, 4.2.1.2
1030				var keyid []byte
1031				_, err = asn1.Unmarshal(e.Value, &keyid)
1032				if err != nil {
1033					return nil, err
1034				}
1035				out.SubjectKeyId = keyid
1036				continue
1037
1038			case 32:
1039				// RFC 5280 4.2.1.4: Certificate Policies
1040				var policies []policyInformation
1041				if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
1042					return nil, err
1043				}
1044				out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1045				for i, policy := range policies {
1046					out.PolicyIdentifiers[i] = policy.Policy
1047				}
1048			}
1049		} else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1050			// RFC 5280 4.2.2.1: Authority Information Access
1051			var aia []authorityInfoAccess
1052			if _, err = asn1.Unmarshal(e.Value, &aia); err != nil {
1053				return nil, err
1054			}
1055
1056			for _, v := range aia {
1057				// GeneralName: uniformResourceIdentifier [6] IA5String
1058				if v.Location.Tag != 6 {
1059					continue
1060				}
1061				if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1062					out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1063				} else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1064					out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1065				}
1066			}
1067		}
1068
1069		if e.Critical {
1070			return out, UnhandledCriticalExtension{}
1071		}
1072	}
1073
1074	return out, nil
1075}
1076
1077// ParseCertificate parses a single certificate from the given ASN.1 DER data.
1078func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1079	var cert certificate
1080	rest, err := asn1.Unmarshal(asn1Data, &cert)
1081	if err != nil {
1082		return nil, err
1083	}
1084	if len(rest) > 0 {
1085		return nil, asn1.SyntaxError{Msg: "trailing data"}
1086	}
1087
1088	return parseCertificate(&cert)
1089}
1090
1091// ParseCertificates parses one or more certificates from the given ASN.1 DER
1092// data. The certificates must be concatenated with no intermediate padding.
1093func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1094	var v []*certificate
1095
1096	for len(asn1Data) > 0 {
1097		cert := new(certificate)
1098		var err error
1099		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1100		if err != nil {
1101			return nil, err
1102		}
1103		v = append(v, cert)
1104	}
1105
1106	ret := make([]*Certificate, len(v))
1107	for i, ci := range v {
1108		cert, err := parseCertificate(ci)
1109		if err != nil {
1110			return nil, err
1111		}
1112		ret[i] = cert
1113	}
1114
1115	return ret, nil
1116}
1117
1118func reverseBitsInAByte(in byte) byte {
1119	b1 := in>>4 | in<<4
1120	b2 := b1>>2&0x33 | b1<<2&0xcc
1121	b3 := b2>>1&0x55 | b2<<1&0xaa
1122	return b3
1123}
1124
1125var (
1126	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
1127	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
1128	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
1129	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
1130	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
1131	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
1132	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
1133	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
1134	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1135	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1136)
1137
1138var (
1139	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1140	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1141)
1142
1143// oidNotInExtensions returns whether an extension with the given oid exists in
1144// extensions.
1145func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1146	for _, e := range extensions {
1147		if e.Id.Equal(oid) {
1148			return true
1149		}
1150	}
1151	return false
1152}
1153
1154func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
1155	ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1156	n := 0
1157
1158	if template.KeyUsage != 0 &&
1159		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1160		ret[n].Id = oidExtensionKeyUsage
1161		ret[n].Critical = true
1162
1163		var a [2]byte
1164		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1165		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1166
1167		l := 1
1168		if a[1] != 0 {
1169			l = 2
1170		}
1171
1172		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
1173		if err != nil {
1174			return
1175		}
1176		n++
1177	}
1178
1179	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1180		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1181		ret[n].Id = oidExtensionExtendedKeyUsage
1182
1183		var oids []asn1.ObjectIdentifier
1184		for _, u := range template.ExtKeyUsage {
1185			if oid, ok := oidFromExtKeyUsage(u); ok {
1186				oids = append(oids, oid)
1187			} else {
1188				panic("internal error")
1189			}
1190		}
1191
1192		oids = append(oids, template.UnknownExtKeyUsage...)
1193
1194		ret[n].Value, err = asn1.Marshal(oids)
1195		if err != nil {
1196			return
1197		}
1198		n++
1199	}
1200
1201	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1202		ret[n].Id = oidExtensionBasicConstraints
1203		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
1204		ret[n].Critical = true
1205		if err != nil {
1206			return
1207		}
1208		n++
1209	}
1210
1211	if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1212		ret[n].Id = oidExtensionSubjectKeyId
1213		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1214		if err != nil {
1215			return
1216		}
1217		n++
1218	}
1219
1220	if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1221		ret[n].Id = oidExtensionAuthorityKeyId
1222		ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
1223		if err != nil {
1224			return
1225		}
1226		n++
1227	}
1228
1229	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1230		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1231		ret[n].Id = oidExtensionAuthorityInfoAccess
1232		var aiaValues []authorityInfoAccess
1233		for _, name := range template.OCSPServer {
1234			aiaValues = append(aiaValues, authorityInfoAccess{
1235				Method:   oidAuthorityInfoAccessOcsp,
1236				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1237			})
1238		}
1239		for _, name := range template.IssuingCertificateURL {
1240			aiaValues = append(aiaValues, authorityInfoAccess{
1241				Method:   oidAuthorityInfoAccessIssuers,
1242				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1243			})
1244		}
1245		ret[n].Value, err = asn1.Marshal(aiaValues)
1246		if err != nil {
1247			return
1248		}
1249		n++
1250	}
1251
1252	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
1253		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1254		ret[n].Id = oidExtensionSubjectAltName
1255		var rawValues []asn1.RawValue
1256		for _, name := range template.DNSNames {
1257			rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
1258		}
1259		for _, email := range template.EmailAddresses {
1260			rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
1261		}
1262		for _, rawIP := range template.IPAddresses {
1263			// If possible, we always want to encode IPv4 addresses in 4 bytes.
1264			ip := rawIP.To4()
1265			if ip == nil {
1266				ip = rawIP
1267			}
1268			rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
1269		}
1270		ret[n].Value, err = asn1.Marshal(rawValues)
1271		if err != nil {
1272			return
1273		}
1274		n++
1275	}
1276
1277	if len(template.PolicyIdentifiers) > 0 &&
1278		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1279		ret[n].Id = oidExtensionCertificatePolicies
1280		policies := make([]policyInformation, len(template.PolicyIdentifiers))
1281		for i, policy := range template.PolicyIdentifiers {
1282			policies[i].Policy = policy
1283		}
1284		ret[n].Value, err = asn1.Marshal(policies)
1285		if err != nil {
1286			return
1287		}
1288		n++
1289	}
1290
1291	if len(template.PermittedDNSDomains) > 0 &&
1292		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1293		ret[n].Id = oidExtensionNameConstraints
1294		ret[n].Critical = template.PermittedDNSDomainsCritical
1295
1296		var out nameConstraints
1297		out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
1298		for i, permitted := range template.PermittedDNSDomains {
1299			out.Permitted[i] = generalSubtree{Name: permitted}
1300		}
1301		ret[n].Value, err = asn1.Marshal(out)
1302		if err != nil {
1303			return
1304		}
1305		n++
1306	}
1307
1308	if len(template.CRLDistributionPoints) > 0 &&
1309		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1310		ret[n].Id = oidExtensionCRLDistributionPoints
1311
1312		var crlDp []distributionPoint
1313		for _, name := range template.CRLDistributionPoints {
1314			rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
1315
1316			dp := distributionPoint{
1317				DistributionPoint: distributionPointName{
1318					FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName},
1319				},
1320			}
1321			crlDp = append(crlDp, dp)
1322		}
1323
1324		ret[n].Value, err = asn1.Marshal(crlDp)
1325		if err != nil {
1326			return
1327		}
1328		n++
1329	}
1330
1331	// Adding another extension here? Remember to update the maximum number
1332	// of elements in the make() at the top of the function.
1333
1334	return append(ret[:n], template.ExtraExtensions...), nil
1335}
1336
1337func subjectBytes(cert *Certificate) ([]byte, error) {
1338	if len(cert.RawSubject) > 0 {
1339		return cert.RawSubject, nil
1340	}
1341
1342	return asn1.Marshal(cert.Subject.ToRDNSequence())
1343}
1344
1345// CreateCertificate creates a new certificate based on a template. The
1346// following members of template are used: SerialNumber, Subject, NotBefore,
1347// NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
1348// IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
1349// PermittedDNSDomains.
1350//
1351// The certificate is signed by parent. If parent is equal to template then the
1352// certificate is self-signed. The parameter pub is the public key of the
1353// signee and priv is the private key of the signer.
1354//
1355// The returned slice is the certificate in DER encoding.
1356//
1357// The only supported key types are RSA and ECDSA (*rsa.PublicKey or
1358// *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv).
1359func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
1360	var publicKeyBytes []byte
1361	var publicKeyAlgorithm pkix.AlgorithmIdentifier
1362
1363	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
1364		return nil, err
1365	}
1366
1367	var signatureAlgorithm pkix.AlgorithmIdentifier
1368	var hashFunc crypto.Hash
1369
1370	switch priv := priv.(type) {
1371	case *rsa.PrivateKey:
1372		signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA
1373		hashFunc = crypto.SHA1
1374	case *ecdsa.PrivateKey:
1375		switch priv.Curve {
1376		case elliptic.P224(), elliptic.P256():
1377			hashFunc = crypto.SHA256
1378			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256
1379		case elliptic.P384():
1380			hashFunc = crypto.SHA384
1381			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384
1382		case elliptic.P521():
1383			hashFunc = crypto.SHA512
1384			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512
1385		default:
1386			return nil, errors.New("x509: unknown elliptic curve")
1387		}
1388	default:
1389		return nil, errors.New("x509: only RSA and ECDSA private keys supported")
1390	}
1391
1392	if err != nil {
1393		return
1394	}
1395
1396	if len(parent.SubjectKeyId) > 0 {
1397		template.AuthorityKeyId = parent.SubjectKeyId
1398	}
1399
1400	extensions, err := buildExtensions(template)
1401	if err != nil {
1402		return
1403	}
1404
1405	asn1Issuer, err := subjectBytes(parent)
1406	if err != nil {
1407		return
1408	}
1409
1410	asn1Subject, err := subjectBytes(template)
1411	if err != nil {
1412		return
1413	}
1414
1415	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1416	c := tbsCertificate{
1417		Version:            2,
1418		SerialNumber:       template.SerialNumber,
1419		SignatureAlgorithm: signatureAlgorithm,
1420		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
1421		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1422		Subject:            asn1.RawValue{FullBytes: asn1Subject},
1423		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1424		Extensions:         extensions,
1425	}
1426
1427	tbsCertContents, err := asn1.Marshal(c)
1428	if err != nil {
1429		return
1430	}
1431
1432	c.Raw = tbsCertContents
1433
1434	h := hashFunc.New()
1435	h.Write(tbsCertContents)
1436	digest := h.Sum(nil)
1437
1438	var signature []byte
1439
1440	switch priv := priv.(type) {
1441	case *rsa.PrivateKey:
1442		signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest)
1443	case *ecdsa.PrivateKey:
1444		var r, s *big.Int
1445		if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil {
1446			signature, err = asn1.Marshal(ecdsaSignature{r, s})
1447		}
1448	default:
1449		panic("internal error")
1450	}
1451
1452	if err != nil {
1453		return
1454	}
1455
1456	cert, err = asn1.Marshal(certificate{
1457		nil,
1458		c,
1459		signatureAlgorithm,
1460		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1461	})
1462	return
1463}
1464
1465// pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1466// CRL.
1467var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1468
1469// pemType is the type of a PEM encoded CRL.
1470var pemType = "X509 CRL"
1471
1472// ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1473// encoded CRLs will appear where they should be DER encoded, so this function
1474// will transparently handle PEM encoding as long as there isn't any leading
1475// garbage.
1476func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
1477	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1478		block, _ := pem.Decode(crlBytes)
1479		if block != nil && block.Type == pemType {
1480			crlBytes = block.Bytes
1481		}
1482	}
1483	return ParseDERCRL(crlBytes)
1484}
1485
1486// ParseDERCRL parses a DER encoded CRL from the given bytes.
1487func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
1488	certList = new(pkix.CertificateList)
1489	_, err = asn1.Unmarshal(derBytes, certList)
1490	if err != nil {
1491		certList = nil
1492	}
1493	return
1494}
1495
1496// CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1497// contains the given list of revoked certificates.
1498//
1499// The only supported key type is RSA (*rsa.PrivateKey for priv).
1500func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1501	rsaPriv, ok := priv.(*rsa.PrivateKey)
1502	if !ok {
1503		return nil, errors.New("x509: non-RSA private keys not supported")
1504	}
1505	tbsCertList := pkix.TBSCertificateList{
1506		Version: 2,
1507		Signature: pkix.AlgorithmIdentifier{
1508			Algorithm: oidSignatureSHA1WithRSA,
1509		},
1510		Issuer:              c.Subject.ToRDNSequence(),
1511		ThisUpdate:          now.UTC(),
1512		NextUpdate:          expiry.UTC(),
1513		RevokedCertificates: revokedCerts,
1514	}
1515
1516	tbsCertListContents, err := asn1.Marshal(tbsCertList)
1517	if err != nil {
1518		return
1519	}
1520
1521	h := sha1.New()
1522	h.Write(tbsCertListContents)
1523	digest := h.Sum(nil)
1524
1525	signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1526	if err != nil {
1527		return
1528	}
1529
1530	return asn1.Marshal(pkix.CertificateList{
1531		TBSCertList: tbsCertList,
1532		SignatureAlgorithm: pkix.AlgorithmIdentifier{
1533			Algorithm: oidSignatureSHA1WithRSA,
1534		},
1535		SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1536	})
1537}
1538