DKIM: Ed25519 signatures (GnuTLS 3.6.0 and later)
[exim.git] / src / src / pdkim / pdkim.c
1 /*
2  *  PDKIM - a RFC4871 (DKIM) implementation
3  *
4  *  Copyright (C) 2009 - 2016  Tom Kistner <tom@duncanthrax.net>
5  *  Copyright (C) 2016 - 2017  Jeremy Harris <jgh@exim.org>
6  *
7  *  http://duncanthrax.net/pdkim/
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License along
20  *  with this program; if not, write to the Free Software Foundation, Inc.,
21  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include "../exim.h"
25
26
27 #ifndef DISABLE_DKIM    /* entire file */
28
29 #ifndef SUPPORT_TLS
30 # error Need SUPPORT_TLS for DKIM
31 #endif
32
33 #include "crypt_ver.h"
34
35 #ifdef SIGN_OPENSSL
36 # include <openssl/rsa.h>
37 # include <openssl/ssl.h>
38 # include <openssl/err.h>
39 #elif defined(SIGN_GNUTLS)
40 # include <gnutls/gnutls.h>
41 # include <gnutls/x509.h>
42 #endif
43
44 #include "pdkim.h"
45 #include "signing.h"
46
47 #define PDKIM_SIGNATURE_VERSION     "1"
48 #define PDKIM_PUB_RECORD_VERSION    US "DKIM1"
49
50 #define PDKIM_MAX_HEADER_LEN        65536
51 #define PDKIM_MAX_HEADERS           512
52 #define PDKIM_MAX_BODY_LINE_LEN     16384
53 #define PDKIM_DNS_TXT_MAX_NAMELEN   1024
54
55 /* -------------------------------------------------------------------------- */
56 struct pdkim_stringlist {
57   uschar * value;
58   int      tag;
59   void *   next;
60 };
61
62 /* -------------------------------------------------------------------------- */
63 /* A bunch of list constants */
64 const uschar * pdkim_querymethods[] = {
65   US"dns/txt",
66   NULL
67 };
68 const uschar * pdkim_canons[] = {
69   US"simple",
70   US"relaxed",
71   NULL
72 };
73
74 typedef struct {
75   const uschar * dkim_hashname;
76   hashmethod     exim_hashmethod;
77 } pdkim_hashtype;
78 static const pdkim_hashtype pdkim_hashes[] = {
79   { US"sha1",   HASH_SHA1 },
80   { US"sha256", HASH_SHA2_256 },
81   { US"sha512", HASH_SHA2_512 }
82 };
83
84 const uschar * pdkim_keytypes[] = {
85   [KEYTYPE_RSA] =       US"rsa",
86 #ifdef SIGN_HAVE_ED25519
87   [KEYTYPE_ED25519] =   US"ed25519",            /* Works for 3.6.0 GnuTLS */
88 #endif
89
90 #ifdef notyet_EC_dkim_extensions        /* https://tools.ietf.org/html/draft-srose-dkim-ecc-00 */
91   US"eccp256",
92   US"eccp348",
93   US"ed448",
94 #endif
95 };
96
97 typedef struct pdkim_combined_canon_entry {
98   const uschar *        str;
99   int                   canon_headers;
100   int                   canon_body;
101 } pdkim_combined_canon_entry;
102
103 pdkim_combined_canon_entry pdkim_combined_canons[] = {
104   { US"simple/simple",    PDKIM_CANON_SIMPLE,   PDKIM_CANON_SIMPLE },
105   { US"simple/relaxed",   PDKIM_CANON_SIMPLE,   PDKIM_CANON_RELAXED },
106   { US"relaxed/simple",   PDKIM_CANON_RELAXED,  PDKIM_CANON_SIMPLE },
107   { US"relaxed/relaxed",  PDKIM_CANON_RELAXED,  PDKIM_CANON_RELAXED },
108   { US"simple",           PDKIM_CANON_SIMPLE,   PDKIM_CANON_SIMPLE },
109   { US"relaxed",          PDKIM_CANON_RELAXED,  PDKIM_CANON_SIMPLE },
110   { NULL,                 0,                    0 }
111 };
112
113
114 static blob lineending = {.data = US"\r\n", .len = 2};
115
116 /* -------------------------------------------------------------------------- */
117 uschar *
118 dkim_sig_to_a_tag(const pdkim_signature * sig)
119 {
120 if (  sig->keytype < 0  || sig->keytype > nelem(pdkim_keytypes)
121    || sig->hashtype < 0 || sig->hashtype > nelem(pdkim_hashes))
122   return US"err";
123 return string_sprintf("%s-%s",
124   pdkim_keytypes[sig->keytype], pdkim_hashes[sig->hashtype].dkim_hashname);
125 }
126
127
128
129 const char *
130 pdkim_verify_status_str(int status)
131 {
132 switch(status)
133   {
134   case PDKIM_VERIFY_NONE:    return "PDKIM_VERIFY_NONE";
135   case PDKIM_VERIFY_INVALID: return "PDKIM_VERIFY_INVALID";
136   case PDKIM_VERIFY_FAIL:    return "PDKIM_VERIFY_FAIL";
137   case PDKIM_VERIFY_PASS:    return "PDKIM_VERIFY_PASS";
138   default:                   return "PDKIM_VERIFY_UNKNOWN";
139   }
140 }
141
142 const char *
143 pdkim_verify_ext_status_str(int ext_status)
144 {
145 switch(ext_status)
146   {
147   case PDKIM_VERIFY_FAIL_BODY: return "PDKIM_VERIFY_FAIL_BODY";
148   case PDKIM_VERIFY_FAIL_MESSAGE: return "PDKIM_VERIFY_FAIL_MESSAGE";
149   case PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH: return "PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH";
150   case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
151   case PDKIM_VERIFY_INVALID_BUFFER_SIZE: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
152   case PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD: return "PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD";
153   case PDKIM_VERIFY_INVALID_PUBKEY_IMPORT: return "PDKIM_VERIFY_INVALID_PUBKEY_IMPORT";
154   case PDKIM_VERIFY_INVALID_SIGNATURE_ERROR: return "PDKIM_VERIFY_INVALID_SIGNATURE_ERROR";
155   case PDKIM_VERIFY_INVALID_DKIM_VERSION: return "PDKIM_VERIFY_INVALID_DKIM_VERSION";
156   default: return "PDKIM_VERIFY_UNKNOWN";
157   }
158 }
159
160 const uschar *
161 pdkim_errstr(int status)
162 {
163 switch(status)
164   {
165   case PDKIM_OK:                return US"OK";
166   case PDKIM_FAIL:              return US"FAIL";
167   case PDKIM_ERR_RSA_PRIVKEY:   return US"PRIVKEY";
168   case PDKIM_ERR_RSA_SIGNING:   return US"SIGNING";
169   case PDKIM_ERR_LONG_LINE:     return US"LONG_LINE";
170   case PDKIM_ERR_BUFFER_TOO_SMALL:      return US"BUFFER_TOO_SMALL";
171   case PDKIM_SIGN_PRIVKEY_WRAP: return US"PRIVKEY_WRAP";
172   case PDKIM_SIGN_PRIVKEY_B64D: return US"PRIVKEY_B64D";
173   default: return US"(unknown)";
174   }
175 }
176
177
178 /* -------------------------------------------------------------------------- */
179 /* Print debugging functions */
180 static void
181 pdkim_quoteprint(const uschar *data, int len)
182 {
183 int i;
184 for (i = 0; i < len; i++)
185   {
186   const int c = data[i];
187   switch (c)
188     {
189     case ' ' : debug_printf("{SP}"); break;
190     case '\t': debug_printf("{TB}"); break;
191     case '\r': debug_printf("{CR}"); break;
192     case '\n': debug_printf("{LF}"); break;
193     case '{' : debug_printf("{BO}"); break;
194     case '}' : debug_printf("{BC}"); break;
195     default:
196       if ( (c < 32) || (c > 127) )
197         debug_printf("{%02x}", c);
198       else
199         debug_printf("%c", c);
200       break;
201     }
202   }
203 debug_printf("\n");
204 }
205
206 static void
207 pdkim_hexprint(const uschar *data, int len)
208 {
209 int i;
210 if (data) for (i = 0 ; i < len; i++) debug_printf("%02x", data[i]);
211 else debug_printf("<NULL>");
212 debug_printf("\n");
213 }
214
215
216
217 static pdkim_stringlist *
218 pdkim_prepend_stringlist(pdkim_stringlist * base, const uschar * str)
219 {
220 pdkim_stringlist * new_entry = store_get(sizeof(pdkim_stringlist));
221
222 memset(new_entry, 0, sizeof(pdkim_stringlist));
223 new_entry->value = string_copy(str);
224 if (base) new_entry->next = base;
225 return new_entry;
226 }
227
228
229
230 /* Trim whitespace fore & aft */
231
232 static void
233 pdkim_strtrim(gstring * str)
234 {
235 uschar * p = str->s;
236 uschar * q;
237
238 while (*p == '\t' || *p == ' ')         /* dump the leading whitespace */
239   { str->size--; str->ptr--; str->s++; }
240
241 while (  str->ptr > 0
242       && ((q = str->s + str->ptr - 1),  (*q == '\t' || *q == ' '))
243       )
244   str->ptr--;                           /* dump trailing whitespace */
245
246 (void) string_from_gstring(str);
247 }
248
249
250
251 /* -------------------------------------------------------------------------- */
252
253 DLLEXPORT void
254 pdkim_free_ctx(pdkim_ctx *ctx)
255 {
256 }
257
258
259 /* -------------------------------------------------------------------------- */
260 /* Matches the name of the passed raw "header" against
261    the passed colon-separated "tick", and invalidates
262    the entry in tick.  Entries can be prefixed for multi- or over-signing,
263    in which case do not invalidate.
264
265    Returns OK for a match, or fail-code
266 */
267
268 static int
269 header_name_match(const uschar * header, uschar * tick)
270 {
271 const uschar * ticklist = tick;
272 int sep = ':';
273 BOOL multisign;
274 uschar * hname, * p, * ele;
275 uschar * hcolon = Ustrchr(header, ':');         /* Get header name */
276
277 if (!hcolon)
278   return PDKIM_FAIL; /* This isn't a header */
279
280 /* if we had strncmpic() we wouldn't need this copy */
281 hname = string_copyn(header, hcolon-header);
282
283 while (p = US ticklist, ele = string_nextinlist(&ticklist, &sep, NULL, 0))
284   {
285   switch (*ele)
286   {
287   case '=': case '+':   multisign = TRUE; ele++; break;
288   default:              multisign = FALSE; break;
289   }
290
291   if (strcmpic(ele, hname) == 0)
292     {
293     if (!multisign)
294       *p = '_'; /* Invalidate this header name instance in tick-off list */
295     return PDKIM_OK;
296     }
297   }
298 return PDKIM_FAIL;
299 }
300
301
302 /* -------------------------------------------------------------------------- */
303 /* Performs "relaxed" canonicalization of a header. */
304
305 static uschar *
306 pdkim_relax_header(const uschar * header, BOOL append_crlf)
307 {
308 BOOL past_field_name = FALSE;
309 BOOL seen_wsp = FALSE;
310 const uschar * p;
311 uschar * relaxed = store_get(Ustrlen(header)+3);
312 uschar * q = relaxed;
313
314 for (p = header; *p; p++)
315   {
316   uschar c = *p;
317
318   if (c == '\r' || c == '\n')   /* Ignore CR & LF */
319     continue;
320   if (c == '\t' || c == ' ')
321     {
322     if (seen_wsp)
323       continue;
324     c = ' ';                    /* Turns WSP into SP */
325     seen_wsp = TRUE;
326     }
327   else
328     if (!past_field_name && c == ':')
329       {
330       if (seen_wsp) q--;        /* This removes WSP immediately before the colon */
331       seen_wsp = TRUE;          /* This removes WSP immediately after the colon */
332       past_field_name = TRUE;
333       }
334     else
335       seen_wsp = FALSE;
336
337   /* Lowercase header name */
338   if (!past_field_name) c = tolower(c);
339   *q++ = c;
340   }
341
342 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
343
344 if (append_crlf) { *q++ = '\r'; *q++ = '\n'; }
345 *q = '\0';
346 return relaxed;
347 }
348
349
350 /* -------------------------------------------------------------------------- */
351 #define PDKIM_QP_ERROR_DECODE -1
352
353 static const uschar *
354 pdkim_decode_qp_char(const uschar *qp_p, int *c)
355 {
356 const uschar *initial_pos = qp_p;
357
358 /* Advance one char */
359 qp_p++;
360
361 /* Check for two hex digits and decode them */
362 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
363   {
364   /* Do hex conversion */
365   *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
366   *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
367   return qp_p + 2;
368   }
369
370 /* Illegal char here */
371 *c = PDKIM_QP_ERROR_DECODE;
372 return initial_pos;
373 }
374
375
376 /* -------------------------------------------------------------------------- */
377
378 static uschar *
379 pdkim_decode_qp(const uschar * str)
380 {
381 int nchar = 0;
382 uschar * q;
383 const uschar * p = str;
384 uschar * n = store_get(Ustrlen(str)+1);
385
386 *n = '\0';
387 q = n;
388 while (*p)
389   {
390   if (*p == '=')
391     {
392     p = pdkim_decode_qp_char(p, &nchar);
393     if (nchar >= 0)
394       {
395       *q++ = nchar;
396       continue;
397       }
398     }
399   else
400     *q++ = *p;
401   p++;
402   }
403 *q = '\0';
404 return n;
405 }
406
407
408 /* -------------------------------------------------------------------------- */
409
410 static void
411 pdkim_decode_base64(const uschar * str, blob * b)
412 {
413 int dlen;
414 dlen = b64decode(str, &b->data);
415 if (dlen < 0) b->data = NULL;
416 b->len = dlen;
417 }
418
419 static uschar *
420 pdkim_encode_base64(blob * b)
421 {
422 return b64encode(b->data, b->len);
423 }
424
425
426 /* -------------------------------------------------------------------------- */
427 #define PDKIM_HDR_LIMBO 0
428 #define PDKIM_HDR_TAG   1
429 #define PDKIM_HDR_VALUE 2
430
431 static pdkim_signature *
432 pdkim_parse_sig_header(pdkim_ctx * ctx, uschar * raw_hdr)
433 {
434 pdkim_signature * sig;
435 uschar *p, *q;
436 gstring * cur_tag = NULL;
437 gstring * cur_val = NULL;
438 BOOL past_hname = FALSE;
439 BOOL in_b_val = FALSE;
440 int where = PDKIM_HDR_LIMBO;
441 int i;
442
443 sig = store_get(sizeof(pdkim_signature));
444 memset(sig, 0, sizeof(pdkim_signature));
445 sig->bodylength = -1;
446
447 /* Set so invalid/missing data error display is accurate */
448 sig->version = 0;
449 sig->keytype = -1;
450 sig->hashtype = -1;
451
452 q = sig->rawsig_no_b_val = store_get(Ustrlen(raw_hdr)+1);
453
454 for (p = raw_hdr; ; p++)
455   {
456   char c = *p;
457
458   /* Ignore FWS */
459   if (c == '\r' || c == '\n')
460     goto NEXT_CHAR;
461
462   /* Fast-forward through header name */
463   if (!past_hname)
464     {
465     if (c == ':') past_hname = TRUE;
466     goto NEXT_CHAR;
467     }
468
469   if (where == PDKIM_HDR_LIMBO)
470     {
471     /* In limbo, just wait for a tag-char to appear */
472     if (!(c >= 'a' && c <= 'z'))
473       goto NEXT_CHAR;
474
475     where = PDKIM_HDR_TAG;
476     }
477
478   if (where == PDKIM_HDR_TAG)
479     {
480     if (c >= 'a' && c <= 'z')
481       cur_tag = string_catn(cur_tag, p, 1);
482
483     if (c == '=')
484       {
485       if (Ustrcmp(string_from_gstring(cur_tag), "b") == 0)
486         {
487         *q++ = '=';
488         in_b_val = TRUE;
489         }
490       where = PDKIM_HDR_VALUE;
491       goto NEXT_CHAR;
492       }
493     }
494
495   if (where == PDKIM_HDR_VALUE)
496     {
497     if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
498       goto NEXT_CHAR;
499
500     if (c == ';' || c == '\0')
501       {
502       /* We must have both tag and value, and tags must be one char except
503       for the possibility of "bh". */
504
505       if (  cur_tag && cur_val
506          && (cur_tag->ptr == 1 || *cur_tag->s == 'b')
507          )
508         {
509         (void) string_from_gstring(cur_val);
510         pdkim_strtrim(cur_val);
511
512         DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->s, cur_val->s);
513
514         switch (*cur_tag->s)
515           {
516           case 'b':                             /* sig-data or body-hash */
517             switch (cur_tag->s[1])
518               {
519               case '\0': pdkim_decode_base64(cur_val->s, &sig->sighash); break;
520               case 'h':  if (cur_tag->ptr == 2)
521                            pdkim_decode_base64(cur_val->s, &sig->bodyhash);
522                          break;
523               default:   break;
524               }
525             break;
526           case 'v':                                     /* version */
527               /* We only support version 1, and that is currently the
528                  only version there is. */
529             sig->version =
530               Ustrcmp(cur_val->s, PDKIM_SIGNATURE_VERSION) == 0 ? 1 : -1;
531             break;
532           case 'a':                                     /* algorithm */
533             {
534             uschar * s = Ustrchr(cur_val->s, '-');
535
536             for(i = 0; i < nelem(pdkim_keytypes); i++)
537               if (Ustrncmp(cur_val->s, pdkim_keytypes[i], s - cur_val->s) == 0)
538                 { sig->keytype = i; break; }
539             if (sig->keytype < 0)
540               log_write(0, LOG_MAIN,
541                 "DKIM: ignoring signature due to nonhandled keytype in a=%s",
542                 cur_val->s);
543
544             for (++s, i = 0; i < nelem(pdkim_hashes); i++)
545               if (Ustrcmp(s, pdkim_hashes[i].dkim_hashname) == 0)
546                 { sig->hashtype = i; break; }
547             if (sig->hashtype < 0)
548               log_write(0, LOG_MAIN,
549                 "DKIM: ignoring signature due to nonhandled hashtype in a=%s",
550                 cur_val);
551             break;
552             }
553
554           case 'c':                                     /* canonicalization */
555             for (i = 0; pdkim_combined_canons[i].str; i++)
556               if (Ustrcmp(cur_val->s, pdkim_combined_canons[i].str) == 0)
557                 {
558                 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
559                 sig->canon_body    = pdkim_combined_canons[i].canon_body;
560                 break;
561                 }
562             break;
563           case 'q':                             /* Query method (for pubkey)*/
564             for (i = 0; pdkim_querymethods[i]; i++)
565               if (Ustrcmp(cur_val->s, pdkim_querymethods[i]) == 0)
566                 {
567                 sig->querymethod = i;   /* we never actually use this */
568                 break;
569                 }
570             break;
571           case 's':                                     /* Selector */
572             sig->selector = string_copyn(cur_val->s, cur_val->ptr); break;
573           case 'd':                                     /* SDID */
574             sig->domain = string_copyn(cur_val->s, cur_val->ptr); break;
575           case 'i':                                     /* AUID */
576             sig->identity = pdkim_decode_qp(cur_val->s); break;
577           case 't':                                     /* Timestamp */
578             sig->created = strtoul(CS cur_val->s, NULL, 10); break;
579           case 'x':                                     /* Expiration */
580             sig->expires = strtoul(CS cur_val->s, NULL, 10); break;
581           case 'l':                                     /* Body length count */
582             sig->bodylength = strtol(CS cur_val->s, NULL, 10); break;
583           case 'h':                                     /* signed header fields */
584             sig->headernames = string_copyn(cur_val->s, cur_val->ptr); break;
585           case 'z':                                     /* Copied headfields */
586             sig->copiedheaders = pdkim_decode_qp(cur_val->s); break;
587 /*XXX draft-ietf-dcrup-dkim-crypto-05 would need 'p' tag support
588 for rsafp signatures.  But later discussion is dropping those. */
589           default:
590             DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
591             break;
592           }
593         }
594       cur_tag = cur_val = NULL;
595       in_b_val = FALSE;
596       where = PDKIM_HDR_LIMBO;
597       }
598     else
599       cur_val = string_catn(cur_val, p, 1);
600     }
601
602 NEXT_CHAR:
603   if (c == '\0')
604     break;
605
606   if (!in_b_val)
607     *q++ = c;
608   }
609
610 if (sig->keytype < 0 || sig->hashtype < 0)      /* Cannot verify this signature */
611   return NULL;
612
613 *q = '\0';
614 /* Chomp raw header. The final newline must not be added to the signature. */
615 while (--q > sig->rawsig_no_b_val  && (*q == '\r' || *q == '\n'))
616   *q = '\0';
617
618 DEBUG(D_acl)
619   {
620   debug_printf(
621           "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
622   pdkim_quoteprint(US sig->rawsig_no_b_val, Ustrlen(sig->rawsig_no_b_val));
623   debug_printf(
624           "PDKIM >> Sig size: %4u bits\n", (unsigned) sig->sighash.len*8);
625   debug_printf(
626           "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
627   }
628
629 if (!pdkim_set_bodyhash(ctx, sig))
630   return NULL;
631
632 return sig;
633 }
634
635
636 /* -------------------------------------------------------------------------- */
637
638 static pdkim_pubkey *
639 pdkim_parse_pubkey_record(pdkim_ctx *ctx, const uschar *raw_record)
640 {
641 const uschar * ele;
642 int sep = ';';
643 pdkim_pubkey * pub;
644
645 pub = store_get(sizeof(pdkim_pubkey));
646 memset(pub, 0, sizeof(pdkim_pubkey));
647
648 while ((ele = string_nextinlist(&raw_record, &sep, NULL, 0)))
649   {
650   const uschar * val;
651
652   if ((val = Ustrchr(ele, '=')))
653     {
654     int taglen = val++ - ele;
655
656     DEBUG(D_acl) debug_printf(" %.*s=%s\n", taglen, ele, val);
657     switch (ele[0])
658       {
659       case 'v': pub->version = val;                     break;
660       case 'h': pub->hashes = val;                      break;
661       case 'k': pub->keytype = val;                     break;
662       case 'g': pub->granularity = val;                 break;
663       case 'n': pub->notes = pdkim_decode_qp(val);      break;
664       case 'p': pdkim_decode_base64(val, &pub->key);    break;
665       case 's': pub->srvtype = val;                     break;
666       case 't': if (Ustrchr(val, 'y')) pub->testing = 1;
667                 if (Ustrchr(val, 's')) pub->no_subdomaining = 1;
668                 break;
669       default:  DEBUG(D_acl) debug_printf(" Unknown tag encountered\n"); break;
670       }
671     }
672   }
673
674 /* Set fallback defaults */
675 if (!pub->version)
676   pub->version = string_copy(PDKIM_PUB_RECORD_VERSION);
677 else if (Ustrcmp(pub->version, PDKIM_PUB_RECORD_VERSION) != 0)
678   {
679   DEBUG(D_acl) debug_printf(" Bad v= field\n");
680   return NULL;
681   }
682
683 if (!pub->granularity) pub->granularity = US"*";
684 if (!pub->keytype    ) pub->keytype     = US"rsa";
685 if (!pub->srvtype    ) pub->srvtype     = US"*";
686
687 /* p= is required */
688 if (pub->key.data)
689   return pub;
690
691 DEBUG(D_acl) debug_printf(" Missing p= field\n");
692 return NULL;
693 }
694
695
696 /* -------------------------------------------------------------------------- */
697
698 /* Update one bodyhash with some additional data.
699 If we have to relax the data for this sig, return our copy of it. */
700
701 static blob *
702 pdkim_update_ctx_bodyhash(pdkim_bodyhash * b, blob * orig_data, blob * relaxed_data)
703 {
704 blob * canon_data = orig_data;
705 /* Defaults to simple canon (no further treatment necessary) */
706
707 if (b->canon_method == PDKIM_CANON_RELAXED)
708   {
709   /* Relax the line if not done already */
710   if (!relaxed_data)
711     {
712     BOOL seen_wsp = FALSE;
713     const uschar * p;
714     int q = 0;
715
716     /* We want to be able to free this else we allocate
717     for the entire message which could be many MB. Since
718     we don't know what allocations the SHA routines might
719     do, not safe to use store_get()/store_reset(). */
720
721     relaxed_data = store_malloc(sizeof(blob) + orig_data->len+1);
722     relaxed_data->data = US (relaxed_data+1);
723
724     for (p = orig_data->data; *p; p++)
725       {
726       char c = *p;
727       if (c == '\r')
728         {
729         if (q > 0 && relaxed_data->data[q-1] == ' ')
730           q--;
731         }
732       else if (c == '\t' || c == ' ')
733         {
734         c = ' '; /* Turns WSP into SP */
735         if (seen_wsp)
736           continue;
737         seen_wsp = TRUE;
738         }
739       else
740         seen_wsp = FALSE;
741       relaxed_data->data[q++] = c;
742       }
743     relaxed_data->data[q] = '\0';
744     relaxed_data->len = q;
745     }
746   canon_data = relaxed_data;
747   }
748
749 /* Make sure we don't exceed the to-be-signed body length */
750 if (  b->bodylength >= 0
751    && b->signed_body_bytes + (unsigned long)canon_data->len > b->bodylength
752    )
753   canon_data->len = b->bodylength - b->signed_body_bytes;
754
755 if (canon_data->len > 0)
756   {
757   exim_sha_update(&b->body_hash_ctx, CUS canon_data->data, canon_data->len);
758   b->signed_body_bytes += canon_data->len;
759   DEBUG(D_acl) pdkim_quoteprint(canon_data->data, canon_data->len);
760   }
761
762 return relaxed_data;
763 }
764
765
766 /* -------------------------------------------------------------------------- */
767
768 static void
769 pdkim_finish_bodyhash(pdkim_ctx * ctx)
770 {
771 pdkim_bodyhash * b;
772 pdkim_signature * sig;
773
774 for (b = ctx->bodyhash; b; b = b->next)         /* Finish hashes */
775   exim_sha_finish(&b->body_hash_ctx, &b->bh);
776
777 /* Traverse all signatures */
778 for (sig = ctx->sig; sig; sig = sig->next)
779   {
780   b = sig->calc_body_hash;
781
782   DEBUG(D_acl)
783     {
784     debug_printf("PDKIM [%s] Body bytes hashed: %lu\n"
785                  "PDKIM [%s] Body %s computed: ",
786                 sig->domain, b->signed_body_bytes,
787                 sig->domain, pdkim_hashes[sig->hashtype].dkim_hashname);
788     pdkim_hexprint(CUS b->bh.data, b->bh.len);
789     }
790
791   /* SIGNING -------------------------------------------------------------- */
792   if (ctx->flags & PDKIM_MODE_SIGN)
793     {
794     /* If bodylength limit is set, and we have received less bytes
795        than the requested amount, effectively remove the limit tag. */
796     if (b->signed_body_bytes < sig->bodylength)
797       sig->bodylength = -1;
798     }
799
800   else
801   /* VERIFICATION --------------------------------------------------------- */
802   /* Be careful that the header sig included a bodyash */
803
804     if (  sig->bodyhash.data
805        && memcmp(b->bh.data, sig->bodyhash.data, b->bh.len) == 0)
806       {
807       DEBUG(D_acl) debug_printf("PDKIM [%s] Body hash verified OK\n", sig->domain);
808       }
809     else
810       {
811       DEBUG(D_acl)
812         {
813         debug_printf("PDKIM [%s] Body hash signature from headers: ", sig->domain);
814         pdkim_hexprint(sig->bodyhash.data, sig->bodyhash.len);
815         debug_printf("PDKIM [%s] Body hash did NOT verify\n", sig->domain);
816         }
817       sig->verify_status     = PDKIM_VERIFY_FAIL;
818       sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
819       }
820   }
821 }
822
823
824
825 static void
826 pdkim_body_complete(pdkim_ctx * ctx)
827 {
828 pdkim_bodyhash * b;
829
830 /* In simple body mode, if any empty lines were buffered,
831 replace with one. rfc 4871 3.4.3 */
832 /*XXX checking the signed-body-bytes is a gross hack; I think
833 it indicates that all linebreaks should be buffered, including
834 the one terminating a text line */
835
836 for (b = ctx->bodyhash; b; b = b->next)
837   if (  b->canon_method == PDKIM_CANON_SIMPLE
838      && b->signed_body_bytes == 0
839      && b->num_buffered_blanklines > 0
840      )
841     (void) pdkim_update_ctx_bodyhash(b, &lineending, NULL);
842
843 ctx->flags |= PDKIM_SEEN_EOD;
844 ctx->linebuf_offset = 0;
845 }
846
847
848
849 /* -------------------------------------------------------------------------- */
850 /* Call from pdkim_feed below for processing complete body lines */
851
852 static void
853 pdkim_bodyline_complete(pdkim_ctx * ctx)
854 {
855 blob line = {.data = ctx->linebuf, .len = ctx->linebuf_offset};
856 pdkim_bodyhash * b;
857 blob * rnl = NULL;
858 blob * rline = NULL;
859
860 /* Ignore extra data if we've seen the end-of-data marker */
861 if (ctx->flags & PDKIM_SEEN_EOD) goto all_skip;
862
863 /* We've always got one extra byte to stuff a zero ... */
864 ctx->linebuf[line.len] = '\0';
865
866 /* Terminate on EOD marker */
867 if (ctx->flags & PDKIM_DOT_TERM)
868   {
869   if (memcmp(line.data, ".\r\n", 3) == 0)
870     { pdkim_body_complete(ctx); return; }
871
872   /* Unstuff dots */
873   if (memcmp(line.data, "..", 2) == 0)
874     { line.data++; line.len--; }
875   }
876
877 /* Empty lines need to be buffered until we find a non-empty line */
878 if (memcmp(line.data, "\r\n", 2) == 0)
879   {
880   for (b = ctx->bodyhash; b; b = b->next) b->num_buffered_blanklines++;
881   goto all_skip;
882   }
883
884 /* Process line for each bodyhash separately */
885 for (b = ctx->bodyhash; b; b = b->next)
886   {
887   if (b->canon_method == PDKIM_CANON_RELAXED)
888     {
889     /* Lines with just spaces need to be buffered too */
890     uschar * cp = line.data;
891     char c;
892
893     while ((c = *cp))
894       {
895       if (c == '\r' && cp[1] == '\n') break;
896       if (c != ' ' && c != '\t') goto hash_process;
897       cp++;
898       }
899
900     b->num_buffered_blanklines++;
901     goto hash_skip;
902     }
903
904 hash_process:
905   /* At this point, we have a non-empty line, so release the buffered ones. */
906
907   while (b->num_buffered_blanklines)
908     {
909     rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
910     b->num_buffered_blanklines--;
911     }
912
913   rline = pdkim_update_ctx_bodyhash(b, &line, rline);
914 hash_skip: ;
915   }
916
917 if (rnl) store_free(rnl);
918 if (rline) store_free(rline);
919
920 all_skip:
921
922 ctx->linebuf_offset = 0;
923 return;
924 }
925
926
927 /* -------------------------------------------------------------------------- */
928 /* Callback from pdkim_feed below for processing complete headers */
929 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
930
931 static int
932 pdkim_header_complete(pdkim_ctx * ctx)
933 {
934 pdkim_signature * sig, * last_sig;
935
936 /* Special case: The last header can have an extra \r appended */
937 if ( (ctx->cur_header->ptr > 1) &&
938      (ctx->cur_header->s[ctx->cur_header->ptr-1] == '\r') )
939   --ctx->cur_header->ptr;
940 (void) string_from_gstring(ctx->cur_header);
941
942 if (++ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
943
944 /* SIGNING -------------------------------------------------------------- */
945 if (ctx->flags & PDKIM_MODE_SIGN)
946   for (sig = ctx->sig; sig; sig = sig->next)                    /* Traverse all signatures */
947
948     /* Add header to the signed headers list (in reverse order) */
949     sig->headers = pdkim_prepend_stringlist(sig->headers, ctx->cur_header->s);
950
951 /* VERIFICATION ----------------------------------------------------------- */
952 /* DKIM-Signature: headers are added to the verification list */
953 else
954   {
955 #ifdef notdef
956   DEBUG(D_acl)
957     {
958     debug_printf("PDKIM >> raw hdr: ");
959     pdkim_quoteprint(CUS ctx->cur_header->s, ctx->cur_header->ptr);
960     }
961 #endif
962   if (strncasecmp(CCS ctx->cur_header->s,
963                   DKIM_SIGNATURE_HEADERNAME,
964                   Ustrlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
965     {
966     /* Create and chain new signature block.  We could error-check for all
967     required tags here, but prefer to create the internal sig and expicitly
968     fail verification of it later. */
969
970     DEBUG(D_acl) debug_printf(
971         "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
972
973     sig = pdkim_parse_sig_header(ctx, ctx->cur_header->s);
974
975     if (!(last_sig = ctx->sig))
976       ctx->sig = sig;
977     else
978       {
979       while (last_sig->next) last_sig = last_sig->next;
980       last_sig->next = sig;
981       }
982     }
983
984   /* all headers are stored for signature verification */
985   ctx->headers = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->s);
986   }
987
988 BAIL:
989 ctx->cur_header->s[ctx->cur_header->ptr = 0] = '\0';    /* leave buffer for reuse */
990 return PDKIM_OK;
991 }
992
993
994
995 /* -------------------------------------------------------------------------- */
996 #define HEADER_BUFFER_FRAG_SIZE 256
997
998 DLLEXPORT int
999 pdkim_feed(pdkim_ctx * ctx, uschar * data, int len)
1000 {
1001 int p, rc;
1002
1003 /* Alternate EOD signal, used in non-dotstuffing mode */
1004 if (!data)
1005   pdkim_body_complete(ctx);
1006
1007 else for (p = 0; p<len; p++)
1008   {
1009   uschar c = data[p];
1010
1011   if (ctx->flags & PDKIM_PAST_HDRS)
1012     {
1013     if (c == '\n' && !(ctx->flags & PDKIM_SEEN_CR))     /* emulate the CR */
1014       {
1015       ctx->linebuf[ctx->linebuf_offset++] = '\r';
1016       if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1017         return PDKIM_ERR_LONG_LINE;
1018       }
1019
1020     /* Processing body byte */
1021     ctx->linebuf[ctx->linebuf_offset++] = c;
1022     if (c == '\r')
1023       ctx->flags |= PDKIM_SEEN_CR;
1024     else if (c == '\n')
1025       {
1026       ctx->flags &= ~PDKIM_SEEN_CR;
1027       pdkim_bodyline_complete(ctx);
1028       }
1029
1030     if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1031       return PDKIM_ERR_LONG_LINE;
1032     }
1033   else
1034     {
1035     /* Processing header byte */
1036     if (c == '\r')
1037       ctx->flags |= PDKIM_SEEN_CR;
1038     else if (c == '\n')
1039       {
1040       if (!(ctx->flags & PDKIM_SEEN_CR))                /* emulate the CR */
1041         ctx->cur_header = string_catn(ctx->cur_header, CUS "\r", 1);
1042
1043       if (ctx->flags & PDKIM_SEEN_LF)           /* Seen last header line */
1044         {
1045         if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1046           return rc;
1047
1048         ctx->flags = (ctx->flags & ~(PDKIM_SEEN_LF|PDKIM_SEEN_CR)) | PDKIM_PAST_HDRS;
1049         DEBUG(D_acl) debug_printf(
1050             "PDKIM >> Body data for hash, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1051         continue;
1052         }
1053       else
1054         ctx->flags = (ctx->flags & ~PDKIM_SEEN_CR) | PDKIM_SEEN_LF;
1055       }
1056     else if (ctx->flags & PDKIM_SEEN_LF)
1057       {
1058       if (!(c == '\t' || c == ' '))                     /* End of header */
1059         if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1060           return rc;
1061       ctx->flags &= ~PDKIM_SEEN_LF;
1062       }
1063
1064     if (!ctx->cur_header || ctx->cur_header->ptr < PDKIM_MAX_HEADER_LEN)
1065       ctx->cur_header = string_catn(ctx->cur_header, CUS &data[p], 1);
1066     }
1067   }
1068 return PDKIM_OK;
1069 }
1070
1071
1072
1073 /* Extend a growing header with a continuation-linebreak */
1074 static gstring *
1075 pdkim_hdr_cont(gstring * str, int * col)
1076 {
1077 *col = 1;
1078 return string_catn(str, US"\r\n\t", 3);
1079 }
1080
1081
1082
1083 /*
1084  * RFC 5322 specifies that header line length SHOULD be no more than 78
1085  * lets make it so!
1086  *  pdkim_headcat
1087  *
1088  * returns uschar * (not nul-terminated)
1089  *
1090  * col: this int holds and receives column number (octets since last '\n')
1091  * str: partial string to append to
1092  * pad: padding, split line or space after before or after eg: ";"
1093  * intro: - must join to payload eg "h=", usually the tag name
1094  * payload: eg base64 data - long data can be split arbitrarily.
1095  *
1096  * this code doesn't fold the header in some of the places that RFC4871
1097  * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1098  * pairs and inside long values. it also always spaces or breaks after the
1099  * "pad"
1100  *
1101  * no guarantees are made for output given out-of range input. like tag
1102  * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1103  */
1104
1105 static gstring *
1106 pdkim_headcat(int * col, gstring * str,
1107   const uschar * pad, const uschar * intro, const uschar * payload)
1108 {
1109 size_t l;
1110
1111 if (pad)
1112   {
1113   l = Ustrlen(pad);
1114   if (*col + l > 78)
1115     str = pdkim_hdr_cont(str, col);
1116   str = string_catn(str, pad, l);
1117   *col += l;
1118   }
1119
1120 l = (pad?1:0) + (intro?Ustrlen(intro):0);
1121
1122 if (*col + l > 78)
1123   { /*can't fit intro - start a new line to make room.*/
1124   str = pdkim_hdr_cont(str, col);
1125   l = intro?Ustrlen(intro):0;
1126   }
1127
1128 l += payload ? Ustrlen(payload):0 ;
1129
1130 while (l>77)
1131   { /* this fragment will not fit on a single line */
1132   if (pad)
1133     {
1134     str = string_catn(str, US" ", 1);
1135     *col += 1;
1136     pad = NULL; /* only want this once */
1137     l--;
1138     }
1139
1140   if (intro)
1141     {
1142     size_t sl = Ustrlen(intro);
1143
1144     str = string_catn(str, intro, sl);
1145     *col += sl;
1146     l -= sl;
1147     intro = NULL; /* only want this once */
1148     }
1149
1150   if (payload)
1151     {
1152     size_t sl = Ustrlen(payload);
1153     size_t chomp = *col+sl < 77 ? sl : 78-*col;
1154
1155     str = string_catn(str, payload, chomp);
1156     *col += chomp;
1157     payload += chomp;
1158     l -= chomp-1;
1159     }
1160
1161   /* the while precondition tells us it didn't fit. */
1162   str = pdkim_hdr_cont(str, col);
1163   }
1164
1165 if (*col + l > 78)
1166   {
1167   str = pdkim_hdr_cont(str, col);
1168   pad = NULL;
1169   }
1170
1171 if (pad)
1172   {
1173   str = string_catn(str, US" ", 1);
1174   *col += 1;
1175   pad = NULL;
1176   }
1177
1178 if (intro)
1179   {
1180   size_t sl = Ustrlen(intro);
1181
1182   str = string_catn(str, intro, sl);
1183   *col += sl;
1184   l -= sl;
1185   intro = NULL;
1186   }
1187
1188 if (payload)
1189   {
1190   size_t sl = Ustrlen(payload);
1191
1192   str = string_catn(str, payload, sl);
1193   *col += sl;
1194   }
1195
1196 return str;
1197 }
1198
1199
1200 /* -------------------------------------------------------------------------- */
1201
1202 /* Signing: create signature header
1203 */
1204 static uschar *
1205 pdkim_create_header(pdkim_signature * sig, BOOL final)
1206 {
1207 uschar * base64_bh;
1208 uschar * base64_b;
1209 int col = 0;
1210 gstring * hdr;
1211 gstring * canon_all;
1212
1213 canon_all = string_cat (NULL, pdkim_canons[sig->canon_headers]);
1214 canon_all = string_catn(canon_all, US"/", 1);
1215 canon_all = string_cat (canon_all, pdkim_canons[sig->canon_body]);
1216 (void) string_from_gstring(canon_all);
1217
1218 hdr = string_cat(NULL, US"DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1219 col = hdr->ptr;
1220
1221 /* Required and static bits */
1222 hdr = pdkim_headcat(&col, hdr, US";", US"a=", dkim_sig_to_a_tag(sig));
1223 hdr = pdkim_headcat(&col, hdr, US";", US"q=", pdkim_querymethods[sig->querymethod]);
1224 hdr = pdkim_headcat(&col, hdr, US";", US"c=", canon_all->s);
1225 hdr = pdkim_headcat(&col, hdr, US";", US"d=", sig->domain);
1226 hdr = pdkim_headcat(&col, hdr, US";", US"s=", sig->selector);
1227
1228 /* list of header names can be split between items. */
1229   {
1230   uschar * n = string_copy(sig->headernames);
1231   uschar * i = US"h=";
1232   uschar * s = US";";
1233
1234   while (*n)
1235     {
1236     uschar * c = Ustrchr(n, ':');
1237
1238     if (c) *c ='\0';
1239
1240     if (!i)
1241       hdr = pdkim_headcat(&col, hdr, NULL, NULL, US":");
1242
1243     hdr = pdkim_headcat(&col, hdr, s, i, n);
1244
1245     if (!c)
1246       break;
1247
1248     n = c+1;
1249     s = NULL;
1250     i = NULL;
1251     }
1252   }
1253
1254 base64_bh = pdkim_encode_base64(&sig->calc_body_hash->bh);
1255 hdr = pdkim_headcat(&col, hdr, US";", US"bh=", base64_bh);
1256
1257 /* Optional bits */
1258 if (sig->identity)
1259   hdr = pdkim_headcat(&col, hdr, US";", US"i=", sig->identity);
1260
1261 if (sig->created > 0)
1262   {
1263   uschar minibuf[20];
1264
1265   snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->created);
1266   hdr = pdkim_headcat(&col, hdr, US";", US"t=", minibuf);
1267 }
1268
1269 if (sig->expires > 0)
1270   {
1271   uschar minibuf[20];
1272
1273   snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->expires);
1274   hdr = pdkim_headcat(&col, hdr, US";", US"x=", minibuf);
1275   }
1276
1277 if (sig->bodylength >= 0)
1278   {
1279   uschar minibuf[20];
1280
1281   snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->bodylength);
1282   hdr = pdkim_headcat(&col, hdr, US";", US"l=", minibuf);
1283   }
1284
1285 /* Preliminary or final version? */
1286 if (final)
1287   {
1288   base64_b = pdkim_encode_base64(&sig->sighash);
1289   hdr = pdkim_headcat(&col, hdr, US";", US"b=", base64_b);
1290
1291   /* add trailing semicolon: I'm not sure if this is actually needed */
1292   hdr = pdkim_headcat(&col, hdr, NULL, US";", US"");
1293   }
1294 else
1295   {
1296   /* To satisfy the rule "all surrounding whitespace [...] deleted"
1297   ( RFC 6376 section 3.7 ) we ensure there is no whitespace here.  Otherwise
1298   the headcat routine could insert a linebreak which the relaxer would reduce
1299   to a single space preceding the terminating semicolon, resulting in an
1300   incorrect header-hash. */
1301   hdr = pdkim_headcat(&col, hdr, US";", US"b=;", US"");
1302   }
1303
1304 return string_from_gstring(hdr);
1305 }
1306
1307
1308 /* -------------------------------------------------------------------------- */
1309
1310 static pdkim_pubkey *
1311 pdkim_key_from_dns(pdkim_ctx * ctx, pdkim_signature * sig, ev_ctx * vctx,
1312   const uschar ** errstr)
1313 {
1314 uschar * dns_txt_name, * dns_txt_reply;
1315 pdkim_pubkey * p;
1316
1317 /* Fetch public key for signing domain, from DNS */
1318
1319 dns_txt_name = string_sprintf("%s._domainkey.%s.", sig->selector, sig->domain);
1320
1321 if (  !(dns_txt_reply = ctx->dns_txt_callback(CS dns_txt_name))
1322    || dns_txt_reply[0] == '\0'
1323    )
1324   {
1325   sig->verify_status =      PDKIM_VERIFY_INVALID;
1326   sig->verify_ext_status =  PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1327   return NULL;
1328   }
1329
1330 DEBUG(D_acl)
1331   {
1332   debug_printf(
1333     "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
1334     " %s\n"
1335     " Raw record: ",
1336     dns_txt_name);
1337   pdkim_quoteprint(CUS dns_txt_reply, Ustrlen(dns_txt_reply));
1338   }
1339
1340 if (  !(p = pdkim_parse_pubkey_record(ctx, CUS dns_txt_reply))
1341    || (Ustrcmp(p->srvtype, "*") != 0 && Ustrcmp(p->srvtype, "email") != 0)
1342    )
1343   {
1344   sig->verify_status =      PDKIM_VERIFY_INVALID;
1345   sig->verify_ext_status =  PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD;
1346
1347   DEBUG(D_acl)
1348     {
1349     if (p)
1350       debug_printf(" Invalid public key service type '%s'\n", p->srvtype);
1351     else
1352       debug_printf(" Error while parsing public key record\n");
1353     debug_printf(
1354       "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1355     }
1356   return NULL;
1357   }
1358
1359 DEBUG(D_acl) debug_printf(
1360       "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1361
1362 /* Import public key */
1363
1364 if ((*errstr = exim_dkim_verify_init(&p->key,
1365             sig->keytype == KEYTYPE_ED25519 ? KEYFMT_ED25519_BARE : KEYFMT_DER,
1366             vctx)))
1367   {
1368   DEBUG(D_acl) debug_printf("verify_init: %s\n", *errstr);
1369   sig->verify_status =      PDKIM_VERIFY_INVALID;
1370   sig->verify_ext_status =  PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
1371   return NULL;
1372   }
1373
1374 vctx->keytype = sig->keytype;
1375 return p;
1376 }
1377
1378
1379 /* -------------------------------------------------------------------------- */
1380
1381 DLLEXPORT int
1382 pdkim_feed_finish(pdkim_ctx * ctx, pdkim_signature ** return_signatures,
1383   const uschar ** err)
1384 {
1385 pdkim_bodyhash * b;
1386 pdkim_signature * sig;
1387 BOOL verify_pass = FALSE;
1388 es_ctx sctx;
1389
1390 /* Check if we must still flush a (partial) header. If that is the
1391    case, the message has no body, and we must compute a body hash
1392    out of '<CR><LF>' */
1393 if (ctx->cur_header && ctx->cur_header->ptr > 0)
1394   {
1395   blob * rnl = NULL;
1396   int rc;
1397
1398   if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1399     return rc;
1400
1401   for (b = ctx->bodyhash; b; b = b->next)
1402     rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
1403   if (rnl) store_free(rnl);
1404   }
1405 else
1406   DEBUG(D_acl) debug_printf(
1407       "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1408
1409 if (!ctx->sig)
1410   {
1411   DEBUG(D_acl) debug_printf("PDKIM: no signatures\n");
1412   return PDKIM_OK;
1413   }
1414
1415 /* Build (and/or evaluate) body hash */
1416 pdkim_finish_bodyhash(ctx);
1417
1418 for (sig = ctx->sig; sig; sig = sig->next)
1419   {
1420   hctx hhash_ctx;
1421   uschar * sig_hdr = US"";
1422   blob hhash;
1423   gstring * hdata = NULL;
1424   es_ctx sctx;
1425
1426   /*XXX The hash of the headers is needed for GCrypt (for which we can do RSA
1427   suging only, as it happens) and for either GnuTLS and OpenSSL when we are
1428   signing with EC (specifically, Ed25519).  The former is because the GCrypt
1429   signing operation is pure (does not do its own hash) so we must hash.  The
1430   latter is because we (stupidly, but this is what the IETF draft is saying)
1431   must hash with the declared hash method, then pass the result to the library
1432   hash-and-sign routine (because that's all the libraries are providing.  And
1433   we're stuck with whatever that hidden hash method is, too).  We may as well
1434   do this hash incrementally.
1435   We don't need the hash we're calculating here for the GnuTLS and OpenSSL
1436   cases of RSA signing, since those library routines can do hash-and-sign.
1437  
1438   Some time in the future we could easily avoid doing the hash here for those
1439   cases (which will be common for a long while.  We could also change from
1440   the current copy-all-the-headers-into-one-block, then call the hash-and-sign
1441   implementation  - to a proper incremental one.  Unfortunately, GnuTLS just
1442   cannot do incremental - either signing or verification.  Unsure about GCrypt.
1443   */
1444
1445   /*XXX The header hash is also used (so far) by the verify operation */
1446
1447   if (!exim_sha_init(&hhash_ctx, pdkim_hashes[sig->hashtype].exim_hashmethod))
1448     {
1449     log_write(0, LOG_MAIN|LOG_PANIC,
1450       "PDKIM: hash setup error, possibly nonhandled hashtype");
1451     break;
1452     }
1453
1454   if (ctx->flags & PDKIM_MODE_SIGN)
1455     DEBUG(D_acl) debug_printf(
1456         "PDKIM >> Headers to be signed:                            >>>>>>>>>>>>\n"
1457         " %s\n",
1458         sig->sign_headers);
1459
1460   DEBUG(D_acl) debug_printf(
1461       "PDKIM >> Header data for hash, canonicalized, in sequence >>>>>>>>>>>>\n");
1462
1463
1464   /* SIGNING ---------------------------------------------------------------- */
1465   /* When signing, walk through our header list and add them to the hash. As we
1466      go, construct a list of the header's names to use for the h= parameter.
1467      Then append to that list any remaining header names for which there was no
1468      header to sign. */
1469
1470   if (ctx->flags & PDKIM_MODE_SIGN)
1471     {
1472     gstring * g = NULL;
1473     pdkim_stringlist *p;
1474     const uschar * l;
1475     uschar * s;
1476     int sep = 0;
1477
1478     /* Import private key, including the keytype which we need for building
1479     the signature header  */
1480
1481 /*XXX extend for non-RSA algos */
1482     if ((*err = exim_dkim_signing_init(US sig->privkey, &sctx)))
1483       {
1484       log_write(0, LOG_MAIN|LOG_PANIC, "signing_init: %s", *err);
1485       return PDKIM_ERR_RSA_PRIVKEY;
1486       }
1487     sig->keytype = sctx.keytype;
1488
1489     for (sig->headernames = NULL,               /* Collected signed header names */
1490           p = sig->headers; p; p = p->next)
1491       {
1492       uschar * rh = p->value;
1493
1494       if (header_name_match(rh, sig->sign_headers) == PDKIM_OK)
1495         {
1496         /* Collect header names (Note: colon presence is guaranteed here) */
1497         g = string_append_listele_n(g, ':', rh, Ustrchr(rh, ':') - rh);
1498
1499         if (sig->canon_headers == PDKIM_CANON_RELAXED)
1500           rh = pdkim_relax_header(rh, TRUE);    /* cook header for relaxed canon */
1501
1502         /* Feed header to the hash algorithm */
1503         exim_sha_update(&hhash_ctx, CUS rh, Ustrlen(rh));
1504
1505         /* Remember headers block for signing (when the library cannot do incremental)  */
1506         /*XXX we could avoid doing this for all but the GnuTLS/RSA case */
1507         hdata = exim_dkim_data_append(hdata, rh);
1508
1509         DEBUG(D_acl) pdkim_quoteprint(rh, Ustrlen(rh));
1510         }
1511       }
1512
1513     /* Any headers we wanted to sign but were not present must also be listed.
1514     Ignore elements that have been ticked-off or are marked as never-oversign. */
1515
1516     l = sig->sign_headers;
1517     while((s = string_nextinlist(&l, &sep, NULL, 0)))
1518       {
1519       if (*s == '+')                    /* skip oversigning marker */
1520         s++;
1521       if (*s != '_' && *s != '=')
1522         g = string_append_listele(g, ':', s);
1523       }
1524     sig->headernames = string_from_gstring(g);
1525
1526     /* Create signature header with b= omitted */
1527     sig_hdr = pdkim_create_header(sig, FALSE);
1528     }
1529
1530   /* VERIFICATION ----------------------------------------------------------- */
1531   /* When verifying, walk through the header name list in the h= parameter and
1532      add the headers to the hash in that order. */
1533   else
1534     {
1535     uschar * p = sig->headernames;
1536     uschar * q;
1537     pdkim_stringlist * hdrs;
1538
1539     if (p)
1540       {
1541       /* clear tags */
1542       for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1543         hdrs->tag = 0;
1544
1545       p = string_copy(p);
1546       while(1)
1547         {
1548         if ((q = Ustrchr(p, ':')))
1549           *q = '\0';
1550
1551   /*XXX walk the list of headers in same order as received. */
1552         for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1553           if (  hdrs->tag == 0
1554              && strncasecmp(CCS hdrs->value, CCS p, Ustrlen(p)) == 0
1555              && (hdrs->value)[Ustrlen(p)] == ':'
1556              )
1557             {
1558             /* cook header for relaxed canon, or just copy it for simple  */
1559
1560             uschar * rh = sig->canon_headers == PDKIM_CANON_RELAXED
1561               ? pdkim_relax_header(hdrs->value, TRUE)
1562               : string_copy(CUS hdrs->value);
1563
1564             /* Feed header to the hash algorithm */
1565             exim_sha_update(&hhash_ctx, CUS rh, Ustrlen(rh));
1566
1567             DEBUG(D_acl) pdkim_quoteprint(rh, Ustrlen(rh));
1568             hdrs->tag = 1;
1569             break;
1570             }
1571
1572         if (!q) break;
1573         p = q+1;
1574         }
1575
1576       sig_hdr = string_copy(sig->rawsig_no_b_val);
1577       }
1578     }
1579
1580   DEBUG(D_acl) debug_printf(
1581             "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1582
1583   DEBUG(D_acl)
1584     {
1585     debug_printf(
1586             "PDKIM >> Signed DKIM-Signature header, pre-canonicalized >>>>>>>>>>>>>\n");
1587     pdkim_quoteprint(CUS sig_hdr, Ustrlen(sig_hdr));
1588     debug_printf(
1589             "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1590     }
1591
1592   /* Relax header if necessary */
1593   if (sig->canon_headers == PDKIM_CANON_RELAXED)
1594     sig_hdr = pdkim_relax_header(sig_hdr, FALSE);
1595
1596   DEBUG(D_acl)
1597     {
1598     debug_printf(
1599             "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1600     pdkim_quoteprint(CUS sig_hdr, Ustrlen(sig_hdr));
1601     debug_printf(
1602             "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1603     }
1604
1605   /* Finalize header hash */
1606   exim_sha_update(&hhash_ctx, CUS sig_hdr, Ustrlen(sig_hdr));
1607   exim_sha_finish(&hhash_ctx, &hhash);
1608
1609   DEBUG(D_acl)
1610     {
1611     debug_printf("PDKIM [%s] Header %s computed: ",
1612       sig->domain, pdkim_hashes[sig->hashtype].dkim_hashname);
1613     pdkim_hexprint(hhash.data, hhash.len);
1614     }
1615
1616   /* Remember headers block for signing (when the signing library cannot do
1617   incremental)  */
1618   if (ctx->flags & PDKIM_MODE_SIGN)
1619     hdata = exim_dkim_data_append(hdata, US sig_hdr);
1620
1621   /* SIGNING ---------------------------------------------------------------- */
1622   if (ctx->flags & PDKIM_MODE_SIGN)
1623     {
1624     hashmethod hm = sig->keytype == KEYTYPE_ED25519
1625       ? HASH_SHA2_512 : pdkim_hashes[sig->hashtype].exim_hashmethod;
1626
1627 #ifdef SIGN_HAVE_ED25519
1628     /* For GCrypt, and for EC, we pass the hash-of-headers to the signing
1629     routine.  For anything else we just pass the headers. */
1630
1631     if (sig->keytype != KEYTYPE_ED25519)
1632 #endif
1633       {
1634       hhash.data = hdata->s;
1635       hhash.len = hdata->ptr;
1636       }
1637
1638 /*XXX extend for non-RSA algos */
1639 /*- done for GnuTLS */
1640     if ((*err = exim_dkim_sign(&sctx, hm, &hhash, &sig->sighash)))
1641       {
1642       log_write(0, LOG_MAIN|LOG_PANIC, "signing: %s", *err);
1643       return PDKIM_ERR_RSA_SIGNING;
1644       }
1645
1646     DEBUG(D_acl)
1647       {
1648       debug_printf( "PDKIM [%s] b computed: ", sig->domain);
1649       pdkim_hexprint(sig->sighash.data, sig->sighash.len);
1650       }
1651
1652     sig->signature_header = pdkim_create_header(sig, TRUE);
1653     }
1654
1655   /* VERIFICATION ----------------------------------------------------------- */
1656   else
1657     {
1658     ev_ctx vctx;
1659
1660     /* Make sure we have all required signature tags */
1661     if (!(  sig->domain        && *sig->domain
1662          && sig->selector      && *sig->selector
1663          && sig->headernames   && *sig->headernames
1664          && sig->bodyhash.data
1665          && sig->sighash.data
1666          && sig->keytype >= 0
1667          && sig->hashtype >= 0
1668          && sig->version
1669        ) )
1670       {
1671       sig->verify_status     = PDKIM_VERIFY_INVALID;
1672       sig->verify_ext_status = PDKIM_VERIFY_INVALID_SIGNATURE_ERROR;
1673
1674       DEBUG(D_acl) debug_printf(
1675           " Error in DKIM-Signature header: tags missing or invalid\n"
1676           "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1677       goto NEXT_VERIFY;
1678       }
1679
1680     /* Make sure sig uses supported DKIM version (only v1) */
1681     if (sig->version != 1)
1682       {
1683       sig->verify_status     = PDKIM_VERIFY_INVALID;
1684       sig->verify_ext_status = PDKIM_VERIFY_INVALID_DKIM_VERSION;
1685
1686       DEBUG(D_acl) debug_printf(
1687           " Error in DKIM-Signature header: unsupported DKIM version\n"
1688           "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1689       goto NEXT_VERIFY;
1690       }
1691
1692     DEBUG(D_acl)
1693       {
1694       debug_printf( "PDKIM [%s] b from mail: ", sig->domain);
1695       pdkim_hexprint(sig->sighash.data, sig->sighash.len);
1696       }
1697
1698     if (!(sig->pubkey = pdkim_key_from_dns(ctx, sig, &vctx, err)))
1699       {
1700       log_write(0, LOG_MAIN, "PDKIM: %s%s %s%s [failed key import]",
1701         sig->domain   ? "d=" : "", sig->domain   ? sig->domain   : US"",
1702         sig->selector ? "s=" : "", sig->selector ? sig->selector : US"");
1703       goto NEXT_VERIFY;
1704       }
1705
1706     /* If the pubkey limits to a list of specific hashes, ignore sigs that
1707     do not have the hash part of the sig algorithm matching */
1708
1709     if (sig->pubkey->hashes)
1710       {
1711       const uschar * list = sig->pubkey->hashes, * ele;
1712       int sep = ':';
1713       while ((ele = string_nextinlist(&list, &sep, NULL, 0)))
1714         if (Ustrcmp(ele, pdkim_hashes[sig->hashtype].dkim_hashname) == 0) break;
1715       if (!ele)
1716         {
1717         DEBUG(D_acl) debug_printf("pubkey h=%s vs. sig a=%s_%s\n",
1718           sig->pubkey->hashes,
1719           pdkim_keytypes[sig->keytype],
1720           pdkim_hashes[sig->hashtype].dkim_hashname);
1721         sig->verify_status =      PDKIM_VERIFY_FAIL;
1722         sig->verify_ext_status =  PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH;
1723         goto NEXT_VERIFY;
1724         }
1725       }
1726
1727     /* Check the signature */
1728 /*XXX extend for non-RSA algos */
1729 /*- done for GnuTLS */
1730     if ((*err = exim_dkim_verify(&vctx,
1731                                 pdkim_hashes[sig->hashtype].exim_hashmethod,
1732                                 &hhash, &sig->sighash)))
1733       {
1734       DEBUG(D_acl) debug_printf("headers verify: %s\n", *err);
1735       sig->verify_status =      PDKIM_VERIFY_FAIL;
1736       sig->verify_ext_status =  PDKIM_VERIFY_FAIL_MESSAGE;
1737       goto NEXT_VERIFY;
1738       }
1739
1740
1741     /* We have a winner! (if bodyhash was correct earlier) */
1742     if (sig->verify_status == PDKIM_VERIFY_NONE)
1743       {
1744       sig->verify_status = PDKIM_VERIFY_PASS;
1745       verify_pass = TRUE;
1746       }
1747
1748 NEXT_VERIFY:
1749
1750     DEBUG(D_acl)
1751       {
1752       debug_printf("PDKIM [%s] %s signature status: %s",
1753               sig->domain, dkim_sig_to_a_tag(sig),
1754               pdkim_verify_status_str(sig->verify_status));
1755       if (sig->verify_ext_status > 0)
1756         debug_printf(" (%s)\n",
1757                 pdkim_verify_ext_status_str(sig->verify_ext_status));
1758       else
1759         debug_printf("\n");
1760       }
1761     }
1762   }
1763
1764 /* If requested, set return pointer to signature(s) */
1765 if (return_signatures)
1766   *return_signatures = ctx->sig;
1767
1768 return ctx->flags & PDKIM_MODE_SIGN  ||  verify_pass
1769   ? PDKIM_OK : PDKIM_FAIL;
1770 }
1771
1772
1773 /* -------------------------------------------------------------------------- */
1774
1775 DLLEXPORT pdkim_ctx *
1776 pdkim_init_verify(uschar * (*dns_txt_callback)(char *), BOOL dot_stuffing)
1777 {
1778 pdkim_ctx * ctx;
1779
1780 ctx = store_get(sizeof(pdkim_ctx));
1781 memset(ctx, 0, sizeof(pdkim_ctx));
1782
1783 if (dot_stuffing) ctx->flags = PDKIM_DOT_TERM;
1784 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN);
1785 ctx->dns_txt_callback = dns_txt_callback;
1786
1787 return ctx;
1788 }
1789
1790
1791 /* -------------------------------------------------------------------------- */
1792
1793 DLLEXPORT pdkim_signature *
1794 pdkim_init_sign(pdkim_ctx * ctx,
1795   uschar * domain, uschar * selector, uschar * privkey,
1796   uschar * hashname, const uschar ** errstr)
1797 {
1798 int hashtype;
1799 pdkim_signature * sig;
1800
1801 if (!domain || !selector || !privkey)
1802   return NULL;
1803
1804 /* Allocate & init one signature struct */
1805
1806 sig = store_get(sizeof(pdkim_signature));
1807 memset(sig, 0, sizeof(pdkim_signature));
1808
1809 sig->bodylength = -1;
1810
1811 sig->domain = string_copy(US domain);
1812 sig->selector = string_copy(US selector);
1813 sig->privkey = string_copy(US privkey);
1814 sig->keytype = -1;
1815
1816 for (hashtype = 0; hashtype < nelem(pdkim_hashes); hashtype++)
1817   if (Ustrcmp(hashname, pdkim_hashes[hashtype].dkim_hashname) == 0)
1818   { sig->hashtype = hashtype; break; }
1819 if (hashtype >= nelem(pdkim_hashes))
1820   {
1821   log_write(0, LOG_MAIN|LOG_PANIC,
1822     "PDKIM: unrecognised hashname '%s'", hashname);
1823   return NULL;
1824   }
1825
1826 DEBUG(D_acl)
1827   {
1828   pdkim_signature s = *sig;
1829   ev_ctx vctx;
1830
1831   debug_printf("PDKIM (checking verify key)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1832   if (!pdkim_key_from_dns(ctx, &s, &vctx, errstr))
1833     debug_printf("WARNING: bad dkim key in dns\n");
1834   debug_printf("PDKIM (finished checking verify key)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1835   }
1836 return sig;
1837 }
1838
1839
1840 /* -------------------------------------------------------------------------- */
1841
1842 DLLEXPORT void
1843 pdkim_set_optional(pdkim_signature * sig,
1844                        char * sign_headers,
1845                        char * identity,
1846                        int canon_headers,
1847                        int canon_body,
1848                        long bodylength,
1849                        unsigned long created,
1850                        unsigned long expires)
1851 {
1852 if (identity)
1853   sig->identity = string_copy(US identity);
1854
1855 sig->sign_headers = string_copy(sign_headers
1856         ? US sign_headers : US PDKIM_DEFAULT_SIGN_HEADERS);
1857
1858 sig->canon_headers = canon_headers;
1859 sig->canon_body = canon_body;
1860 sig->bodylength = bodylength;
1861 sig->created = created;
1862 sig->expires = expires;
1863
1864 return;
1865 }
1866
1867
1868
1869 /* Set up a blob for calculating the bodyhash according to the
1870 needs of this signature.  Use an existing one if possible, or
1871 create a new one.
1872
1873 Return: hashblob pointer, or NULL on error (only used as a boolean).
1874 */
1875 pdkim_bodyhash *
1876 pdkim_set_bodyhash(pdkim_ctx * ctx, pdkim_signature * sig)
1877 {
1878 pdkim_bodyhash * b;
1879
1880 for (b = ctx->bodyhash; b; b = b->next)
1881   if (  sig->hashtype == b->hashtype
1882      && sig->canon_body == b->canon_method
1883      && sig->bodylength == b->bodylength)
1884     goto old;
1885
1886 b = store_get(sizeof(pdkim_bodyhash));
1887 b->next = ctx->bodyhash;
1888 b->hashtype = sig->hashtype;
1889 b->canon_method = sig->canon_body;
1890 b->bodylength = sig->bodylength;
1891 if (!exim_sha_init(&b->body_hash_ctx,           /*XXX hash method: extend for sha512 */
1892                   pdkim_hashes[sig->hashtype].exim_hashmethod))
1893   {
1894   DEBUG(D_acl)
1895     debug_printf("PDKIM: hash init error, possibly nonhandled hashtype\n");
1896   return NULL;
1897   }
1898 b->signed_body_bytes = 0;
1899 b->num_buffered_blanklines = 0;
1900 ctx->bodyhash = b;
1901
1902 old:
1903 sig->calc_body_hash = b;
1904 return b;
1905 }
1906
1907
1908 /* -------------------------------------------------------------------------- */
1909
1910
1911 void
1912 pdkim_init_context(pdkim_ctx * ctx, BOOL dot_stuffed,
1913   uschar * (*dns_txt_callback)(char *))
1914 {
1915 memset(ctx, 0, sizeof(pdkim_ctx));
1916 ctx->flags = dot_stuffed ? PDKIM_MODE_SIGN | PDKIM_DOT_TERM : PDKIM_MODE_SIGN;
1917 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN);
1918 DEBUG(D_acl) ctx->dns_txt_callback = dns_txt_callback;
1919 }
1920
1921
1922 void
1923 pdkim_init(void)
1924 {
1925 exim_dkim_init();
1926 }
1927
1928
1929
1930 #endif  /*DISABLE_DKIM*/