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 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.
13 // -----BEGIN PGP SIGNED MESSAGE-----
16 // Content-Type: text/vnd.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: hex nonce, uniq nonce vs uniq drawer.nonce
35 // TODO: denom, issuer from key (key representation: armor?)
41 "crypto/openpgp/armor"
42 "crypto/openpgp/packet"
55 MaxLineLength = 160 // 1 sha512 + 1 key (without \n)
56 MaxValueLength = 1300 // 20 sha256 space separated (without \n)
58 MaxDenominationLength = 100
61 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
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",
72 // OpenPGP signed cleartext document representation
74 // Sign and CleanSigned sets Hash for FormatSigned
77 // Signed text (no dash escape, no trailing space, \n new lines)
79 // Armored detached text signature of the Body
83 // parsed epoint document
84 type Document struct {
86 Fields map[string]string
90 var fieldtype = map[string]string{
92 "Authorized-By": "id",
97 "Denomination": "text",
101 "Expiry-Date": "date",
105 "Last-Credit-Serial": "int",
106 "Last-Debit-Serial": "int",
107 "Maturity-Date": "date",
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",
131 MaturityDate *int64 // optional
132 ExpiryDate *int64 // optional
134 Notes *string // optional
140 Notes *string // optional
141 References []string // may be empty (startup notice)
152 Notes *string // optional
153 LastDebitSerial int64 // 0 if none
154 LastCreditSerial int64 // 0 if none
155 LastCert *string // nil if serial == 1
161 type DebitCert struct {
166 type CreditCert struct {
172 type BounceCert struct {
175 LastCert *string // optional
176 Balance int64 // 0 if none
179 Notes *string // optional
183 func ToCert(v interface{}) (cert *Cert, err error) {
185 switch x := v.(type) {
191 err = fmt.Errorf("ToCert: only debit or credit document can be converted to cert")
196 func cleanBody(s []byte) []byte {
198 a := bytes.Split(s, nl)
200 a[i] = bytes.TrimRight(a[i], " \t")
202 return bytes.Join(a, nl)
205 // sha1 sum of the (cleaned) document body as uppercase hex string
206 func Id(c *Signed) string {
209 return fmt.Sprintf("%040X", h.Sum())
212 // parse an epoint document without checking the signature and format details
213 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
214 c, err = ParseSigned(s)
218 doc, err := ParseDocument(c.Body)
222 iv, err = ParseStruct(doc)
226 // format and sign an epoint document
227 func Format(iv interface{}, key *openpgp.Entity) (s []byte, c *Signed, err error) {
228 doc, err := FormatStruct(iv)
232 body, err := FormatDocument(doc)
236 c, err = Sign(body, key)
240 s, err = FormatSigned(c)
244 // verify an epoint document, return the cleaned version as well
245 func Verify(c *Signed, key openpgp.KeyRing) (err error) {
246 msg := bytes.NewBuffer(c.Body)
247 sig := bytes.NewBuffer(c.Signature)
248 // TODO: verify signature
250 // _, err = openpgp.CheckArmoredDetachedSignature(key, msg, sig)
254 // sign body with given secret key
255 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
258 c.Body = cleanBody(body)
259 w := new(bytes.Buffer)
260 err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
264 // close armored document with a \n
265 _, _ = w.Write([]byte{'\n'})
266 c.Signature = w.Bytes()
270 // split a clear signed document into body and armored signature
271 func ParseSigned(s []byte) (c *Signed, err error) {
272 // look for clear signed header
273 for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
276 err = fmt.Errorf("ParseSigned: clear signed header is missing")
280 s = s[len(ClearSignedHeader):]
281 // end of line after the header
282 empty, s := getLine(s)
284 err = fmt.Errorf("ParseSigned: bad clear signed header")
287 // skip all hash headers, section 7.
288 for bytes.HasPrefix(s, []byte("Hash: ")) {
292 empty, s = getLine(s)
294 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
298 for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
301 // dash unescape, section 7.1.
302 if bytes.HasPrefix(line, []byte("- ")) {
305 // empty values are not supported: "Key: \n"
306 lines = append(lines, bytes.TrimRight(line, " \t"))
309 // last line is not closed by \n
310 c.Body = bytes.Join(lines, []byte("\n"))
311 // signature is just the rest of the input data
316 // clean up, check and reencode signature
317 // used on drafts before calculating the signed document hash
318 func CleanSigned(c *Signed) (err error) {
319 b, err := armor.Decode(bytes.NewBuffer(c.Signature))
323 if b.Type != openpgp.SignatureType {
324 err = fmt.Errorf("CleanSigned: invalid armored signature type")
327 p, err := packet.Read(b.Body)
331 sig, ok := p.(*packet.Signature)
333 err = fmt.Errorf("CleanSigned: invalid signature packet")
337 if sig.SigType != packet.SigTypeText {
338 err = fmt.Errorf("CleanSigned: expected text signature")
347 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
350 // TODO: check CreationTime and other subpackets
351 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
352 err = fmt.Errorf("CleanSigned: signature must not expire")
355 out := new(bytes.Buffer)
356 w, err := armor.Encode(out, openpgp.SignatureType, nil)
360 err = sig.Serialize(w)
368 c.Signature = out.Bytes()
372 // create clear signed document
373 func FormatSigned(c *Signed) (data []byte, err error) {
374 s := ClearSignedHeader + "\n"
376 s += "Hash: " + c.Hash + "\n"
381 s += string(c.Signature)
386 // parse type and fields of a document body
387 func ParseDocument(body []byte) (doc *Document, err error) {
388 // parse content type header first
389 fields, s, err := ParseFields(body)
393 ctype, ok := fields["Content-Type"]
394 if len(fields) != 1 || !ok {
395 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
398 for k, v := range ContentType {
405 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
408 doc.Fields, s, err = ParseFields(s)
409 if err == nil && len(s) > 0 {
410 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
415 // create document body
416 func FormatDocument(doc *Document) (body []byte, err error) {
417 ctype, ok := ContentType[doc.Type]
419 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
422 s := "Content-Type: " + ctype + "\n\n"
423 for _, k := range doc.Order {
424 s += k + ": " + doc.Fields[k] + "\n"
426 return []byte(s), nil
429 // parse doc fields into a struct according to the document type
430 func parseStruct(v reflect.Value, fields map[string]string, seen map[string]bool) (err error) {
433 for i := 0; i < n && err == nil; i++ {
436 if ft.Anonymous && fv.Kind() == reflect.Struct {
437 err = parseStruct(fv, fields, seen)
440 key := fieldname[ft.Name]
446 if fv.Kind() == reflect.Ptr {
447 // missing optional key: leave the pointer as nil
450 return fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
453 if fv.Kind() == reflect.Ptr {
454 if s == "" || s == "-" {
456 // empty optional key: same as missing
459 fv.Set(reflect.New(fv.Type().Elem()))
462 switch fieldtype[key] {
465 val, err = parseId(s)
469 val, err = parseString(s)
473 val, err = strconv.Atoi64(s)
477 val, err = parseDate(s)
480 // TODO: empty slice?
481 ids := strings.Split(s, " ")
482 val := make([]string, len(ids))
483 for j, id := range ids {
484 val[j], err = parseId(id)
489 fv.Set(reflect.ValueOf(val))
491 panic("bad field type " + key + " " + fieldtype[key])
497 func ParseStruct(doc *Document) (iv interface{}, err error) {
510 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
513 seen := make(map[string]bool)
514 err = parseStruct(reflect.ValueOf(iv).Elem(), doc.Fields, seen)
518 if len(doc.Fields) != len(seen) {
519 for f := range doc.Fields {
521 err = fmt.Errorf("ParseStruct: unknown field %s in %s", f, doc.Type)
529 // turn a struct into a document
530 func formatStruct(v reflect.Value, doc *Document) (err error) {
533 for i := 0; i < n; i++ {
536 if ft.Anonymous && fv.Kind() == reflect.Struct {
537 err = formatStruct(fv, doc)
543 key := fieldname[ft.Name]
548 if fv.Kind() == reflect.Ptr {
550 // keep empty optional fields but mark them
556 switch fieldtype[key] {
558 val = formatId(fv.String())
560 val = formatString(fv.String())
562 val = strconv.Itoa64(fv.Int())
564 val = formatDate(fv.Int())
567 for j := 0; j < k; j++ {
571 val += formatId(fv.Index(j).String())
574 panic("bad field type " + key + " " + fieldtype[key])
577 doc.Fields[key] = val
578 doc.Order = append(doc.Order, key)
583 // turn 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")
590 doc.Type = v.Elem().Type().Name()
591 doc.Fields = make(map[string]string)
592 err = formatStruct(v.Elem(), doc)
596 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
598 fields = make(map[string]string)
600 // \n is optional after the last field and an extra \n is allowed as well
603 line, rest = getLine(rest)
604 // empty line after the last field is consumed
608 if line[0] == ' ' && key != "" {
609 // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
610 fields[key] += string(line)
613 if line[0] < 'A' || line[0] > 'Z' {
614 err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
617 i := bytes.IndexByte(line, ':')
619 err = fmt.Errorf("ParseFields: missing ':'")
622 key = string(line[:i])
623 if _, ok := fields[key]; ok {
624 err = fmt.Errorf("ParseFields: repeated fields are not allowed")
627 fields[key] = string(line[i+1:])
629 for key, v := range fields {
630 // either a single space follows ':' or the value is empty
631 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
632 // bad: "Key:value\n", "Key: \nvalue\n"
633 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
638 err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
646 // TODO: limit errors
648 func parseId(s string) (string, error) {
649 // check if hex decodable
650 // TODO: length check
651 dst := make([]byte, len(s)/2)
652 _, err := hex.Decode(dst, []byte(s))
656 func formatId(s string) string {
660 func parseString(s string) (string, error) {
661 if len(s) > MaxValueLength {
662 return "", fmt.Errorf("parseString: length limit is exceeded")
667 func formatString(s string) string {
671 func parseDate(s string) (int64, error) {
672 // TODO: fractional seconds?
673 t, err := time.Parse(time.RFC3339, s)
677 return t.Seconds(), nil
680 func formatDate(i int64) string {
681 return time.SecondsToUTC(i).Format(time.RFC3339)
684 func getLine(data []byte) (line, rest []byte) {
685 i := bytes.IndexByte(data, '\n')
690 } else if i > 0 && data[i-1] == '\r' {
693 return data[:i], data[j:]