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