1 // Package document implements epoint document parsing and creation.
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 are 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.
13 // -----BEGIN PGP SIGNED MESSAGE-----
16 // Content-Type: text/plain.epoint.type; charset=utf-8
19 // Another-Key: Value2
23 // -----BEGIN PGP SIGNATURE-----
26 // -----END PGP SIGNATURE-----
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: fix Cert mess
35 // TODO: nonce is id, id is even number of hex digits (require only draftid.nonce to be uniq)
36 // TODO: denom, issuer from key (key representation: armor?)
42 "crypto/openpgp/armor"
43 "crypto/openpgp/packet"
56 MaxLineLength = 160 // 1 sha512 + 1 key (without \n)
57 MaxValueLength = 1300 // 20 sha256 space separated (without \n)
59 MaxDenominationLength = 100
62 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
64 // MIME type for epoint documents, see RFC 4288
65 var ContentType = map[string]string{
66 "Draft": "text/vnd.epoint.draft; charset=utf-8",
67 "Notice": "text/vnd.epoint.notice; charset=utf-8",
68 "DebitCert": "text/vnd.epoint.debit; charset=utf-8",
69 "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
70 "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
73 // OpenPGP signed cleartext document representation
75 // Sign and CleanSigned sets Hash for FormatSigned
78 // Signed text (no dash escape, no trailing space, \n new lines)
80 // Armored detached text signature of the Body
84 // parsed epoint document
85 type Document struct {
87 Fields map[string]string
91 var fieldtype = map[string]string{
93 "Authorized-By": "id",
98 "Denomination": "text",
102 "Expiry-Date": "date",
106 "Last-Credit-Serial": "int",
107 "Last-Debit-Serial": "int",
108 "Maturity-Date": "date",
115 var fieldname = map[string]string{
116 "AuthorizedBy": "Authorized-By",
117 "DebitCert": "Debit-Cert",
118 "ExpiryDate": "Expiry-Date",
119 "LastCert": "Last-Cert",
120 "LastCreditSerial": "Last-Credit-Serial",
121 "LastDebitSerial": "Last-Debit-Serial",
122 "MaturityDate": "Maturity-Date",
132 MaturityDate *int64 // optional
133 ExpiryDate *int64 // optional
135 Notes *string // optional
141 Notes *string // optional
142 References []string // may be empty (startup notice)
155 Beneficiary *string // only in debit cert
156 Drawer *string // only in credit cert
157 DebitCert *string // only in credit cert
159 Notes *string // optional
160 LastDebitSerial int64 // 0 if none
161 LastCreditSerial int64 // 0 if none
162 LastCert *string // nil if serial == 1
166 type DebitCert struct {
177 Notes *string // optional
178 LastDebitSerial int64 // 0 if none
179 LastCreditSerial int64 // 0 if none
180 LastCert *string // nil if serial == 1
184 type CreditCert struct {
196 Notes *string // optional
197 LastDebitSerial int64 // 0 if none
198 LastCreditSerial int64 // 0 if none
199 LastCert *string // ? if serial == 1
203 type BounceCert struct {
206 LastCert *string // optional
207 Balance int64 // 0 if none
210 Notes *string // optional
214 func ToCert(v interface{}) (cert *Cert, err error) {
216 switch x := v.(type) {
219 cert.Beneficiary = &x.Beneficiary
221 cert.Holder = x.Holder
222 cert.Serial = x.Serial
223 cert.Balance = x.Balance
224 cert.Denomination = x.Denomination
225 cert.Issuer = x.Issuer
227 cert.Difference = x.Difference
229 cert.AuthorizedBy = x.AuthorizedBy
231 cert.LastDebitSerial = x.LastDebitSerial
232 cert.LastCreditSerial = x.LastCreditSerial
233 cert.LastCert = x.LastCert
234 cert.References = x.References
238 cert.Drawer = &x.Drawer
239 cert.DebitCert = &x.DebitCert
241 cert.Holder = x.Holder
242 cert.Serial = x.Serial
243 cert.Balance = x.Balance
244 cert.Denomination = x.Denomination
245 cert.Issuer = x.Issuer
247 cert.Difference = x.Difference
249 cert.AuthorizedBy = x.AuthorizedBy
251 cert.LastDebitSerial = x.LastDebitSerial
252 cert.LastCreditSerial = x.LastCreditSerial
253 cert.LastCert = x.LastCert
254 cert.References = x.References
256 err = fmt.Errorf("ToCert: only debit or credit document can be converted to cert")
261 func cleanBody(s []byte) []byte {
263 a := bytes.Split(s, nl)
265 a[i] = bytes.TrimRight(a[i], " \t")
267 return bytes.Join(a, nl)
270 // sha1 sum of the (cleaned) document body as uppercase hex string
271 func Id(c *Signed) string {
274 return fmt.Sprintf("%040X", h.Sum())
277 // parse an epoint document without checking the signature and format details
278 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
279 c, err = ParseSigned(s)
283 doc, err := ParseDocument(c.Body)
287 iv, err = ParseStruct(doc)
291 // format and sign an epoint document
292 func Format(iv interface{}, key *openpgp.Entity) (s []byte, c *Signed, err error) {
293 doc, err := FormatStruct(iv)
297 body, err := FormatDocument(doc)
301 c, err = Sign(body, key)
305 s, err = FormatSigned(c)
309 // verify an epoint document, return the cleaned version as well
310 func Verify(c *Signed, key openpgp.KeyRing) (err error) {
311 msg := bytes.NewBuffer(c.Body)
312 sig := bytes.NewBuffer(c.Signature)
313 // TODO: verify signature
315 // _, err = openpgp.CheckArmoredDetachedSignature(key, msg, sig)
319 // sign body with given secret key
320 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
323 c.Body = cleanBody(body)
324 w := new(bytes.Buffer)
325 err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
329 // close armored document with a \n
330 _, _ = w.Write([]byte{'\n'})
331 c.Signature = w.Bytes()
335 // split a clear signed document into body and armored signature
336 func ParseSigned(s []byte) (c *Signed, err error) {
337 // look for clear signed header
338 for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
341 err = fmt.Errorf("ParseSigned: clear signed header is missing")
345 s = s[len(ClearSignedHeader):]
346 // end of line after the header
347 empty, s := getLine(s)
349 err = fmt.Errorf("ParseSigned: bad clear signed header")
352 // skip all hash headers, section 7.
353 for bytes.HasPrefix(s, []byte("Hash: ")) {
357 empty, s = getLine(s)
359 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
363 for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
366 // dash unescape, section 7.1.
367 if bytes.HasPrefix(line, []byte("- ")) {
370 // empty values are not supported: "Key: \n"
371 lines = append(lines, bytes.TrimRight(line, " \t"))
374 // last line is not closed by \n
375 c.Body = bytes.Join(lines, []byte("\n"))
376 // signature is just the rest of the input data
381 // clean up, check and reencode signature
382 // used on drafts before calculating the signed document hash
383 func CleanSigned(c *Signed) (err error) {
384 b, err := armor.Decode(bytes.NewBuffer(c.Signature))
388 if b.Type != openpgp.SignatureType {
389 err = fmt.Errorf("CleanSigned: invalid armored signature type")
392 p, err := packet.Read(b.Body)
396 sig, ok := p.(*packet.Signature)
398 err = fmt.Errorf("CleanSigned: invalid signature packet")
402 if sig.SigType != packet.SigTypeText {
403 err = fmt.Errorf("CleanSigned: expected text signature")
412 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
415 // TODO: check CreationTime and other subpackets
416 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
417 err = fmt.Errorf("CleanSigned: signature must not expire")
420 out := new(bytes.Buffer)
421 w, err := armor.Encode(out, openpgp.SignatureType, nil)
425 err = sig.Serialize(w)
433 c.Signature = out.Bytes()
437 // create clear signed document
438 func FormatSigned(c *Signed) (data []byte, err error) {
439 s := ClearSignedHeader + "\n"
441 s += "Hash: " + c.Hash + "\n"
446 s += string(c.Signature)
451 // parse type and fields of a document body
452 func ParseDocument(body []byte) (doc *Document, err error) {
453 // parse content type header first
454 fields, s, err := ParseFields(body)
458 ctype, ok := fields["Content-Type"]
459 if len(fields) != 1 || !ok {
460 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
463 for k, v := range ContentType {
470 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
473 doc.Fields, s, err = ParseFields(s)
474 if err == nil && len(s) > 0 {
475 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
480 // create document body
481 func FormatDocument(doc *Document) (body []byte, err error) {
482 ctype, ok := ContentType[doc.Type]
484 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
487 s := "Content-Type: " + ctype + "\n\n"
488 for _, k := range doc.Order {
489 s += k + ": " + doc.Fields[k] + "\n"
491 return []byte(s), nil
494 // parse doc fields into a struct according to the document type
495 func ParseStruct(doc *Document) (iv interface{}, err error) {
508 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
511 seen := make(map[string]bool)
512 v := reflect.ValueOf(iv).Elem()
516 for i := 0; i < n; i++ {
519 key := fieldname[ft.Name]
524 s, ok := doc.Fields[key]
526 if fv.Kind() == reflect.Ptr {
527 // missing optional key: leave the pointer as nil
531 return nil, fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
533 if fv.Kind() == reflect.Ptr {
534 if s == "" || s == "-" {
536 // empty optional key: same as missing
539 fv.Set(reflect.New(fv.Type().Elem()))
542 switch fieldtype[key] {
545 val, err = parseId(s)
549 val, err = parseString(s)
553 val, err = strconv.Atoi64(s)
557 val, err = parseDate(s)
560 // TODO: empty slice?
561 ids := strings.Split(s, " ")
562 val := make([]string, len(ids))
563 for j, id := range ids {
564 val[j], err = parseId(id)
569 fv.Set(reflect.ValueOf(val))
571 panic("bad field type " + key + " " + fieldtype[key])
577 if len(doc.Fields)+nokey != n {
578 for k := range doc.Fields {
580 err = fmt.Errorf("ParseStruct: unknown field %s in %s", k, t.Name())
588 // turn a struct into a document
589 func FormatStruct(iv interface{}) (doc *Document, err error) {
590 v := reflect.ValueOf(iv)
591 if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
592 panic("input is not a pointer to struct")
599 doc.Fields = make(map[string]string)
600 for i := 0; i < n; i++ {
603 key := fieldname[ft.Name]
608 if fv.Kind() == reflect.Ptr {
610 // keep empty optional fields but mark them
616 switch fieldtype[key] {
618 val = formatId(fv.String())
620 val = formatString(fv.String())
622 val = strconv.Itoa64(fv.Int())
624 val = formatDate(fv.Int())
627 for j := 0; j < k; j++ {
631 val += formatId(fv.Index(j).String())
634 panic("bad field type " + key + " " + fieldtype[key])
637 doc.Fields[key] = val
638 doc.Order = append(doc.Order, key)
643 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
645 fields = make(map[string]string)
647 // \n is optional after the last field and an extra \n is allowed as well
650 line, rest = getLine(rest)
651 // empty line after the last field is consumed
655 if line[0] == ' ' && key != "" {
656 // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
657 fields[key] += string(line)
660 if line[0] < 'A' || line[0] > 'Z' {
661 err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
664 i := bytes.IndexByte(line, ':')
666 err = fmt.Errorf("ParseFields: missing ':'")
669 key = string(line[:i])
670 if _, ok := fields[key]; ok {
671 err = fmt.Errorf("ParseFields: repeated fields are not allowed")
674 fields[key] = string(line[i+1:])
676 for key, v := range fields {
677 // either a single space follows ':' or the value is empty
678 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
679 // bad: "Key:value\n", "Key: \nvalue\n"
680 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
685 err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
693 // TODO: limit errors
695 func parseId(s string) (string, error) {
696 // check if hex decodable
697 // TODO: length check
698 dst := make([]byte, len(s)/2)
699 _, err := hex.Decode(dst, []byte(s))
703 func formatId(s string) string {
707 func parseString(s string) (string, error) {
708 if len(s) > MaxValueLength {
709 return "", fmt.Errorf("parseString: length limit is exceeded")
714 func formatString(s string) string {
718 func parseDate(s string) (int64, error) {
719 // TODO: fractional seconds?
720 t, err := time.Parse(time.RFC3339, s)
724 return t.Seconds(), nil
727 func formatDate(i int64) string {
728 return time.SecondsToUTC(i).Format(time.RFC3339)
731 func getLine(data []byte) (line, rest []byte) {
732 i := bytes.IndexByte(data, '\n')
737 } else if i > 0 && data[i-1] == '\r' {
740 return data[:i], data[j:]