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