OSDN Git Service

Update to current version of Go library.
[pf3gnuchains/gcc-fork.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         "asn1"
10         "big"
11         "bytes"
12         "container/vector"
13         "crypto"
14         "crypto/rsa"
15         "crypto/sha1"
16         "hash"
17         "io"
18         "os"
19         "time"
20 )
21
22 // pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
23 type pkcs1PrivateKey struct {
24         Version int
25         N       asn1.RawValue
26         E       int
27         D       asn1.RawValue
28         P       asn1.RawValue
29         Q       asn1.RawValue
30         // We ignore these values, if present, because rsa will calculate them.
31         Dp   asn1.RawValue "optional"
32         Dq   asn1.RawValue "optional"
33         Qinv asn1.RawValue "optional"
34
35         AdditionalPrimes []pkcs1AddtionalRSAPrime "optional"
36 }
37
38 type pkcs1AddtionalRSAPrime struct {
39         Prime asn1.RawValue
40
41         // We ignore these values because rsa will calculate them.
42         Exp   asn1.RawValue
43         Coeff asn1.RawValue
44 }
45
46 // rawValueIsInteger returns true iff the given ASN.1 RawValue is an INTEGER type.
47 func rawValueIsInteger(raw *asn1.RawValue) bool {
48         return raw.Class == 0 && raw.Tag == 2 && raw.IsCompound == false
49 }
50
51 // ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
52 func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
53         var priv pkcs1PrivateKey
54         rest, err := asn1.Unmarshal(der, &priv)
55         if len(rest) > 0 {
56                 err = asn1.SyntaxError{"trailing data"}
57                 return
58         }
59         if err != nil {
60                 return
61         }
62
63         if priv.Version > 1 {
64                 return nil, os.ErrorString("x509: unsupported private key version")
65         }
66
67         if !rawValueIsInteger(&priv.N) ||
68                 !rawValueIsInteger(&priv.D) ||
69                 !rawValueIsInteger(&priv.P) ||
70                 !rawValueIsInteger(&priv.Q) {
71                 err = asn1.StructuralError{"tags don't match"}
72                 return
73         }
74
75         key = new(rsa.PrivateKey)
76         key.PublicKey = rsa.PublicKey{
77                 E: priv.E,
78                 N: new(big.Int).SetBytes(priv.N.Bytes),
79         }
80
81         key.D = new(big.Int).SetBytes(priv.D.Bytes)
82         key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
83         key.Primes[0] = new(big.Int).SetBytes(priv.P.Bytes)
84         key.Primes[1] = new(big.Int).SetBytes(priv.Q.Bytes)
85         for i, a := range priv.AdditionalPrimes {
86                 if !rawValueIsInteger(&a.Prime) {
87                         return nil, asn1.StructuralError{"tags don't match"}
88                 }
89                 key.Primes[i+2] = new(big.Int).SetBytes(a.Prime.Bytes)
90                 // We ignore the other two values because rsa will calculate
91                 // them as needed.
92         }
93
94         err = key.Validate()
95         if err != nil {
96                 return nil, err
97         }
98         key.Precompute()
99
100         return
101 }
102
103 // rawValueForBig returns an asn1.RawValue which represents the given integer.
104 func rawValueForBig(n *big.Int) asn1.RawValue {
105         b := n.Bytes()
106         if n.Sign() >= 0 && len(b) > 0 && b[0]&0x80 != 0 {
107                 // This positive number would be interpreted as a negative
108                 // number in ASN.1 because the MSB is set.
109                 padded := make([]byte, len(b)+1)
110                 copy(padded[1:], b)
111                 b = padded
112         }
113         return asn1.RawValue{Tag: 2, Bytes: b}
114 }
115
116 // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
117 func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
118         key.Precompute()
119
120         version := 0
121         if len(key.Primes) > 2 {
122                 version = 1
123         }
124
125         priv := pkcs1PrivateKey{
126                 Version: version,
127                 N:       rawValueForBig(key.N),
128                 E:       key.PublicKey.E,
129                 D:       rawValueForBig(key.D),
130                 P:       rawValueForBig(key.Primes[0]),
131                 Q:       rawValueForBig(key.Primes[1]),
132                 Dp:      rawValueForBig(key.Precomputed.Dp),
133                 Dq:      rawValueForBig(key.Precomputed.Dq),
134                 Qinv:    rawValueForBig(key.Precomputed.Qinv),
135         }
136
137         priv.AdditionalPrimes = make([]pkcs1AddtionalRSAPrime, len(key.Precomputed.CRTValues))
138         for i, values := range key.Precomputed.CRTValues {
139                 priv.AdditionalPrimes[i].Prime = rawValueForBig(key.Primes[2+i])
140                 priv.AdditionalPrimes[i].Exp = rawValueForBig(values.Exp)
141                 priv.AdditionalPrimes[i].Coeff = rawValueForBig(values.Coeff)
142         }
143
144         b, _ := asn1.Marshal(priv)
145         return b
146 }
147
148 // These structures reflect the ASN.1 structure of X.509 certificates.:
149
150 type certificate struct {
151         Raw                asn1.RawContent
152         TBSCertificate     tbsCertificate
153         SignatureAlgorithm algorithmIdentifier
154         SignatureValue     asn1.BitString
155 }
156
157 type tbsCertificate struct {
158         Raw                asn1.RawContent
159         Version            int "optional,explicit,default:1,tag:0"
160         SerialNumber       asn1.RawValue
161         SignatureAlgorithm algorithmIdentifier
162         Issuer             rdnSequence
163         Validity           validity
164         Subject            rdnSequence
165         PublicKey          publicKeyInfo
166         UniqueId           asn1.BitString "optional,tag:1"
167         SubjectUniqueId    asn1.BitString "optional,tag:2"
168         Extensions         []extension    "optional,explicit,tag:3"
169 }
170
171 type algorithmIdentifier struct {
172         Algorithm asn1.ObjectIdentifier
173 }
174
175 type rdnSequence []relativeDistinguishedNameSET
176
177 type relativeDistinguishedNameSET []attributeTypeAndValue
178
179 type attributeTypeAndValue struct {
180         Type  asn1.ObjectIdentifier
181         Value interface{}
182 }
183
184 type validity struct {
185         NotBefore, NotAfter *time.Time
186 }
187
188 type publicKeyInfo struct {
189         Raw       asn1.RawContent
190         Algorithm algorithmIdentifier
191         PublicKey asn1.BitString
192 }
193
194 type extension struct {
195         Id       asn1.ObjectIdentifier
196         Critical bool "optional"
197         Value    []byte
198 }
199
200 // RFC 5280,  4.2.1.1
201 type authKeyId struct {
202         Id []byte "optional,tag:0"
203 }
204
205 type SignatureAlgorithm int
206
207 const (
208         UnknownSignatureAlgorithm SignatureAlgorithm = iota
209         MD2WithRSA
210         MD5WithRSA
211         SHA1WithRSA
212         SHA256WithRSA
213         SHA384WithRSA
214         SHA512WithRSA
215 )
216
217 type PublicKeyAlgorithm int
218
219 const (
220         UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
221         RSA
222 )
223
224 // Name represents an X.509 distinguished name. This only includes the common
225 // elements of a DN.  Additional elements in the name are ignored.
226 type Name struct {
227         Country, Organization, OrganizationalUnit []string
228         Locality, Province                        []string
229         StreetAddress, PostalCode                 []string
230         SerialNumber, CommonName                  string
231 }
232
233 func (n *Name) fillFromRDNSequence(rdns *rdnSequence) {
234         for _, rdn := range *rdns {
235                 if len(rdn) == 0 {
236                         continue
237                 }
238                 atv := rdn[0]
239                 value, ok := atv.Value.(string)
240                 if !ok {
241                         continue
242                 }
243
244                 t := atv.Type
245                 if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
246                         switch t[3] {
247                         case 3:
248                                 n.CommonName = value
249                         case 5:
250                                 n.SerialNumber = value
251                         case 6:
252                                 n.Country = append(n.Country, value)
253                         case 7:
254                                 n.Locality = append(n.Locality, value)
255                         case 8:
256                                 n.Province = append(n.Province, value)
257                         case 9:
258                                 n.StreetAddress = append(n.StreetAddress, value)
259                         case 10:
260                                 n.Organization = append(n.Organization, value)
261                         case 11:
262                                 n.OrganizationalUnit = append(n.OrganizationalUnit, value)
263                         case 17:
264                                 n.PostalCode = append(n.PostalCode, value)
265                         }
266                 }
267         }
268 }
269
270 var (
271         oidCountry            = []int{2, 5, 4, 6}
272         oidOrganization       = []int{2, 5, 4, 10}
273         oidOrganizationalUnit = []int{2, 5, 4, 11}
274         oidCommonName         = []int{2, 5, 4, 3}
275         oidSerialNumber       = []int{2, 5, 4, 5}
276         oidLocatity           = []int{2, 5, 4, 7}
277         oidProvince           = []int{2, 5, 4, 8}
278         oidStreetAddress      = []int{2, 5, 4, 9}
279         oidPostalCode         = []int{2, 5, 4, 17}
280 )
281
282 // appendRDNs appends a relativeDistinguishedNameSET to the given rdnSequence
283 // and returns the new value. The relativeDistinguishedNameSET contains an
284 // attributeTypeAndValue for each of the given values. See RFC 5280, A.1, and
285 // search for AttributeTypeAndValue.
286 func appendRDNs(in rdnSequence, values []string, oid asn1.ObjectIdentifier) rdnSequence {
287         if len(values) == 0 {
288                 return in
289         }
290
291         s := make([]attributeTypeAndValue, len(values))
292         for i, value := range values {
293                 s[i].Type = oid
294                 s[i].Value = value
295         }
296
297         return append(in, s)
298 }
299
300 func (n Name) toRDNSequence() (ret rdnSequence) {
301         ret = appendRDNs(ret, n.Country, oidCountry)
302         ret = appendRDNs(ret, n.Organization, oidOrganization)
303         ret = appendRDNs(ret, n.OrganizationalUnit, oidOrganizationalUnit)
304         ret = appendRDNs(ret, n.Locality, oidLocatity)
305         ret = appendRDNs(ret, n.Province, oidProvince)
306         ret = appendRDNs(ret, n.StreetAddress, oidStreetAddress)
307         ret = appendRDNs(ret, n.PostalCode, oidPostalCode)
308         if len(n.CommonName) > 0 {
309                 ret = appendRDNs(ret, []string{n.CommonName}, oidCommonName)
310         }
311         if len(n.SerialNumber) > 0 {
312                 ret = appendRDNs(ret, []string{n.SerialNumber}, oidSerialNumber)
313         }
314
315         return ret
316 }
317
318 func getSignatureAlgorithmFromOID(oid []int) SignatureAlgorithm {
319         if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
320                 oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
321                 switch oid[6] {
322                 case 2:
323                         return MD2WithRSA
324                 case 4:
325                         return MD5WithRSA
326                 case 5:
327                         return SHA1WithRSA
328                 case 11:
329                         return SHA256WithRSA
330                 case 12:
331                         return SHA384WithRSA
332                 case 13:
333                         return SHA512WithRSA
334                 }
335         }
336
337         return UnknownSignatureAlgorithm
338 }
339
340 func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
341         if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
342                 oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
343                 switch oid[6] {
344                 case 1:
345                         return RSA
346                 }
347         }
348
349         return UnknownPublicKeyAlgorithm
350 }
351
352 // KeyUsage represents the set of actions that are valid for a given key. It's
353 // a bitmap of the KeyUsage* constants.
354 type KeyUsage int
355
356 const (
357         KeyUsageDigitalSignature KeyUsage = 1 << iota
358         KeyUsageContentCommitment
359         KeyUsageKeyEncipherment
360         KeyUsageDataEncipherment
361         KeyUsageKeyAgreement
362         KeyUsageCertSign
363         KeyUsageCRLSign
364         KeyUsageEncipherOnly
365         KeyUsageDecipherOnly
366 )
367
368 // RFC 5280, 4.2.1.12  Extended Key Usage
369 //
370 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
371 //
372 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
373 //
374 // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
375 // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
376 // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
377 // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
378 // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
379 // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
380 var (
381         oidExtKeyUsageAny             = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
382         oidExtKeyUsageServerAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
383         oidExtKeyUsageClientAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
384         oidExtKeyUsageCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
385         oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
386         oidExtKeyUsageTimeStamping    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
387         oidExtKeyUsageOCSPSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
388 )
389
390 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
391 // Each of the ExtKeyUsage* constants define a unique action.
392 type ExtKeyUsage int
393
394 const (
395         ExtKeyUsageAny ExtKeyUsage = iota
396         ExtKeyUsageServerAuth
397         ExtKeyUsageClientAuth
398         ExtKeyUsageCodeSigning
399         ExtKeyUsageEmailProtection
400         ExtKeyUsageTimeStamping
401         ExtKeyUsageOCSPSigning
402 )
403
404 // A Certificate represents an X.509 certificate.
405 type Certificate struct {
406         Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
407         RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
408         RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
409
410         Signature          []byte
411         SignatureAlgorithm SignatureAlgorithm
412
413         PublicKeyAlgorithm PublicKeyAlgorithm
414         PublicKey          interface{}
415
416         Version             int
417         SerialNumber        []byte
418         Issuer              Name
419         Subject             Name
420         NotBefore, NotAfter *time.Time // Validity bounds.
421         KeyUsage            KeyUsage
422
423         ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
424         UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
425
426         BasicConstraintsValid bool // if true then the next two fields are valid.
427         IsCA                  bool
428         MaxPathLen            int
429
430         SubjectKeyId   []byte
431         AuthorityKeyId []byte
432
433         // Subject Alternate Name values
434         DNSNames       []string
435         EmailAddresses []string
436
437         // Name constraints
438         PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
439         PermittedDNSDomains         []string
440
441         PolicyIdentifiers []asn1.ObjectIdentifier
442 }
443
444 // UnsupportedAlgorithmError results from attempting to perform an operation
445 // that involves algorithms that are not currently implemented.
446 type UnsupportedAlgorithmError struct{}
447
448 func (UnsupportedAlgorithmError) String() string {
449         return "cannot verify signature: algorithm unimplemented"
450 }
451
452 // ConstraintViolationError results when a requested usage is not permitted by
453 // a certificate. For example: checking a signature when the public key isn't a
454 // certificate signing key.
455 type ConstraintViolationError struct{}
456
457 func (ConstraintViolationError) String() string {
458         return "invalid signature: parent certificate cannot sign this kind of certificate"
459 }
460
461 func (c *Certificate) Equal(other *Certificate) bool {
462         return bytes.Equal(c.Raw, other.Raw)
463 }
464
465 // CheckSignatureFrom verifies that the signature on c is a valid signature
466 // from parent.
467 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) {
468         // RFC 5280, 4.2.1.9:
469         // "If the basic constraints extension is not present in a version 3
470         // certificate, or the extension is present but the cA boolean is not
471         // asserted, then the certified public key MUST NOT be used to verify
472         // certificate signatures."
473         if parent.Version == 3 && !parent.BasicConstraintsValid ||
474                 parent.BasicConstraintsValid && !parent.IsCA {
475                 return ConstraintViolationError{}
476         }
477
478         if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
479                 return ConstraintViolationError{}
480         }
481
482         if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
483                 return UnsupportedAlgorithmError{}
484         }
485
486         // TODO(agl): don't ignore the path length constraint.
487
488         var h hash.Hash
489         var hashType crypto.Hash
490
491         switch c.SignatureAlgorithm {
492         case SHA1WithRSA:
493                 h = sha1.New()
494                 hashType = crypto.SHA1
495         default:
496                 return UnsupportedAlgorithmError{}
497         }
498
499         pub, ok := parent.PublicKey.(*rsa.PublicKey)
500         if !ok {
501                 return UnsupportedAlgorithmError{}
502         }
503
504         h.Write(c.RawTBSCertificate)
505         digest := h.Sum()
506
507         return rsa.VerifyPKCS1v15(pub, hashType, digest, c.Signature)
508 }
509
510 type UnhandledCriticalExtension struct{}
511
512 func (h UnhandledCriticalExtension) String() string {
513         return "unhandled critical extension"
514 }
515
516 type basicConstraints struct {
517         IsCA       bool "optional"
518         MaxPathLen int  "optional"
519 }
520
521 type rsaPublicKey struct {
522         N asn1.RawValue
523         E int
524 }
525
526 // RFC 5280 4.2.1.4
527 type policyInformation struct {
528         Policy asn1.ObjectIdentifier
529         // policyQualifiers omitted
530 }
531
532 // RFC 5280, 4.2.1.10
533 type nameConstraints struct {
534         Permitted []generalSubtree "optional,tag:0"
535         Excluded  []generalSubtree "optional,tag:1"
536 }
537
538 type generalSubtree struct {
539         Name string "tag:2,optional,ia5"
540         Min  int    "optional,tag:0"
541         Max  int    "optional,tag:1"
542 }
543
544 func parsePublicKey(algo PublicKeyAlgorithm, asn1Data []byte) (interface{}, os.Error) {
545         switch algo {
546         case RSA:
547                 p := new(rsaPublicKey)
548                 _, err := asn1.Unmarshal(asn1Data, p)
549                 if err != nil {
550                         return nil, err
551                 }
552
553                 if !rawValueIsInteger(&p.N) {
554                         return nil, asn1.StructuralError{"tags don't match"}
555                 }
556
557                 pub := &rsa.PublicKey{
558                         E: p.E,
559                         N: new(big.Int).SetBytes(p.N.Bytes),
560                 }
561                 return pub, nil
562         default:
563                 return nil, nil
564         }
565
566         panic("unreachable")
567 }
568
569 func parseCertificate(in *certificate) (*Certificate, os.Error) {
570         out := new(Certificate)
571         out.Raw = in.Raw
572         out.RawTBSCertificate = in.TBSCertificate.Raw
573         out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
574
575         out.Signature = in.SignatureValue.RightAlign()
576         out.SignatureAlgorithm =
577                 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
578
579         out.PublicKeyAlgorithm =
580                 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
581         var err os.Error
582         out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, in.TBSCertificate.PublicKey.PublicKey.RightAlign())
583         if err != nil {
584                 return nil, err
585         }
586
587         out.Version = in.TBSCertificate.Version + 1
588         out.SerialNumber = in.TBSCertificate.SerialNumber.Bytes
589         out.Issuer.fillFromRDNSequence(&in.TBSCertificate.Issuer)
590         out.Subject.fillFromRDNSequence(&in.TBSCertificate.Subject)
591         out.NotBefore = in.TBSCertificate.Validity.NotBefore
592         out.NotAfter = in.TBSCertificate.Validity.NotAfter
593
594         for _, e := range in.TBSCertificate.Extensions {
595                 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
596                         switch e.Id[3] {
597                         case 15:
598                                 // RFC 5280, 4.2.1.3
599                                 var usageBits asn1.BitString
600                                 _, err := asn1.Unmarshal(e.Value, &usageBits)
601
602                                 if err == nil {
603                                         var usage int
604                                         for i := 0; i < 9; i++ {
605                                                 if usageBits.At(i) != 0 {
606                                                         usage |= 1 << uint(i)
607                                                 }
608                                         }
609                                         out.KeyUsage = KeyUsage(usage)
610                                         continue
611                                 }
612                         case 19:
613                                 // RFC 5280, 4.2.1.9
614                                 var constriants basicConstraints
615                                 _, err := asn1.Unmarshal(e.Value, &constriants)
616
617                                 if err == nil {
618                                         out.BasicConstraintsValid = true
619                                         out.IsCA = constriants.IsCA
620                                         out.MaxPathLen = constriants.MaxPathLen
621                                         continue
622                                 }
623                         case 17:
624                                 // RFC 5280, 4.2.1.6
625
626                                 // SubjectAltName ::= GeneralNames
627                                 //
628                                 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
629                                 //
630                                 // GeneralName ::= CHOICE {
631                                 //      otherName                       [0]     OtherName,
632                                 //      rfc822Name                      [1]     IA5String,
633                                 //      dNSName                         [2]     IA5String,
634                                 //      x400Address                     [3]     ORAddress,
635                                 //      directoryName                   [4]     Name,
636                                 //      ediPartyName                    [5]     EDIPartyName,
637                                 //      uniformResourceIdentifier       [6]     IA5String,
638                                 //      iPAddress                       [7]     OCTET STRING,
639                                 //      registeredID                    [8]     OBJECT IDENTIFIER }
640                                 var seq asn1.RawValue
641                                 _, err := asn1.Unmarshal(e.Value, &seq)
642                                 if err != nil {
643                                         return nil, err
644                                 }
645                                 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
646                                         return nil, asn1.StructuralError{"bad SAN sequence"}
647                                 }
648
649                                 parsedName := false
650
651                                 rest := seq.Bytes
652                                 for len(rest) > 0 {
653                                         var v asn1.RawValue
654                                         rest, err = asn1.Unmarshal(rest, &v)
655                                         if err != nil {
656                                                 return nil, err
657                                         }
658                                         switch v.Tag {
659                                         case 1:
660                                                 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
661                                                 parsedName = true
662                                         case 2:
663                                                 out.DNSNames = append(out.DNSNames, string(v.Bytes))
664                                                 parsedName = true
665                                         }
666                                 }
667
668                                 if parsedName {
669                                         continue
670                                 }
671                                 // If we didn't parse any of the names then we
672                                 // fall through to the critical check below.
673
674                         case 30:
675                                 // RFC 5280, 4.2.1.10
676
677                                 // NameConstraints ::= SEQUENCE {
678                                 //      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
679                                 //      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
680                                 //
681                                 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
682                                 //
683                                 // GeneralSubtree ::= SEQUENCE {
684                                 //      base                    GeneralName,
685                                 //      minimum         [0]     BaseDistance DEFAULT 0,
686                                 //      maximum         [1]     BaseDistance OPTIONAL }
687                                 //
688                                 // BaseDistance ::= INTEGER (0..MAX)
689
690                                 var constraints nameConstraints
691                                 _, err := asn1.Unmarshal(e.Value, &constraints)
692                                 if err != nil {
693                                         return nil, err
694                                 }
695
696                                 if len(constraints.Excluded) > 0 && e.Critical {
697                                         return out, UnhandledCriticalExtension{}
698                                 }
699
700                                 for _, subtree := range constraints.Permitted {
701                                         if subtree.Min > 0 || subtree.Max > 0 || len(subtree.Name) == 0 {
702                                                 if e.Critical {
703                                                         return out, UnhandledCriticalExtension{}
704                                                 }
705                                                 continue
706                                         }
707                                         out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
708                                 }
709                                 continue
710
711                         case 35:
712                                 // RFC 5280, 4.2.1.1
713                                 var a authKeyId
714                                 _, err = asn1.Unmarshal(e.Value, &a)
715                                 if err != nil {
716                                         return nil, err
717                                 }
718                                 out.AuthorityKeyId = a.Id
719                                 continue
720
721                         case 37:
722                                 // RFC 5280, 4.2.1.12.  Extended Key Usage
723
724                                 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
725                                 //
726                                 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
727                                 //
728                                 // KeyPurposeId ::= OBJECT IDENTIFIER
729
730                                 var keyUsage []asn1.ObjectIdentifier
731                                 _, err = asn1.Unmarshal(e.Value, &keyUsage)
732                                 if err != nil {
733                                         return nil, err
734                                 }
735
736                                 for _, u := range keyUsage {
737                                         switch {
738                                         case u.Equal(oidExtKeyUsageAny):
739                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageAny)
740                                         case u.Equal(oidExtKeyUsageServerAuth):
741                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageServerAuth)
742                                         case u.Equal(oidExtKeyUsageClientAuth):
743                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageClientAuth)
744                                         case u.Equal(oidExtKeyUsageCodeSigning):
745                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageCodeSigning)
746                                         case u.Equal(oidExtKeyUsageEmailProtection):
747                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageEmailProtection)
748                                         case u.Equal(oidExtKeyUsageTimeStamping):
749                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageTimeStamping)
750                                         case u.Equal(oidExtKeyUsageOCSPSigning):
751                                                 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageOCSPSigning)
752                                         default:
753                                                 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
754                                         }
755                                 }
756
757                                 continue
758
759                         case 14:
760                                 // RFC 5280, 4.2.1.2
761                                 var keyid []byte
762                                 _, err = asn1.Unmarshal(e.Value, &keyid)
763                                 if err != nil {
764                                         return nil, err
765                                 }
766                                 out.SubjectKeyId = keyid
767                                 continue
768
769                         case 32:
770                                 // RFC 5280 4.2.1.4: Certificate Policies
771                                 var policies []policyInformation
772                                 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
773                                         return nil, err
774                                 }
775                                 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
776                                 for i, policy := range policies {
777                                         out.PolicyIdentifiers[i] = policy.Policy
778                                 }
779                         }
780                 }
781
782                 if e.Critical {
783                         return out, UnhandledCriticalExtension{}
784                 }
785         }
786
787         return out, nil
788 }
789
790 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
791 func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
792         var cert certificate
793         rest, err := asn1.Unmarshal(asn1Data, &cert)
794         if err != nil {
795                 return nil, err
796         }
797         if len(rest) > 0 {
798                 return nil, asn1.SyntaxError{"trailing data"}
799         }
800
801         return parseCertificate(&cert)
802 }
803
804 // ParseCertificates parses one or more certificates from the given ASN.1 DER
805 // data. The certificates must be concatenated with no intermediate padding.
806 func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) {
807         v := new(vector.Vector)
808
809         for len(asn1Data) > 0 {
810                 cert := new(certificate)
811                 var err os.Error
812                 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
813                 if err != nil {
814                         return nil, err
815                 }
816                 v.Push(cert)
817         }
818
819         ret := make([]*Certificate, v.Len())
820         for i := 0; i < v.Len(); i++ {
821                 cert, err := parseCertificate(v.At(i).(*certificate))
822                 if err != nil {
823                         return nil, err
824                 }
825                 ret[i] = cert
826         }
827
828         return ret, nil
829 }
830
831 func reverseBitsInAByte(in byte) byte {
832         b1 := in>>4 | in<<4
833         b2 := b1>>2&0x33 | b1<<2&0xcc
834         b3 := b2>>1&0x55 | b2<<1&0xaa
835         return b3
836 }
837
838 var (
839         oidExtensionSubjectKeyId        = []int{2, 5, 29, 14}
840         oidExtensionKeyUsage            = []int{2, 5, 29, 15}
841         oidExtensionAuthorityKeyId      = []int{2, 5, 29, 35}
842         oidExtensionBasicConstraints    = []int{2, 5, 29, 19}
843         oidExtensionSubjectAltName      = []int{2, 5, 29, 17}
844         oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
845         oidExtensionNameConstraints     = []int{2, 5, 29, 30}
846 )
847
848 func buildExtensions(template *Certificate) (ret []extension, err os.Error) {
849         ret = make([]extension, 7 /* maximum number of elements. */ )
850         n := 0
851
852         if template.KeyUsage != 0 {
853                 ret[n].Id = oidExtensionKeyUsage
854                 ret[n].Critical = true
855
856                 var a [2]byte
857                 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
858                 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
859
860                 l := 1
861                 if a[1] != 0 {
862                         l = 2
863                 }
864
865                 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
866                 if err != nil {
867                         return
868                 }
869                 n++
870         }
871
872         if template.BasicConstraintsValid {
873                 ret[n].Id = oidExtensionBasicConstraints
874                 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
875                 ret[n].Critical = true
876                 if err != nil {
877                         return
878                 }
879                 n++
880         }
881
882         if len(template.SubjectKeyId) > 0 {
883                 ret[n].Id = oidExtensionSubjectKeyId
884                 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
885                 if err != nil {
886                         return
887                 }
888                 n++
889         }
890
891         if len(template.AuthorityKeyId) > 0 {
892                 ret[n].Id = oidExtensionAuthorityKeyId
893                 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
894                 if err != nil {
895                         return
896                 }
897                 n++
898         }
899
900         if len(template.DNSNames) > 0 {
901                 ret[n].Id = oidExtensionSubjectAltName
902                 rawValues := make([]asn1.RawValue, len(template.DNSNames))
903                 for i, name := range template.DNSNames {
904                         rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
905                 }
906                 ret[n].Value, err = asn1.Marshal(rawValues)
907                 if err != nil {
908                         return
909                 }
910                 n++
911         }
912
913         if len(template.PolicyIdentifiers) > 0 {
914                 ret[n].Id = oidExtensionCertificatePolicies
915                 policies := make([]policyInformation, len(template.PolicyIdentifiers))
916                 for i, policy := range template.PolicyIdentifiers {
917                         policies[i].Policy = policy
918                 }
919                 ret[n].Value, err = asn1.Marshal(policies)
920                 if err != nil {
921                         return
922                 }
923                 n++
924         }
925
926         if len(template.PermittedDNSDomains) > 0 {
927                 ret[n].Id = oidExtensionNameConstraints
928                 ret[n].Critical = template.PermittedDNSDomainsCritical
929
930                 var out nameConstraints
931                 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
932                 for i, permitted := range template.PermittedDNSDomains {
933                         out.Permitted[i] = generalSubtree{Name: permitted}
934                 }
935                 ret[n].Value, err = asn1.Marshal(out)
936                 if err != nil {
937                         return
938                 }
939                 n++
940         }
941
942         // Adding another extension here? Remember to update the maximum number
943         // of elements in the make() at the top of the function.
944
945         return ret[0:n], nil
946 }
947
948 var (
949         oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
950         oidRSA         = []int{1, 2, 840, 113549, 1, 1, 1}
951 )
952
953 // CreateSelfSignedCertificate creates a new certificate based on
954 // a template. The following members of template are used: SerialNumber,
955 // Subject, NotBefore, NotAfter, KeyUsage, BasicConstraintsValid, IsCA,
956 // MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
957 // PermittedDNSDomains.
958 //
959 // The certificate is signed by parent. If parent is equal to template then the
960 // certificate is self-signed. The parameter pub is the public key of the
961 // signee and priv is the private key of the signer.
962 //
963 // The returned slice is the certificate in DER encoding.
964 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub *rsa.PublicKey, priv *rsa.PrivateKey) (cert []byte, err os.Error) {
965         asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
966                 N: asn1.RawValue{Tag: 2, Bytes: pub.N.Bytes()},
967                 E: pub.E,
968         })
969         if err != nil {
970                 return
971         }
972
973         if len(parent.SubjectKeyId) > 0 {
974                 template.AuthorityKeyId = parent.SubjectKeyId
975         }
976
977         extensions, err := buildExtensions(template)
978         if err != nil {
979                 return
980         }
981
982         encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
983         c := tbsCertificate{
984                 Version:            2,
985                 SerialNumber:       asn1.RawValue{Bytes: template.SerialNumber, Tag: 2},
986                 SignatureAlgorithm: algorithmIdentifier{oidSHA1WithRSA},
987                 Issuer:             parent.Subject.toRDNSequence(),
988                 Validity:           validity{template.NotBefore, template.NotAfter},
989                 Subject:            template.Subject.toRDNSequence(),
990                 PublicKey:          publicKeyInfo{nil, algorithmIdentifier{oidRSA}, encodedPublicKey},
991                 Extensions:         extensions,
992         }
993
994         tbsCertContents, err := asn1.Marshal(c)
995         if err != nil {
996                 return
997         }
998
999         c.Raw = tbsCertContents
1000
1001         h := sha1.New()
1002         h.Write(tbsCertContents)
1003         digest := h.Sum()
1004
1005         signature, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, digest)
1006         if err != nil {
1007                 return
1008         }
1009
1010         cert, err = asn1.Marshal(certificate{
1011                 nil,
1012                 c,
1013                 algorithmIdentifier{oidSHA1WithRSA},
1014                 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1015         })
1016         return
1017 }