]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/x509/x509.go
[dev.link] all: merge branch 'master' into dev.link
[gostls13.git] / src / crypto / x509 / x509.go
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 package x509
7
8 import (
9         "bytes"
10         "crypto"
11         "crypto/dsa"
12         "crypto/ecdsa"
13         "crypto/ed25519"
14         "crypto/elliptic"
15         "crypto/rsa"
16         "crypto/sha1"
17         _ "crypto/sha1"
18         _ "crypto/sha256"
19         _ "crypto/sha512"
20         "crypto/x509/pkix"
21         "encoding/asn1"
22         "encoding/pem"
23         "errors"
24         "fmt"
25         "io"
26         "math/big"
27         "net"
28         "net/url"
29         "strconv"
30         "strings"
31         "time"
32         "unicode/utf8"
33
34         "golang.org/x/crypto/cryptobyte"
35         cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
36 )
37
38 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
39 // in RFC 3280.
40 type pkixPublicKey struct {
41         Algo      pkix.AlgorithmIdentifier
42         BitString asn1.BitString
43 }
44
45 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
46 // The encoded public key is a SubjectPublicKeyInfo structure
47 // (see RFC 5280, Section 4.1).
48 //
49 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
50 // ed25519.PublicKey. More types might be supported in the future.
51 //
52 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
53 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
54         var pki publicKeyInfo
55         if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
56                 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
57                         return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
58                 }
59                 return nil, err
60         } else if len(rest) != 0 {
61                 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
62         }
63         algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
64         if algo == UnknownPublicKeyAlgorithm {
65                 return nil, errors.New("x509: unknown public key algorithm")
66         }
67         return parsePublicKey(algo, &pki)
68 }
69
70 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
71         switch pub := pub.(type) {
72         case *rsa.PublicKey:
73                 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
74                         N: pub.N,
75                         E: pub.E,
76                 })
77                 if err != nil {
78                         return nil, pkix.AlgorithmIdentifier{}, err
79                 }
80                 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
81                 // This is a NULL parameters value which is required by
82                 // RFC 3279, Section 2.3.1.
83                 publicKeyAlgorithm.Parameters = asn1.NullRawValue
84         case *ecdsa.PublicKey:
85                 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
86                 oid, ok := oidFromNamedCurve(pub.Curve)
87                 if !ok {
88                         return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
89                 }
90                 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
91                 var paramBytes []byte
92                 paramBytes, err = asn1.Marshal(oid)
93                 if err != nil {
94                         return
95                 }
96                 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
97         case ed25519.PublicKey:
98                 publicKeyBytes = pub
99                 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
100         default:
101                 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
102         }
103
104         return publicKeyBytes, publicKeyAlgorithm, nil
105 }
106
107 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
108 // The encoded public key is a SubjectPublicKeyInfo structure
109 // (see RFC 5280, Section 4.1).
110 //
111 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
112 // and ed25519.PublicKey. Unsupported key types result in an error.
113 //
114 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
115 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
116         var publicKeyBytes []byte
117         var publicKeyAlgorithm pkix.AlgorithmIdentifier
118         var err error
119
120         if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
121                 return nil, err
122         }
123
124         pkix := pkixPublicKey{
125                 Algo: publicKeyAlgorithm,
126                 BitString: asn1.BitString{
127                         Bytes:     publicKeyBytes,
128                         BitLength: 8 * len(publicKeyBytes),
129                 },
130         }
131
132         ret, _ := asn1.Marshal(pkix)
133         return ret, nil
134 }
135
136 // These structures reflect the ASN.1 structure of X.509 certificates.:
137
138 type certificate struct {
139         Raw                asn1.RawContent
140         TBSCertificate     tbsCertificate
141         SignatureAlgorithm pkix.AlgorithmIdentifier
142         SignatureValue     asn1.BitString
143 }
144
145 type tbsCertificate struct {
146         Raw                asn1.RawContent
147         Version            int `asn1:"optional,explicit,default:0,tag:0"`
148         SerialNumber       *big.Int
149         SignatureAlgorithm pkix.AlgorithmIdentifier
150         Issuer             asn1.RawValue
151         Validity           validity
152         Subject            asn1.RawValue
153         PublicKey          publicKeyInfo
154         UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
155         SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
156         Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
157 }
158
159 type dsaAlgorithmParameters struct {
160         P, Q, G *big.Int
161 }
162
163 type dsaSignature struct {
164         R, S *big.Int
165 }
166
167 type validity struct {
168         NotBefore, NotAfter time.Time
169 }
170
171 type publicKeyInfo struct {
172         Raw       asn1.RawContent
173         Algorithm pkix.AlgorithmIdentifier
174         PublicKey asn1.BitString
175 }
176
177 // RFC 5280,  4.2.1.1
178 type authKeyId struct {
179         Id []byte `asn1:"optional,tag:0"`
180 }
181
182 type SignatureAlgorithm int
183
184 const (
185         UnknownSignatureAlgorithm SignatureAlgorithm = iota
186         MD2WithRSA
187         MD5WithRSA
188         SHA1WithRSA
189         SHA256WithRSA
190         SHA384WithRSA
191         SHA512WithRSA
192         DSAWithSHA1
193         DSAWithSHA256
194         ECDSAWithSHA1
195         ECDSAWithSHA256
196         ECDSAWithSHA384
197         ECDSAWithSHA512
198         SHA256WithRSAPSS
199         SHA384WithRSAPSS
200         SHA512WithRSAPSS
201         PureEd25519
202 )
203
204 func (algo SignatureAlgorithm) isRSAPSS() bool {
205         switch algo {
206         case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
207                 return true
208         default:
209                 return false
210         }
211 }
212
213 func (algo SignatureAlgorithm) String() string {
214         for _, details := range signatureAlgorithmDetails {
215                 if details.algo == algo {
216                         return details.name
217                 }
218         }
219         return strconv.Itoa(int(algo))
220 }
221
222 type PublicKeyAlgorithm int
223
224 const (
225         UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
226         RSA
227         DSA
228         ECDSA
229         Ed25519
230 )
231
232 var publicKeyAlgoName = [...]string{
233         RSA:     "RSA",
234         DSA:     "DSA",
235         ECDSA:   "ECDSA",
236         Ed25519: "Ed25519",
237 }
238
239 func (algo PublicKeyAlgorithm) String() string {
240         if 0 < algo && int(algo) < len(publicKeyAlgoName) {
241                 return publicKeyAlgoName[algo]
242         }
243         return strconv.Itoa(int(algo))
244 }
245
246 // OIDs for signature algorithms
247 //
248 // pkcs-1 OBJECT IDENTIFIER ::= {
249 //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
250 //
251 //
252 // RFC 3279 2.2.1 RSA Signature Algorithms
253 //
254 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
255 //
256 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
257 //
258 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
259 //
260 // dsaWithSha1 OBJECT IDENTIFIER ::= {
261 //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
262 //
263 // RFC 3279 2.2.3 ECDSA Signature Algorithm
264 //
265 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
266 //        iso(1) member-body(2) us(840) ansi-x962(10045)
267 //    signatures(4) ecdsa-with-SHA1(1)}
268 //
269 //
270 // RFC 4055 5 PKCS #1 Version 1.5
271 //
272 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
273 //
274 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
275 //
276 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
277 //
278 //
279 // RFC 5758 3.1 DSA Signature Algorithms
280 //
281 // dsaWithSha256 OBJECT IDENTIFIER ::= {
282 //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
283 //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
284 //
285 // RFC 5758 3.2 ECDSA Signature Algorithm
286 //
287 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
288 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
289 //
290 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
291 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
292 //
293 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
294 //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
295 //
296 //
297 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
298 //
299 // id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
300
301 var (
302         oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
303         oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
304         oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
305         oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
306         oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
307         oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
308         oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
309         oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
310         oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
311         oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
312         oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
313         oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
314         oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
315         oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
316
317         oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
318         oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
319         oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
320
321         oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
322
323         // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
324         // but it's specified by ISO. Microsoft's makecert.exe has been known
325         // to produce certificates with this OID.
326         oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
327 )
328
329 var signatureAlgorithmDetails = []struct {
330         algo       SignatureAlgorithm
331         name       string
332         oid        asn1.ObjectIdentifier
333         pubKeyAlgo PublicKeyAlgorithm
334         hash       crypto.Hash
335 }{
336         {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
337         {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
338         {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
339         {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
340         {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
341         {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
342         {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
343         {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
344         {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
345         {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
346         {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
347         {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
348         {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
349         {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
350         {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
351         {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
352         {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
353 }
354
355 // pssParameters reflects the parameters in an AlgorithmIdentifier that
356 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
357 type pssParameters struct {
358         // The following three fields are not marked as
359         // optional because the default values specify SHA-1,
360         // which is no longer suitable for use in signatures.
361         Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
362         MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
363         SaltLength   int                      `asn1:"explicit,tag:2"`
364         TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
365 }
366
367 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
368 // in an AlgorithmIdentifier that specifies RSA PSS.
369 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
370         var hashOID asn1.ObjectIdentifier
371
372         switch hashFunc {
373         case crypto.SHA256:
374                 hashOID = oidSHA256
375         case crypto.SHA384:
376                 hashOID = oidSHA384
377         case crypto.SHA512:
378                 hashOID = oidSHA512
379         }
380
381         params := pssParameters{
382                 Hash: pkix.AlgorithmIdentifier{
383                         Algorithm:  hashOID,
384                         Parameters: asn1.NullRawValue,
385                 },
386                 MGF: pkix.AlgorithmIdentifier{
387                         Algorithm: oidMGF1,
388                 },
389                 SaltLength:   hashFunc.Size(),
390                 TrailerField: 1,
391         }
392
393         mgf1Params := pkix.AlgorithmIdentifier{
394                 Algorithm:  hashOID,
395                 Parameters: asn1.NullRawValue,
396         }
397
398         var err error
399         params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
400         if err != nil {
401                 panic(err)
402         }
403
404         serialized, err := asn1.Marshal(params)
405         if err != nil {
406                 panic(err)
407         }
408
409         return asn1.RawValue{FullBytes: serialized}
410 }
411
412 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
413         if ai.Algorithm.Equal(oidSignatureEd25519) {
414                 // RFC 8410, Section 3
415                 // > For all of the OIDs, the parameters MUST be absent.
416                 if len(ai.Parameters.FullBytes) != 0 {
417                         return UnknownSignatureAlgorithm
418                 }
419         }
420
421         if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
422                 for _, details := range signatureAlgorithmDetails {
423                         if ai.Algorithm.Equal(details.oid) {
424                                 return details.algo
425                         }
426                 }
427                 return UnknownSignatureAlgorithm
428         }
429
430         // RSA PSS is special because it encodes important parameters
431         // in the Parameters.
432
433         var params pssParameters
434         if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
435                 return UnknownSignatureAlgorithm
436         }
437
438         var mgf1HashFunc pkix.AlgorithmIdentifier
439         if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
440                 return UnknownSignatureAlgorithm
441         }
442
443         // PSS is greatly overburdened with options. This code forces them into
444         // three buckets by requiring that the MGF1 hash function always match the
445         // message hash function (as recommended in RFC 3447, Section 8.1), that the
446         // salt length matches the hash length, and that the trailer field has the
447         // default value.
448         if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
449                 !params.MGF.Algorithm.Equal(oidMGF1) ||
450                 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
451                 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
452                 params.TrailerField != 1 {
453                 return UnknownSignatureAlgorithm
454         }
455
456         switch {
457         case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
458                 return SHA256WithRSAPSS
459         case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
460                 return SHA384WithRSAPSS
461         case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
462                 return SHA512WithRSAPSS
463         }
464
465         return UnknownSignatureAlgorithm
466 }
467
468 // RFC 3279, 2.3 Public Key Algorithms
469 //
470 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
471 //    rsadsi(113549) pkcs(1) 1 }
472 //
473 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
474 //
475 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
476 //    x9-57(10040) x9cm(4) 1 }
477 //
478 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
479 //
480 // id-ecPublicKey OBJECT IDENTIFIER ::= {
481 //       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
482 var (
483         oidPublicKeyRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
484         oidPublicKeyDSA     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
485         oidPublicKeyECDSA   = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
486         oidPublicKeyEd25519 = oidSignatureEd25519
487 )
488
489 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
490         switch {
491         case oid.Equal(oidPublicKeyRSA):
492                 return RSA
493         case oid.Equal(oidPublicKeyDSA):
494                 return DSA
495         case oid.Equal(oidPublicKeyECDSA):
496                 return ECDSA
497         case oid.Equal(oidPublicKeyEd25519):
498                 return Ed25519
499         }
500         return UnknownPublicKeyAlgorithm
501 }
502
503 // RFC 5480, 2.1.1.1. Named Curve
504 //
505 // secp224r1 OBJECT IDENTIFIER ::= {
506 //   iso(1) identified-organization(3) certicom(132) curve(0) 33 }
507 //
508 // secp256r1 OBJECT IDENTIFIER ::= {
509 //   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
510 //   prime(1) 7 }
511 //
512 // secp384r1 OBJECT IDENTIFIER ::= {
513 //   iso(1) identified-organization(3) certicom(132) curve(0) 34 }
514 //
515 // secp521r1 OBJECT IDENTIFIER ::= {
516 //   iso(1) identified-organization(3) certicom(132) curve(0) 35 }
517 //
518 // NB: secp256r1 is equivalent to prime256v1
519 var (
520         oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
521         oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
522         oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
523         oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
524 )
525
526 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
527         switch {
528         case oid.Equal(oidNamedCurveP224):
529                 return elliptic.P224()
530         case oid.Equal(oidNamedCurveP256):
531                 return elliptic.P256()
532         case oid.Equal(oidNamedCurveP384):
533                 return elliptic.P384()
534         case oid.Equal(oidNamedCurveP521):
535                 return elliptic.P521()
536         }
537         return nil
538 }
539
540 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
541         switch curve {
542         case elliptic.P224():
543                 return oidNamedCurveP224, true
544         case elliptic.P256():
545                 return oidNamedCurveP256, true
546         case elliptic.P384():
547                 return oidNamedCurveP384, true
548         case elliptic.P521():
549                 return oidNamedCurveP521, true
550         }
551
552         return nil, false
553 }
554
555 // KeyUsage represents the set of actions that are valid for a given key. It's
556 // a bitmap of the KeyUsage* constants.
557 type KeyUsage int
558
559 const (
560         KeyUsageDigitalSignature KeyUsage = 1 << iota
561         KeyUsageContentCommitment
562         KeyUsageKeyEncipherment
563         KeyUsageDataEncipherment
564         KeyUsageKeyAgreement
565         KeyUsageCertSign
566         KeyUsageCRLSign
567         KeyUsageEncipherOnly
568         KeyUsageDecipherOnly
569 )
570
571 // RFC 5280, 4.2.1.12  Extended Key Usage
572 //
573 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
574 //
575 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
576 //
577 // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
578 // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
579 // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
580 // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
581 // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
582 // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
583 var (
584         oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
585         oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
586         oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
587         oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
588         oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
589         oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
590         oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
591         oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
592         oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
593         oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
594         oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
595         oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
596         oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
597         oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
598 )
599
600 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
601 // Each of the ExtKeyUsage* constants define a unique action.
602 type ExtKeyUsage int
603
604 const (
605         ExtKeyUsageAny ExtKeyUsage = iota
606         ExtKeyUsageServerAuth
607         ExtKeyUsageClientAuth
608         ExtKeyUsageCodeSigning
609         ExtKeyUsageEmailProtection
610         ExtKeyUsageIPSECEndSystem
611         ExtKeyUsageIPSECTunnel
612         ExtKeyUsageIPSECUser
613         ExtKeyUsageTimeStamping
614         ExtKeyUsageOCSPSigning
615         ExtKeyUsageMicrosoftServerGatedCrypto
616         ExtKeyUsageNetscapeServerGatedCrypto
617         ExtKeyUsageMicrosoftCommercialCodeSigning
618         ExtKeyUsageMicrosoftKernelCodeSigning
619 )
620
621 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
622 var extKeyUsageOIDs = []struct {
623         extKeyUsage ExtKeyUsage
624         oid         asn1.ObjectIdentifier
625 }{
626         {ExtKeyUsageAny, oidExtKeyUsageAny},
627         {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
628         {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
629         {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
630         {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
631         {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
632         {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
633         {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
634         {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
635         {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
636         {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
637         {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
638         {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
639         {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
640 }
641
642 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
643         for _, pair := range extKeyUsageOIDs {
644                 if oid.Equal(pair.oid) {
645                         return pair.extKeyUsage, true
646                 }
647         }
648         return
649 }
650
651 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
652         for _, pair := range extKeyUsageOIDs {
653                 if eku == pair.extKeyUsage {
654                         return pair.oid, true
655                 }
656         }
657         return
658 }
659
660 // A Certificate represents an X.509 certificate.
661 type Certificate struct {
662         Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
663         RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
664         RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
665         RawSubject              []byte // DER encoded Subject
666         RawIssuer               []byte // DER encoded Issuer
667
668         Signature          []byte
669         SignatureAlgorithm SignatureAlgorithm
670
671         PublicKeyAlgorithm PublicKeyAlgorithm
672         PublicKey          interface{}
673
674         Version             int
675         SerialNumber        *big.Int
676         Issuer              pkix.Name
677         Subject             pkix.Name
678         NotBefore, NotAfter time.Time // Validity bounds.
679         KeyUsage            KeyUsage
680
681         // Extensions contains raw X.509 extensions. When parsing certificates,
682         // this can be used to extract non-critical extensions that are not
683         // parsed by this package. When marshaling certificates, the Extensions
684         // field is ignored, see ExtraExtensions.
685         Extensions []pkix.Extension
686
687         // ExtraExtensions contains extensions to be copied, raw, into any
688         // marshaled certificates. Values override any extensions that would
689         // otherwise be produced based on the other fields. The ExtraExtensions
690         // field is not populated when parsing certificates, see Extensions.
691         ExtraExtensions []pkix.Extension
692
693         // UnhandledCriticalExtensions contains a list of extension IDs that
694         // were not (fully) processed when parsing. Verify will fail if this
695         // slice is non-empty, unless verification is delegated to an OS
696         // library which understands all the critical extensions.
697         //
698         // Users can access these extensions using Extensions and can remove
699         // elements from this slice if they believe that they have been
700         // handled.
701         UnhandledCriticalExtensions []asn1.ObjectIdentifier
702
703         ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
704         UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
705
706         // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
707         // and MaxPathLenZero are valid.
708         BasicConstraintsValid bool
709         IsCA                  bool
710
711         // MaxPathLen and MaxPathLenZero indicate the presence and
712         // value of the BasicConstraints' "pathLenConstraint".
713         //
714         // When parsing a certificate, a positive non-zero MaxPathLen
715         // means that the field was specified, -1 means it was unset,
716         // and MaxPathLenZero being true mean that the field was
717         // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
718         // should be treated equivalent to -1 (unset).
719         //
720         // When generating a certificate, an unset pathLenConstraint
721         // can be requested with either MaxPathLen == -1 or using the
722         // zero value for both MaxPathLen and MaxPathLenZero.
723         MaxPathLen int
724         // MaxPathLenZero indicates that BasicConstraintsValid==true
725         // and MaxPathLen==0 should be interpreted as an actual
726         // maximum path length of zero. Otherwise, that combination is
727         // interpreted as MaxPathLen not being set.
728         MaxPathLenZero bool
729
730         SubjectKeyId   []byte
731         AuthorityKeyId []byte
732
733         // RFC 5280, 4.2.2.1 (Authority Information Access)
734         OCSPServer            []string
735         IssuingCertificateURL []string
736
737         // Subject Alternate Name values. (Note that these values may not be valid
738         // if invalid values were contained within a parsed certificate. For
739         // example, an element of DNSNames may not be a valid DNS domain name.)
740         DNSNames       []string
741         EmailAddresses []string
742         IPAddresses    []net.IP
743         URIs           []*url.URL
744
745         // Name constraints
746         PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
747         PermittedDNSDomains         []string
748         ExcludedDNSDomains          []string
749         PermittedIPRanges           []*net.IPNet
750         ExcludedIPRanges            []*net.IPNet
751         PermittedEmailAddresses     []string
752         ExcludedEmailAddresses      []string
753         PermittedURIDomains         []string
754         ExcludedURIDomains          []string
755
756         // CRL Distribution Points
757         CRLDistributionPoints []string
758
759         PolicyIdentifiers []asn1.ObjectIdentifier
760 }
761
762 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
763 // involves algorithms that are not currently implemented.
764 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
765
766 // An InsecureAlgorithmError
767 type InsecureAlgorithmError SignatureAlgorithm
768
769 func (e InsecureAlgorithmError) Error() string {
770         return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
771 }
772
773 // ConstraintViolationError results when a requested usage is not permitted by
774 // a certificate. For example: checking a signature when the public key isn't a
775 // certificate signing key.
776 type ConstraintViolationError struct{}
777
778 func (ConstraintViolationError) Error() string {
779         return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
780 }
781
782 func (c *Certificate) Equal(other *Certificate) bool {
783         if c == nil || other == nil {
784                 return c == other
785         }
786         return bytes.Equal(c.Raw, other.Raw)
787 }
788
789 func (c *Certificate) hasSANExtension() bool {
790         return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
791 }
792
793 // CheckSignatureFrom verifies that the signature on c is a valid signature
794 // from parent.
795 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
796         // RFC 5280, 4.2.1.9:
797         // "If the basic constraints extension is not present in a version 3
798         // certificate, or the extension is present but the cA boolean is not
799         // asserted, then the certified public key MUST NOT be used to verify
800         // certificate signatures."
801         if parent.Version == 3 && !parent.BasicConstraintsValid ||
802                 parent.BasicConstraintsValid && !parent.IsCA {
803                 return ConstraintViolationError{}
804         }
805
806         if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
807                 return ConstraintViolationError{}
808         }
809
810         if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
811                 return ErrUnsupportedAlgorithm
812         }
813
814         // TODO(agl): don't ignore the path length constraint.
815
816         return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
817 }
818
819 // CheckSignature verifies that signature is a valid signature over signed from
820 // c's public key.
821 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
822         return checkSignature(algo, signed, signature, c.PublicKey)
823 }
824
825 func (c *Certificate) hasNameConstraints() bool {
826         return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
827 }
828
829 func (c *Certificate) getSANExtension() []byte {
830         for _, e := range c.Extensions {
831                 if e.Id.Equal(oidExtensionSubjectAltName) {
832                         return e.Value
833                 }
834         }
835         return nil
836 }
837
838 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
839         return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
840 }
841
842 // CheckSignature verifies that signature is a valid signature over signed from
843 // a crypto.PublicKey.
844 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
845         var hashType crypto.Hash
846         var pubKeyAlgo PublicKeyAlgorithm
847
848         for _, details := range signatureAlgorithmDetails {
849                 if details.algo == algo {
850                         hashType = details.hash
851                         pubKeyAlgo = details.pubKeyAlgo
852                 }
853         }
854
855         switch hashType {
856         case crypto.Hash(0):
857                 if pubKeyAlgo != Ed25519 {
858                         return ErrUnsupportedAlgorithm
859                 }
860         case crypto.MD5:
861                 return InsecureAlgorithmError(algo)
862         default:
863                 if !hashType.Available() {
864                         return ErrUnsupportedAlgorithm
865                 }
866                 h := hashType.New()
867                 h.Write(signed)
868                 signed = h.Sum(nil)
869         }
870
871         switch pub := publicKey.(type) {
872         case *rsa.PublicKey:
873                 if pubKeyAlgo != RSA {
874                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
875                 }
876                 if algo.isRSAPSS() {
877                         return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
878                 } else {
879                         return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
880                 }
881         case *dsa.PublicKey:
882                 if pubKeyAlgo != DSA {
883                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
884                 }
885                 dsaSig := new(dsaSignature)
886                 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
887                         return err
888                 } else if len(rest) != 0 {
889                         return errors.New("x509: trailing data after DSA signature")
890                 }
891                 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
892                         return errors.New("x509: DSA signature contained zero or negative values")
893                 }
894                 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
895                 // than the key length, but crypto/dsa doesn't do it automatically.
896                 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
897                         signed = signed[:maxHashLen]
898                 }
899                 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
900                         return errors.New("x509: DSA verification failure")
901                 }
902                 return
903         case *ecdsa.PublicKey:
904                 if pubKeyAlgo != ECDSA {
905                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
906                 }
907                 if !ecdsa.VerifyASN1(pub, signed, signature) {
908                         return errors.New("x509: ECDSA verification failure")
909                 }
910                 return
911         case ed25519.PublicKey:
912                 if pubKeyAlgo != Ed25519 {
913                         return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
914                 }
915                 if !ed25519.Verify(pub, signed, signature) {
916                         return errors.New("x509: Ed25519 verification failure")
917                 }
918                 return
919         }
920         return ErrUnsupportedAlgorithm
921 }
922
923 // CheckCRLSignature checks that the signature in crl is from c.
924 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
925         algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
926         return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
927 }
928
929 type UnhandledCriticalExtension struct{}
930
931 func (h UnhandledCriticalExtension) Error() string {
932         return "x509: unhandled critical extension"
933 }
934
935 type basicConstraints struct {
936         IsCA       bool `asn1:"optional"`
937         MaxPathLen int  `asn1:"optional,default:-1"`
938 }
939
940 // RFC 5280 4.2.1.4
941 type policyInformation struct {
942         Policy asn1.ObjectIdentifier
943         // policyQualifiers omitted
944 }
945
946 const (
947         nameTypeEmail = 1
948         nameTypeDNS   = 2
949         nameTypeURI   = 6
950         nameTypeIP    = 7
951 )
952
953 // RFC 5280, 4.2.2.1
954 type authorityInfoAccess struct {
955         Method   asn1.ObjectIdentifier
956         Location asn1.RawValue
957 }
958
959 // RFC 5280, 4.2.1.14
960 type distributionPoint struct {
961         DistributionPoint distributionPointName `asn1:"optional,tag:0"`
962         Reason            asn1.BitString        `asn1:"optional,tag:1"`
963         CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
964 }
965
966 type distributionPointName struct {
967         FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
968         RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
969 }
970
971 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
972         asn1Data := keyData.PublicKey.RightAlign()
973         switch algo {
974         case RSA:
975                 // RSA public keys must have a NULL in the parameters.
976                 // See RFC 3279, Section 2.3.1.
977                 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
978                         return nil, errors.New("x509: RSA key missing NULL parameters")
979                 }
980
981                 p := new(pkcs1PublicKey)
982                 rest, err := asn1.Unmarshal(asn1Data, p)
983                 if err != nil {
984                         return nil, err
985                 }
986                 if len(rest) != 0 {
987                         return nil, errors.New("x509: trailing data after RSA public key")
988                 }
989
990                 if p.N.Sign() <= 0 {
991                         return nil, errors.New("x509: RSA modulus is not a positive number")
992                 }
993                 if p.E <= 0 {
994                         return nil, errors.New("x509: RSA public exponent is not a positive number")
995                 }
996
997                 pub := &rsa.PublicKey{
998                         E: p.E,
999                         N: p.N,
1000                 }
1001                 return pub, nil
1002         case DSA:
1003                 var p *big.Int
1004                 rest, err := asn1.Unmarshal(asn1Data, &p)
1005                 if err != nil {
1006                         return nil, err
1007                 }
1008                 if len(rest) != 0 {
1009                         return nil, errors.New("x509: trailing data after DSA public key")
1010                 }
1011                 paramsData := keyData.Algorithm.Parameters.FullBytes
1012                 params := new(dsaAlgorithmParameters)
1013                 rest, err = asn1.Unmarshal(paramsData, params)
1014                 if err != nil {
1015                         return nil, err
1016                 }
1017                 if len(rest) != 0 {
1018                         return nil, errors.New("x509: trailing data after DSA parameters")
1019                 }
1020                 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1021                         return nil, errors.New("x509: zero or negative DSA parameter")
1022                 }
1023                 pub := &dsa.PublicKey{
1024                         Parameters: dsa.Parameters{
1025                                 P: params.P,
1026                                 Q: params.Q,
1027                                 G: params.G,
1028                         },
1029                         Y: p,
1030                 }
1031                 return pub, nil
1032         case ECDSA:
1033                 paramsData := keyData.Algorithm.Parameters.FullBytes
1034                 namedCurveOID := new(asn1.ObjectIdentifier)
1035                 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1036                 if err != nil {
1037                         return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1038                 }
1039                 if len(rest) != 0 {
1040                         return nil, errors.New("x509: trailing data after ECDSA parameters")
1041                 }
1042                 namedCurve := namedCurveFromOID(*namedCurveOID)
1043                 if namedCurve == nil {
1044                         return nil, errors.New("x509: unsupported elliptic curve")
1045                 }
1046                 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1047                 if x == nil {
1048                         return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1049                 }
1050                 pub := &ecdsa.PublicKey{
1051                         Curve: namedCurve,
1052                         X:     x,
1053                         Y:     y,
1054                 }
1055                 return pub, nil
1056         case Ed25519:
1057                 // RFC 8410, Section 3
1058                 // > For all of the OIDs, the parameters MUST be absent.
1059                 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1060                         return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1061                 }
1062                 if len(asn1Data) != ed25519.PublicKeySize {
1063                         return nil, errors.New("x509: wrong Ed25519 public key size")
1064                 }
1065                 pub := make([]byte, ed25519.PublicKeySize)
1066                 copy(pub, asn1Data)
1067                 return ed25519.PublicKey(pub), nil
1068         default:
1069                 return nil, nil
1070         }
1071 }
1072
1073 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1074         // RFC 5280, 4.2.1.6
1075
1076         // SubjectAltName ::= GeneralNames
1077         //
1078         // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1079         //
1080         // GeneralName ::= CHOICE {
1081         //      otherName                       [0]     OtherName,
1082         //      rfc822Name                      [1]     IA5String,
1083         //      dNSName                         [2]     IA5String,
1084         //      x400Address                     [3]     ORAddress,
1085         //      directoryName                   [4]     Name,
1086         //      ediPartyName                    [5]     EDIPartyName,
1087         //      uniformResourceIdentifier       [6]     IA5String,
1088         //      iPAddress                       [7]     OCTET STRING,
1089         //      registeredID                    [8]     OBJECT IDENTIFIER }
1090         var seq asn1.RawValue
1091         rest, err := asn1.Unmarshal(extension, &seq)
1092         if err != nil {
1093                 return err
1094         } else if len(rest) != 0 {
1095                 return errors.New("x509: trailing data after X.509 extension")
1096         }
1097         if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1098                 return asn1.StructuralError{Msg: "bad SAN sequence"}
1099         }
1100
1101         rest = seq.Bytes
1102         for len(rest) > 0 {
1103                 var v asn1.RawValue
1104                 rest, err = asn1.Unmarshal(rest, &v)
1105                 if err != nil {
1106                         return err
1107                 }
1108
1109                 if err := callback(v.Tag, v.Bytes); err != nil {
1110                         return err
1111                 }
1112         }
1113
1114         return nil
1115 }
1116
1117 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1118         err = forEachSAN(value, func(tag int, data []byte) error {
1119                 switch tag {
1120                 case nameTypeEmail:
1121                         emailAddresses = append(emailAddresses, string(data))
1122                 case nameTypeDNS:
1123                         dnsNames = append(dnsNames, string(data))
1124                 case nameTypeURI:
1125                         uri, err := url.Parse(string(data))
1126                         if err != nil {
1127                                 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1128                         }
1129                         if len(uri.Host) > 0 {
1130                                 if _, ok := domainToReverseLabels(uri.Host); !ok {
1131                                         return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1132                                 }
1133                         }
1134                         uris = append(uris, uri)
1135                 case nameTypeIP:
1136                         switch len(data) {
1137                         case net.IPv4len, net.IPv6len:
1138                                 ipAddresses = append(ipAddresses, data)
1139                         default:
1140                                 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1141                         }
1142                 }
1143
1144                 return nil
1145         })
1146
1147         return
1148 }
1149
1150 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1151 func isValidIPMask(mask []byte) bool {
1152         seenZero := false
1153
1154         for _, b := range mask {
1155                 if seenZero {
1156                         if b != 0 {
1157                                 return false
1158                         }
1159
1160                         continue
1161                 }
1162
1163                 switch b {
1164                 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1165                         seenZero = true
1166                 case 0xff:
1167                 default:
1168                         return false
1169                 }
1170         }
1171
1172         return true
1173 }
1174
1175 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1176         // RFC 5280, 4.2.1.10
1177
1178         // NameConstraints ::= SEQUENCE {
1179         //      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
1180         //      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
1181         //
1182         // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1183         //
1184         // GeneralSubtree ::= SEQUENCE {
1185         //      base                    GeneralName,
1186         //      minimum         [0]     BaseDistance DEFAULT 0,
1187         //      maximum         [1]     BaseDistance OPTIONAL }
1188         //
1189         // BaseDistance ::= INTEGER (0..MAX)
1190
1191         outer := cryptobyte.String(e.Value)
1192         var toplevel, permitted, excluded cryptobyte.String
1193         var havePermitted, haveExcluded bool
1194         if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1195                 !outer.Empty() ||
1196                 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1197                 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1198                 !toplevel.Empty() {
1199                 return false, errors.New("x509: invalid NameConstraints extension")
1200         }
1201
1202         if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1203                 // From RFC 5280, Section 4.2.1.10:
1204                 //   “either the permittedSubtrees field
1205                 //   or the excludedSubtrees MUST be
1206                 //   present”
1207                 return false, errors.New("x509: empty name constraints extension")
1208         }
1209
1210         getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1211                 for !subtrees.Empty() {
1212                         var seq, value cryptobyte.String
1213                         var tag cryptobyte_asn1.Tag
1214                         if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1215                                 !seq.ReadAnyASN1(&value, &tag) {
1216                                 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1217                         }
1218
1219                         var (
1220                                 dnsTag   = cryptobyte_asn1.Tag(2).ContextSpecific()
1221                                 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1222                                 ipTag    = cryptobyte_asn1.Tag(7).ContextSpecific()
1223                                 uriTag   = cryptobyte_asn1.Tag(6).ContextSpecific()
1224                         )
1225
1226                         switch tag {
1227                         case dnsTag:
1228                                 domain := string(value)
1229                                 if err := isIA5String(domain); err != nil {
1230                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1231                                 }
1232
1233                                 trimmedDomain := domain
1234                                 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1235                                         // constraints can have a leading
1236                                         // period to exclude the domain
1237                                         // itself, but that's not valid in a
1238                                         // normal domain name.
1239                                         trimmedDomain = trimmedDomain[1:]
1240                                 }
1241                                 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1242                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1243                                 }
1244                                 dnsNames = append(dnsNames, domain)
1245
1246                         case ipTag:
1247                                 l := len(value)
1248                                 var ip, mask []byte
1249
1250                                 switch l {
1251                                 case 8:
1252                                         ip = value[:4]
1253                                         mask = value[4:]
1254
1255                                 case 32:
1256                                         ip = value[:16]
1257                                         mask = value[16:]
1258
1259                                 default:
1260                                         return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1261                                 }
1262
1263                                 if !isValidIPMask(mask) {
1264                                         return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1265                                 }
1266
1267                                 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1268
1269                         case emailTag:
1270                                 constraint := string(value)
1271                                 if err := isIA5String(constraint); err != nil {
1272                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1273                                 }
1274
1275                                 // If the constraint contains an @ then
1276                                 // it specifies an exact mailbox name.
1277                                 if strings.Contains(constraint, "@") {
1278                                         if _, ok := parseRFC2821Mailbox(constraint); !ok {
1279                                                 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1280                                         }
1281                                 } else {
1282                                         // Otherwise it's a domain name.
1283                                         domain := constraint
1284                                         if len(domain) > 0 && domain[0] == '.' {
1285                                                 domain = domain[1:]
1286                                         }
1287                                         if _, ok := domainToReverseLabels(domain); !ok {
1288                                                 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1289                                         }
1290                                 }
1291                                 emails = append(emails, constraint)
1292
1293                         case uriTag:
1294                                 domain := string(value)
1295                                 if err := isIA5String(domain); err != nil {
1296                                         return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1297                                 }
1298
1299                                 if net.ParseIP(domain) != nil {
1300                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1301                                 }
1302
1303                                 trimmedDomain := domain
1304                                 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1305                                         // constraints can have a leading
1306                                         // period to exclude the domain itself,
1307                                         // but that's not valid in a normal
1308                                         // domain name.
1309                                         trimmedDomain = trimmedDomain[1:]
1310                                 }
1311                                 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1312                                         return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1313                                 }
1314                                 uriDomains = append(uriDomains, domain)
1315
1316                         default:
1317                                 unhandled = true
1318                         }
1319                 }
1320
1321                 return dnsNames, ips, emails, uriDomains, nil
1322         }
1323
1324         if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1325                 return false, err
1326         }
1327         if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1328                 return false, err
1329         }
1330         out.PermittedDNSDomainsCritical = e.Critical
1331
1332         return unhandled, nil
1333 }
1334
1335 func parseCertificate(in *certificate) (*Certificate, error) {
1336         out := new(Certificate)
1337         out.Raw = in.Raw
1338         out.RawTBSCertificate = in.TBSCertificate.Raw
1339         out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1340         out.RawSubject = in.TBSCertificate.Subject.FullBytes
1341         out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1342
1343         out.Signature = in.SignatureValue.RightAlign()
1344         out.SignatureAlgorithm =
1345                 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1346
1347         out.PublicKeyAlgorithm =
1348                 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1349         var err error
1350         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1351         if err != nil {
1352                 return nil, err
1353         }
1354
1355         out.Version = in.TBSCertificate.Version + 1
1356         out.SerialNumber = in.TBSCertificate.SerialNumber
1357
1358         var issuer, subject pkix.RDNSequence
1359         if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1360                 return nil, err
1361         } else if len(rest) != 0 {
1362                 return nil, errors.New("x509: trailing data after X.509 subject")
1363         }
1364         if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1365                 return nil, err
1366         } else if len(rest) != 0 {
1367                 return nil, errors.New("x509: trailing data after X.509 issuer")
1368         }
1369
1370         out.Issuer.FillFromRDNSequence(&issuer)
1371         out.Subject.FillFromRDNSequence(&subject)
1372
1373         out.NotBefore = in.TBSCertificate.Validity.NotBefore
1374         out.NotAfter = in.TBSCertificate.Validity.NotAfter
1375
1376         for _, e := range in.TBSCertificate.Extensions {
1377                 out.Extensions = append(out.Extensions, e)
1378                 unhandled := false
1379
1380                 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1381                         switch e.Id[3] {
1382                         case 15:
1383                                 // RFC 5280, 4.2.1.3
1384                                 var usageBits asn1.BitString
1385                                 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1386                                         return nil, err
1387                                 } else if len(rest) != 0 {
1388                                         return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1389                                 }
1390
1391                                 var usage int
1392                                 for i := 0; i < 9; i++ {
1393                                         if usageBits.At(i) != 0 {
1394                                                 usage |= 1 << uint(i)
1395                                         }
1396                                 }
1397                                 out.KeyUsage = KeyUsage(usage)
1398
1399                         case 19:
1400                                 // RFC 5280, 4.2.1.9
1401                                 var constraints basicConstraints
1402                                 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1403                                         return nil, err
1404                                 } else if len(rest) != 0 {
1405                                         return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1406                                 }
1407
1408                                 out.BasicConstraintsValid = true
1409                                 out.IsCA = constraints.IsCA
1410                                 out.MaxPathLen = constraints.MaxPathLen
1411                                 out.MaxPathLenZero = out.MaxPathLen == 0
1412                                 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1413                         case 17:
1414                                 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1415                                 if err != nil {
1416                                         return nil, err
1417                                 }
1418
1419                                 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1420                                         // If we didn't parse anything then we do the critical check, below.
1421                                         unhandled = true
1422                                 }
1423
1424                         case 30:
1425                                 unhandled, err = parseNameConstraintsExtension(out, e)
1426                                 if err != nil {
1427                                         return nil, err
1428                                 }
1429
1430                         case 31:
1431                                 // RFC 5280, 4.2.1.13
1432
1433                                 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1434                                 //
1435                                 // DistributionPoint ::= SEQUENCE {
1436                                 //     distributionPoint       [0]     DistributionPointName OPTIONAL,
1437                                 //     reasons                 [1]     ReasonFlags OPTIONAL,
1438                                 //     cRLIssuer               [2]     GeneralNames OPTIONAL }
1439                                 //
1440                                 // DistributionPointName ::= CHOICE {
1441                                 //     fullName                [0]     GeneralNames,
1442                                 //     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
1443
1444                                 var cdp []distributionPoint
1445                                 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1446                                         return nil, err
1447                                 } else if len(rest) != 0 {
1448                                         return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1449                                 }
1450
1451                                 for _, dp := range cdp {
1452                                         // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1453                                         if len(dp.DistributionPoint.FullName) == 0 {
1454                                                 continue
1455                                         }
1456
1457                                         for _, fullName := range dp.DistributionPoint.FullName {
1458                                                 if fullName.Tag == 6 {
1459                                                         out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1460                                                 }
1461                                         }
1462                                 }
1463
1464                         case 35:
1465                                 // RFC 5280, 4.2.1.1
1466                                 var a authKeyId
1467                                 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1468                                         return nil, err
1469                                 } else if len(rest) != 0 {
1470                                         return nil, errors.New("x509: trailing data after X.509 authority key-id")
1471                                 }
1472                                 out.AuthorityKeyId = a.Id
1473
1474                         case 37:
1475                                 // RFC 5280, 4.2.1.12.  Extended Key Usage
1476
1477                                 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1478                                 //
1479                                 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1480                                 //
1481                                 // KeyPurposeId ::= OBJECT IDENTIFIER
1482
1483                                 var keyUsage []asn1.ObjectIdentifier
1484                                 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1485                                         return nil, err
1486                                 } else if len(rest) != 0 {
1487                                         return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1488                                 }
1489
1490                                 for _, u := range keyUsage {
1491                                         if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1492                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1493                                         } else {
1494                                                 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1495                                         }
1496                                 }
1497
1498                         case 14:
1499                                 // RFC 5280, 4.2.1.2
1500                                 var keyid []byte
1501                                 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1502                                         return nil, err
1503                                 } else if len(rest) != 0 {
1504                                         return nil, errors.New("x509: trailing data after X.509 key-id")
1505                                 }
1506                                 out.SubjectKeyId = keyid
1507
1508                         case 32:
1509                                 // RFC 5280 4.2.1.4: Certificate Policies
1510                                 var policies []policyInformation
1511                                 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1512                                         return nil, err
1513                                 } else if len(rest) != 0 {
1514                                         return nil, errors.New("x509: trailing data after X.509 certificate policies")
1515                                 }
1516                                 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1517                                 for i, policy := range policies {
1518                                         out.PolicyIdentifiers[i] = policy.Policy
1519                                 }
1520
1521                         default:
1522                                 // Unknown extensions are recorded if critical.
1523                                 unhandled = true
1524                         }
1525                 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1526                         // RFC 5280 4.2.2.1: Authority Information Access
1527                         var aia []authorityInfoAccess
1528                         if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1529                                 return nil, err
1530                         } else if len(rest) != 0 {
1531                                 return nil, errors.New("x509: trailing data after X.509 authority information")
1532                         }
1533
1534                         for _, v := range aia {
1535                                 // GeneralName: uniformResourceIdentifier [6] IA5String
1536                                 if v.Location.Tag != 6 {
1537                                         continue
1538                                 }
1539                                 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1540                                         out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1541                                 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1542                                         out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1543                                 }
1544                         }
1545                 } else {
1546                         // Unknown extensions are recorded if critical.
1547                         unhandled = true
1548                 }
1549
1550                 if e.Critical && unhandled {
1551                         out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1552                 }
1553         }
1554
1555         return out, nil
1556 }
1557
1558 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1559 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1560         var cert certificate
1561         rest, err := asn1.Unmarshal(asn1Data, &cert)
1562         if err != nil {
1563                 return nil, err
1564         }
1565         if len(rest) > 0 {
1566                 return nil, asn1.SyntaxError{Msg: "trailing data"}
1567         }
1568
1569         return parseCertificate(&cert)
1570 }
1571
1572 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1573 // data. The certificates must be concatenated with no intermediate padding.
1574 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1575         var v []*certificate
1576
1577         for len(asn1Data) > 0 {
1578                 cert := new(certificate)
1579                 var err error
1580                 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1581                 if err != nil {
1582                         return nil, err
1583                 }
1584                 v = append(v, cert)
1585         }
1586
1587         ret := make([]*Certificate, len(v))
1588         for i, ci := range v {
1589                 cert, err := parseCertificate(ci)
1590                 if err != nil {
1591                         return nil, err
1592                 }
1593                 ret[i] = cert
1594         }
1595
1596         return ret, nil
1597 }
1598
1599 func reverseBitsInAByte(in byte) byte {
1600         b1 := in>>4 | in<<4
1601         b2 := b1>>2&0x33 | b1<<2&0xcc
1602         b3 := b2>>1&0x55 | b2<<1&0xaa
1603         return b3
1604 }
1605
1606 // asn1BitLength returns the bit-length of bitString by considering the
1607 // most-significant bit in a byte to be the "first" bit. This convention
1608 // matches ASN.1, but differs from almost everything else.
1609 func asn1BitLength(bitString []byte) int {
1610         bitLen := len(bitString) * 8
1611
1612         for i := range bitString {
1613                 b := bitString[len(bitString)-i-1]
1614
1615                 for bit := uint(0); bit < 8; bit++ {
1616                         if (b>>bit)&1 == 1 {
1617                                 return bitLen
1618                         }
1619                         bitLen--
1620                 }
1621         }
1622
1623         return 0
1624 }
1625
1626 var (
1627         oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
1628         oidExtensionKeyUsage              = []int{2, 5, 29, 15}
1629         oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
1630         oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
1631         oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
1632         oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
1633         oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
1634         oidExtensionNameConstraints       = []int{2, 5, 29, 30}
1635         oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1636         oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1637         oidExtensionCRLNumber             = []int{2, 5, 29, 20}
1638 )
1639
1640 var (
1641         oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1642         oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1643 )
1644
1645 // oidNotInExtensions reports whether an extension with the given oid exists in
1646 // extensions.
1647 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1648         for _, e := range extensions {
1649                 if e.Id.Equal(oid) {
1650                         return true
1651                 }
1652         }
1653         return false
1654 }
1655
1656 // marshalSANs marshals a list of addresses into a the contents of an X.509
1657 // SubjectAlternativeName extension.
1658 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1659         var rawValues []asn1.RawValue
1660         for _, name := range dnsNames {
1661                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1662         }
1663         for _, email := range emailAddresses {
1664                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1665         }
1666         for _, rawIP := range ipAddresses {
1667                 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1668                 ip := rawIP.To4()
1669                 if ip == nil {
1670                         ip = rawIP
1671                 }
1672                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1673         }
1674         for _, uri := range uris {
1675                 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
1676         }
1677         return asn1.Marshal(rawValues)
1678 }
1679
1680 func isIA5String(s string) error {
1681         for _, r := range s {
1682                 if r >= utf8.RuneSelf {
1683                         return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1684                 }
1685         }
1686
1687         return nil
1688 }
1689
1690 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1691         ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1692         n := 0
1693
1694         if template.KeyUsage != 0 &&
1695                 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1696                 ret[n].Id = oidExtensionKeyUsage
1697                 ret[n].Critical = true
1698
1699                 var a [2]byte
1700                 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1701                 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1702
1703                 l := 1
1704                 if a[1] != 0 {
1705                         l = 2
1706                 }
1707
1708                 bitString := a[:l]
1709                 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1710                 if err != nil {
1711                         return
1712                 }
1713                 n++
1714         }
1715
1716         if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1717                 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1718                 ret[n].Id = oidExtensionExtendedKeyUsage
1719
1720                 var oids []asn1.ObjectIdentifier
1721                 for _, u := range template.ExtKeyUsage {
1722                         if oid, ok := oidFromExtKeyUsage(u); ok {
1723                                 oids = append(oids, oid)
1724                         } else {
1725                                 panic("internal error")
1726                         }
1727                 }
1728
1729                 oids = append(oids, template.UnknownExtKeyUsage...)
1730
1731                 ret[n].Value, err = asn1.Marshal(oids)
1732                 if err != nil {
1733                         return
1734                 }
1735                 n++
1736         }
1737
1738         if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1739                 // Leaving MaxPathLen as zero indicates that no maximum path
1740                 // length is desired, unless MaxPathLenZero is set. A value of
1741                 // -1 causes encoding/asn1 to omit the value as desired.
1742                 maxPathLen := template.MaxPathLen
1743                 if maxPathLen == 0 && !template.MaxPathLenZero {
1744                         maxPathLen = -1
1745                 }
1746                 ret[n].Id = oidExtensionBasicConstraints
1747                 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1748                 ret[n].Critical = true
1749                 if err != nil {
1750                         return
1751                 }
1752                 n++
1753         }
1754
1755         if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1756                 ret[n].Id = oidExtensionSubjectKeyId
1757                 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1758                 if err != nil {
1759                         return
1760                 }
1761                 n++
1762         }
1763
1764         if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1765                 ret[n].Id = oidExtensionAuthorityKeyId
1766                 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1767                 if err != nil {
1768                         return
1769                 }
1770                 n++
1771         }
1772
1773         if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1774                 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1775                 ret[n].Id = oidExtensionAuthorityInfoAccess
1776                 var aiaValues []authorityInfoAccess
1777                 for _, name := range template.OCSPServer {
1778                         aiaValues = append(aiaValues, authorityInfoAccess{
1779                                 Method:   oidAuthorityInfoAccessOcsp,
1780                                 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1781                         })
1782                 }
1783                 for _, name := range template.IssuingCertificateURL {
1784                         aiaValues = append(aiaValues, authorityInfoAccess{
1785                                 Method:   oidAuthorityInfoAccessIssuers,
1786                                 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1787                         })
1788                 }
1789                 ret[n].Value, err = asn1.Marshal(aiaValues)
1790                 if err != nil {
1791                         return
1792                 }
1793                 n++
1794         }
1795
1796         if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1797                 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1798                 ret[n].Id = oidExtensionSubjectAltName
1799                 // From RFC 5280, Section 4.2.1.6:
1800                 // “If the subject field contains an empty sequence ... then
1801                 // subjectAltName extension ... is marked as critical”
1802                 ret[n].Critical = subjectIsEmpty
1803                 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1804                 if err != nil {
1805                         return
1806                 }
1807                 n++
1808         }
1809
1810         if len(template.PolicyIdentifiers) > 0 &&
1811                 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1812                 ret[n].Id = oidExtensionCertificatePolicies
1813                 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1814                 for i, policy := range template.PolicyIdentifiers {
1815                         policies[i].Policy = policy
1816                 }
1817                 ret[n].Value, err = asn1.Marshal(policies)
1818                 if err != nil {
1819                         return
1820                 }
1821                 n++
1822         }
1823
1824         if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1825                 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1826                 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1827                 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1828                 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1829                 ret[n].Id = oidExtensionNameConstraints
1830                 ret[n].Critical = template.PermittedDNSDomainsCritical
1831
1832                 ipAndMask := func(ipNet *net.IPNet) []byte {
1833                         maskedIP := ipNet.IP.Mask(ipNet.Mask)
1834                         ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1835                         ipAndMask = append(ipAndMask, maskedIP...)
1836                         ipAndMask = append(ipAndMask, ipNet.Mask...)
1837                         return ipAndMask
1838                 }
1839
1840                 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1841                         var b cryptobyte.Builder
1842
1843                         for _, name := range dns {
1844                                 if err = isIA5String(name); err != nil {
1845                                         return nil, err
1846                                 }
1847
1848                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1849                                         b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1850                                                 b.AddBytes([]byte(name))
1851                                         })
1852                                 })
1853                         }
1854
1855                         for _, ipNet := range ips {
1856                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1857                                         b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1858                                                 b.AddBytes(ipAndMask(ipNet))
1859                                         })
1860                                 })
1861                         }
1862
1863                         for _, email := range emails {
1864                                 if err = isIA5String(email); err != nil {
1865                                         return nil, err
1866                                 }
1867
1868                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1869                                         b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1870                                                 b.AddBytes([]byte(email))
1871                                         })
1872                                 })
1873                         }
1874
1875                         for _, uriDomain := range uriDomains {
1876                                 if err = isIA5String(uriDomain); err != nil {
1877                                         return nil, err
1878                                 }
1879
1880                                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1881                                         b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1882                                                 b.AddBytes([]byte(uriDomain))
1883                                         })
1884                                 })
1885                         }
1886
1887                         return b.Bytes()
1888                 }
1889
1890                 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1891                 if err != nil {
1892                         return nil, err
1893                 }
1894
1895                 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1896                 if err != nil {
1897                         return nil, err
1898                 }
1899
1900                 var b cryptobyte.Builder
1901                 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1902                         if len(permitted) > 0 {
1903                                 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1904                                         b.AddBytes(permitted)
1905                                 })
1906                         }
1907
1908                         if len(excluded) > 0 {
1909                                 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1910                                         b.AddBytes(excluded)
1911                                 })
1912                         }
1913                 })
1914
1915                 ret[n].Value, err = b.Bytes()
1916                 if err != nil {
1917                         return nil, err
1918                 }
1919                 n++
1920         }
1921
1922         if len(template.CRLDistributionPoints) > 0 &&
1923                 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1924                 ret[n].Id = oidExtensionCRLDistributionPoints
1925
1926                 var crlDp []distributionPoint
1927                 for _, name := range template.CRLDistributionPoints {
1928                         dp := distributionPoint{
1929                                 DistributionPoint: distributionPointName{
1930                                         FullName: []asn1.RawValue{
1931                                                 {Tag: 6, Class: 2, Bytes: []byte(name)},
1932                                         },
1933                                 },
1934                         }
1935                         crlDp = append(crlDp, dp)
1936                 }
1937
1938                 ret[n].Value, err = asn1.Marshal(crlDp)
1939                 if err != nil {
1940                         return
1941                 }
1942                 n++
1943         }
1944
1945         // Adding another extension here? Remember to update the maximum number
1946         // of elements in the make() at the top of the function and the list of
1947         // template fields used in CreateCertificate documentation.
1948
1949         return append(ret[:n], template.ExtraExtensions...), nil
1950 }
1951
1952 func subjectBytes(cert *Certificate) ([]byte, error) {
1953         if len(cert.RawSubject) > 0 {
1954                 return cert.RawSubject, nil
1955         }
1956
1957         return asn1.Marshal(cert.Subject.ToRDNSequence())
1958 }
1959
1960 // signingParamsForPublicKey returns the parameters to use for signing with
1961 // priv. If requestedSigAlgo is not zero then it overrides the default
1962 // signature algorithm.
1963 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1964         var pubType PublicKeyAlgorithm
1965
1966         switch pub := pub.(type) {
1967         case *rsa.PublicKey:
1968                 pubType = RSA
1969                 hashFunc = crypto.SHA256
1970                 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1971                 sigAlgo.Parameters = asn1.NullRawValue
1972
1973         case *ecdsa.PublicKey:
1974                 pubType = ECDSA
1975
1976                 switch pub.Curve {
1977                 case elliptic.P224(), elliptic.P256():
1978                         hashFunc = crypto.SHA256
1979                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1980                 case elliptic.P384():
1981                         hashFunc = crypto.SHA384
1982                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1983                 case elliptic.P521():
1984                         hashFunc = crypto.SHA512
1985                         sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1986                 default:
1987                         err = errors.New("x509: unknown elliptic curve")
1988                 }
1989
1990         case ed25519.PublicKey:
1991                 pubType = Ed25519
1992                 sigAlgo.Algorithm = oidSignatureEd25519
1993
1994         default:
1995                 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1996         }
1997
1998         if err != nil {
1999                 return
2000         }
2001
2002         if requestedSigAlgo == 0 {
2003                 return
2004         }
2005
2006         found := false
2007         for _, details := range signatureAlgorithmDetails {
2008                 if details.algo == requestedSigAlgo {
2009                         if details.pubKeyAlgo != pubType {
2010                                 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2011                                 return
2012                         }
2013                         sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2014                         if hashFunc == 0 && pubType != Ed25519 {
2015                                 err = errors.New("x509: cannot sign with hash function requested")
2016                                 return
2017                         }
2018                         if requestedSigAlgo.isRSAPSS() {
2019                                 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2020                         }
2021                         found = true
2022                         break
2023                 }
2024         }
2025
2026         if !found {
2027                 err = errors.New("x509: unknown SignatureAlgorithm")
2028         }
2029
2030         return
2031 }
2032
2033 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2034 // just an empty SEQUENCE.
2035 var emptyASN1Subject = []byte{0x30, 0}
2036
2037 // CreateCertificate creates a new X.509v3 certificate based on a template.
2038 // The following members of template are used:
2039 //
2040 //  - AuthorityKeyId
2041 //  - BasicConstraintsValid
2042 //  - CRLDistributionPoints
2043 //  - DNSNames
2044 //  - EmailAddresses
2045 //  - ExcludedDNSDomains
2046 //  - ExcludedEmailAddresses
2047 //  - ExcludedIPRanges
2048 //  - ExcludedURIDomains
2049 //  - ExtKeyUsage
2050 //  - ExtraExtensions
2051 //  - IPAddresses
2052 //  - IsCA
2053 //  - IssuingCertificateURL
2054 //  - KeyUsage
2055 //  - MaxPathLen
2056 //  - MaxPathLenZero
2057 //  - NotAfter
2058 //  - NotBefore
2059 //  - OCSPServer
2060 //  - PermittedDNSDomains
2061 //  - PermittedDNSDomainsCritical
2062 //  - PermittedEmailAddresses
2063 //  - PermittedIPRanges
2064 //  - PermittedURIDomains
2065 //  - PolicyIdentifiers
2066 //  - SerialNumber
2067 //  - SignatureAlgorithm
2068 //  - Subject
2069 //  - SubjectKeyId
2070 //  - URIs
2071 //  - UnknownExtKeyUsage
2072 //
2073 // The certificate is signed by parent. If parent is equal to template then the
2074 // certificate is self-signed. The parameter pub is the public key of the
2075 // signee and priv is the private key of the signer.
2076 //
2077 // The returned slice is the certificate in DER encoding.
2078 //
2079 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2080 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2081 // crypto.Signer with a supported public key.
2082 //
2083 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2084 // unless the resulting certificate is self-signed. Otherwise the value from
2085 // template will be used.
2086 //
2087 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
2088 // will be generated from the hash of the public key.
2089 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2090         key, ok := priv.(crypto.Signer)
2091         if !ok {
2092                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2093         }
2094
2095         if template.SerialNumber == nil {
2096                 return nil, errors.New("x509: no SerialNumber given")
2097         }
2098
2099         if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
2100                 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
2101         }
2102
2103         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2104         if err != nil {
2105                 return nil, err
2106         }
2107
2108         publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2109         if err != nil {
2110                 return nil, err
2111         }
2112
2113         asn1Issuer, err := subjectBytes(parent)
2114         if err != nil {
2115                 return
2116         }
2117
2118         asn1Subject, err := subjectBytes(template)
2119         if err != nil {
2120                 return
2121         }
2122
2123         authorityKeyId := template.AuthorityKeyId
2124         if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2125                 authorityKeyId = parent.SubjectKeyId
2126         }
2127
2128         subjectKeyId := template.SubjectKeyId
2129         if len(subjectKeyId) == 0 && template.IsCA {
2130                 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
2131                 //   (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
2132                 //   value of the BIT STRING subjectPublicKey (excluding the tag,
2133                 //   length, and number of unused bits).
2134                 h := sha1.Sum(publicKeyBytes)
2135                 subjectKeyId = h[:]
2136         }
2137
2138         extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
2139         if err != nil {
2140                 return
2141         }
2142
2143         encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2144         c := tbsCertificate{
2145                 Version:            2,
2146                 SerialNumber:       template.SerialNumber,
2147                 SignatureAlgorithm: signatureAlgorithm,
2148                 Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
2149                 Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2150                 Subject:            asn1.RawValue{FullBytes: asn1Subject},
2151                 PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2152                 Extensions:         extensions,
2153         }
2154
2155         tbsCertContents, err := asn1.Marshal(c)
2156         if err != nil {
2157                 return
2158         }
2159         c.Raw = tbsCertContents
2160
2161         signed := tbsCertContents
2162         if hashFunc != 0 {
2163                 h := hashFunc.New()
2164                 h.Write(signed)
2165                 signed = h.Sum(nil)
2166         }
2167
2168         var signerOpts crypto.SignerOpts = hashFunc
2169         if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2170                 signerOpts = &rsa.PSSOptions{
2171                         SaltLength: rsa.PSSSaltLengthEqualsHash,
2172                         Hash:       hashFunc,
2173                 }
2174         }
2175
2176         var signature []byte
2177         signature, err = key.Sign(rand, signed, signerOpts)
2178         if err != nil {
2179                 return
2180         }
2181
2182         return asn1.Marshal(certificate{
2183                 nil,
2184                 c,
2185                 signatureAlgorithm,
2186                 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2187         })
2188 }
2189
2190 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2191 // CRL.
2192 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2193
2194 // pemType is the type of a PEM encoded CRL.
2195 var pemType = "X509 CRL"
2196
2197 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2198 // encoded CRLs will appear where they should be DER encoded, so this function
2199 // will transparently handle PEM encoding as long as there isn't any leading
2200 // garbage.
2201 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2202         if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2203                 block, _ := pem.Decode(crlBytes)
2204                 if block != nil && block.Type == pemType {
2205                         crlBytes = block.Bytes
2206                 }
2207         }
2208         return ParseDERCRL(crlBytes)
2209 }
2210
2211 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2212 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2213         certList := new(pkix.CertificateList)
2214         if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2215                 return nil, err
2216         } else if len(rest) != 0 {
2217                 return nil, errors.New("x509: trailing data after CRL")
2218         }
2219         return certList, nil
2220 }
2221
2222 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2223 // contains the given list of revoked certificates.
2224 //
2225 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2226 // To generate a standards compliant CRL, use CreateRevocationList instead.
2227 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2228         key, ok := priv.(crypto.Signer)
2229         if !ok {
2230                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2231         }
2232
2233         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2234         if err != nil {
2235                 return nil, err
2236         }
2237
2238         // Force revocation times to UTC per RFC 5280.
2239         revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2240         for i, rc := range revokedCerts {
2241                 rc.RevocationTime = rc.RevocationTime.UTC()
2242                 revokedCertsUTC[i] = rc
2243         }
2244
2245         tbsCertList := pkix.TBSCertificateList{
2246                 Version:             1,
2247                 Signature:           signatureAlgorithm,
2248                 Issuer:              c.Subject.ToRDNSequence(),
2249                 ThisUpdate:          now.UTC(),
2250                 NextUpdate:          expiry.UTC(),
2251                 RevokedCertificates: revokedCertsUTC,
2252         }
2253
2254         // Authority Key Id
2255         if len(c.SubjectKeyId) > 0 {
2256                 var aki pkix.Extension
2257                 aki.Id = oidExtensionAuthorityKeyId
2258                 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2259                 if err != nil {
2260                         return
2261                 }
2262                 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2263         }
2264
2265         tbsCertListContents, err := asn1.Marshal(tbsCertList)
2266         if err != nil {
2267                 return
2268         }
2269
2270         signed := tbsCertListContents
2271         if hashFunc != 0 {
2272                 h := hashFunc.New()
2273                 h.Write(signed)
2274                 signed = h.Sum(nil)
2275         }
2276
2277         var signature []byte
2278         signature, err = key.Sign(rand, signed, hashFunc)
2279         if err != nil {
2280                 return
2281         }
2282
2283         return asn1.Marshal(pkix.CertificateList{
2284                 TBSCertList:        tbsCertList,
2285                 SignatureAlgorithm: signatureAlgorithm,
2286                 SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2287         })
2288 }
2289
2290 // CertificateRequest represents a PKCS #10, certificate signature request.
2291 type CertificateRequest struct {
2292         Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2293         RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2294         RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
2295         RawSubject               []byte // DER encoded Subject.
2296
2297         Version            int
2298         Signature          []byte
2299         SignatureAlgorithm SignatureAlgorithm
2300
2301         PublicKeyAlgorithm PublicKeyAlgorithm
2302         PublicKey          interface{}
2303
2304         Subject pkix.Name
2305
2306         // Attributes contains the CSR attributes that can parse as
2307         // pkix.AttributeTypeAndValueSET.
2308         //
2309         // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2310         // generating the requestedExtensions attribute.
2311         Attributes []pkix.AttributeTypeAndValueSET
2312
2313         // Extensions contains all requested extensions, in raw form. When parsing
2314         // CSRs, this can be used to extract extensions that are not parsed by this
2315         // package.
2316         Extensions []pkix.Extension
2317
2318         // ExtraExtensions contains extensions to be copied, raw, into any CSR
2319         // marshaled by CreateCertificateRequest. Values override any extensions
2320         // that would otherwise be produced based on the other fields but are
2321         // overridden by any extensions specified in Attributes.
2322         //
2323         // The ExtraExtensions field is not populated by ParseCertificateRequest,
2324         // see Extensions instead.
2325         ExtraExtensions []pkix.Extension
2326
2327         // Subject Alternate Name values.
2328         DNSNames       []string
2329         EmailAddresses []string
2330         IPAddresses    []net.IP
2331         URIs           []*url.URL
2332 }
2333
2334 // These structures reflect the ASN.1 structure of X.509 certificate
2335 // signature requests (see RFC 2986):
2336
2337 type tbsCertificateRequest struct {
2338         Raw           asn1.RawContent
2339         Version       int
2340         Subject       asn1.RawValue
2341         PublicKey     publicKeyInfo
2342         RawAttributes []asn1.RawValue `asn1:"tag:0"`
2343 }
2344
2345 type certificateRequest struct {
2346         Raw                asn1.RawContent
2347         TBSCSR             tbsCertificateRequest
2348         SignatureAlgorithm pkix.AlgorithmIdentifier
2349         SignatureValue     asn1.BitString
2350 }
2351
2352 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2353 // extensions in a CSR.
2354 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2355
2356 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2357 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2358 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2359         var rawAttributes []asn1.RawValue
2360         b, err := asn1.Marshal(attributes)
2361         if err != nil {
2362                 return nil, err
2363         }
2364         rest, err := asn1.Unmarshal(b, &rawAttributes)
2365         if err != nil {
2366                 return nil, err
2367         }
2368         if len(rest) != 0 {
2369                 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2370         }
2371         return rawAttributes, nil
2372 }
2373
2374 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2375 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2376         var attributes []pkix.AttributeTypeAndValueSET
2377         for _, rawAttr := range rawAttributes {
2378                 var attr pkix.AttributeTypeAndValueSET
2379                 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2380                 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2381                 // (i.e.: challengePassword or unstructuredName).
2382                 if err == nil && len(rest) == 0 {
2383                         attributes = append(attributes, attr)
2384                 }
2385         }
2386         return attributes
2387 }
2388
2389 // parseCSRExtensions parses the attributes from a CSR and extracts any
2390 // requested extensions.
2391 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2392         // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2393         type pkcs10Attribute struct {
2394                 Id     asn1.ObjectIdentifier
2395                 Values []asn1.RawValue `asn1:"set"`
2396         }
2397
2398         var ret []pkix.Extension
2399         for _, rawAttr := range rawAttributes {
2400                 var attr pkcs10Attribute
2401                 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2402                         // Ignore attributes that don't parse.
2403                         continue
2404                 }
2405
2406                 if !attr.Id.Equal(oidExtensionRequest) {
2407                         continue
2408                 }
2409
2410                 var extensions []pkix.Extension
2411                 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2412                         return nil, err
2413                 }
2414                 ret = append(ret, extensions...)
2415         }
2416
2417         return ret, nil
2418 }
2419
2420 // CreateCertificateRequest creates a new certificate request based on a
2421 // template. The following members of template are used:
2422 //
2423 //  - SignatureAlgorithm
2424 //  - Subject
2425 //  - DNSNames
2426 //  - EmailAddresses
2427 //  - IPAddresses
2428 //  - URIs
2429 //  - ExtraExtensions
2430 //  - Attributes (deprecated)
2431 //
2432 // priv is the private key to sign the CSR with, and the corresponding public
2433 // key will be included in the CSR. It must implement crypto.Signer and its
2434 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2435 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2436 // ed25519.PrivateKey satisfies this.)
2437 //
2438 // The returned slice is the certificate request in DER encoding.
2439 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2440         key, ok := priv.(crypto.Signer)
2441         if !ok {
2442                 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2443         }
2444
2445         var hashFunc crypto.Hash
2446         var sigAlgo pkix.AlgorithmIdentifier
2447         hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2448         if err != nil {
2449                 return nil, err
2450         }
2451
2452         var publicKeyBytes []byte
2453         var publicKeyAlgorithm pkix.AlgorithmIdentifier
2454         publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2455         if err != nil {
2456                 return nil, err
2457         }
2458
2459         var extensions []pkix.Extension
2460
2461         if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2462                 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2463                 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2464                 if err != nil {
2465                         return nil, err
2466                 }
2467
2468                 extensions = append(extensions, pkix.Extension{
2469                         Id:    oidExtensionSubjectAltName,
2470                         Value: sanBytes,
2471                 })
2472         }
2473
2474         extensions = append(extensions, template.ExtraExtensions...)
2475
2476         // Make a copy of template.Attributes because we may alter it below.
2477         attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2478         for _, attr := range template.Attributes {
2479                 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2480                 copy(values, attr.Value)
2481                 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2482                         Type:  attr.Type,
2483                         Value: values,
2484                 })
2485         }
2486
2487         extensionsAppended := false
2488         if len(extensions) > 0 {
2489                 // Append the extensions to an existing attribute if possible.
2490                 for _, atvSet := range attributes {
2491                         if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2492                                 continue
2493                         }
2494
2495                         // specifiedExtensions contains all the extensions that we
2496                         // found specified via template.Attributes.
2497                         specifiedExtensions := make(map[string]bool)
2498
2499                         for _, atvs := range atvSet.Value {
2500                                 for _, atv := range atvs {
2501                                         specifiedExtensions[atv.Type.String()] = true
2502                                 }
2503                         }
2504
2505                         newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2506                         newValue = append(newValue, atvSet.Value[0]...)
2507
2508                         for _, e := range extensions {
2509                                 if specifiedExtensions[e.Id.String()] {
2510                                         // Attributes already contained a value for
2511                                         // this extension and it takes priority.
2512                                         continue
2513                                 }
2514
2515                                 newValue = append(newValue, pkix.AttributeTypeAndValue{
2516                                         // There is no place for the critical
2517                                         // flag in an AttributeTypeAndValue.
2518                                         Type:  e.Id,
2519                                         Value: e.Value,
2520                                 })
2521                         }
2522
2523                         atvSet.Value[0] = newValue
2524                         extensionsAppended = true
2525                         break
2526                 }
2527         }
2528
2529         rawAttributes, err := newRawAttributes(attributes)
2530         if err != nil {
2531                 return
2532         }
2533
2534         // If not included in attributes, add a new attribute for the
2535         // extensions.
2536         if len(extensions) > 0 && !extensionsAppended {
2537                 attr := struct {
2538                         Type  asn1.ObjectIdentifier
2539                         Value [][]pkix.Extension `asn1:"set"`
2540                 }{
2541                         Type:  oidExtensionRequest,
2542                         Value: [][]pkix.Extension{extensions},
2543                 }
2544
2545                 b, err := asn1.Marshal(attr)
2546                 if err != nil {
2547                         return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2548                 }
2549
2550                 var rawValue asn1.RawValue
2551                 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2552                         return nil, err
2553                 }
2554
2555                 rawAttributes = append(rawAttributes, rawValue)
2556         }
2557
2558         asn1Subject := template.RawSubject
2559         if len(asn1Subject) == 0 {
2560                 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2561                 if err != nil {
2562                         return nil, err
2563                 }
2564         }
2565
2566         tbsCSR := tbsCertificateRequest{
2567                 Version: 0, // PKCS #10, RFC 2986
2568                 Subject: asn1.RawValue{FullBytes: asn1Subject},
2569                 PublicKey: publicKeyInfo{
2570                         Algorithm: publicKeyAlgorithm,
2571                         PublicKey: asn1.BitString{
2572                                 Bytes:     publicKeyBytes,
2573                                 BitLength: len(publicKeyBytes) * 8,
2574                         },
2575                 },
2576                 RawAttributes: rawAttributes,
2577         }
2578
2579         tbsCSRContents, err := asn1.Marshal(tbsCSR)
2580         if err != nil {
2581                 return
2582         }
2583         tbsCSR.Raw = tbsCSRContents
2584
2585         signed := tbsCSRContents
2586         if hashFunc != 0 {
2587                 h := hashFunc.New()
2588                 h.Write(signed)
2589                 signed = h.Sum(nil)
2590         }
2591
2592         var signature []byte
2593         signature, err = key.Sign(rand, signed, hashFunc)
2594         if err != nil {
2595                 return
2596         }
2597
2598         return asn1.Marshal(certificateRequest{
2599                 TBSCSR:             tbsCSR,
2600                 SignatureAlgorithm: sigAlgo,
2601                 SignatureValue: asn1.BitString{
2602                         Bytes:     signature,
2603                         BitLength: len(signature) * 8,
2604                 },
2605         })
2606 }
2607
2608 // ParseCertificateRequest parses a single certificate request from the
2609 // given ASN.1 DER data.
2610 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2611         var csr certificateRequest
2612
2613         rest, err := asn1.Unmarshal(asn1Data, &csr)
2614         if err != nil {
2615                 return nil, err
2616         } else if len(rest) != 0 {
2617                 return nil, asn1.SyntaxError{Msg: "trailing data"}
2618         }
2619
2620         return parseCertificateRequest(&csr)
2621 }
2622
2623 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2624         out := &CertificateRequest{
2625                 Raw:                      in.Raw,
2626                 RawTBSCertificateRequest: in.TBSCSR.Raw,
2627                 RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
2628                 RawSubject:               in.TBSCSR.Subject.FullBytes,
2629
2630                 Signature:          in.SignatureValue.RightAlign(),
2631                 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2632
2633                 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2634
2635                 Version:    in.TBSCSR.Version,
2636                 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2637         }
2638
2639         var err error
2640         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2641         if err != nil {
2642                 return nil, err
2643         }
2644
2645         var subject pkix.RDNSequence
2646         if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2647                 return nil, err
2648         } else if len(rest) != 0 {
2649                 return nil, errors.New("x509: trailing data after X.509 Subject")
2650         }
2651
2652         out.Subject.FillFromRDNSequence(&subject)
2653
2654         if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2655                 return nil, err
2656         }
2657
2658         for _, extension := range out.Extensions {
2659                 if extension.Id.Equal(oidExtensionSubjectAltName) {
2660                         out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2661                         if err != nil {
2662                                 return nil, err
2663                         }
2664                 }
2665         }
2666
2667         return out, nil
2668 }
2669
2670 // CheckSignature reports whether the signature on c is valid.
2671 func (c *CertificateRequest) CheckSignature() error {
2672         return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2673 }
2674
2675 // RevocationList contains the fields used to create an X.509 v2 Certificate
2676 // Revocation list with CreateRevocationList.
2677 type RevocationList struct {
2678         // SignatureAlgorithm is used to determine the signature algorithm to be
2679         // used when signing the CRL. If 0 the default algorithm for the signing
2680         // key will be used.
2681         SignatureAlgorithm SignatureAlgorithm
2682
2683         // RevokedCertificates is used to populate the revokedCertificates
2684         // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2685         // in which case an empty CRL will be created.
2686         RevokedCertificates []pkix.RevokedCertificate
2687
2688         // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2689         // which should be a monotonically increasing sequence number for a given
2690         // CRL scope and CRL issuer.
2691         Number *big.Int
2692         // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2693         // indicates the issuance date of the CRL.
2694         ThisUpdate time.Time
2695         // NextUpdate is used to populate the nextUpdate field in the CRL, which
2696         // indicates the date by which the next CRL will be issued. NextUpdate
2697         // must be greater than ThisUpdate.
2698         NextUpdate time.Time
2699         // ExtraExtensions contains any additional extensions to add directly to
2700         // the CRL.
2701         ExtraExtensions []pkix.Extension
2702 }
2703
2704 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2705 // according to RFC 5280, based on template.
2706 //
2707 // The CRL is signed by priv which should be the private key associated with
2708 // the public key in the issuer certificate.
2709 //
2710 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2711 // order to use it as a CRL issuer.
2712 //
2713 // The issuer distinguished name CRL field and authority key identifier
2714 // extension are populated using the issuer certificate. issuer must have
2715 // SubjectKeyId set.
2716 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2717         if template == nil {
2718                 return nil, errors.New("x509: template can not be nil")
2719         }
2720         if issuer == nil {
2721                 return nil, errors.New("x509: issuer can not be nil")
2722         }
2723         if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2724                 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2725         }
2726         if len(issuer.SubjectKeyId) == 0 {
2727                 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2728         }
2729         if template.NextUpdate.Before(template.ThisUpdate) {
2730                 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2731         }
2732         if template.Number == nil {
2733                 return nil, errors.New("x509: template contains nil Number field")
2734         }
2735
2736         hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2737         if err != nil {
2738                 return nil, err
2739         }
2740
2741         // Force revocation times to UTC per RFC 5280.
2742         revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2743         for i, rc := range template.RevokedCertificates {
2744                 rc.RevocationTime = rc.RevocationTime.UTC()
2745                 revokedCertsUTC[i] = rc
2746         }
2747
2748         aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2749         if err != nil {
2750                 return nil, err
2751         }
2752         crlNum, err := asn1.Marshal(template.Number)
2753         if err != nil {
2754                 return nil, err
2755         }
2756
2757         tbsCertList := pkix.TBSCertificateList{
2758                 Version:    1, // v2
2759                 Signature:  signatureAlgorithm,
2760                 Issuer:     issuer.Subject.ToRDNSequence(),
2761                 ThisUpdate: template.ThisUpdate.UTC(),
2762                 NextUpdate: template.NextUpdate.UTC(),
2763                 Extensions: []pkix.Extension{
2764                         {
2765                                 Id:    oidExtensionAuthorityKeyId,
2766                                 Value: aki,
2767                         },
2768                         {
2769                                 Id:    oidExtensionCRLNumber,
2770                                 Value: crlNum,
2771                         },
2772                 },
2773         }
2774         if len(revokedCertsUTC) > 0 {
2775                 tbsCertList.RevokedCertificates = revokedCertsUTC
2776         }
2777
2778         if len(template.ExtraExtensions) > 0 {
2779                 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2780         }
2781
2782         tbsCertListContents, err := asn1.Marshal(tbsCertList)
2783         if err != nil {
2784                 return nil, err
2785         }
2786
2787         input := tbsCertListContents
2788         if hashFunc != 0 {
2789                 h := hashFunc.New()
2790                 h.Write(tbsCertListContents)
2791                 input = h.Sum(nil)
2792         }
2793         var signerOpts crypto.SignerOpts = hashFunc
2794         if template.SignatureAlgorithm.isRSAPSS() {
2795                 signerOpts = &rsa.PSSOptions{
2796                         SaltLength: rsa.PSSSaltLengthEqualsHash,
2797                         Hash:       hashFunc,
2798                 }
2799         }
2800
2801         signature, err := priv.Sign(rand, input, signerOpts)
2802         if err != nil {
2803                 return nil, err
2804         }
2805
2806         return asn1.Marshal(pkix.CertificateList{
2807                 TBSCertList:        tbsCertList,
2808                 SignatureAlgorithm: signatureAlgorithm,
2809                 SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2810         })
2811 }