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