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