Add string-hashing interface
[exim.git] / src / src / arc.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4 /* Experimental ARC support for Exim
5    Copyright (c) Jeremy Harris 2018 - 2020
6    Copyright (c) The Exim Maintainers 2021
7    License: GPL
8 */
9
10 #include "exim.h"
11 #if defined EXPERIMENTAL_ARC
12 # if defined DISABLE_DKIM
13 #  error DKIM must also be enabled for ARC
14 # else
15
16 #  include "functions.h"
17 #  include "pdkim/pdkim.h"
18 #  include "pdkim/signing.h"
19
20 extern pdkim_ctx * dkim_verify_ctx;
21 extern pdkim_ctx dkim_sign_ctx;
22
23 #define ARC_SIGN_OPT_TSTAMP     BIT(0)
24 #define ARC_SIGN_OPT_EXPIRE     BIT(1)
25
26 #define ARC_SIGN_DEFAULT_EXPIRE_DELTA (60 * 60 * 24 * 30)       /* one month */
27
28 /******************************************************************************/
29
30 typedef struct hdr_rlist {
31   struct hdr_rlist *    prev;
32   BOOL                  used;
33   header_line *         h;
34 } hdr_rlist;
35
36 typedef struct arc_line {
37   header_line * complete;       /* including the header name; nul-term */
38   uschar *      relaxed;
39
40   /* identified tag contents */
41   /*XXX t= for AS? */
42   blob          i;
43   blob          cv;
44   blob          a;
45   blob          b;
46   blob          bh;
47   blob          d;
48   blob          h;
49   blob          s;
50   blob          c;
51   blob          l;
52
53   /* tag content sub-portions */
54   blob          a_algo;
55   blob          a_hash;
56
57   blob          c_head;
58   blob          c_body;
59
60   /* modified copy of b= field in line */
61   blob          rawsig_no_b_val;
62 } arc_line;
63
64 typedef struct arc_set {
65   struct arc_set *      next;
66   struct arc_set *      prev;
67
68   unsigned              instance;
69   arc_line *            hdr_aar;
70   arc_line *            hdr_ams;
71   arc_line *            hdr_as;
72
73   const uschar *        ams_verify_done;
74   BOOL                  ams_verify_passed;
75 } arc_set;
76
77 typedef struct arc_ctx {
78   arc_set *     arcset_chain;
79   arc_set *     arcset_chain_last;
80 } arc_ctx;
81
82 #define ARC_HDR_AAR     US"ARC-Authentication-Results:"
83 #define ARC_HDRLEN_AAR  27
84 #define ARC_HDR_AMS     US"ARC-Message-Signature:"
85 #define ARC_HDRLEN_AMS  22
86 #define ARC_HDR_AS      US"ARC-Seal:"
87 #define ARC_HDRLEN_AS   9
88 #define HDR_AR          US"Authentication-Results:"
89 #define HDRLEN_AR       23
90
91 static time_t now;
92 static time_t expire;
93 static hdr_rlist * headers_rlist;
94 static arc_ctx arc_sign_ctx = { NULL };
95 static arc_ctx arc_verify_ctx = { NULL };
96
97
98 /******************************************************************************/
99
100
101 /* Get the instance number from the header.
102 Return 0 on error */
103 static unsigned
104 arc_instance_from_hdr(const arc_line * al)
105 {
106 const uschar * s = al->i.data;
107 if (!s || !al->i.len) return 0;
108 return (unsigned) atoi(CCS s);
109 }
110
111
112 static uschar *
113 skip_fws(uschar * s)
114 {
115 uschar c = *s;
116 while (c && (c == ' ' || c == '\t' || c == '\n' || c == '\r')) c = *++s;
117 return s;
118 }
119
120
121 /* Locate instance struct on chain, inserting a new one if
122 needed.  The chain is in increasing-instance-number order
123 by the "next" link, and we have a "prev" link also.
124 */
125
126 static arc_set *
127 arc_find_set(arc_ctx * ctx, unsigned i)
128 {
129 arc_set ** pas, * as, * next, * prev;
130
131 for (pas = &ctx->arcset_chain, prev = NULL, next = ctx->arcset_chain;
132      as = *pas; pas = &as->next)
133   {
134   if (as->instance > i) break;
135   if (as->instance == i)
136     {
137     DEBUG(D_acl) debug_printf("ARC: existing instance %u\n", i);
138     return as;
139     }
140   next = as->next;
141   prev = as;
142   }
143
144 DEBUG(D_acl) debug_printf("ARC: new instance %u\n", i);
145 *pas = as = store_get(sizeof(arc_set), GET_UNTAINTED);
146 memset(as, 0, sizeof(arc_set));
147 as->next = next;
148 as->prev = prev;
149 as->instance = i;
150 if (next)
151   next->prev = as;
152 else
153   ctx->arcset_chain_last = as;
154 return as;
155 }
156
157
158
159 /* Insert a tag content into the line structure.
160 Note this is a reference to existing data, not a copy.
161 Check for already-seen tag.
162 The string-pointer is on the '=' for entry.  Update it past the
163 content (to the ;) on return;
164 */
165
166 static uschar *
167 arc_insert_tagvalue(arc_line * al, unsigned loff, uschar ** ss)
168 {
169 uschar * s = *ss;
170 uschar c = *++s;
171 blob * b = (blob *)(US al + loff);
172 size_t len = 0;
173
174 /* [FWS] tag-value [FWS] */
175
176 if (b->data) return US"fail";
177 s = skip_fws(s);                                                /* FWS */
178
179 b->data = s;
180 while ((c = *s) && c != ';') { len++; s++; }
181 *ss = s;
182 while (len && ((c = s[-1]) == ' ' || c == '\t' || c == '\n' || c == '\r'))
183   { s--; len--; }                                               /* FWS */
184 b->len = len;
185 return NULL;
186 }
187
188
189 /* Inspect a header line, noting known tag fields.
190 Check for duplicates. */
191
192 static uschar *
193 arc_parse_line(arc_line * al, header_line * h, unsigned off, BOOL instance_only)
194 {
195 uschar * s = h->text + off;
196 uschar * r = NULL;      /* compiler-quietening */
197 uschar c;
198
199 al->complete = h;
200
201 if (!instance_only)
202   {
203   al->rawsig_no_b_val.data = store_get(h->slen + 1, GET_TAINTED);
204   memcpy(al->rawsig_no_b_val.data, h->text, off);       /* copy the header name blind */
205   r = al->rawsig_no_b_val.data + off;
206   al->rawsig_no_b_val.len = off;
207   }
208
209 /* tag-list  =  tag-spec *( ";" tag-spec ) [ ";" ] */
210
211 while ((c = *s))
212   {
213   char tagchar;
214   uschar * t;
215   unsigned i = 0;
216   uschar * fieldstart = s;
217   uschar * bstart = NULL, * bend;
218
219   /* tag-spec  =  [FWS] tag-name [FWS] "=" [FWS] tag-value [FWS] */
220
221   s = skip_fws(s);                                              /* FWS */
222   if (!*s) break;
223 /* debug_printf("%s: consider '%s'\n", __FUNCTION__, s); */
224   tagchar = *s++;
225   s = skip_fws(s);                                              /* FWS */
226   if (!*s) break;
227
228   if (!instance_only || tagchar == 'i') switch (tagchar)
229     {
230     case 'a':                           /* a= AMS algorithm */
231       {
232       if (*s != '=') return US"no 'a' value";
233       if (arc_insert_tagvalue(al, offsetof(arc_line, a), &s)) return US"a tag dup";
234
235       /* substructure: algo-hash   (eg. rsa-sha256) */
236
237       t = al->a_algo.data = al->a.data;
238       while (*t != '-')
239         if (!*t++ || ++i > al->a.len) return US"no '-' in 'a' value";
240       al->a_algo.len = i;
241       if (*t++ != '-') return US"no '-' in 'a' value";
242       al->a_hash.data = t;
243       al->a_hash.len = al->a.len - i - 1;
244       }
245       break;
246     case 'b':
247       {
248       gstring * g = NULL;
249
250       switch (*s)
251         {
252         case '=':                       /* b= AMS signature */
253           if (al->b.data) return US"already b data";
254           bstart = s+1;
255
256           /* The signature can have FWS inserted in the content;
257           make a stripped copy */
258
259           while ((c = *++s) && c != ';')
260             if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
261               g = string_catn(g, s, 1);
262           if (!g) return US"no b= value";
263           al->b.data = string_from_gstring(g);
264           al->b.len = g->ptr;
265           gstring_release_unused(g);
266           bend = s;
267           break;
268         case 'h':                       /* bh= AMS body hash */
269           s = skip_fws(++s);                                    /* FWS */
270           if (*s != '=') return US"no bh value";
271           if (al->bh.data) return US"already bh data";
272
273           /* The bodyhash can have FWS inserted in the content;
274           make a stripped copy */
275
276           while ((c = *++s) && c != ';')
277             if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
278               g = string_catn(g, s, 1);
279           if (!g) return US"no bh= value";
280           al->bh.data = string_from_gstring(g);
281           al->bh.len = g->ptr;
282           gstring_release_unused(g);
283           break;
284         default:
285           return US"b? tag";
286         }
287       }
288       break;
289     case 'c':
290       switch (*s)
291         {
292         case '=':                       /* c= AMS canonicalisation */
293           if (arc_insert_tagvalue(al, offsetof(arc_line, c), &s)) return US"c tag dup";
294
295           /* substructure: head/body   (eg. relaxed/simple)) */
296
297           t = al->c_head.data = al->c.data;
298           while (isalpha(*t))
299             if (!*t++ || ++i > al->a.len) break;
300           al->c_head.len = i;
301           if (*t++ == '/')              /* /body is optional */
302             {
303             al->c_body.data = t;
304             al->c_body.len = al->c.len - i - 1;
305             }
306           else
307             {
308             al->c_body.data = US"simple";
309             al->c_body.len = 6;
310             }
311           break;
312         case 'v':                       /* cv= AS validity */
313           if (*++s != '=') return US"cv tag val";
314           if (arc_insert_tagvalue(al, offsetof(arc_line, cv), &s)) return US"cv tag dup";
315           break;
316         default:
317           return US"c? tag";
318         }
319       break;
320     case 'd':                           /* d= AMS domain */
321       if (*s != '=') return US"d tag val";
322       if (arc_insert_tagvalue(al, offsetof(arc_line, d), &s)) return US"d tag dup";
323       break;
324     case 'h':                           /* h= AMS headers */
325       if (*s != '=') return US"h tag val";
326       if (arc_insert_tagvalue(al, offsetof(arc_line, h), &s)) return US"h tag dup";
327       break;
328     case 'i':                           /* i= ARC set instance */
329       if (*s != '=') return US"i tag val";
330       if (arc_insert_tagvalue(al, offsetof(arc_line, i), &s)) return US"i tag dup";
331       if (instance_only) goto done;
332       break;
333     case 'l':                           /* l= bodylength */
334       if (*s != '=') return US"l tag val";
335       if (arc_insert_tagvalue(al, offsetof(arc_line, l), &s)) return US"l tag dup";
336       break;
337     case 's':                           /* s= AMS selector */
338       if (*s != '=') return US"s tag val";
339       if (arc_insert_tagvalue(al, offsetof(arc_line, s), &s)) return US"s tag dup";
340       break;
341     }
342
343   while ((c = *s) && c != ';') s++;
344   if (c) s++;                           /* ; after tag-spec */
345
346   /* for all but the b= tag, copy the field including FWS.  For the b=,
347   drop the tag content. */
348
349   if (!instance_only)
350     if (bstart)
351       {
352       size_t n = bstart - fieldstart;
353       memcpy(r, fieldstart, n);         /* FWS "b=" */
354       r += n;
355       al->rawsig_no_b_val.len += n;
356       n = s - bend;
357       memcpy(r, bend, n);               /* FWS ";" */
358       r += n;
359       al->rawsig_no_b_val.len += n;
360       }
361     else
362       {
363       size_t n = s - fieldstart;
364       memcpy(r, fieldstart, n);
365       r += n;
366       al->rawsig_no_b_val.len += n;
367       }
368   }
369
370 if (!instance_only)
371   *r = '\0';
372
373 done:
374 /* debug_printf("%s: finshed\n", __FUNCTION__); */
375 return NULL;
376 }
377
378
379 /* Insert one header line in the correct set of the chain,
380 adding instances as needed and checking for duplicate lines.
381 */
382
383 static uschar *
384 arc_insert_hdr(arc_ctx * ctx, header_line * h, unsigned off, unsigned hoff,
385   BOOL instance_only, arc_line ** alp_ret)
386 {
387 unsigned i;
388 arc_set * as;
389 arc_line * al = store_get(sizeof(arc_line), GET_UNTAINTED), ** alp;
390 uschar * e;
391
392 memset(al, 0, sizeof(arc_line));
393
394 if ((e = arc_parse_line(al, h, off, instance_only)))
395   {
396   DEBUG(D_acl) if (e) debug_printf("ARC: %s\n", e);
397   return US"line parse";
398   }
399 if (!(i = arc_instance_from_hdr(al)))   return US"instance find";
400 if (i > 50)                             return US"overlarge instance number";
401 if (!(as = arc_find_set(ctx, i)))       return US"set find";
402 if (*(alp = (arc_line **)(US as + hoff))) return US"dup hdr";
403
404 *alp = al;
405 if (alp_ret) *alp_ret = al;
406 return NULL;
407 }
408
409
410
411
412 static const uschar *
413 arc_try_header(arc_ctx * ctx, header_line * h, BOOL instance_only)
414 {
415 const uschar * e;
416
417 /*debug_printf("consider hdr '%s'\n", h->text);*/
418 if (strncmpic(ARC_HDR_AAR, h->text, ARC_HDRLEN_AAR) == 0)
419   {
420   DEBUG(D_acl)
421     {
422     int len = h->slen;
423     uschar * s;
424     for (s = h->text + h->slen; s[-1] == '\r' || s[-1] == '\n'; )
425       s--, len--;
426     debug_printf("ARC: found AAR: %.*s\n", len, h->text);
427     }
428   if ((e = arc_insert_hdr(ctx, h, ARC_HDRLEN_AAR, offsetof(arc_set, hdr_aar),
429                           TRUE, NULL)))
430     {
431     DEBUG(D_acl) debug_printf("inserting AAR: %s\n", e);
432     return US"inserting AAR";
433     }
434   }
435 else if (strncmpic(ARC_HDR_AMS, h->text, ARC_HDRLEN_AMS) == 0)
436   {
437   arc_line * ams;
438
439   DEBUG(D_acl)
440     {
441     int len = h->slen;
442     uschar * s;
443     for (s = h->text + h->slen; s[-1] == '\r' || s[-1] == '\n'; )
444       s--, len--;
445     debug_printf("ARC: found AMS: %.*s\n", len, h->text);
446     }
447   if ((e = arc_insert_hdr(ctx, h, ARC_HDRLEN_AMS, offsetof(arc_set, hdr_ams),
448                           instance_only, &ams)))
449     {
450     DEBUG(D_acl) debug_printf("inserting AMS: %s\n", e);
451     return US"inserting AMS";
452     }
453
454   /* defaults */
455   if (!ams->c.data)
456     {
457     ams->c_head.data = US"simple"; ams->c_head.len = 6;
458     ams->c_body = ams->c_head;
459     }
460   }
461 else if (strncmpic(ARC_HDR_AS, h->text, ARC_HDRLEN_AS) == 0)
462   {
463   DEBUG(D_acl)
464     {
465     int len = h->slen;
466     uschar * s;
467     for (s = h->text + h->slen; s[-1] == '\r' || s[-1] == '\n'; )
468       s--, len--;
469     debug_printf("ARC: found AS: %.*s\n", len, h->text);
470     }
471   if ((e = arc_insert_hdr(ctx, h, ARC_HDRLEN_AS, offsetof(arc_set, hdr_as),
472                           instance_only, NULL)))
473     {
474     DEBUG(D_acl) debug_printf("inserting AS: %s\n", e);
475     return US"inserting AS";
476     }
477   }
478 return NULL;
479 }
480
481
482
483 /* Gather the chain of arc sets from the headers.
484 Check for duplicates while that is done.  Also build the
485 reverse-order headers list;
486
487 Return: ARC state if determined, eg. by lack of any ARC chain.
488 */
489
490 static const uschar *
491 arc_vfy_collect_hdrs(arc_ctx * ctx)
492 {
493 header_line * h;
494 hdr_rlist * r = NULL, * rprev = NULL;
495 const uschar * e;
496
497 DEBUG(D_acl) debug_printf("ARC: collecting arc sets\n");
498 for (h = header_list; h; h = h->next)
499   {
500   r = store_get(sizeof(hdr_rlist), GET_UNTAINTED);
501   r->prev = rprev;
502   r->used = FALSE;
503   r->h = h;
504   rprev = r;
505
506   if ((e = arc_try_header(ctx, h, FALSE)))
507     {
508     arc_state_reason = string_sprintf("collecting headers: %s", e);
509     return US"fail";
510     }
511   }
512 headers_rlist = r;
513
514 if (!ctx->arcset_chain) return US"none";
515 return NULL;
516 }
517
518
519 static BOOL
520 arc_cv_match(arc_line * al, const uschar * s)
521 {
522 return Ustrncmp(s, al->cv.data, al->cv.len) == 0;
523 }
524
525 /******************************************************************************/
526
527 /* Return the hash of headers from the message that the AMS claims it
528 signed.
529 */
530
531 static void
532 arc_get_verify_hhash(arc_ctx * ctx, arc_line * ams, blob * hhash)
533 {
534 const uschar * headernames = string_copyn(ams->h.data, ams->h.len);
535 const uschar * hn;
536 int sep = ':';
537 hdr_rlist * r;
538 BOOL relaxed = Ustrncmp(US"relaxed", ams->c_head.data, ams->c_head.len) == 0;
539 int hashtype = pdkim_hashname_to_hashtype(
540                     ams->a_hash.data, ams->a_hash.len);
541 hctx hhash_ctx;
542 const uschar * s;
543 int len;
544
545 if (  hashtype == -1
546    || !exim_sha_init(&hhash_ctx, pdkim_hashes[hashtype].exim_hashmethod))
547   {
548   DEBUG(D_acl)
549       debug_printf("ARC: hash setup error, possibly nonhandled hashtype\n");
550   return;
551   }
552
553 /* For each headername in the list from the AMS (walking in order)
554 walk the message headers in reverse order, adding to the hash any
555 found for the first time. For that last point, maintain used-marks
556 on the list of message headers. */
557
558 DEBUG(D_acl) debug_printf("ARC: AMS header data for verification:\n");
559
560 for (r = headers_rlist; r; r = r->prev)
561   r->used = FALSE;
562 while ((hn = string_nextinlist(&headernames, &sep, NULL, 0)))
563   for (r = headers_rlist; r; r = r->prev)
564     if (  !r->used
565        && strncasecmp(CCS (s = r->h->text), CCS hn, Ustrlen(hn)) == 0
566        )
567       {
568       if (relaxed) s = pdkim_relax_header_n(s, r->h->slen, TRUE);
569
570       len = Ustrlen(s);
571       DEBUG(D_acl) pdkim_quoteprint(s, len);
572       exim_sha_update_string(&hhash_ctx, s);
573       r->used = TRUE;
574       break;
575       }
576
577 /* Finally add in the signature header (with the b= tag stripped); no CRLF */
578
579 s = ams->rawsig_no_b_val.data, len = ams->rawsig_no_b_val.len;
580 if (relaxed)
581   len = Ustrlen(s = pdkim_relax_header_n(s, len, FALSE));
582 DEBUG(D_acl) pdkim_quoteprint(s, len);
583 exim_sha_update(&hhash_ctx, s, len);
584
585 exim_sha_finish(&hhash_ctx, hhash);
586 DEBUG(D_acl)
587   { debug_printf("ARC: header hash: "); pdkim_hexprint(hhash->data, hhash->len); }
588 return;
589 }
590
591
592
593
594 static pdkim_pubkey *
595 arc_line_to_pubkey(arc_line * al)
596 {
597 uschar * dns_txt;
598 pdkim_pubkey * p;
599
600 if (!(dns_txt = dkim_exim_query_dns_txt(string_sprintf("%.*s._domainkey.%.*s",
601           (int)al->s.len, al->s.data, (int)al->d.len, al->d.data))))
602   {
603   DEBUG(D_acl) debug_printf("pubkey dns lookup fail\n");
604   return NULL;
605   }
606
607 if (  !(p = pdkim_parse_pubkey_record(dns_txt))
608    || (Ustrcmp(p->srvtype, "*") != 0 && Ustrcmp(p->srvtype, "email") != 0)
609    )
610   {
611   DEBUG(D_acl) debug_printf("pubkey dns lookup format error\n");
612   return NULL;
613   }
614
615 /* If the pubkey limits use to specified hashes, reject unusable
616 signatures. XXX should we have looked for multiple dns records? */
617
618 if (p->hashes)
619   {
620   const uschar * list = p->hashes, * ele;
621   int sep = ':';
622
623   while ((ele = string_nextinlist(&list, &sep, NULL, 0)))
624     if (Ustrncmp(ele, al->a_hash.data, al->a_hash.len) == 0) break;
625   if (!ele)
626     {
627     DEBUG(D_acl) debug_printf("pubkey h=%s vs sig a=%.*s\n",
628                               p->hashes, (int)al->a.len, al->a.data);
629     return NULL;
630     }
631   }
632 return p;
633 }
634
635
636
637
638 static pdkim_bodyhash *
639 arc_ams_setup_vfy_bodyhash(arc_line * ams)
640 {
641 int canon_head = -1, canon_body = -1;
642 long bodylen;
643
644 if (!ams->c.data) ams->c.data = US"simple";     /* RFC 6376 (DKIM) default */
645 pdkim_cstring_to_canons(ams->c.data, ams->c.len, &canon_head, &canon_body);
646 bodylen = ams->l.data
647         ? strtol(CS string_copyn(ams->l.data, ams->l.len), NULL, 10) : -1;
648
649 return pdkim_set_bodyhash(dkim_verify_ctx,
650         pdkim_hashname_to_hashtype(ams->a_hash.data, ams->a_hash.len),
651         canon_body,
652         bodylen);
653 }
654
655
656
657 /* Verify an AMS. This is a DKIM-sig header, but with an ARC i= tag
658 and without a DKIM v= tag.
659 */
660
661 static const uschar *
662 arc_ams_verify(arc_ctx * ctx, arc_set * as)
663 {
664 arc_line * ams = as->hdr_ams;
665 pdkim_bodyhash * b;
666 pdkim_pubkey * p;
667 blob sighash;
668 blob hhash;
669 ev_ctx vctx;
670 int hashtype;
671 const uschar * errstr;
672
673 as->ams_verify_done = US"in-progress";
674
675 /* Check the AMS has all the required tags:
676    "a="  algorithm
677    "b="  signature
678    "bh=" body hash
679    "d="  domain (for key lookup)
680    "h="  headers (included in signature)
681    "s="  key-selector (for key lookup)
682 */
683 if (  !ams->a.data || !ams->b.data || !ams->bh.data || !ams->d.data
684    || !ams->h.data || !ams->s.data)
685   {
686   as->ams_verify_done = arc_state_reason = US"required tag missing";
687   return US"fail";
688   }
689
690
691 /* The bodyhash should have been created earlier, and the dkim code should
692 have managed calculating it during message input.  Find the reference to it. */
693
694 if (!(b = arc_ams_setup_vfy_bodyhash(ams)))
695   {
696   as->ams_verify_done = arc_state_reason = US"internal hash setup error";
697   return US"fail";
698   }
699
700 DEBUG(D_acl)
701   {
702   debug_printf("ARC i=%d AMS   Body bytes hashed: %lu\n"
703                "              Body %.*s computed: ",
704                as->instance, b->signed_body_bytes,
705                (int)ams->a_hash.len, ams->a_hash.data);
706   pdkim_hexprint(CUS b->bh.data, b->bh.len);
707   }
708
709 /* We know the bh-tag blob is of a nul-term string, so safe as a string */
710
711 if (  !ams->bh.data
712    || (pdkim_decode_base64(ams->bh.data, &sighash), sighash.len != b->bh.len)
713    || memcmp(sighash.data, b->bh.data, b->bh.len) != 0
714    )
715   {
716   DEBUG(D_acl)
717     {
718     debug_printf("ARC i=%d AMS Body hash from headers: ", as->instance);
719     pdkim_hexprint(sighash.data, sighash.len);
720     debug_printf("ARC i=%d AMS Body hash did NOT match\n", as->instance);
721     }
722   return as->ams_verify_done = arc_state_reason = US"AMS body hash miscompare";
723   }
724
725 DEBUG(D_acl) debug_printf("ARC i=%d AMS Body hash compared OK\n", as->instance);
726
727 /* Get the public key from DNS */
728
729 if (!(p = arc_line_to_pubkey(ams)))
730   return as->ams_verify_done = arc_state_reason = US"pubkey problem";
731
732 /* We know the b-tag blob is of a nul-term string, so safe as a string */
733 pdkim_decode_base64(ams->b.data, &sighash);
734
735 arc_get_verify_hhash(ctx, ams, &hhash);
736
737 /* Setup the interface to the signing library */
738
739 if ((errstr = exim_dkim_verify_init(&p->key, KEYFMT_DER, &vctx, NULL)))
740   {
741   DEBUG(D_acl) debug_printf("ARC verify init: %s\n", errstr);
742   as->ams_verify_done = arc_state_reason = US"internal sigverify init error";
743   return US"fail";
744   }
745
746 hashtype = pdkim_hashname_to_hashtype(ams->a_hash.data, ams->a_hash.len);
747 if (hashtype == -1)
748   {
749   DEBUG(D_acl) debug_printf("ARC i=%d AMS verify bad a_hash\n", as->instance);
750   return as->ams_verify_done = arc_state_reason = US"AMS sig nonverify";
751   }
752
753 if ((errstr = exim_dkim_verify(&vctx,
754           pdkim_hashes[hashtype].exim_hashmethod, &hhash, &sighash)))
755   {
756   DEBUG(D_acl) debug_printf("ARC i=%d AMS verify %s\n", as->instance, errstr);
757   return as->ams_verify_done = arc_state_reason = US"AMS sig nonverify";
758   }
759
760 DEBUG(D_acl) debug_printf("ARC i=%d AMS verify pass\n", as->instance);
761 as->ams_verify_passed = TRUE;
762 return NULL;
763 }
764
765
766
767 /* Check the sets are instance-continuous and that all
768 members are present.  Check that no arc_seals are "fail".
769 Set the highest instance number global.
770 Verify the latest AMS.
771 */
772 static uschar *
773 arc_headers_check(arc_ctx * ctx)
774 {
775 arc_set * as;
776 int inst;
777 BOOL ams_fail_found = FALSE;
778
779 if (!(as = ctx->arcset_chain_last))
780   return US"none";
781
782 for(inst = as->instance; as; as = as->prev, inst--)
783   {
784   if (as->instance != inst)
785     arc_state_reason = string_sprintf("i=%d (sequence; expected %d)",
786       as->instance, inst);
787   else if (!as->hdr_aar || !as->hdr_ams || !as->hdr_as)
788     arc_state_reason = string_sprintf("i=%d (missing header)", as->instance);
789   else if (arc_cv_match(as->hdr_as, US"fail"))
790     arc_state_reason = string_sprintf("i=%d (cv)", as->instance);
791   else
792     goto good;
793
794   DEBUG(D_acl) debug_printf("ARC chain fail at %s\n", arc_state_reason);
795   return US"fail";
796
797   good:
798   /* Evaluate the oldest-pass AMS validation while we're here.
799   It does not affect the AS chain validation but is reported as
800   auxilary info. */
801
802   if (!ams_fail_found)
803     if (arc_ams_verify(ctx, as))
804       ams_fail_found = TRUE;
805     else
806       arc_oldest_pass = inst;
807   arc_state_reason = NULL;
808   }
809 if (inst != 0)
810   {
811   arc_state_reason = string_sprintf("(sequence; expected i=%d)", inst);
812   DEBUG(D_acl) debug_printf("ARC chain fail %s\n", arc_state_reason);
813   return US"fail";
814   }
815
816 arc_received = ctx->arcset_chain_last;
817 arc_received_instance = arc_received->instance;
818
819 /* We can skip the latest-AMS validation, if we already did it. */
820
821 as = ctx->arcset_chain_last;
822 if (!as->ams_verify_passed)
823   {
824   if (as->ams_verify_done)
825     {
826     arc_state_reason = as->ams_verify_done;
827     return US"fail";
828     }
829   if (!!arc_ams_verify(ctx, as))
830     return US"fail";
831   }
832 return NULL;
833 }
834
835
836 /******************************************************************************/
837 static const uschar *
838 arc_seal_verify(arc_ctx * ctx, arc_set * as)
839 {
840 arc_line * hdr_as = as->hdr_as;
841 arc_set * as2;
842 int hashtype;
843 hctx hhash_ctx;
844 blob hhash_computed;
845 blob sighash;
846 ev_ctx vctx;
847 pdkim_pubkey * p;
848 const uschar * errstr;
849
850 DEBUG(D_acl) debug_printf("ARC: AS vfy i=%d\n", as->instance);
851 /*
852        1.  If the value of the "cv" tag on that seal is "fail", the
853            chain state is "fail" and the algorithm stops here.  (This
854            step SHOULD be skipped if the earlier step (2.1) was
855            performed) [it was]
856
857        2.  In Boolean nomenclature: if ((i == 1 && cv != "none") or (cv
858            == "none" && i != 1)) then the chain state is "fail" and the
859            algorithm stops here (note that the ordering of the logic is
860            structured for short-circuit evaluation).
861 */
862
863 if (  as->instance == 1 && !arc_cv_match(hdr_as, US"none")
864    || arc_cv_match(hdr_as, US"none") && as->instance != 1
865    )
866   {
867   arc_state_reason = US"seal cv state";
868   return US"fail";
869   }
870
871 /*
872        3.  Initialize a hash function corresponding to the "a" tag of
873            the ARC-Seal.
874 */
875
876 hashtype = pdkim_hashname_to_hashtype(hdr_as->a_hash.data, hdr_as->a_hash.len);
877
878 if (  hashtype == -1
879    || !exim_sha_init(&hhash_ctx, pdkim_hashes[hashtype].exim_hashmethod))
880   {
881   DEBUG(D_acl)
882       debug_printf("ARC: hash setup error, possibly nonhandled hashtype\n");
883   arc_state_reason = US"seal hash setup error";
884   return US"fail";
885   }
886
887 /*
888        4.  Compute the canonicalized form of the ARC header fields, in
889            the order described in Section 5.4.2, using the "relaxed"
890            header canonicalization defined in Section 3.4.2 of
891            [RFC6376].  Pass the canonicalized result to the hash
892            function.
893
894 Headers are CRLF-separated, but the last one is not crlf-terminated.
895 */
896
897 DEBUG(D_acl) debug_printf("ARC: AS header data for verification:\n");
898 for (as2 = ctx->arcset_chain;
899      as2 && as2->instance <= as->instance;
900      as2 = as2->next)
901   {
902   arc_line * al;
903   uschar * s;
904   int len;
905
906   al = as2->hdr_aar;
907   if (!(s = al->relaxed))
908     al->relaxed = s = pdkim_relax_header_n(al->complete->text,
909                                             al->complete->slen, TRUE);
910   len = Ustrlen(s);
911   DEBUG(D_acl) pdkim_quoteprint(s, len);
912   exim_sha_update(&hhash_ctx, s, len);
913
914   al = as2->hdr_ams;
915   if (!(s = al->relaxed))
916     al->relaxed = s = pdkim_relax_header_n(al->complete->text,
917                                             al->complete->slen, TRUE);
918   len = Ustrlen(s);
919   DEBUG(D_acl) pdkim_quoteprint(s, len);
920   exim_sha_update(&hhash_ctx, s, len);
921
922   al = as2->hdr_as;
923   if (as2->instance == as->instance)
924     s = pdkim_relax_header_n(al->rawsig_no_b_val.data,
925                                         al->rawsig_no_b_val.len, FALSE);
926   else if (!(s = al->relaxed))
927     al->relaxed = s = pdkim_relax_header_n(al->complete->text,
928                                             al->complete->slen, TRUE);
929   len = Ustrlen(s);
930   DEBUG(D_acl) pdkim_quoteprint(s, len);
931   exim_sha_update(&hhash_ctx, s, len);
932   }
933
934 /*
935        5.  Retrieve the final digest from the hash function.
936 */
937
938 exim_sha_finish(&hhash_ctx, &hhash_computed);
939 DEBUG(D_acl)
940   {
941   debug_printf("ARC i=%d AS Header %.*s computed: ",
942     as->instance, (int)hdr_as->a_hash.len, hdr_as->a_hash.data);
943   pdkim_hexprint(hhash_computed.data, hhash_computed.len);
944   }
945
946
947 /*
948        6.  Retrieve the public key identified by the "s" and "d" tags in
949            the ARC-Seal, as described in Section 4.1.6.
950 */
951
952 if (!(p = arc_line_to_pubkey(hdr_as)))
953   return US"pubkey problem";
954
955 /*
956        7.  Determine whether the signature portion ("b" tag) of the ARC-
957            Seal and the digest computed above are valid according to the
958            public key.  (See also Section Section 8.4 for failure case
959            handling)
960
961        8.  If the signature is not valid, the chain state is "fail" and
962            the algorithm stops here.
963 */
964
965 /* We know the b-tag blob is of a nul-term string, so safe as a string */
966 pdkim_decode_base64(hdr_as->b.data, &sighash);
967
968 if ((errstr = exim_dkim_verify_init(&p->key, KEYFMT_DER, &vctx, NULL)))
969   {
970   DEBUG(D_acl) debug_printf("ARC verify init: %s\n", errstr);
971   return US"fail";
972   }
973
974 if ((errstr = exim_dkim_verify(&vctx,
975               pdkim_hashes[hashtype].exim_hashmethod,
976               &hhash_computed, &sighash)))
977   {
978   DEBUG(D_acl)
979     debug_printf("ARC i=%d AS headers verify: %s\n", as->instance, errstr);
980   arc_state_reason = US"seal sigverify error";
981   return US"fail";
982   }
983
984 DEBUG(D_acl) debug_printf("ARC: AS vfy i=%d pass\n", as->instance);
985 return NULL;
986 }
987
988
989 static const uschar *
990 arc_verify_seals(arc_ctx * ctx)
991 {
992 arc_set * as = ctx->arcset_chain_last;
993
994 if (!as)
995   return US"none";
996
997 for ( ; as; as = as->prev) if (arc_seal_verify(ctx, as)) return US"fail";
998
999 DEBUG(D_acl) debug_printf("ARC: AS vfy overall pass\n");
1000 return NULL;
1001 }
1002 /******************************************************************************/
1003
1004 /* Do ARC verification.  Called from DATA ACL, on a verify = arc
1005 condition.  No arguments; we are checking globals.
1006
1007 Return:  The ARC state, or NULL on error.
1008 */
1009
1010 const uschar *
1011 acl_verify_arc(void)
1012 {
1013 const uschar * res;
1014
1015 memset(&arc_verify_ctx, 0, sizeof(arc_verify_ctx));
1016
1017 if (!dkim_verify_ctx)
1018   {
1019   DEBUG(D_acl) debug_printf("ARC: no DKIM verify context\n");
1020   return NULL;
1021   }
1022
1023 /* AS evaluation, per
1024 https://tools.ietf.org/html/draft-ietf-dmarc-arc-protocol-10#section-6
1025 */
1026 /* 1.  Collect all ARC sets currently on the message.  If there were
1027        none, the ARC state is "none" and the algorithm stops here.
1028 */
1029
1030 if ((res = arc_vfy_collect_hdrs(&arc_verify_ctx)))
1031   goto out;
1032
1033 /* 2.  If the form of any ARC set is invalid (e.g., does not contain
1034        exactly one of each of the three ARC-specific header fields),
1035        then the chain state is "fail" and the algorithm stops here.
1036
1037        1.  To avoid the overhead of unnecessary computation and delay
1038            from crypto and DNS operations, the cv value for all ARC-
1039            Seal(s) MAY be checked at this point.  If any of the values
1040            are "fail", then the overall state of the chain is "fail" and
1041            the algorithm stops here.
1042
1043    3.  Conduct verification of the ARC-Message-Signature header field
1044        bearing the highest instance number.  If this verification fails,
1045        then the chain state is "fail" and the algorithm stops here.
1046 */
1047
1048 if ((res = arc_headers_check(&arc_verify_ctx)))
1049   goto out;
1050
1051 /* 4.  For each ARC-Seal from the "N"th instance to the first, apply the
1052        following logic:
1053
1054        1.  If the value of the "cv" tag on that seal is "fail", the
1055            chain state is "fail" and the algorithm stops here.  (This
1056            step SHOULD be skipped if the earlier step (2.1) was
1057            performed)
1058
1059        2.  In Boolean nomenclature: if ((i == 1 && cv != "none") or (cv
1060            == "none" && i != 1)) then the chain state is "fail" and the
1061            algorithm stops here (note that the ordering of the logic is
1062            structured for short-circuit evaluation).
1063
1064        3.  Initialize a hash function corresponding to the "a" tag of
1065            the ARC-Seal.
1066
1067        4.  Compute the canonicalized form of the ARC header fields, in
1068            the order described in Section 5.4.2, using the "relaxed"
1069            header canonicalization defined in Section 3.4.2 of
1070            [RFC6376].  Pass the canonicalized result to the hash
1071            function.
1072
1073        5.  Retrieve the final digest from the hash function.
1074
1075        6.  Retrieve the public key identified by the "s" and "d" tags in
1076            the ARC-Seal, as described in Section 4.1.6.
1077
1078        7.  Determine whether the signature portion ("b" tag) of the ARC-
1079            Seal and the digest computed above are valid according to the
1080            public key.  (See also Section Section 8.4 for failure case
1081            handling)
1082
1083        8.  If the signature is not valid, the chain state is "fail" and
1084            the algorithm stops here.
1085
1086    5.  If all seals pass validation, then the chain state is "pass", and
1087        the algorithm is complete.
1088 */
1089
1090 if ((res = arc_verify_seals(&arc_verify_ctx)))
1091   goto out;
1092
1093 res = US"pass";
1094
1095 out:
1096   return res;
1097 }
1098
1099 /******************************************************************************/
1100
1101 /* Prepend the header to the rlist */
1102
1103 static hdr_rlist *
1104 arc_rlist_entry(hdr_rlist * list, const uschar * s, int len)
1105 {
1106 hdr_rlist * r = store_get(sizeof(hdr_rlist) + sizeof(header_line), GET_UNTAINTED);
1107 header_line * h = r->h = (header_line *)(r+1);
1108
1109 r->prev = list;
1110 r->used = FALSE;
1111 h->next = NULL;
1112 h->type = 0;
1113 h->slen = len;
1114 h->text = US s;
1115
1116 /* This works for either NL or CRLF lines; also nul-termination */
1117 while (*++s)
1118   if (*s == '\n' && s[1] != '\t' && s[1] != ' ') break;
1119 s++;            /* move past end of line */
1120
1121 return r;
1122 }
1123
1124
1125 /* Walk the given headers strings identifying each header, and construct
1126 a reverse-order list.
1127 */
1128
1129 static hdr_rlist *
1130 arc_sign_scan_headers(arc_ctx * ctx, gstring * sigheaders)
1131 {
1132 const uschar * s;
1133 hdr_rlist * rheaders = NULL;
1134
1135 s = sigheaders ? sigheaders->s : NULL;
1136 if (s) while (*s)
1137   {
1138   const uschar * s2 = s;
1139
1140   /* This works for either NL or CRLF lines; also nul-termination */
1141   while (*++s2)
1142     if (*s2 == '\n' && s2[1] != '\t' && s2[1] != ' ') break;
1143   s2++;         /* move past end of line */
1144
1145   rheaders = arc_rlist_entry(rheaders, s, s2 - s);
1146   s = s2;
1147   }
1148 return rheaders;
1149 }
1150
1151
1152
1153 /* Return the A-R content, without identity, with line-ending and
1154 NUL termination. */
1155
1156 static BOOL
1157 arc_sign_find_ar(header_line * headers, const uschar * identity, blob * ret)
1158 {
1159 header_line * h;
1160 int ilen = Ustrlen(identity);
1161
1162 ret->data = NULL;
1163 for(h = headers; h; h = h->next)
1164   {
1165   uschar * s = h->text, c;
1166   int len = h->slen;
1167
1168   if (Ustrncmp(s, HDR_AR, HDRLEN_AR) != 0) continue;
1169   s += HDRLEN_AR, len -= HDRLEN_AR;             /* header name */
1170   while (  len > 0
1171         && (c = *s) && (c == ' ' || c == '\t' || c == '\r' || c == '\n'))
1172     s++, len--;                                 /* FWS */
1173   if (Ustrncmp(s, identity, ilen) != 0) continue;
1174   s += ilen; len -= ilen;                       /* identity */
1175   if (len <= 0) continue;
1176   if ((c = *s) && c == ';') s++, len--;         /* identity terminator */
1177   while (  len > 0
1178         && (c = *s) && (c == ' ' || c == '\t' || c == '\r' || c == '\n'))
1179     s++, len--;                                 /* FWS */
1180   if (len <= 0) continue;
1181   ret->data = s;
1182   ret->len = len;
1183   return TRUE;
1184   }
1185 return FALSE;
1186 }
1187
1188
1189
1190 /* Append a constructed AAR including CRLF.  Add it to the arc_ctx too.  */
1191
1192 static gstring *
1193 arc_sign_append_aar(gstring * g, arc_ctx * ctx,
1194   const uschar * identity, int instance, blob * ar)
1195 {
1196 int aar_off = gstring_length(g);
1197 arc_set * as =
1198   store_get(sizeof(arc_set) + sizeof(arc_line) + sizeof(header_line), GET_UNTAINTED);
1199 arc_line * al = (arc_line *)(as+1);
1200 header_line * h = (header_line *)(al+1);
1201
1202 g = string_catn(g, ARC_HDR_AAR, ARC_HDRLEN_AAR);
1203 g = string_fmt_append(g, " i=%d; %s;\r\n\t", instance, identity);
1204 g = string_catn(g, US ar->data, ar->len);
1205
1206 h->slen = g->ptr - aar_off;
1207 h->text = g->s + aar_off;
1208 al->complete = h;
1209 as->next = NULL;
1210 as->prev = ctx->arcset_chain_last;
1211 as->instance = instance;
1212 as->hdr_aar = al;
1213 if (instance == 1)
1214   ctx->arcset_chain = as;
1215 else
1216   ctx->arcset_chain_last->next = as;
1217 ctx->arcset_chain_last = as;
1218
1219 DEBUG(D_transport) debug_printf("ARC: AAR '%.*s'\n", h->slen - 2, h->text);
1220 return g;
1221 }
1222
1223
1224
1225 static BOOL
1226 arc_sig_from_pseudoheader(gstring * hdata, int hashtype, const uschar * privkey,
1227   blob * sig, const uschar * why)
1228 {
1229 hashmethod hm = /*sig->keytype == KEYTYPE_ED25519*/ FALSE
1230   ? HASH_SHA2_512 : pdkim_hashes[hashtype].exim_hashmethod;
1231 blob hhash;
1232 es_ctx sctx;
1233 const uschar * errstr;
1234
1235 DEBUG(D_transport)
1236   {
1237   hctx hhash_ctx;
1238   debug_printf("ARC: %s header data for signing:\n", why);
1239   pdkim_quoteprint(hdata->s, hdata->ptr);
1240
1241   (void) exim_sha_init(&hhash_ctx, pdkim_hashes[hashtype].exim_hashmethod);
1242   exim_sha_update(&hhash_ctx, hdata->s, hdata->ptr);
1243   exim_sha_finish(&hhash_ctx, &hhash);
1244   debug_printf("ARC: header hash: "); pdkim_hexprint(hhash.data, hhash.len);
1245   }
1246
1247 if (FALSE /*need hash for Ed25519 or GCrypt signing*/ )
1248   {
1249   hctx hhash_ctx;
1250   (void) exim_sha_init(&hhash_ctx, pdkim_hashes[hashtype].exim_hashmethod);
1251   exim_sha_update(&hhash_ctx, hdata->s, hdata->ptr);
1252   exim_sha_finish(&hhash_ctx, &hhash);
1253   }
1254 else
1255   {
1256   hhash.data = hdata->s;
1257   hhash.len = hdata->ptr;
1258   }
1259
1260 if (  (errstr = exim_dkim_signing_init(privkey, &sctx))
1261    || (errstr = exim_dkim_sign(&sctx, hm, &hhash, sig)))
1262   {
1263   log_write(0, LOG_MAIN, "ARC: %s signing: %s\n", why, errstr);
1264   DEBUG(D_transport)
1265     debug_printf("private key, or private-key file content, was: '%s'\n",
1266       privkey);
1267   return FALSE;
1268   }
1269 return TRUE;
1270 }
1271
1272
1273
1274 static gstring *
1275 arc_sign_append_sig(gstring * g, blob * sig)
1276 {
1277 /*debug_printf("%s: raw sig ", __FUNCTION__); pdkim_hexprint(sig->data, sig->len);*/
1278 sig->data = pdkim_encode_base64(sig);
1279 sig->len = Ustrlen(sig->data);
1280 for (;;)
1281   {
1282   int len = MIN(sig->len, 74);
1283   g = string_catn(g, sig->data, len);
1284   if ((sig->len -= len) == 0) break;
1285   sig->data += len;
1286   g = string_catn(g, US"\r\n\t  ", 5);
1287   }
1288 g = string_catn(g, US";\r\n", 3);
1289 gstring_release_unused(g);
1290 string_from_gstring(g);
1291 return g;
1292 }
1293
1294
1295 /* Append a constructed AMS including CRLF.  Add it to the arc_ctx too. */
1296
1297 static gstring *
1298 arc_sign_append_ams(gstring * g, arc_ctx * ctx, int instance,
1299   const uschar * identity, const uschar * selector, blob * bodyhash,
1300   hdr_rlist * rheaders, const uschar * privkey, unsigned options)
1301 {
1302 uschar * s;
1303 gstring * hdata = NULL;
1304 int col;
1305 int hashtype = pdkim_hashname_to_hashtype(US"sha256", 6);       /*XXX hardwired */
1306 blob sig;
1307 int ams_off;
1308 arc_line * al = store_get(sizeof(header_line) + sizeof(arc_line), GET_UNTAINTED);
1309 header_line * h = (header_line *)(al+1);
1310
1311 /* debug_printf("%s\n", __FUNCTION__); */
1312
1313 /* Construct the to-be-signed AMS pseudo-header: everything but the sig. */
1314
1315 ams_off = g->ptr;
1316 g = string_fmt_append(g, "%s i=%d; a=rsa-sha256; c=relaxed; d=%s; s=%s",
1317       ARC_HDR_AMS, instance, identity, selector);       /*XXX hardwired a= */
1318 if (options & ARC_SIGN_OPT_TSTAMP)
1319   g = string_fmt_append(g, "; t=%lu", (u_long)now);
1320 if (options & ARC_SIGN_OPT_EXPIRE)
1321   g = string_fmt_append(g, "; x=%lu", (u_long)expire);
1322 g = string_fmt_append(g, ";\r\n\tbh=%s;\r\n\th=",
1323       pdkim_encode_base64(bodyhash));
1324
1325 for(col = 3; rheaders; rheaders = rheaders->prev)
1326   {
1327   const uschar * hnames = US"DKIM-Signature:" PDKIM_DEFAULT_SIGN_HEADERS;
1328   uschar * name, * htext = rheaders->h->text;
1329   int sep = ':';
1330
1331   /* Spot headers of interest */
1332
1333   while ((name = string_nextinlist(&hnames, &sep, NULL, 0)))
1334     {
1335     int len = Ustrlen(name);
1336     if (strncasecmp(CCS htext, CCS name, len) == 0)
1337       {
1338       /* If too long, fold line in h= field */
1339
1340       if (col + len > 78) g = string_catn(g, US"\r\n\t  ", 5), col = 3;
1341
1342       /* Add name to h= list */
1343
1344       g = string_catn(g, name, len);
1345       g = string_catn(g, US":", 1);
1346       col += len + 1;
1347
1348       /* Accumulate header for hashing/signing */
1349
1350       hdata = string_cat(hdata,
1351                 pdkim_relax_header_n(htext, rheaders->h->slen, TRUE));  /*XXX hardwired */
1352       break;
1353       }
1354     }
1355   }
1356
1357 /* Lose the last colon from the h= list */
1358
1359 if (g->s[g->ptr - 1] == ':') g->ptr--;
1360
1361 g = string_catn(g, US";\r\n\tb=;", 7);
1362
1363 /* Include the pseudo-header in the accumulation */
1364
1365 s = pdkim_relax_header_n(g->s + ams_off, g->ptr - ams_off, FALSE);
1366 hdata = string_cat(hdata, s);
1367
1368 /* Calculate the signature from the accumulation */
1369 /*XXX does that need further relaxation? there are spaces embedded in the b= strings! */
1370
1371 if (!arc_sig_from_pseudoheader(hdata, hashtype, privkey, &sig, US"AMS"))
1372   return NULL;
1373
1374 /* Lose the trailing semicolon from the psuedo-header, and append the signature
1375 (folded over lines) and termination to complete it. */
1376
1377 g->ptr--;
1378 g = arc_sign_append_sig(g, &sig);
1379
1380 h->slen = g->ptr - ams_off;
1381 h->text = g->s + ams_off;
1382 al->complete = h;
1383 ctx->arcset_chain_last->hdr_ams = al;
1384
1385 DEBUG(D_transport) debug_printf("ARC: AMS '%.*s'\n", h->slen - 2, h->text);
1386 return g;
1387 }
1388
1389
1390
1391 /* Look for an arc= result in an A-R header blob.  We know that its data
1392 happens to be a NUL-term string. */
1393
1394 static uschar *
1395 arc_ar_cv_status(blob * ar)
1396 {
1397 const uschar * resinfo = ar->data;
1398 int sep = ';';
1399 uschar * methodspec, * s;
1400
1401 while ((methodspec = string_nextinlist(&resinfo, &sep, NULL, 0)))
1402   if (Ustrncmp(methodspec, US"arc=", 4) == 0)
1403     {
1404     uschar c;
1405     for (s = methodspec += 4;
1406          (c = *s) && c != ';' && c != ' ' && c != '\r' && c != '\n'; ) s++;
1407     return string_copyn(methodspec, s - methodspec);
1408     }
1409 return US"none";
1410 }
1411
1412
1413
1414 /* Build the AS header and prepend it */
1415
1416 static gstring *
1417 arc_sign_prepend_as(gstring * arcset_interim, arc_ctx * ctx,
1418   int instance, const uschar * identity, const uschar * selector, blob * ar,
1419   const uschar * privkey, unsigned options)
1420 {
1421 gstring * arcset;
1422 uschar * status = arc_ar_cv_status(ar);
1423 arc_line * al = store_get(sizeof(header_line) + sizeof(arc_line), GET_UNTAINTED);
1424 header_line * h = (header_line *)(al+1);
1425 uschar * badline_str;
1426
1427 gstring * hdata = NULL;
1428 int hashtype = pdkim_hashname_to_hashtype(US"sha256", 6);       /*XXX hardwired */
1429 blob sig;
1430
1431 /*
1432 - Generate AS
1433   - no body coverage
1434   - no h= tag; implicit coverage
1435   - arc status from A-R
1436     - if fail:
1437       - coverage is just the new ARC set
1438         including self (but with an empty b= in self)
1439     - if non-fail:
1440       - all ARC set headers, set-number order, aar then ams then as,
1441         including self (but with an empty b= in self)
1442 */
1443 DEBUG(D_transport) debug_printf("ARC: building AS for status '%s'\n", status);
1444
1445 /* Construct the AS except for the signature */
1446
1447 arcset = string_append(NULL, 9,
1448           ARC_HDR_AS,
1449           US" i=", string_sprintf("%d", instance),
1450           US"; cv=", status,
1451           US"; a=rsa-sha256; d=", identity,                     /*XXX hardwired */
1452           US"; s=", selector);                                  /*XXX same as AMS */
1453 if (options & ARC_SIGN_OPT_TSTAMP)
1454   arcset = string_append(arcset, 2,
1455       US"; t=", string_sprintf("%lu", (u_long)now));
1456 arcset = string_cat(arcset,
1457           US";\r\n\t b=;");
1458
1459 h->slen = arcset->ptr;
1460 h->text = arcset->s;
1461 al->complete = h;
1462 ctx->arcset_chain_last->hdr_as = al;
1463
1464 /* For any but "fail" chain-verify status, walk the entire chain in order by
1465 instance.  For fail, only the new arc-set.  Accumulate the elements walked. */
1466
1467 for (arc_set * as = Ustrcmp(status, US"fail") == 0
1468         ? ctx->arcset_chain_last : ctx->arcset_chain;
1469      as; as = as->next)
1470   {
1471   arc_line * l;
1472   /* Accumulate AAR then AMS then AS.  Relaxed canonicalisation
1473   is required per standard. */
1474
1475   badline_str = US"aar";
1476   if (!(l = as->hdr_aar)) goto badline;
1477   h = l->complete;
1478   hdata = string_cat(hdata, pdkim_relax_header_n(h->text, h->slen, TRUE));
1479   badline_str = US"ams";
1480   if (!(l = as->hdr_ams)) goto badline;
1481   h = l->complete;
1482   hdata = string_cat(hdata, pdkim_relax_header_n(h->text, h->slen, TRUE));
1483   badline_str = US"as";
1484   if (!(l = as->hdr_as)) goto badline;
1485   h = l->complete;
1486   hdata = string_cat(hdata, pdkim_relax_header_n(h->text, h->slen, !!as->next));
1487   }
1488
1489 /* Calculate the signature from the accumulation */
1490
1491 if (!arc_sig_from_pseudoheader(hdata, hashtype, privkey, &sig, US"AS"))
1492   return NULL;
1493
1494 /* Lose the trailing semicolon */
1495 arcset->ptr--;
1496 arcset = arc_sign_append_sig(arcset, &sig);
1497 DEBUG(D_transport) debug_printf("ARC: AS  '%.*s'\n", arcset->ptr - 2, arcset->s);
1498
1499 /* Finally, append the AMS and AAR to the new AS */
1500
1501 return string_catn(arcset, arcset_interim->s, arcset_interim->ptr);
1502
1503 badline:
1504   DEBUG(D_transport)
1505     debug_printf("ARC: while building AS, missing %s in chain\n", badline_str);
1506   return NULL;
1507 }
1508
1509
1510 /**************************************/
1511
1512 /* Return pointer to pdkim_bodyhash for given hash method, creating new
1513 method if needed.
1514 */
1515
1516 void *
1517 arc_ams_setup_sign_bodyhash(void)
1518 {
1519 int canon_head, canon_body;
1520
1521 DEBUG(D_transport) debug_printf("ARC: requesting bodyhash\n");
1522 pdkim_cstring_to_canons(US"relaxed", 7, &canon_head, &canon_body);      /*XXX hardwired */
1523 return pdkim_set_bodyhash(&dkim_sign_ctx,
1524         pdkim_hashname_to_hashtype(US"sha256", 6),                      /*XXX hardwired */
1525         canon_body,
1526         -1);
1527 }
1528
1529
1530
1531 void
1532 arc_sign_init(void)
1533 {
1534 memset(&arc_sign_ctx, 0, sizeof(arc_sign_ctx));
1535 }
1536
1537
1538
1539 /* A "normal" header line, identified by DKIM processing.  These arrive before
1540 the call to arc_sign(), which carries any newly-created DKIM headers - and
1541 those go textually before the normal ones in the message.
1542
1543 We have to take the feed from DKIM as, in the transport-filter case, the
1544 headers are not in memory at the time of the call to arc_sign().
1545
1546 Take a copy of the header and construct a reverse-order list.
1547 Also parse ARC-chain headers and build the chain struct, retaining pointers
1548 into the copies.
1549 */
1550
1551 static const uschar *
1552 arc_header_sign_feed(gstring * g)
1553 {
1554 uschar * s = string_copyn(g->s, g->ptr);
1555 headers_rlist = arc_rlist_entry(headers_rlist, s, g->ptr);
1556 return arc_try_header(&arc_sign_ctx, headers_rlist->h, TRUE);
1557 }
1558
1559
1560
1561 /* Per RFCs 6376, 7489 the only allowed chars in either an ADMD id
1562 or a selector are ALPHA/DIGGIT/'-'/'.'
1563
1564 Check, to help catch misconfigurations such as a missing selector
1565 element in the arc_sign list.
1566 */
1567
1568 static BOOL
1569 arc_valid_id(const uschar * s)
1570 {
1571 for (uschar c; c = *s++; )
1572   if (!isalnum(c) && c != '-' && c != '.') return FALSE;
1573 return TRUE;
1574 }
1575
1576
1577
1578 /* ARC signing.  Called from the smtp transport, if the arc_sign option is set.
1579 The dkim_exim_sign() function has already been called, so will have hashed the
1580 message body for us so long as we requested a hash previously.
1581
1582 Arguments:
1583   signspec      Three-element colon-sep list: identity, selector, privkey.
1584                 Optional fourth element: comma-sep list of options.
1585                 Already expanded
1586   sigheaders    Any signature headers already generated, eg. by DKIM, or NULL
1587   errstr        Error string
1588
1589 Return value
1590   Set of headers to prepend to the message, including the supplied sigheaders
1591   but not the plainheaders.
1592 */
1593
1594 gstring *
1595 arc_sign(const uschar * signspec, gstring * sigheaders, uschar ** errstr)
1596 {
1597 const uschar * identity, * selector, * privkey, * opts, * s;
1598 unsigned options = 0;
1599 int sep = 0;
1600 header_line * headers;
1601 hdr_rlist * rheaders;
1602 blob ar;
1603 int instance;
1604 gstring * g = NULL;
1605 pdkim_bodyhash * b;
1606
1607 expire = now = 0;
1608
1609 /* Parse the signing specification */
1610
1611 if (!(identity = string_nextinlist(&signspec, &sep, NULL, 0)) || !*identity)
1612   { s = US"identity"; goto bad_arg_ret; }
1613 if (!(selector = string_nextinlist(&signspec, &sep, NULL, 0)) || !*selector)
1614   { s = US"selector"; goto bad_arg_ret; }
1615 if (!(privkey = string_nextinlist(&signspec, &sep, NULL, 0))  || !*privkey)
1616   { s = US"privkey"; goto bad_arg_ret; }
1617 if (!arc_valid_id(identity))
1618   { s = US"identity"; goto bad_arg_ret; }
1619 if (!arc_valid_id(selector))
1620   { s = US"selector"; goto bad_arg_ret; }
1621 if (*privkey == '/' && !(privkey = expand_file_big_buffer(privkey)))
1622   goto ret_sigheaders;
1623
1624 if ((opts = string_nextinlist(&signspec, &sep, NULL, 0)))
1625   {
1626   int osep = ',';
1627   while ((s = string_nextinlist(&opts, &osep, NULL, 0)))
1628     if (Ustrcmp(s, "timestamps") == 0)
1629       {
1630       options |= ARC_SIGN_OPT_TSTAMP;
1631       if (!now) now = time(NULL);
1632       }
1633     else if (Ustrncmp(s, "expire", 6) == 0)
1634       {
1635       options |= ARC_SIGN_OPT_EXPIRE;
1636       if (*(s += 6) == '=')
1637         if (*++s == '+')
1638           {
1639           if (!(expire = (time_t)atoi(CS ++s)))
1640             expire = ARC_SIGN_DEFAULT_EXPIRE_DELTA;
1641           if (!now) now = time(NULL);
1642           expire += now;
1643           }
1644         else
1645           expire = (time_t)atol(CS s);
1646       else
1647         {
1648         if (!now) now = time(NULL);
1649         expire = now + ARC_SIGN_DEFAULT_EXPIRE_DELTA;
1650         }
1651       }
1652   }
1653
1654 DEBUG(D_transport) debug_printf("ARC: sign for %s\n", identity);
1655
1656 /* Make an rlist of any new DKIM headers, then add the "normals" rlist to it.
1657 Then scan the list for an A-R header. */
1658
1659 string_from_gstring(sigheaders);
1660 if ((rheaders = arc_sign_scan_headers(&arc_sign_ctx, sigheaders)))
1661   {
1662   hdr_rlist ** rp;
1663   for (rp = &headers_rlist; *rp; ) rp = &(*rp)->prev;
1664   *rp = rheaders;
1665   }
1666
1667 /* Finally, build a normal-order headers list */
1668 /*XXX only needed for hunt-the-AR? */
1669 /*XXX also, we really should be accepting any number of ADMD-matching ARs */
1670   {
1671   header_line * hnext = NULL;
1672   for (rheaders = headers_rlist; rheaders;
1673        hnext = rheaders->h, rheaders = rheaders->prev)
1674     rheaders->h->next = hnext;
1675   headers = hnext;
1676   }
1677
1678 if (!(arc_sign_find_ar(headers, identity, &ar)))
1679   {
1680   log_write(0, LOG_MAIN, "ARC: no Authentication-Results header for signing");
1681   goto ret_sigheaders;
1682   }
1683
1684 /* We previously built the data-struct for the existing ARC chain, if any, using a headers
1685 feed from the DKIM module.  Use that to give the instance number for the ARC set we are
1686 about to build. */
1687
1688 DEBUG(D_transport)
1689   if (arc_sign_ctx.arcset_chain_last)
1690     debug_printf("ARC: existing chain highest instance: %d\n",
1691       arc_sign_ctx.arcset_chain_last->instance);
1692   else
1693     debug_printf("ARC: no existing chain\n");
1694
1695 instance = arc_sign_ctx.arcset_chain_last ? arc_sign_ctx.arcset_chain_last->instance + 1 : 1;
1696
1697 /*
1698 - Generate AAR
1699   - copy the A-R; prepend i= & identity
1700 */
1701
1702 g = arc_sign_append_aar(g, &arc_sign_ctx, identity, instance, &ar);
1703
1704 /*
1705 - Generate AMS
1706   - Looks fairly like a DKIM sig
1707   - Cover all DKIM sig headers as well as the usuals
1708     - ? oversigning?
1709   - Covers the data
1710   - we must have requested a suitable bodyhash previously
1711 */
1712
1713 b = arc_ams_setup_sign_bodyhash();
1714 g = arc_sign_append_ams(g, &arc_sign_ctx, instance, identity, selector,
1715       &b->bh, headers_rlist, privkey, options);
1716
1717 /*
1718 - Generate AS
1719   - no body coverage
1720   - no h= tag; implicit coverage
1721   - arc status from A-R
1722     - if fail:
1723       - coverage is just the new ARC set
1724         including self (but with an empty b= in self)
1725     - if non-fail:
1726       - all ARC set headers, set-number order, aar then ams then as,
1727         including self (but with an empty b= in self)
1728 */
1729
1730 if (g)
1731   g = arc_sign_prepend_as(g, &arc_sign_ctx, instance, identity, selector, &ar,
1732       privkey, options);
1733
1734 /* Finally, append the dkim headers and return the lot. */
1735
1736 if (sigheaders) g = string_catn(g, sigheaders->s, sigheaders->ptr);
1737
1738 out:
1739   if (!g) return string_get(1);
1740   (void) string_from_gstring(g);
1741   gstring_release_unused(g);
1742   return g;
1743
1744
1745 bad_arg_ret:
1746   log_write(0, LOG_MAIN, "ARC: bad signing-specification (%s)", s);
1747 ret_sigheaders:
1748   g = sigheaders;
1749   goto out;
1750 }
1751
1752
1753 /******************************************************************************/
1754
1755 /* Check to see if the line is an AMS and if so, set up to validate it.
1756 Called from the DKIM input processing.  This must be done now as the message
1757 body data is hashed during input.
1758
1759 We call the DKIM code to request a body-hash; it has the facility already
1760 and the hash parameters might be common with other requests.
1761 */
1762
1763 static const uschar *
1764 arc_header_vfy_feed(gstring * g)
1765 {
1766 header_line h;
1767 arc_line al;
1768 pdkim_bodyhash * b;
1769 uschar * errstr;
1770
1771 if (!dkim_verify_ctx) return US"no dkim context";
1772
1773 if (strncmpic(ARC_HDR_AMS, g->s, ARC_HDRLEN_AMS) != 0) return US"not AMS";
1774
1775 DEBUG(D_receive) debug_printf("ARC: spotted AMS header\n");
1776 /* Parse the AMS header */
1777
1778 h.next = NULL;
1779 h.slen = g->size;
1780 h.text = g->s;
1781 memset(&al, 0, sizeof(arc_line));
1782 if ((errstr = arc_parse_line(&al, &h, ARC_HDRLEN_AMS, FALSE)))
1783   {
1784   DEBUG(D_acl) if (errstr) debug_printf("ARC: %s\n", errstr);
1785   goto badline;
1786   }
1787
1788 if (!al.a_hash.data)
1789   {
1790   DEBUG(D_acl) debug_printf("ARC: no a_hash from '%.*s'\n", h.slen, h.text);
1791   goto badline;
1792   }
1793
1794 /* defaults */
1795 if (!al.c.data)
1796   {
1797   al.c_body.data = US"simple"; al.c_body.len = 6;
1798   al.c_head = al.c_body;
1799   }
1800
1801 /* Ask the dkim code to calc a bodyhash with those specs */
1802
1803 if (!(b = arc_ams_setup_vfy_bodyhash(&al)))
1804   return US"dkim hash setup fail";
1805
1806 /* Discard the reference; search again at verify time, knowing that one
1807 should have been created here. */
1808
1809 return NULL;
1810
1811 badline:
1812   return US"line parsing error";
1813 }
1814
1815
1816
1817 /* A header line has been identified by DKIM processing.
1818
1819 Arguments:
1820   g             Header line
1821   is_vfy        TRUE for verify mode or FALSE for signing mode
1822
1823 Return:
1824   NULL for success, or an error string (probably unused)
1825 */
1826
1827 const uschar *
1828 arc_header_feed(gstring * g, BOOL is_vfy)
1829 {
1830 return is_vfy ? arc_header_vfy_feed(g) : arc_header_sign_feed(g);
1831 }
1832
1833
1834
1835 /******************************************************************************/
1836
1837 /* Construct the list of domains from the ARC chain after validation */
1838
1839 uschar *
1840 fn_arc_domains(void)
1841 {
1842 arc_set * as;
1843 unsigned inst;
1844 gstring * g = NULL;
1845
1846 for (as = arc_verify_ctx.arcset_chain, inst = 1; as; as = as->next, inst++)
1847   {
1848   arc_line * hdr_as = as->hdr_as;
1849   if (hdr_as)
1850     {
1851     blob * d = &hdr_as->d;
1852
1853     for (; inst < as->instance; inst++)
1854       g = string_catn(g, US":", 1);
1855
1856     g = d->data && d->len
1857       ? string_append_listele_n(g, ':', d->data, d->len)
1858       : string_catn(g, US":", 1);
1859     }
1860   else
1861     g = string_catn(g, US":", 1);
1862   }
1863 return g ? g->s : US"";
1864 }
1865
1866
1867 /* Construct an Authentication-Results header portion, for the ARC module */
1868
1869 gstring *
1870 authres_arc(gstring * g)
1871 {
1872 if (arc_state)
1873   {
1874   arc_line * highest_ams;
1875   int start = 0;                /* Compiler quietening */
1876   DEBUG(D_acl) start = g->ptr;
1877
1878   g = string_append(g, 2, US";\n\tarc=", arc_state);
1879   if (arc_received_instance > 0)
1880     {
1881     g = string_fmt_append(g, " (i=%d)", arc_received_instance);
1882     if (arc_state_reason)
1883       g = string_append(g, 3, US"(", arc_state_reason, US")");
1884     g = string_catn(g, US" header.s=", 10);
1885     highest_ams = arc_received->hdr_ams;
1886     g = string_catn(g, highest_ams->s.data, highest_ams->s.len);
1887
1888     g = string_fmt_append(g, " arc.oldest-pass=%d", arc_oldest_pass);
1889
1890     if (sender_host_address)
1891       g = string_append(g, 2, US" smtp.remote-ip=", sender_host_address);
1892     }
1893   else if (arc_state_reason)
1894     g = string_append(g, 3, US" (", arc_state_reason, US")");
1895   DEBUG(D_acl) debug_printf("ARC:  authres '%.*s'\n",
1896                   g->ptr - start - 3, g->s + start + 3);
1897   }
1898 else
1899   DEBUG(D_acl) debug_printf("ARC:  no authres\n");
1900 return g;
1901 }
1902
1903
1904 # endif /* DISABLE_DKIM */
1905 #endif /* EXPERIMENTAL_ARC */
1906 /* vi: aw ai sw=2
1907  */