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