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