document: verify signature
[epoint] / pkg / document / document.go
1 // Package document implements epoint document parsing and creation.
2 //
3 // An epoint document is an OpenPGP (RFC 4880) clear signed
4 // utf-8 text of key-value pairs.
5 // The body contains a content-type MIME header so the document
6 // can be used in OpenPGP/MIME (RFC 3156) emails.
7 // The format of the key-value pairs is similar to MIME header
8 // fields: keys and values are separated by ": ", repeated keys
9 // are not allowed, long values can be split before a space.
10 //
11 // Example:
12 //
13 // -----BEGIN PGP SIGNED MESSAGE-----
14 // Hash: SHA1
15 //
16 // Content-Type: text/vnd.epoint.type; charset=utf-8
17 //
18 // Key: Value1
19 // Another-Key: Value2
20 // Last-Key: Long
21 //  value that spans
22 //  multiple lines
23 // -----BEGIN PGP SIGNATURE-----
24 //
25 // pgp signature
26 // -----END PGP SIGNATURE-----
27 package document
28
29 // TODO: error wrapper (so reporting to user or creating bounce cert is simple)
30 // TODO: optional fields: exact semantics ("" vs "-" vs nil)
31 // TODO: trailing space handling in ParseFields
32 // TODO: fields of notice (last notice, serial, failure notice,..)
33 // TODO: limits and cert type specific input validation
34 // TODO: hex nonce, uniq nonce vs uniq drawer.nonce
35 // TODO: denom, issuer from key (key representation: armor?)
36
37 import (
38         "bytes"
39         "crypto"
40         "crypto/openpgp"
41         "crypto/openpgp/armor"
42         "crypto/openpgp/packet"
43         "crypto/sha1"
44         "encoding/hex"
45         "fmt"
46         "reflect"
47         "strconv"
48         "strings"
49         "time"
50 )
51
52 // limits
53 const (
54         MaxFields             = 20
55         MaxLineLength         = 160  // 1 sha512 + 1 key (without \n)
56         MaxValueLength        = 1300 // 20 sha256 space separated (without \n)
57         MaxNonceLength        = 20
58         MaxDenominationLength = 100
59 )
60
61 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
62
63 // MIME type for epoint documents, see RFC 4288
64 var ContentType = map[string]string{
65         "Draft":      "text/vnd.epoint.draft; charset=utf-8",
66         "Notice":     "text/vnd.epoint.notice; charset=utf-8",
67         "DebitCert":  "text/vnd.epoint.debit; charset=utf-8",
68         "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
69         "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
70 }
71
72 // OpenPGP signed cleartext document representation
73 type Signed struct {
74         // Sign and CleanSigned sets Hash for FormatSigned
75         // TODO: CreationDate
76         Hash string
77         // Signed text (no dash escape, no trailing space, \n new lines)
78         Body []byte
79         // Armored detached text signature of the Body
80         Signature []byte
81 }
82
83 // parsed epoint document
84 type Document struct {
85         Type   string
86         Fields map[string]string
87         Order  []string
88 }
89
90 var fieldtype = map[string]string{
91         "Amount":             "int",
92         "Authorized-By":      "id",
93         "Balance":            "int",
94         "Beneficiary":        "id",
95         "Date":               "date",
96         "Debit-Cert":         "id",
97         "Denomination":       "text",
98         "Difference":         "int",
99         "Draft":              "id",
100         "Drawer":             "id",
101         "Expiry-Date":        "date",
102         "Holder":             "id",
103         "Issuer":             "id",
104         "Last-Cert":          "id",
105         "Last-Credit-Serial": "int",
106         "Last-Debit-Serial":  "int",
107         "Maturity-Date":      "date",
108         "Nonce":              "id",
109         "Notes":              "text",
110         "References":         "ids",
111         "Serial":             "int",
112 }
113
114 var fieldname = map[string]string{
115         "AuthorizedBy":     "Authorized-By",
116         "DebitCert":        "Debit-Cert",
117         "ExpiryDate":       "Expiry-Date",
118         "LastCert":         "Last-Cert",
119         "LastCreditSerial": "Last-Credit-Serial",
120         "LastDebitSerial":  "Last-Debit-Serial",
121         "MaturityDate":     "Maturity-Date",
122 }
123
124 type Draft struct {
125         Drawer       string
126         Beneficiary  string
127         Amount       int64
128         Denomination string
129         Issuer       string
130         AuthorizedBy string
131         MaturityDate *int64 // optional
132         ExpiryDate   *int64 // optional
133         Nonce        string
134         Notes        *string // optional
135 }
136
137 type Notice struct {
138         Date         int64
139         AuthorizedBy string
140         Notes        *string  // optional
141         References   []string // may be empty (startup notice)
142 }
143
144 type Cert struct {
145         Holder           string
146         Serial           int64
147         Balance          int64
148         Denomination     string
149         Issuer           string
150         Date             int64
151         AuthorizedBy     string
152         Notes            *string // optional
153         LastDebitSerial  int64   // 0 if none
154         LastCreditSerial int64   // 0 if none
155         LastCert         *string // nil if serial == 1
156         References       []string
157         Difference       int64
158         Draft            string
159 }
160
161 type DebitCert struct {
162         Cert
163         Beneficiary string
164 }
165
166 type CreditCert struct {
167         Cert
168         Drawer    string
169         DebitCert string
170 }
171
172 type BounceCert struct {
173         Drawer       string
174         Draft        string
175         LastCert     *string // optional
176         Balance      int64   // 0 if none
177         Date         int64
178         AuthorizedBy string
179         Notes        *string // optional
180         References   []string
181 }
182
183 // Common cert part of a debit or credit cert
184 func ToCert(v interface{}) (cert *Cert, err error) {
185         cert = new(Cert)
186         switch x := v.(type) {
187         case *DebitCert:
188                 cert = &x.Cert
189         case *CreditCert:
190                 cert = &x.Cert
191         default:
192                 err = fmt.Errorf("ToCert: only debit or credit document can be converted to cert")
193         }
194         return
195 }
196
197 func cleanBody(s []byte) []byte {
198         nl := []byte{'\n'}
199         a := bytes.Split(s, nl)
200         for i := range a {
201                 a[i] = bytes.TrimRight(a[i], " \t")
202         }
203         return bytes.Join(a, nl)
204 }
205
206 // sha1 sum of the (cleaned) document body as uppercase hex string
207 func Id(c *Signed) string {
208         h := sha1.New()
209         h.Write(c.Body)
210         return fmt.Sprintf("%040X", h.Sum())
211 }
212
213 // Parse an epoint document without checking the signature and format details
214 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
215         c, err = ParseSigned(s)
216         if err != nil {
217                 return
218         }
219         doc, err := ParseDocument(c.Body)
220         if err != nil {
221                 return
222         }
223         iv, err = ParseStruct(doc)
224         return
225 }
226
227 // Format and sign an epoint document
228 func Format(iv interface{}, key *openpgp.Entity) (s []byte, c *Signed, err error) {
229         doc, err := FormatStruct(iv)
230         if err != nil {
231                 return
232         }
233         body, err := FormatDocument(doc)
234         if err != nil {
235                 return
236         }
237         c, err = Sign(body, key)
238         if err != nil {
239                 return
240         }
241         s, err = FormatSigned(c)
242         return
243 }
244
245 // Verify an epoint document, return the cleaned version as well
246 func Verify(c *Signed, keys openpgp.KeyRing) (err error) {
247         msg := bytes.NewBuffer(c.Body)
248         sig := bytes.NewBuffer(c.Signature)
249         _, err = openpgp.CheckArmoredDetachedSignature(keys, msg, sig)
250         return
251 }
252
253 // Sign body with given secret key
254 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
255         c = new(Signed)
256         c.Hash = "SHA256"
257         c.Body = cleanBody(body)
258         w := new(bytes.Buffer)
259         err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
260         if err != nil {
261                 return
262         }
263         // close armored document with a \n
264         _, _ = w.Write([]byte{'\n'})
265         c.Signature = w.Bytes()
266         return
267 }
268
269 // split a clear signed document into body and armored signature
270 func ParseSigned(s []byte) (c *Signed, err error) {
271         // look for clear signed header
272         for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
273                 _, s = getLine(s)
274                 if len(s) == 0 {
275                         err = fmt.Errorf("ParseSigned: clear signed header is missing")
276                         return
277                 }
278         }
279         s = s[len(ClearSignedHeader):]
280         // end of line after the header
281         empty, s := getLine(s)
282         if len(empty) != 0 {
283                 err = fmt.Errorf("ParseSigned: bad clear signed header")
284                 return
285         }
286         // skip all hash headers, section 7.
287         for bytes.HasPrefix(s, []byte("Hash: ")) {
288                 _, s = getLine(s)
289         }
290         // skip empty line
291         empty, s = getLine(s)
292         if len(empty) != 0 {
293                 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
294                 return
295         }
296         lines := [][]byte{}
297         for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
298                 var line []byte
299                 line, s = getLine(s)
300                 // dash unescape, section 7.1.
301                 if bytes.HasPrefix(line, []byte("- ")) {
302                         line = line[2:]
303                 }
304                 // empty values are not supported: "Key: \n"
305                 lines = append(lines, bytes.TrimRight(line, " \t"))
306         }
307         c = new(Signed)
308         // last line is not closed by \n
309         c.Body = bytes.Join(lines, []byte("\n"))
310         // signature is just the rest of the input data
311         c.Signature = s
312         return
313 }
314
315 // clean up, check and reencode signature
316 // used on drafts before calculating the signed document hash
317 func CleanSigned(c *Signed) (err error) {
318         b, err := armor.Decode(bytes.NewBuffer(c.Signature))
319         if err != nil {
320                 return
321         }
322         if b.Type != openpgp.SignatureType {
323                 err = fmt.Errorf("CleanSigned: invalid armored signature type")
324                 return
325         }
326         p, err := packet.Read(b.Body)
327         if err != nil {
328                 return
329         }
330         sig, ok := p.(*packet.Signature)
331         if !ok {
332                 err = fmt.Errorf("CleanSigned: invalid signature packet")
333                 return
334         }
335         // section 5.2.3
336         if sig.SigType != packet.SigTypeText {
337                 err = fmt.Errorf("CleanSigned: expected text signature")
338                 return
339         }
340         switch sig.Hash {
341         case crypto.SHA1:
342                 c.Hash = "SHA1"
343         case crypto.SHA256:
344                 c.Hash = "SHA256"
345         default:
346                 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
347                 return
348         }
349         // TODO: check CreationTime and other subpackets
350         if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
351                 err = fmt.Errorf("CleanSigned: signature must not expire")
352                 return
353         }
354         out := new(bytes.Buffer)
355         w, err := armor.Encode(out, openpgp.SignatureType, nil)
356         if err != nil {
357                 return
358         }
359         err = sig.Serialize(w)
360         if err != nil {
361                 return
362         }
363         err = w.Close()
364         if err != nil {
365                 return
366         }
367         c.Signature = out.Bytes()
368         return
369 }
370
371 // create clear signed document
372 func FormatSigned(c *Signed) (data []byte, err error) {
373         s := ClearSignedHeader + "\n"
374         if c.Hash != "" {
375                 s += "Hash: " + c.Hash + "\n"
376         }
377         s += "\n"
378         s += string(c.Body)
379         s += "\n"
380         s += string(c.Signature)
381         data = []byte(s)
382         return
383 }
384
385 // parse type and fields of a document body
386 func ParseDocument(body []byte) (doc *Document, err error) {
387         // parse content type header first
388         fields, s, err := ParseFields(body)
389         if err != nil {
390                 return
391         }
392         ctype, ok := fields["Content-Type"]
393         if len(fields) != 1 || !ok {
394                 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
395         }
396         doc = new(Document)
397         for k, v := range ContentType {
398                 if ctype == v {
399                         doc.Type = k
400                         break
401                 }
402         }
403         if doc.Type == "" {
404                 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
405         }
406         // TODO: doc.Order
407         doc.Fields, s, err = ParseFields(s)
408         if err == nil && len(s) > 0 {
409                 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
410         }
411         return
412 }
413
414 // create document body
415 func FormatDocument(doc *Document) (body []byte, err error) {
416         ctype, ok := ContentType[doc.Type]
417         if !ok {
418                 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
419                 return
420         }
421         s := "Content-Type: " + ctype + "\n\n"
422         for _, k := range doc.Order {
423                 s += k + ": " + doc.Fields[k] + "\n"
424         }
425         return []byte(s), nil
426 }
427
428 // parse doc fields into a struct according to the document type
429 func parseStruct(v reflect.Value, fields map[string]string, seen map[string]bool) (err error) {
430         t := v.Type()
431         n := v.NumField()
432         for i := 0; i < n && err == nil; i++ {
433                 ft := t.Field(i)
434                 fv := v.Field(i)
435                 if ft.Anonymous && fv.Kind() == reflect.Struct {
436                         err = parseStruct(fv, fields, seen)
437                         continue
438                 }
439                 key := fieldname[ft.Name]
440                 if key == "" {
441                         key = ft.Name
442                 }
443                 s, ok := fields[key]
444                 if !ok {
445                         if fv.Kind() == reflect.Ptr {
446                                 // missing optional key: leave the pointer as nil
447                                 continue
448                         }
449                         return fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
450                 }
451                 seen[key] = true
452                 if fv.Kind() == reflect.Ptr {
453                         if s == "" || s == "-" {
454                                 // TODO
455                                 // empty optional key: same as missing
456                                 continue
457                         }
458                         fv.Set(reflect.New(fv.Type().Elem()))
459                         fv = fv.Elem()
460                 }
461                 switch fieldtype[key] {
462                 case "id":
463                         var val string
464                         val, err = parseId(s)
465                         fv.SetString(val)
466                 case "text":
467                         var val string
468                         val, err = parseString(s)
469                         fv.SetString(val)
470                 case "int":
471                         var val int64
472                         val, err = strconv.Atoi64(s)
473                         fv.SetInt(val)
474                 case "date":
475                         var val int64
476                         val, err = parseDate(s)
477                         fv.SetInt(val)
478                 case "ids":
479                         // TODO: empty slice?
480                         ids := strings.Split(s, " ")
481                         val := make([]string, len(ids))
482                         for j, id := range ids {
483                                 val[j], err = parseId(id)
484                                 if err != nil {
485                                         return
486                                 }
487                         }
488                         fv.Set(reflect.ValueOf(val))
489                 default:
490                         panic("bad field type " + key + " " + fieldtype[key])
491                 }
492         }
493         return
494 }
495
496 // ParseStruct parses an epoint document and returns a struct representation
497 func ParseStruct(doc *Document) (iv interface{}, err error) {
498         switch doc.Type {
499         case "Draft":
500                 iv = new(Draft)
501         case "Notice":
502                 iv = new(Notice)
503         case "DebitCert":
504                 iv = new(DebitCert)
505         case "CreditCert":
506                 iv = new(CreditCert)
507         case "BounceCert":
508                 iv = new(BounceCert)
509         default:
510                 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
511                 return
512         }
513         seen := make(map[string]bool)
514         err = parseStruct(reflect.ValueOf(iv).Elem(), doc.Fields, seen)
515         if err != nil {
516                 return
517         }
518         if len(doc.Fields) != len(seen) {
519                 for f := range doc.Fields {
520                         if !seen[f] {
521                                 err = fmt.Errorf("ParseStruct: unknown field %s in %s", f, doc.Type)
522                                 return
523                         }
524                 }
525         }
526         return
527 }
528
529 // turn a struct into a document
530 func formatStruct(v reflect.Value, doc *Document) (err error) {
531         t := v.Type()
532         n := v.NumField()
533         for i := 0; i < n; i++ {
534                 ft := t.Field(i)
535                 fv := v.Field(i)
536                 if ft.Anonymous && fv.Kind() == reflect.Struct {
537                         err = formatStruct(fv, doc)
538                         if err != nil {
539                                 return
540                         }
541                         continue
542                 }
543                 key := fieldname[ft.Name]
544                 if key == "" {
545                         key = ft.Name
546                 }
547                 val := ""
548                 if fv.Kind() == reflect.Ptr {
549                         if fv.IsNil() {
550                                 // keep empty optional fields but mark them
551                                 val = "-"
552                                 goto setval
553                         }
554                         fv = fv.Elem()
555                 }
556                 switch fieldtype[key] {
557                 case "id":
558                         val = formatId(fv.String())
559                 case "text":
560                         val = formatString(fv.String())
561                 case "int":
562                         val = strconv.Itoa64(fv.Int())
563                 case "date":
564                         val = formatDate(fv.Int())
565                 case "ids":
566                         k := fv.Len()
567                         for j := 0; j < k; j++ {
568                                 if j > 0 {
569                                         val += "\n "
570                                 }
571                                 val += formatId(fv.Index(j).String())
572                         }
573                 default:
574                         panic("bad field type " + key + " " + fieldtype[key])
575                 }
576         setval:
577                 doc.Fields[key] = val
578                 doc.Order = append(doc.Order, key)
579         }
580         return
581 }
582
583 // FormatStruct turns a struct into a document
584 func FormatStruct(iv interface{}) (doc *Document, err error) {
585         v := reflect.ValueOf(iv)
586         if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
587                 panic("input is not a pointer to struct")
588         }
589         doc = new(Document)
590         doc.Type = v.Elem().Type().Name()
591         doc.Fields = make(map[string]string)
592         err = formatStruct(v.Elem(), doc)
593         return
594 }
595
596 // ParseFields parses a key value sequence into a fields map
597 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
598         rest = s
599         fields = make(map[string]string)
600         key := ""
601         // \n is optional after the last field and an extra \n is allowed as well
602         for len(rest) > 0 {
603                 var line []byte
604                 line, rest = getLine(rest)
605                 // empty line after the last field is consumed
606                 if len(line) == 0 {
607                         break
608                 }
609                 if line[0] == ' ' && key != "" {
610                         // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
611                         fields[key] += string(line)
612                         continue
613                 }
614                 if line[0] < 'A' || line[0] > 'Z' {
615                         err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
616                         return
617                 }
618                 i := bytes.IndexByte(line, ':')
619                 if i < 0 {
620                         err = fmt.Errorf("ParseFields: missing ':'")
621                         return
622                 }
623                 key = string(line[:i])
624                 if _, ok := fields[key]; ok {
625                         err = fmt.Errorf("ParseFields: repeated fields are not allowed")
626                         return
627                 }
628                 fields[key] = string(line[i+1:])
629         }
630         for key, v := range fields {
631                 // either a single space follows ':' or the value is empty
632                 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
633                 // bad: "Key:value\n", "Key: \nvalue\n"
634                 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
635                 if len(v) == 0 {
636                         continue
637                 }
638                 if v[0] != ' ' {
639                         err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
640                         return
641                 }
642                 fields[key] = v[1:]
643         }
644         return
645 }
646
647 // TODO: limit errors
648
649 func parseId(s string) (string, error) {
650         // check if hex decodable
651         // TODO: length check
652         dst := make([]byte, len(s)/2)
653         _, err := hex.Decode(dst, []byte(s))
654         return s, err
655 }
656
657 func formatId(s string) string {
658         return s
659 }
660
661 func parseString(s string) (string, error) {
662         if len(s) > MaxValueLength {
663                 return "", fmt.Errorf("parseString: length limit is exceeded")
664         }
665         return s, nil
666 }
667
668 func formatString(s string) string {
669         return s
670 }
671
672 func parseDate(s string) (int64, error) {
673         // TODO: fractional seconds?
674         t, err := time.Parse(time.RFC3339, s)
675         if err != nil {
676                 return 0, err
677         }
678         return t.Seconds(), nil
679 }
680
681 func formatDate(i int64) string {
682         return time.SecondsToUTC(i).Format(time.RFC3339)
683 }
684
685 func getLine(data []byte) (line, rest []byte) {
686         i := bytes.IndexByte(data, '\n')
687         j := i + 1
688         if i < 0 {
689                 i = len(data)
690                 j = i
691         } else if i > 0 && data[i-1] == '\r' {
692                 i--
693         }
694         return data[:i], data[j:]
695 }