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