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"
52 MaxLineLength = 160 // 1 sha512 + 1 key (without \n)
53 MaxValueLength = 1300 // 20 sha256 space separated (without \n)
55 MaxDenominationLength = 100
58 const ClearSignedHeader = "-----BEGIN PGP SIGNED MESSAGE-----"
60 // MIME type for epoint documents, see RFC 4288
61 var ContentType = map[string]string{
62 "Draft": "text/vnd.epoint.draft; charset=utf-8",
63 "Notice": "text/vnd.epoint.notice; charset=utf-8",
64 "DebitCert": "text/vnd.epoint.debit; charset=utf-8",
65 "CreditCert": "text/vnd.epoint.credit; charset=utf-8",
66 "BounceCert": "text/vnd.epoint.bounce; charset=utf-8",
69 // OpenPGP signed cleartext document representation
71 // Sign and CleanSigned sets Hash for FormatSigned
74 // Signed text (no dash escape, no trailing space, \n new lines)
76 // Armored detached text signature of the Body
80 // parsed epoint document
81 type Document struct {
83 Fields map[string]string
87 var fieldtype = map[string]string{
89 "Authorized-By": "id",
94 "Denomination": "text",
98 "Expiry-Date": "date",
102 "Last-Credit-Serial": "int",
103 "Last-Debit-Serial": "int",
104 "Maturity-Date": "date",
111 var fieldname = map[string]string{
112 "AuthorizedBy": "Authorized-By",
113 "DebitCert": "Debit-Cert",
114 "ExpiryDate": "Expiry-Date",
115 "LastCert": "Last-Cert",
116 "LastCreditSerial": "Last-Credit-Serial",
117 "LastDebitSerial": "Last-Debit-Serial",
118 "MaturityDate": "Maturity-Date",
128 MaturityDate *int64 // optional
129 ExpiryDate *int64 // optional
130 Nonce *string // optional
131 Notes *string // optional
137 Notes *string // optional
138 References []string // may be empty (startup notice)
141 type DebitCert struct {
151 Notes *string // optional
152 LastDebitSerial int64 // 0 if none
153 LastCreditSerial int64 // 0 if none
154 LastCert *string // ? if serial == 1
158 type CreditCert struct {
170 Notes *string // optional
171 LastDebitSerial int64 // 0 if none
172 LastCreditSerial int64 // 0 if none
173 LastCert *string // ? if serial == 1
177 type BounceCert struct {
180 LastCert *string // optional
181 Balance int64 // 0 if none
184 Notes *string // optional
188 // parse an epoint document without checking the signature and format details
189 func Parse(s []byte) (iv interface{}, c *Signed, err error) {
190 c, err = ParseSigned(s)
194 doc, err := ParseDocument(c.Body)
198 iv, err = ParseStruct(doc)
202 // format and sign an epoint document
203 func Format(iv interface{}, key *openpgp.Entity) (s []byte, err error) {
204 doc, err := FormatStruct(iv)
208 body, err := FormatDocument(doc)
212 c, err := Sign(body, key)
216 return FormatSigned(c)
219 // verify an epoint document, return the cleaned version as well
220 func Verify(c *Signed, key *openpgp.Entity) (cleaned []byte, err error) {
225 err = VerifyCleaned(c, key)
229 return FormatSigned(c)
232 // verify signature of body with given key
233 func VerifyCleaned(c *Signed, key *openpgp.Entity) (err error) {
234 kr := openpgp.EntityList{key}
235 msg := bytes.NewBuffer(c.Body)
236 sig := bytes.NewBuffer(c.Signature)
237 _, err = openpgp.CheckArmoredDetachedSignature(kr, msg, sig)
241 // sign body with given secret key
242 func Sign(body []byte, key *openpgp.Entity) (c *Signed, err error) {
246 w := new(bytes.Buffer)
247 err = openpgp.ArmoredDetachSignText(w, key, bytes.NewBuffer(c.Body))
248 c.Signature = w.Bytes()
252 // split a clear signed document into body and armored signature
253 func ParseSigned(s []byte) (c *Signed, err error) {
254 // look for clear signed header
255 for !bytes.HasPrefix(s, []byte(ClearSignedHeader)) {
258 err = fmt.Errorf("ParseSigned: clear signed header is missing")
262 s = s[len(ClearSignedHeader):]
263 // end of line after the header
264 empty, s := getLine(s)
266 err = fmt.Errorf("ParseSigned: bad clear signed header")
269 // skip all hash headers, section 7.
270 for bytes.HasPrefix(s, []byte("Hash: ")) {
274 empty, s = getLine(s)
276 err = fmt.Errorf("ParseSigned: expected an empty line after armor headers")
280 for !bytes.HasPrefix(s, []byte("-----BEGIN")) {
283 // dash unescape, section 7.1.
284 if bytes.HasPrefix(line, []byte("- ")) {
287 // empty values are not supported: "Key: \n"
288 lines = append(lines, bytes.TrimRight(line, " \t"))
291 // last line is not closed by \n
292 c.Body = bytes.Join(lines, []byte("\n"))
293 // signature is just the rest of the input data
298 // clean up, check and reencode signature
299 // used on drafts before calculating the signed document hash
300 func CleanSigned(c *Signed) (err error) {
301 b, err := armor.Decode(bytes.NewBuffer(c.Signature))
305 if b.Type != openpgp.SignatureType {
306 err = fmt.Errorf("CleanSigned: invalid armored signature type")
309 p, err := packet.Read(b.Body)
313 sig, ok := p.(*packet.Signature)
315 err = fmt.Errorf("CleanSigned: invalid signature packet")
319 if sig.SigType != packet.SigTypeText {
320 err = fmt.Errorf("CleanSigned: expected text signature")
329 err = fmt.Errorf("CleanSigned: expected SHA1 or SHA256 signature hash")
332 // TODO: check CreationTime and other subpackets
333 if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
334 err = fmt.Errorf("CleanSigned: signature must not expire")
337 out := new(bytes.Buffer)
338 w, err := armor.Encode(out, openpgp.SignatureType, nil)
342 err = sig.Serialize(w)
350 c.Signature = out.Bytes()
354 // create clear signed document
355 func FormatSigned(c *Signed) (data []byte, err error) {
356 s := ClearSignedHeader + "\n"
358 s += "Hash: " + c.Hash + "\n"
363 s += string(c.Signature)
368 // parse type and fields of a document body
369 func ParseDocument(body []byte) (doc *Document, err error) {
370 // parse content type header first
371 fields, s, err := ParseFields(body)
375 ctype, ok := fields["Content-Type"]
376 if len(fields) != 1 || !ok {
377 return nil, fmt.Errorf("ParseBody: expected a single Content-Type header field")
380 for k, v := range ContentType {
387 return nil, fmt.Errorf("ParseBody: unknown Content-Type: %s", ctype)
390 doc.Fields, s, err = ParseFields(s)
391 if err == nil && len(s) > 0 {
392 err = fmt.Errorf("ParseBody: extra data after fields: %q", s)
397 // create document body
398 func FormatDocument(doc *Document) (body []byte, err error) {
399 ctype, ok := ContentType[doc.Type]
401 err = fmt.Errorf("FormatDocument: unknown document type: %s", doc.Type)
404 s := "Content-Type: " + ctype + "\n\n"
405 for _, k := range doc.Order {
406 s += k + ": " + doc.Fields[k] + "\n"
408 return []byte(s), nil
411 // parse doc fields into a struct according to the document type
412 func ParseStruct(doc *Document) (iv interface{}, err error) {
425 err = fmt.Errorf("ParseStruct: unkown doc type: %s", doc.Type)
428 seen := make(map[string]bool)
429 v := reflect.ValueOf(iv).Elem()
433 for i := 0; i < n; i++ {
436 key := fieldname[ft.Name]
441 s, ok := doc.Fields[key]
443 if fv.Kind() == reflect.Ptr {
444 // missing optional key: leave the pointer as nil
448 return nil, fmt.Errorf("ParseStruct: field %s of %s is missing\n", key, t.Name())
450 if fv.Kind() == reflect.Ptr {
451 if s == "" || s == "-" {
453 // empty optional key: same as missing
456 fv.Set(reflect.New(fv.Type().Elem()))
459 switch fieldtype[key] {
462 val, err = parseId(s)
466 val, err = parseString(s)
470 val, err = strconv.Atoi64(s)
474 val, err = parseDate(s)
477 // TODO: empty slice?
478 ids := strings.Split(s, " ")
479 val := make([]string, len(ids))
480 for j, id := range ids {
481 val[j], err = parseId(id)
486 fv.Set(reflect.ValueOf(val))
488 panic("bad field type " + key + " " + fieldtype[key])
494 if len(doc.Fields)+nokey != n {
495 for k := range doc.Fields {
497 err = fmt.Errorf("ParseStruct: unknown field %s in %s", k, t.Name())
505 // turn a struct into a document
506 func FormatStruct(iv interface{}) (doc *Document, err error) {
507 v := reflect.ValueOf(iv)
508 if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
509 panic("input is not a pointer to struct")
516 doc.Fields = make(map[string]string)
517 for i := 0; i < n; i++ {
520 key := fieldname[ft.Name]
525 if fv.Kind() == reflect.Ptr {
527 // keep empty optional fields but mark them
533 switch fieldtype[key] {
535 val = formatId(fv.String())
537 val = formatString(fv.String())
539 val = strconv.Itoa64(fv.Int())
541 val = formatDate(fv.Int())
544 for j := 0; j < k; j++ {
548 val += formatId(fv.Index(j).String())
551 panic("bad field type " + key + " " + fieldtype[key])
554 doc.Fields[key] = val
555 doc.Order = append(doc.Order, key)
560 func ParseFields(s []byte) (fields map[string]string, rest []byte, err error) {
562 fields = make(map[string]string)
564 // \n is optional after the last field and an extra \n is allowed as well
567 line, rest = getLine(rest)
568 // empty line after the last field is consumed
572 if line[0] == ' ' && key != "" {
573 // "Key: v1\n v2\n" is equivalent to "Key: v1 v2\n"
574 fields[key] += string(line)
577 if line[0] < 'A' || line[0] > 'Z' {
578 err = fmt.Errorf("ParseFields: field name must start with an upper-case ascii letter")
581 i := bytes.IndexByte(line, ':')
583 err = fmt.Errorf("ParseFields: missing ':'")
586 key = string(line[:i])
587 if _, ok := fields[key]; ok {
588 err = fmt.Errorf("ParseFields: repeated fields are not allowed")
591 fields[key] = string(line[i+1:])
593 for key, v := range fields {
594 // either a single space follows ':' or the value is empty
595 // good: "Key:\n", "Key:\n value\n", "Key: value\n", "Key: v1\n v2\n"
596 // bad: "Key:value\n", "Key: \nvalue\n"
597 // bad but not checked here: "Key: \n", "Key: value \n", "Key:\n \n value\n"
602 err = fmt.Errorf("ParseFields: ':' is not followed by ' '")
610 // TODO: limit errors
612 func parseId(s string) (string, error) {
613 // check if hex decodable
614 // TODO: length check
615 dst := make([]byte, len(s)/2)
616 _, err := hex.Decode(dst, []byte(s))
620 func formatId(s string) string {
624 func parseString(s string) (string, error) {
625 if len(s) > MaxValueLength {
626 return "", fmt.Errorf("parseString: length limit is exceeded")
631 func formatString(s string) string {
635 func parseDate(s string) (int64, error) {
636 // TODO: fractional seconds?
637 t, err := time.Parse(time.RFC3339, s)
641 return t.Seconds(), nil
644 func formatDate(i int64) string {
645 return time.SecondsToUTC(i).Format(time.RFC3339)
648 func getLine(data []byte) (line, rest []byte) {
649 i := bytes.IndexByte(data, '\n')
654 } else if i > 0 && data[i-1] == '\r' {
657 return data[:i], data[j:]