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
39 "crypto/openpgp/armor"
40 "crypto/openpgp/packet"
53 MaxLineLength = 160 // 1 sha512 + 1 key (without \n)
54 MaxValueLength = 1300 // 20 sha256 space separated (without \n)
56 MaxDenominationLength = 100
59 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
61 // MIME type for epoint documents, see RFC 4288
62 var ContentType = map[string]string{
63 "Draft": "text/vnd.epoint.draft; charset=utf-8",
64 "Notice": "text/vnd.epoint.notice; charset=utf-8",
65 "DebitCert": "text/vnd.epoint.debit; charset=utf-8",
66 "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
67 "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
70 // OpenPGP signed cleartext document representation
72 // Sign and CleanSigned sets Hash for FormatSigned
75 // Signed text (no dash escape, no trailing space, \n new lines)
77 // Armored detached text signature of the Body
81 // parsed epoint document
82 type Document struct {
84 Fields map[string]string
88 var fieldtype = map[string]string{
90 "Authorized-By": "id",
95 "Denomination": "text",
99 "Expiry-Date": "date",
103 "Last-Credit-Serial": "int",
104 "Last-Debit-Serial": "int",
105 "Maturity-Date": "date",
112 var fieldname = map[string]string{
113 "AuthorizedBy": "Authorized-By",
114 "DebitCert": "Debit-Cert",
115 "ExpiryDate": "Expiry-Date",
116 "LastCert": "Last-Cert",
117 "LastCreditSerial": "Last-Credit-Serial",
118 "LastDebitSerial": "Last-Debit-Serial",
119 "MaturityDate": "Maturity-Date",
129 MaturityDate *int64 // optional
130 ExpiryDate *int64 // optional
131 Nonce *string // optional
132 Notes *string // optional
138 Notes *string // optional
139 References []string // may be empty (startup notice)
142 type DebitCert struct {
153 Notes *string // optional
154 LastDebitSerial int64 // 0 if none
155 LastCreditSerial int64 // 0 if none
156 LastCert *string // ? if serial == 1
160 type CreditCert struct {
172 Notes *string // optional
173 LastDebitSerial int64 // 0 if none
174 LastCreditSerial int64 // 0 if none
175 LastCert *string // ? if serial == 1
179 type BounceCert struct {
182 LastCert *string // optional
183 Balance int64 // 0 if none
186 Notes *string // optional
190 // sha1 sum of the (cleaned) document as uppercase hex string
191 func Id(d []byte) string {
194 return fmt.Sprintf("%040X", h.Sum())
197 // parse an epoint document without checking the signature and format details
198 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
199 c, err = ParseSigned(s)
203 doc, err := ParseDocument(c.Body)
207 iv, err = ParseStruct(doc)
211 // format and sign an epoint document
212 func Format(iv interface{}, key *openpgp.Entity) (s []byte, err error) {
213 doc, err := FormatStruct(iv)
217 body, err := FormatDocument(doc)
221 c, err := Sign(body, key)
225 return FormatSigned(c)
228 // verify an epoint document, return the cleaned version as well
229 func Verify(c *Signed, key openpgp.KeyRing) (cleaned []byte, err error) {
234 err = VerifyCleaned(c, key)
238 return FormatSigned(c)
241 // verify signature of body with given key
242 func VerifyCleaned(c *Signed, key openpgp.KeyRing) (err error) {
243 msg := bytes.NewBuffer(c.Body)
244 sig := bytes.NewBuffer(c.Signature)
245 _, err = openpgp.CheckArmoredDetachedSignature(key, msg, sig)
249 // sign body with given secret key
250 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
254 w := new(bytes.Buffer)
255 err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
256 c.Signature = w.Bytes()
260 // split a clear signed document into body and armored signature
261 func ParseSigned(s []byte) (c *Signed, err error) {
262 // look for clear signed header
263 for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
266 err = fmt.Errorf("ParseSigned: clear signed header is missing")
270 s = s[len(ClearSignedHeader):]
271 // end of line after the header
272 empty, s := getLine(s)
274 err = fmt.Errorf("ParseSigned: bad clear signed header")
277 // skip all hash headers, section 7.
278 for bytes.HasPrefix(s, []byte("Hash: ")) {
282 empty, s = getLine(s)
284 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
288 for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
291 // dash unescape, section 7.1.
292 if bytes.HasPrefix(line, []byte("- ")) {
295 // empty values are not supported: "Key: \n"
296 lines = append(lines, bytes.TrimRight(line, " \t"))
299 // last line is not closed by \n
300 c.Body = bytes.Join(lines, []byte("\n"))
301 // signature is just the rest of the input data
306 // clean up, check and reencode signature
307 // used on drafts before calculating the signed document hash
308 func CleanSigned(c *Signed) (err error) {
309 b, err := armor.Decode(bytes.NewBuffer(c.Signature))
313 if b.Type != openpgp.SignatureType {
314 err = fmt.Errorf("CleanSigned: invalid armored signature type")
317 p, err := packet.Read(b.Body)
321 sig, ok := p.(*packet.Signature)
323 err = fmt.Errorf("CleanSigned: invalid signature packet")
327 if sig.SigType != packet.SigTypeText {
328 err = fmt.Errorf("CleanSigned: expected text signature")
337 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
340 // TODO: check CreationTime and other subpackets
341 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
342 err = fmt.Errorf("CleanSigned: signature must not expire")
345 out := new(bytes.Buffer)
346 w, err := armor.Encode(out, openpgp.SignatureType, nil)
350 err = sig.Serialize(w)
358 c.Signature = out.Bytes()
362 // create clear signed document
363 func FormatSigned(c *Signed) (data []byte, err error) {
364 s := ClearSignedHeader + "\n"
366 s += "Hash: " + c.Hash + "\n"
371 s += string(c.Signature)
376 // parse type and fields of a document body
377 func ParseDocument(body []byte) (doc *Document, err error) {
378 // parse content type header first
379 fields, s, err := ParseFields(body)
383 ctype, ok := fields["Content-Type"]
384 if len(fields) != 1 || !ok {
385 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
388 for k, v := range ContentType {
395 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
398 doc.Fields, s, err = ParseFields(s)
399 if err == nil && len(s) > 0 {
400 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
405 // create document body
406 func FormatDocument(doc *Document) (body []byte, err error) {
407 ctype, ok := ContentType[doc.Type]
409 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
412 s := "Content-Type: " + ctype + "\n\n"
413 for _, k := range doc.Order {
414 s += k + ": " + doc.Fields[k] + "\n"
416 return []byte(s), nil
419 // parse doc fields into a struct according to the document type
420 func ParseStruct(doc *Document) (iv interface{}, err error) {
433 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
436 seen := make(map[string]bool)
437 v := reflect.ValueOf(iv).Elem()
441 for i := 0; i < n; i++ {
444 key := fieldname[ft.Name]
449 s, ok := doc.Fields[key]
451 if fv.Kind() == reflect.Ptr {
452 // missing optional key: leave the pointer as nil
456 return nil, fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
458 if fv.Kind() == reflect.Ptr {
459 if s == "" || s == "-" {
461 // empty optional key: same as missing
464 fv.Set(reflect.New(fv.Type().Elem()))
467 switch fieldtype[key] {
470 val, err = parseId(s)
474 val, err = parseString(s)
478 val, err = strconv.Atoi64(s)
482 val, err = parseDate(s)
485 // TODO: empty slice?
486 ids := strings.Split(s, " ")
487 val := make([]string, len(ids))
488 for j, id := range ids {
489 val[j], err = parseId(id)
494 fv.Set(reflect.ValueOf(val))
496 panic("bad field type " + key + " " + fieldtype[key])
502 if len(doc.Fields)+nokey != n {
503 for k := range doc.Fields {
505 err = fmt.Errorf("ParseStruct: unknown field %s in %s", k, t.Name())
513 // turn a struct into a document
514 func FormatStruct(iv interface{}) (doc *Document, err error) {
515 v := reflect.ValueOf(iv)
516 if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
517 panic("input is not a pointer to struct")
524 doc.Fields = make(map[string]string)
525 for i := 0; i < n; i++ {
528 key := fieldname[ft.Name]
533 if fv.Kind() == reflect.Ptr {
535 // keep empty optional fields but mark them
541 switch fieldtype[key] {
543 val = formatId(fv.String())
545 val = formatString(fv.String())
547 val = strconv.Itoa64(fv.Int())
549 val = formatDate(fv.Int())
552 for j := 0; j < k; j++ {
556 val += formatId(fv.Index(j).String())
559 panic("bad field type " + key + " " + fieldtype[key])
562 doc.Fields[key] = val
563 doc.Order = append(doc.Order, key)
568 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
570 fields = make(map[string]string)
572 // \n is optional after the last field and an extra \n is allowed as well
575 line, rest = getLine(rest)
576 // empty line after the last field is consumed
580 if line[0] == ' ' && key != "" {
581 // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
582 fields[key] += string(line)
585 if line[0] < 'A' || line[0] > 'Z' {
586 err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
589 i := bytes.IndexByte(line, ':')
591 err = fmt.Errorf("ParseFields: missing ':'")
594 key = string(line[:i])
595 if _, ok := fields[key]; ok {
596 err = fmt.Errorf("ParseFields: repeated fields are not allowed")
599 fields[key] = string(line[i+1:])
601 for key, v := range fields {
602 // either a single space follows ':' or the value is empty
603 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
604 // bad: "Key:value\n", "Key: \nvalue\n"
605 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
610 err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
618 // TODO: limit errors
620 func parseId(s string) (string, error) {
621 // check if hex decodable
622 // TODO: length check
623 dst := make([]byte, len(s)/2)
624 _, err := hex.Decode(dst, []byte(s))
628 func formatId(s string) string {
632 func parseString(s string) (string, error) {
633 if len(s) > MaxValueLength {
634 return "", fmt.Errorf("parseString: length limit is exceeded")
639 func formatString(s string) string {
643 func parseDate(s string) (int64, error) {
644 // TODO: fractional seconds?
645 t, err := time.Parse(time.RFC3339, s)
649 return t.Seconds(), nil
652 func formatDate(i int64) string {
653 return time.SecondsToUTC(i).Format(time.RFC3339)
656 func getLine(data []byte) (line, rest []byte) {
657 i := bytes.IndexByte(data, '\n')
662 } else if i > 0 && data[i-1] == '\r' {
665 return data[:i], data[j:]