Imported Upstream version 4.7.3
[platform/upstream/gcc48.git] / libgo / go / crypto / x509 / x509.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package x509 parses X.509-encoded keys and certificates.
6 package x509
7
8 import (
9         "bytes"
10         "crypto"
11         "crypto/dsa"
12         "crypto/rsa"
13         "crypto/sha1"
14         "crypto/x509/pkix"
15         "encoding/asn1"
16         "encoding/pem"
17         "errors"
18         "io"
19         "math/big"
20         "time"
21 )
22
23 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
24 // in RFC 3280.
25 type pkixPublicKey struct {
26         Algo      pkix.AlgorithmIdentifier
27         BitString asn1.BitString
28 }
29
30 // ParsePKIXPublicKey parses a DER encoded public key. These values are
31 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
32 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
33         var pki publicKeyInfo
34         if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
35                 return
36         }
37         algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
38         if algo == UnknownPublicKeyAlgorithm {
39                 return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
40         }
41         return parsePublicKey(algo, &pki)
42 }
43
44 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
45 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
46         var pubBytes []byte
47
48         switch pub := pub.(type) {
49         case *rsa.PublicKey:
50                 pubBytes, _ = asn1.Marshal(rsaPublicKey{
51                         N: pub.N,
52                         E: pub.E,
53                 })
54         default:
55                 return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
56         }
57
58         pkix := pkixPublicKey{
59                 Algo: pkix.AlgorithmIdentifier{
60                         Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
61                         // This is a NULL parameters value which is technically
62                         // superfluous, but most other code includes it and, by
63                         // doing this, we match their public key hashes.
64                         Parameters: asn1.RawValue{
65                                 Tag: 5,
66                         },
67                 },
68                 BitString: asn1.BitString{
69                         Bytes:     pubBytes,
70                         BitLength: 8 * len(pubBytes),
71                 },
72         }
73
74         ret, _ := asn1.Marshal(pkix)
75         return ret, nil
76 }
77
78 // These structures reflect the ASN.1 structure of X.509 certificates.:
79
80 type certificate struct {
81         Raw                asn1.RawContent
82         TBSCertificate     tbsCertificate
83         SignatureAlgorithm pkix.AlgorithmIdentifier
84         SignatureValue     asn1.BitString
85 }
86
87 type tbsCertificate struct {
88         Raw                asn1.RawContent
89         Version            int `asn1:"optional,explicit,default:1,tag:0"`
90         SerialNumber       *big.Int
91         SignatureAlgorithm pkix.AlgorithmIdentifier
92         Issuer             asn1.RawValue
93         Validity           validity
94         Subject            asn1.RawValue
95         PublicKey          publicKeyInfo
96         UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
97         SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
98         Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
99 }
100
101 type dsaAlgorithmParameters struct {
102         P, Q, G *big.Int
103 }
104
105 type dsaSignature struct {
106         R, S *big.Int
107 }
108
109 type validity struct {
110         NotBefore, NotAfter time.Time
111 }
112
113 type publicKeyInfo struct {
114         Raw       asn1.RawContent
115         Algorithm pkix.AlgorithmIdentifier
116         PublicKey asn1.BitString
117 }
118
119 // RFC 5280,  4.2.1.1
120 type authKeyId struct {
121         Id []byte `asn1:"optional,tag:0"`
122 }
123
124 type SignatureAlgorithm int
125
126 const (
127         UnknownSignatureAlgorithm SignatureAlgorithm = iota
128         MD2WithRSA
129         MD5WithRSA
130         SHA1WithRSA
131         SHA256WithRSA
132         SHA384WithRSA
133         SHA512WithRSA
134         DSAWithSHA1
135         DSAWithSHA256
136 )
137
138 type PublicKeyAlgorithm int
139
140 const (
141         UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
142         RSA
143         DSA
144 )
145
146 // OIDs for signature algorithms
147 //
148 // pkcs-1 OBJECT IDENTIFIER ::= {
149 //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
150 // 
151 // 
152 // RFC 3279 2.2.1 RSA Signature Algorithms
153 //
154 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
155 //
156 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
157 //
158 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
159 // 
160 // dsaWithSha1 OBJECT IDENTIFIER ::= {
161 //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 
162 //
163 //
164 // RFC 4055 5 PKCS #1 Version 1.5
165 // 
166 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
167 //
168 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
169 //
170 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
171 //
172 //
173 // RFC 5758 3.1 DSA Signature Algorithms
174 //
175 // dsaWithSha256 OBJECT IDENTIFIER ::= {
176 //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
177 //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
178 //
179 var (
180         oidSignatureMD2WithRSA    = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
181         oidSignatureMD5WithRSA    = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
182         oidSignatureSHA1WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
183         oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
184         oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
185         oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
186         oidSignatureDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
187         oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
188 )
189
190 func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
191         switch {
192         case oid.Equal(oidSignatureMD2WithRSA):
193                 return MD2WithRSA
194         case oid.Equal(oidSignatureMD5WithRSA):
195                 return MD5WithRSA
196         case oid.Equal(oidSignatureSHA1WithRSA):
197                 return SHA1WithRSA
198         case oid.Equal(oidSignatureSHA256WithRSA):
199                 return SHA256WithRSA
200         case oid.Equal(oidSignatureSHA384WithRSA):
201                 return SHA384WithRSA
202         case oid.Equal(oidSignatureSHA512WithRSA):
203                 return SHA512WithRSA
204         case oid.Equal(oidSignatureDSAWithSHA1):
205                 return DSAWithSHA1
206         case oid.Equal(oidSignatureDSAWithSHA256):
207                 return DSAWithSHA256
208         }
209         return UnknownSignatureAlgorithm
210 }
211
212 // RFC 3279, 2.3 Public Key Algorithms
213 //
214 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
215 //    rsadsi(113549) pkcs(1) 1 }
216 //
217 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
218 //
219 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
220 //    x9-57(10040) x9cm(4) 1 }
221 var (
222         oidPublicKeyRsa = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
223         oidPublicKeyDsa = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
224 )
225
226 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
227         switch {
228         case oid.Equal(oidPublicKeyRsa):
229                 return RSA
230         case oid.Equal(oidPublicKeyDsa):
231                 return DSA
232         }
233         return UnknownPublicKeyAlgorithm
234 }
235
236 // KeyUsage represents the set of actions that are valid for a given key. It's
237 // a bitmap of the KeyUsage* constants.
238 type KeyUsage int
239
240 const (
241         KeyUsageDigitalSignature KeyUsage = 1 << iota
242         KeyUsageContentCommitment
243         KeyUsageKeyEncipherment
244         KeyUsageDataEncipherment
245         KeyUsageKeyAgreement
246         KeyUsageCertSign
247         KeyUsageCRLSign
248         KeyUsageEncipherOnly
249         KeyUsageDecipherOnly
250 )
251
252 // RFC 5280, 4.2.1.12  Extended Key Usage
253 //
254 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
255 //
256 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
257 //
258 // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
259 // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
260 // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
261 // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
262 // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
263 // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
264 var (
265         oidExtKeyUsageAny             = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
266         oidExtKeyUsageServerAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
267         oidExtKeyUsageClientAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
268         oidExtKeyUsageCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
269         oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
270         oidExtKeyUsageTimeStamping    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
271         oidExtKeyUsageOCSPSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
272 )
273
274 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
275 // Each of the ExtKeyUsage* constants define a unique action.
276 type ExtKeyUsage int
277
278 const (
279         ExtKeyUsageAny ExtKeyUsage = iota
280         ExtKeyUsageServerAuth
281         ExtKeyUsageClientAuth
282         ExtKeyUsageCodeSigning
283         ExtKeyUsageEmailProtection
284         ExtKeyUsageTimeStamping
285         ExtKeyUsageOCSPSigning
286 )
287
288 // A Certificate represents an X.509 certificate.
289 type Certificate struct {
290         Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
291         RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
292         RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
293         RawSubject              []byte // DER encoded Subject
294         RawIssuer               []byte // DER encoded Issuer
295
296         Signature          []byte
297         SignatureAlgorithm SignatureAlgorithm
298
299         PublicKeyAlgorithm PublicKeyAlgorithm
300         PublicKey          interface{}
301
302         Version             int
303         SerialNumber        *big.Int
304         Issuer              pkix.Name
305         Subject             pkix.Name
306         NotBefore, NotAfter time.Time // Validity bounds.
307         KeyUsage            KeyUsage
308
309         ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
310         UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
311
312         BasicConstraintsValid bool // if true then the next two fields are valid.
313         IsCA                  bool
314         MaxPathLen            int
315
316         SubjectKeyId   []byte
317         AuthorityKeyId []byte
318
319         // Subject Alternate Name values
320         DNSNames       []string
321         EmailAddresses []string
322
323         // Name constraints
324         PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
325         PermittedDNSDomains         []string
326
327         PolicyIdentifiers []asn1.ObjectIdentifier
328 }
329
330 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
331 // involves algorithms that are not currently implemented.
332 var ErrUnsupportedAlgorithm = errors.New("crypto/x509: cannot verify signature: algorithm unimplemented")
333
334 // ConstraintViolationError results when a requested usage is not permitted by
335 // a certificate. For example: checking a signature when the public key isn't a
336 // certificate signing key.
337 type ConstraintViolationError struct{}
338
339 func (ConstraintViolationError) Error() string {
340         return "crypto/x509: invalid signature: parent certificate cannot sign this kind of certificate"
341 }
342
343 func (c *Certificate) Equal(other *Certificate) bool {
344         return bytes.Equal(c.Raw, other.Raw)
345 }
346
347 // Entrust have a broken root certificate (CN=Entrust.net Certification
348 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
349 // according to PKIX.
350 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
351 // from the Basic Constraints requirement.
352 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
353 //
354 // TODO(agl): remove this hack once their reissued root is sufficiently
355 // widespread.
356 var entrustBrokenSPKI = []byte{
357         0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
358         0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
359         0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
360         0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
361         0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
362         0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
363         0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
364         0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
365         0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
366         0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
367         0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
368         0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
369         0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
370         0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
371         0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
372         0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
373         0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
374         0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
375         0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
376         0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
377         0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
378         0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
379         0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
380         0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
381         0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
382         0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
383         0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
384         0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
385         0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
386         0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
387         0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
388         0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
389         0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
390         0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
391         0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
392         0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
393         0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
394 }
395
396 // CheckSignatureFrom verifies that the signature on c is a valid signature
397 // from parent.
398 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
399         // RFC 5280, 4.2.1.9:
400         // "If the basic constraints extension is not present in a version 3
401         // certificate, or the extension is present but the cA boolean is not
402         // asserted, then the certified public key MUST NOT be used to verify
403         // certificate signatures."
404         // (except for Entrust, see comment above entrustBrokenSPKI)
405         if (parent.Version == 3 && !parent.BasicConstraintsValid ||
406                 parent.BasicConstraintsValid && !parent.IsCA) &&
407                 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
408                 return ConstraintViolationError{}
409         }
410
411         if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
412                 return ConstraintViolationError{}
413         }
414
415         if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
416                 return ErrUnsupportedAlgorithm
417         }
418
419         // TODO(agl): don't ignore the path length constraint.
420
421         return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
422 }
423
424 // CheckSignature verifies that signature is a valid signature over signed from
425 // c's public key.
426 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
427         var hashType crypto.Hash
428
429         switch algo {
430         case SHA1WithRSA, DSAWithSHA1:
431                 hashType = crypto.SHA1
432         case SHA256WithRSA, DSAWithSHA256:
433                 hashType = crypto.SHA256
434         case SHA384WithRSA:
435                 hashType = crypto.SHA384
436         case SHA512WithRSA:
437                 hashType = crypto.SHA512
438         default:
439                 return ErrUnsupportedAlgorithm
440         }
441
442         if !hashType.Available() {
443                 return ErrUnsupportedAlgorithm
444         }
445         h := hashType.New()
446
447         h.Write(signed)
448         digest := h.Sum(nil)
449
450         switch pub := c.PublicKey.(type) {
451         case *rsa.PublicKey:
452                 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
453         case *dsa.PublicKey:
454                 dsaSig := new(dsaSignature)
455                 if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
456                         return err
457                 }
458                 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
459                         return errors.New("DSA signature contained zero or negative values")
460                 }
461                 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
462                         return errors.New("DSA verification failure")
463                 }
464                 return
465         }
466         return ErrUnsupportedAlgorithm
467 }
468
469 // CheckCRLSignature checks that the signature in crl is from c.
470 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
471         algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
472         return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
473 }
474
475 type UnhandledCriticalExtension struct{}
476
477 func (h UnhandledCriticalExtension) Error() string {
478         return "unhandled critical extension"
479 }
480
481 type basicConstraints struct {
482         IsCA       bool `asn1:"optional"`
483         MaxPathLen int  `asn1:"optional,default:-1"`
484 }
485
486 // RFC 5280 4.2.1.4
487 type policyInformation struct {
488         Policy asn1.ObjectIdentifier
489         // policyQualifiers omitted
490 }
491
492 // RFC 5280, 4.2.1.10
493 type nameConstraints struct {
494         Permitted []generalSubtree `asn1:"optional,tag:0"`
495         Excluded  []generalSubtree `asn1:"optional,tag:1"`
496 }
497
498 type generalSubtree struct {
499         Name string `asn1:"tag:2,optional,ia5"`
500         Min  int    `asn1:"optional,tag:0"`
501         Max  int    `asn1:"optional,tag:1"`
502 }
503
504 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
505         asn1Data := keyData.PublicKey.RightAlign()
506         switch algo {
507         case RSA:
508                 p := new(rsaPublicKey)
509                 _, err := asn1.Unmarshal(asn1Data, p)
510                 if err != nil {
511                         return nil, err
512                 }
513
514                 pub := &rsa.PublicKey{
515                         E: p.E,
516                         N: p.N,
517                 }
518                 return pub, nil
519         case DSA:
520                 var p *big.Int
521                 _, err := asn1.Unmarshal(asn1Data, &p)
522                 if err != nil {
523                         return nil, err
524                 }
525                 paramsData := keyData.Algorithm.Parameters.FullBytes
526                 params := new(dsaAlgorithmParameters)
527                 _, err = asn1.Unmarshal(paramsData, params)
528                 if err != nil {
529                         return nil, err
530                 }
531                 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
532                         return nil, errors.New("zero or negative DSA parameter")
533                 }
534                 pub := &dsa.PublicKey{
535                         Parameters: dsa.Parameters{
536                                 P: params.P,
537                                 Q: params.Q,
538                                 G: params.G,
539                         },
540                         Y: p,
541                 }
542                 return pub, nil
543         default:
544                 return nil, nil
545         }
546         panic("unreachable")
547 }
548
549 func parseCertificate(in *certificate) (*Certificate, error) {
550         out := new(Certificate)
551         out.Raw = in.Raw
552         out.RawTBSCertificate = in.TBSCertificate.Raw
553         out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
554         out.RawSubject = in.TBSCertificate.Subject.FullBytes
555         out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
556
557         out.Signature = in.SignatureValue.RightAlign()
558         out.SignatureAlgorithm =
559                 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
560
561         out.PublicKeyAlgorithm =
562                 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
563         var err error
564         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
565         if err != nil {
566                 return nil, err
567         }
568
569         if in.TBSCertificate.SerialNumber.Sign() < 0 {
570                 return nil, errors.New("negative serial number")
571         }
572
573         out.Version = in.TBSCertificate.Version + 1
574         out.SerialNumber = in.TBSCertificate.SerialNumber
575
576         var issuer, subject pkix.RDNSequence
577         if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
578                 return nil, err
579         }
580         if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
581                 return nil, err
582         }
583
584         out.Issuer.FillFromRDNSequence(&issuer)
585         out.Subject.FillFromRDNSequence(&subject)
586
587         out.NotBefore = in.TBSCertificate.Validity.NotBefore
588         out.NotAfter = in.TBSCertificate.Validity.NotAfter
589
590         for _, e := range in.TBSCertificate.Extensions {
591                 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
592                         switch e.Id[3] {
593                         case 15:
594                                 // RFC 5280, 4.2.1.3
595                                 var usageBits asn1.BitString
596                                 _, err := asn1.Unmarshal(e.Value, &usageBits)
597
598                                 if err == nil {
599                                         var usage int
600                                         for i := 0; i < 9; i++ {
601                                                 if usageBits.At(i) != 0 {
602                                                         usage |= 1 << uint(i)
603                                                 }
604                                         }
605                                         out.KeyUsage = KeyUsage(usage)
606                                         continue
607                                 }
608                         case 19:
609                                 // RFC 5280, 4.2.1.9
610                                 var constraints basicConstraints
611                                 _, err := asn1.Unmarshal(e.Value, &constraints)
612
613                                 if err == nil {
614                                         out.BasicConstraintsValid = true
615                                         out.IsCA = constraints.IsCA
616                                         out.MaxPathLen = constraints.MaxPathLen
617                                         continue
618                                 }
619                         case 17:
620                                 // RFC 5280, 4.2.1.6
621
622                                 // SubjectAltName ::= GeneralNames
623                                 //
624                                 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
625                                 //
626                                 // GeneralName ::= CHOICE {
627                                 //      otherName                       [0]     OtherName,
628                                 //      rfc822Name                      [1]     IA5String,
629                                 //      dNSName                         [2]     IA5String,
630                                 //      x400Address                     [3]     ORAddress,
631                                 //      directoryName                   [4]     Name,
632                                 //      ediPartyName                    [5]     EDIPartyName,
633                                 //      uniformResourceIdentifier       [6]     IA5String,
634                                 //      iPAddress                       [7]     OCTET STRING,
635                                 //      registeredID                    [8]     OBJECT IDENTIFIER }
636                                 var seq asn1.RawValue
637                                 _, err := asn1.Unmarshal(e.Value, &seq)
638                                 if err != nil {
639                                         return nil, err
640                                 }
641                                 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
642                                         return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
643                                 }
644
645                                 parsedName := false
646
647                                 rest := seq.Bytes
648                                 for len(rest) > 0 {
649                                         var v asn1.RawValue
650                                         rest, err = asn1.Unmarshal(rest, &v)
651                                         if err != nil {
652                                                 return nil, err
653                                         }
654                                         switch v.Tag {
655                                         case 1:
656                                                 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
657                                                 parsedName = true
658                                         case 2:
659                                                 out.DNSNames = append(out.DNSNames, string(v.Bytes))
660                                                 parsedName = true
661                                         }
662                                 }
663
664                                 if parsedName {
665                                         continue
666                                 }
667                                 // If we didn't parse any of the names then we
668                                 // fall through to the critical check below.
669
670                         case 30:
671                                 // RFC 5280, 4.2.1.10
672
673                                 // NameConstraints ::= SEQUENCE {
674                                 //      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
675                                 //      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
676                                 //
677                                 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
678                                 //
679                                 // GeneralSubtree ::= SEQUENCE {
680                                 //      base                    GeneralName,
681                                 //      minimum         [0]     BaseDistance DEFAULT 0,
682                                 //      maximum         [1]     BaseDistance OPTIONAL }
683                                 //
684                                 // BaseDistance ::= INTEGER (0..MAX)
685
686                                 var constraints nameConstraints
687                                 _, err := asn1.Unmarshal(e.Value, &constraints)
688                                 if err != nil {
689                                         return nil, err
690                                 }
691
692                                 if len(constraints.Excluded) > 0 && e.Critical {
693                                         return out, UnhandledCriticalExtension{}
694                                 }
695
696                                 for _, subtree := range constraints.Permitted {
697                                         if subtree.Min > 0 || subtree.Max > 0 || len(subtree.Name) == 0 {
698                                                 if e.Critical {
699                                                         return out, UnhandledCriticalExtension{}
700                                                 }
701                                                 continue
702                                         }
703                                         out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
704                                 }
705                                 continue
706
707                         case 35:
708                                 // RFC 5280, 4.2.1.1
709                                 var a authKeyId
710                                 _, err = asn1.Unmarshal(e.Value, &a)
711                                 if err != nil {
712                                         return nil, err
713                                 }
714                                 out.AuthorityKeyId = a.Id
715                                 continue
716
717                         case 37:
718                                 // RFC 5280, 4.2.1.12.  Extended Key Usage
719
720                                 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
721                                 //
722                                 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
723                                 //
724                                 // KeyPurposeId ::= OBJECT IDENTIFIER
725
726                                 var keyUsage []asn1.ObjectIdentifier
727                                 _, err = asn1.Unmarshal(e.Value, &keyUsage)
728                                 if err != nil {
729                                         return nil, err
730                                 }
731
732                                 for _, u := range keyUsage {
733                                         switch {
734                                         case u.Equal(oidExtKeyUsageAny):
735                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageAny)
736                                         case u.Equal(oidExtKeyUsageServerAuth):
737                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageServerAuth)
738                                         case u.Equal(oidExtKeyUsageClientAuth):
739                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageClientAuth)
740                                         case u.Equal(oidExtKeyUsageCodeSigning):
741                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageCodeSigning)
742                                         case u.Equal(oidExtKeyUsageEmailProtection):
743                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageEmailProtection)
744                                         case u.Equal(oidExtKeyUsageTimeStamping):
745                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageTimeStamping)
746                                         case u.Equal(oidExtKeyUsageOCSPSigning):
747                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageOCSPSigning)
748                                         default:
749                                                 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
750                                         }
751                                 }
752
753                                 continue
754
755                         case 14:
756                                 // RFC 5280, 4.2.1.2
757                                 var keyid []byte
758                                 _, err = asn1.Unmarshal(e.Value, &keyid)
759                                 if err != nil {
760                                         return nil, err
761                                 }
762                                 out.SubjectKeyId = keyid
763                                 continue
764
765                         case 32:
766                                 // RFC 5280 4.2.1.4: Certificate Policies
767                                 var policies []policyInformation
768                                 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
769                                         return nil, err
770                                 }
771                                 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
772                                 for i, policy := range policies {
773                                         out.PolicyIdentifiers[i] = policy.Policy
774                                 }
775                         }
776                 }
777
778                 if e.Critical {
779                         return out, UnhandledCriticalExtension{}
780                 }
781         }
782
783         return out, nil
784 }
785
786 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
787 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
788         var cert certificate
789         rest, err := asn1.Unmarshal(asn1Data, &cert)
790         if err != nil {
791                 return nil, err
792         }
793         if len(rest) > 0 {
794                 return nil, asn1.SyntaxError{Msg: "trailing data"}
795         }
796
797         return parseCertificate(&cert)
798 }
799
800 // ParseCertificates parses one or more certificates from the given ASN.1 DER
801 // data. The certificates must be concatenated with no intermediate padding.
802 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
803         var v []*certificate
804
805         for len(asn1Data) > 0 {
806                 cert := new(certificate)
807                 var err error
808                 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
809                 if err != nil {
810                         return nil, err
811                 }
812                 v = append(v, cert)
813         }
814
815         ret := make([]*Certificate, len(v))
816         for i, ci := range v {
817                 cert, err := parseCertificate(ci)
818                 if err != nil {
819                         return nil, err
820                 }
821                 ret[i] = cert
822         }
823
824         return ret, nil
825 }
826
827 func reverseBitsInAByte(in byte) byte {
828         b1 := in>>4 | in<<4
829         b2 := b1>>2&0x33 | b1<<2&0xcc
830         b3 := b2>>1&0x55 | b2<<1&0xaa
831         return b3
832 }
833
834 var (
835         oidExtensionSubjectKeyId        = []int{2, 5, 29, 14}
836         oidExtensionKeyUsage            = []int{2, 5, 29, 15}
837         oidExtensionAuthorityKeyId      = []int{2, 5, 29, 35}
838         oidExtensionBasicConstraints    = []int{2, 5, 29, 19}
839         oidExtensionSubjectAltName      = []int{2, 5, 29, 17}
840         oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
841         oidExtensionNameConstraints     = []int{2, 5, 29, 30}
842 )
843
844 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
845         ret = make([]pkix.Extension, 7 /* maximum number of elements. */)
846         n := 0
847
848         if template.KeyUsage != 0 {
849                 ret[n].Id = oidExtensionKeyUsage
850                 ret[n].Critical = true
851
852                 var a [2]byte
853                 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
854                 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
855
856                 l := 1
857                 if a[1] != 0 {
858                         l = 2
859                 }
860
861                 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
862                 if err != nil {
863                         return
864                 }
865                 n++
866         }
867
868         if template.BasicConstraintsValid {
869                 ret[n].Id = oidExtensionBasicConstraints
870                 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
871                 ret[n].Critical = true
872                 if err != nil {
873                         return
874                 }
875                 n++
876         }
877
878         if len(template.SubjectKeyId) > 0 {
879                 ret[n].Id = oidExtensionSubjectKeyId
880                 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
881                 if err != nil {
882                         return
883                 }
884                 n++
885         }
886
887         if len(template.AuthorityKeyId) > 0 {
888                 ret[n].Id = oidExtensionAuthorityKeyId
889                 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
890                 if err != nil {
891                         return
892                 }
893                 n++
894         }
895
896         if len(template.DNSNames) > 0 {
897                 ret[n].Id = oidExtensionSubjectAltName
898                 rawValues := make([]asn1.RawValue, len(template.DNSNames))
899                 for i, name := range template.DNSNames {
900                         rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
901                 }
902                 ret[n].Value, err = asn1.Marshal(rawValues)
903                 if err != nil {
904                         return
905                 }
906                 n++
907         }
908
909         if len(template.PolicyIdentifiers) > 0 {
910                 ret[n].Id = oidExtensionCertificatePolicies
911                 policies := make([]policyInformation, len(template.PolicyIdentifiers))
912                 for i, policy := range template.PolicyIdentifiers {
913                         policies[i].Policy = policy
914                 }
915                 ret[n].Value, err = asn1.Marshal(policies)
916                 if err != nil {
917                         return
918                 }
919                 n++
920         }
921
922         if len(template.PermittedDNSDomains) > 0 {
923                 ret[n].Id = oidExtensionNameConstraints
924                 ret[n].Critical = template.PermittedDNSDomainsCritical
925
926                 var out nameConstraints
927                 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
928                 for i, permitted := range template.PermittedDNSDomains {
929                         out.Permitted[i] = generalSubtree{Name: permitted}
930                 }
931                 ret[n].Value, err = asn1.Marshal(out)
932                 if err != nil {
933                         return
934                 }
935                 n++
936         }
937
938         // Adding another extension here? Remember to update the maximum number
939         // of elements in the make() at the top of the function.
940
941         return ret[0:n], nil
942 }
943
944 var (
945         oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
946         oidRSA         = []int{1, 2, 840, 113549, 1, 1, 1}
947 )
948
949 func subjectBytes(cert *Certificate) ([]byte, error) {
950         if len(cert.RawSubject) > 0 {
951                 return cert.RawSubject, nil
952         }
953
954         return asn1.Marshal(cert.Subject.ToRDNSequence())
955 }
956
957 // CreateCertificate creates a new certificate based on a template. The
958 // following members of template are used: SerialNumber, Subject, NotBefore,
959 // NotAfter, KeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId,
960 // DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains.
961 //
962 // The certificate is signed by parent. If parent is equal to template then the
963 // certificate is self-signed. The parameter pub is the public key of the
964 // signee and priv is the private key of the signer.
965 //
966 // The returned slice is the certificate in DER encoding.
967 //
968 // The only supported key type is RSA (*rsa.PublicKey for pub, *rsa.PrivateKey
969 // for priv).
970 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
971         rsaPub, ok := pub.(*rsa.PublicKey)
972         if !ok {
973                 return nil, errors.New("x509: non-RSA public keys not supported")
974         }
975
976         rsaPriv, ok := priv.(*rsa.PrivateKey)
977         if !ok {
978                 return nil, errors.New("x509: non-RSA private keys not supported")
979         }
980
981         asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
982                 N: rsaPub.N,
983                 E: rsaPub.E,
984         })
985         if err != nil {
986                 return
987         }
988
989         if len(parent.SubjectKeyId) > 0 {
990                 template.AuthorityKeyId = parent.SubjectKeyId
991         }
992
993         extensions, err := buildExtensions(template)
994         if err != nil {
995                 return
996         }
997
998         asn1Issuer, err := subjectBytes(parent)
999         if err != nil {
1000                 return
1001         }
1002
1003         asn1Subject, err := subjectBytes(template)
1004         if err != nil {
1005                 return
1006         }
1007
1008         encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
1009         c := tbsCertificate{
1010                 Version:            2,
1011                 SerialNumber:       template.SerialNumber,
1012                 SignatureAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
1013                 Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
1014                 Validity:           validity{template.NotBefore, template.NotAfter},
1015                 Subject:            asn1.RawValue{FullBytes: asn1Subject},
1016                 PublicKey:          publicKeyInfo{nil, pkix.AlgorithmIdentifier{Algorithm: oidRSA}, encodedPublicKey},
1017                 Extensions:         extensions,
1018         }
1019
1020         tbsCertContents, err := asn1.Marshal(c)
1021         if err != nil {
1022                 return
1023         }
1024
1025         c.Raw = tbsCertContents
1026
1027         h := sha1.New()
1028         h.Write(tbsCertContents)
1029         digest := h.Sum(nil)
1030
1031         signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1032         if err != nil {
1033                 return
1034         }
1035
1036         cert, err = asn1.Marshal(certificate{
1037                 nil,
1038                 c,
1039                 pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
1040                 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1041         })
1042         return
1043 }
1044
1045 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1046 // CRL.
1047 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1048
1049 // pemType is the type of a PEM encoded CRL.
1050 var pemType = "X509 CRL"
1051
1052 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1053 // encoded CRLs will appear where they should be DER encoded, so this function
1054 // will transparently handle PEM encoding as long as there isn't any leading
1055 // garbage.
1056 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
1057         if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1058                 block, _ := pem.Decode(crlBytes)
1059                 if block != nil && block.Type == pemType {
1060                         crlBytes = block.Bytes
1061                 }
1062         }
1063         return ParseDERCRL(crlBytes)
1064 }
1065
1066 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1067 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
1068         certList = new(pkix.CertificateList)
1069         _, err = asn1.Unmarshal(derBytes, certList)
1070         if err != nil {
1071                 certList = nil
1072         }
1073         return
1074 }
1075
1076 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1077 // contains the given list of revoked certificates.
1078 //
1079 // The only supported key type is RSA (*rsa.PrivateKey for priv).
1080 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1081         rsaPriv, ok := priv.(*rsa.PrivateKey)
1082         if !ok {
1083                 return nil, errors.New("x509: non-RSA private keys not supported")
1084         }
1085         tbsCertList := pkix.TBSCertificateList{
1086                 Version: 2,
1087                 Signature: pkix.AlgorithmIdentifier{
1088                         Algorithm: oidSignatureSHA1WithRSA,
1089                 },
1090                 Issuer:              c.Subject.ToRDNSequence(),
1091                 ThisUpdate:          now,
1092                 NextUpdate:          expiry,
1093                 RevokedCertificates: revokedCerts,
1094         }
1095
1096         tbsCertListContents, err := asn1.Marshal(tbsCertList)
1097         if err != nil {
1098                 return
1099         }
1100
1101         h := sha1.New()
1102         h.Write(tbsCertListContents)
1103         digest := h.Sum(nil)
1104
1105         signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1106         if err != nil {
1107                 return
1108         }
1109
1110         return asn1.Marshal(pkix.CertificateList{
1111                 TBSCertList: tbsCertList,
1112                 SignatureAlgorithm: pkix.AlgorithmIdentifier{
1113                         Algorithm: oidSignatureSHA1WithRSA,
1114                 },
1115                 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1116         })
1117 }