OSDN Git Service

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