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