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