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