2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2009 - 2015 Tom Kistner <tom@duncanthrax.net>
6 * http://duncanthrax.net/pdkim/
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.
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.
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.
28 #include "../mytypes.h"
30 #include "pdkim-rsa.h"
32 #include "polarssl/sha1.h"
33 #include "polarssl/sha2.h"
34 #include "polarssl/rsa.h"
35 #include "polarssl/base64.h"
37 #define PDKIM_SIGNATURE_VERSION "1"
38 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
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"
53 /* -------------------------------------------------------------------------- */
54 struct pdkim_stringlist {
60 #define PDKIM_STR_ALLOC_FRAG 256
64 unsigned int allocated;
67 /* -------------------------------------------------------------------------- */
68 /* A bunch of list constants */
69 const char *pdkim_querymethods[] = {
73 const char *pdkim_algos[] = {
78 const char *pdkim_canons[] = {
83 const char *pdkim_hashes[] = {
88 const char *pdkim_keytypes[] = {
93 typedef struct pdkim_combined_canon_entry {
97 } pdkim_combined_canon_entry;
98 pdkim_combined_canon_entry pdkim_combined_canons[] = {
99 { "simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
100 { "simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
101 { "relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
102 { "relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
103 { "simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
104 { "relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
109 const char *pdkim_verify_status_str(int status) {
111 case PDKIM_VERIFY_NONE: return "PDKIM_VERIFY_NONE";
112 case PDKIM_VERIFY_INVALID: return "PDKIM_VERIFY_INVALID";
113 case PDKIM_VERIFY_FAIL: return "PDKIM_VERIFY_FAIL";
114 case PDKIM_VERIFY_PASS: return "PDKIM_VERIFY_PASS";
115 default: return "PDKIM_VERIFY_UNKNOWN";
118 const char *pdkim_verify_ext_status_str(int ext_status) {
120 case PDKIM_VERIFY_FAIL_BODY: return "PDKIM_VERIFY_FAIL_BODY";
121 case PDKIM_VERIFY_FAIL_MESSAGE: return "PDKIM_VERIFY_FAIL_MESSAGE";
122 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
123 case PDKIM_VERIFY_INVALID_BUFFER_SIZE: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
124 case PDKIM_VERIFY_INVALID_PUBKEY_PARSING: return "PDKIM_VERIFY_INVALID_PUBKEY_PARSING";
125 default: return "PDKIM_VERIFY_UNKNOWN";
130 /* -------------------------------------------------------------------------- */
131 /* Print debugging functions */
134 pdkim_quoteprint(FILE *stream, const char *data, int len, int lf)
137 const unsigned char *p = (const unsigned char *)data;
139 for (i = 0; i<len; i++)
144 case ' ' : fprintf(stream,"{SP}"); break;
145 case '\t': fprintf(stream,"{TB}"); break;
146 case '\r': fprintf(stream,"{CR}"); break;
147 case '\n': fprintf(stream,"{LF}"); break;
148 case '{' : fprintf(stream,"{BO}"); break;
149 case '}' : fprintf(stream,"{BC}"); break;
151 if ( (c < 32) || (c > 127) )
152 fprintf(stream,"{%02x}",c);
163 pdkim_hexprint(FILE *stream, const char *data, int len, int lf)
166 const unsigned char *p = (const unsigned char *)data;
168 for (i =0 ; i<len; i++)
171 fprintf(stream,"%02x",c);
179 /* -------------------------------------------------------------------------- */
180 /* Simple string list implementation for convinience */
182 pdkim_append_stringlist(pdkim_stringlist *base, char *str)
184 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
186 if (!new_entry) return NULL;
187 memset(new_entry,0,sizeof(pdkim_stringlist));
188 if (!(new_entry->value = strdup(str))) return NULL;
191 pdkim_stringlist *last = base;
192 while (last->next != NULL) { last = last->next; }
193 last->next = new_entry;
201 pdkim_prepend_stringlist(pdkim_stringlist *base, char *str)
203 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
205 if (!new_entry) return NULL;
206 memset(new_entry,0,sizeof(pdkim_stringlist));
207 if (!(new_entry->value = strdup(str))) return NULL;
209 new_entry->next = base;
214 /* -------------------------------------------------------------------------- */
215 /* A small "growing string" implementation to escape malloc/realloc hell */
218 pdkim_strnew (const char *cstr)
220 unsigned int len = cstr ? strlen(cstr) : 0;
221 pdkim_str *p = malloc(sizeof(pdkim_str));
224 memset(p,0,sizeof(pdkim_str));
225 if (!(p->str = malloc(len+1)))
230 p->allocated = len+1;
235 p->str[p->len] = '\0';
240 pdkim_strncat(pdkim_str *str, const char *data, int len)
242 if ((str->allocated - str->len) < (len+1))
244 /* Extend the buffer */
245 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
246 char *n = realloc(str->str,
247 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
248 if (n == NULL) return NULL;
250 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
252 strncpy(&(str->str[str->len]), data, len);
254 str->str[str->len] = '\0';
259 pdkim_strcat(pdkim_str *str, const char *cstr)
261 return pdkim_strncat(str, cstr, strlen(cstr));
265 pdkim_numcat(pdkim_str *str, unsigned long num)
268 snprintf(minibuf,20,"%lu",num);
269 return pdkim_strcat(str,minibuf);
273 pdkim_strtrim(pdkim_str *str)
277 while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
278 while (*p != '\0') {*q = *p; q++; p++;}
280 while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) )
285 str->len = strlen(str->str);
290 pdkim_strclear(pdkim_str *str)
298 pdkim_strfree(pdkim_str *str)
301 if (str->str) free(str->str);
307 /* -------------------------------------------------------------------------- */
310 pdkim_free_pubkey(pdkim_pubkey *pub)
314 if (pub->version ) free(pub->version);
315 if (pub->granularity) free(pub->granularity);
316 if (pub->hashes ) free(pub->hashes);
317 if (pub->keytype ) free(pub->keytype);
318 if (pub->srvtype ) free(pub->srvtype);
319 if (pub->notes ) free(pub->notes);
320 if (pub->key ) free(pub->key);
326 /* -------------------------------------------------------------------------- */
329 pdkim_free_sig(pdkim_signature *sig)
333 pdkim_signature *next = (pdkim_signature *)sig->next;
335 pdkim_stringlist *e = sig->headers;
338 pdkim_stringlist *c = e;
339 if (e->value) free(e->value);
344 if (sig->sigdata ) free(sig->sigdata);
345 if (sig->bodyhash ) free(sig->bodyhash);
346 if (sig->selector ) free(sig->selector);
347 if (sig->domain ) free(sig->domain);
348 if (sig->identity ) free(sig->identity);
349 if (sig->headernames ) free(sig->headernames);
350 if (sig->copiedheaders ) free(sig->copiedheaders);
351 if (sig->rsa_privkey ) free(sig->rsa_privkey);
352 if (sig->sign_headers ) free(sig->sign_headers);
353 if (sig->signature_header) free(sig->signature_header);
354 if (sig->sha1_body ) free(sig->sha1_body);
355 if (sig->sha2_body ) free(sig->sha2_body);
357 if (sig->pubkey) pdkim_free_pubkey(sig->pubkey);
360 if (next) pdkim_free_sig(next);
365 /* -------------------------------------------------------------------------- */
368 pdkim_free_ctx(pdkim_ctx *ctx)
372 pdkim_stringlist *e = ctx->headers;
375 pdkim_stringlist *c = e;
376 if (e->value) free(e->value);
380 pdkim_free_sig(ctx->sig);
381 pdkim_strfree(ctx->cur_header);
387 /* -------------------------------------------------------------------------- */
388 /* Matches the name of the passed raw "header" against
389 the passed colon-separated "list", starting at entry
390 "start". Returns the position of the header name in
394 header_name_match(const char *header,
404 /* Get header name */
405 char *hcolon = strchr(header,':');
407 if (!hcolon) return rc; /* This isn't a header */
409 if (!(hname = malloc((hcolon-header)+1)))
410 return PDKIM_ERR_OOM;
411 memset(hname,0,(hcolon-header)+1);
412 strncpy(hname,header,(hcolon-header));
414 /* Copy tick-off list locally, so we can punch zeroes into it */
415 if (!(lcopy = strdup(tick)))
418 return PDKIM_ERR_OOM;
426 if (strcasecmp(p,hname) == 0)
429 /* Invalidate header name instance in tick-off list */
430 if (do_tick) tick[p-lcopy] = '_';
438 if (strcasecmp(p,hname) == 0)
441 /* Invalidate header name instance in tick-off list */
442 if (do_tick) tick[p-lcopy] = '_';
452 /* -------------------------------------------------------------------------- */
453 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
457 pdkim_relax_header (char *header, int crlf)
459 BOOL past_field_name = FALSE;
460 BOOL seen_wsp = FALSE;
463 char *relaxed = malloc(strlen(header)+3);
465 if (!relaxed) return NULL;
468 for (p = header; *p != '\0'; p++)
472 if (c == '\r' || c == '\n')
474 if (c == '\t' || c == ' ')
478 c = ' '; /* Turns WSP into SP */
482 if (!past_field_name && c == ':')
484 if (seen_wsp) q--; /* This removes WSP before the colon */
485 seen_wsp = TRUE; /* This removes WSP after the colon */
486 past_field_name = TRUE;
491 /* Lowercase header name */
492 if (!past_field_name) c = tolower(c);
496 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
499 if (crlf) strcat(relaxed,"\r\n");
504 /* -------------------------------------------------------------------------- */
505 #define PDKIM_QP_ERROR_DECODE -1
508 pdkim_decode_qp_char(char *qp_p, int *c)
510 char *initial_pos = qp_p;
512 /* Advance one char */
515 /* Check for two hex digits and decode them */
516 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
518 /* Do hex conversion */
519 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
520 *c != isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
524 /* Illegal char here */
525 *c = PDKIM_QP_ERROR_DECODE;
530 /* -------------------------------------------------------------------------- */
533 pdkim_decode_qp(char *str)
538 char *n = malloc(strlen(p)+1);
548 p = pdkim_decode_qp_char(p, &nchar);
564 /* -------------------------------------------------------------------------- */
567 pdkim_decode_base64(char *str, int *num_decoded)
572 base64_decode(NULL, &dlen, (unsigned char *)str, strlen(str));
574 if (!(res = malloc(dlen+1)))
576 if (base64_decode((unsigned char *)res, &dlen, (unsigned char *)str, strlen(str)) != 0)
582 if (num_decoded) *num_decoded = dlen;
587 /* -------------------------------------------------------------------------- */
590 pdkim_encode_base64(char *str, int num)
595 base64_encode(NULL, &dlen, (unsigned char *)str, num);
597 if (!(res = malloc(dlen+1)))
599 if (base64_encode((unsigned char *)res, &dlen, (unsigned char *)str, num) != 0)
608 /* -------------------------------------------------------------------------- */
609 #define PDKIM_HDR_LIMBO 0
610 #define PDKIM_HDR_TAG 1
611 #define PDKIM_HDR_VALUE 2
614 pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr)
616 pdkim_signature *sig ;
618 pdkim_str *cur_tag = NULL;
619 pdkim_str *cur_val = NULL;
620 BOOL past_hname = FALSE;
621 BOOL in_b_val = FALSE;
622 int where = PDKIM_HDR_LIMBO;
625 if (!(sig = malloc(sizeof(pdkim_signature)))) return NULL;
626 memset(sig,0,sizeof(pdkim_signature));
627 sig->bodylength = -1;
629 if (!(sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1)))
635 q = sig->rawsig_no_b_val;
637 for (p = raw_hdr; ; p++)
642 if (c == '\r' || c == '\n')
645 /* Fast-forward through header name */
648 if (c == ':') past_hname = TRUE;
652 if (where == PDKIM_HDR_LIMBO)
654 /* In limbo, just wait for a tag-char to appear */
655 if (!(c >= 'a' && c <= 'z'))
658 where = PDKIM_HDR_TAG;
661 if (where == PDKIM_HDR_TAG)
664 cur_tag = pdkim_strnew(NULL);
666 if (c >= 'a' && c <= 'z')
667 pdkim_strncat(cur_tag, p, 1);
671 if (strcmp(cur_tag->str, "b") == 0)
676 where = PDKIM_HDR_VALUE;
681 if (where == PDKIM_HDR_VALUE)
684 cur_val = pdkim_strnew(NULL);
686 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
689 if (c == ';' || c == '\0')
691 if (cur_tag->len > 0)
693 pdkim_strtrim(cur_val);
696 if (ctx->debug_stream)
697 fprintf(ctx->debug_stream, " %s=%s\n", cur_tag->str, cur_val->str);
700 switch (cur_tag->str[0])
703 if (cur_tag->str[1] == 'h')
704 sig->bodyhash = pdkim_decode_base64(cur_val->str,
707 sig->sigdata = pdkim_decode_base64(cur_val->str,
711 /* We only support version 1, and that is currently the
712 only version there is. */
713 if (strcmp(cur_val->str, PDKIM_SIGNATURE_VERSION) == 0)
717 for (i = 0; pdkim_algos[i]; i++)
718 if (strcmp(cur_val->str, pdkim_algos[i]) == 0)
725 for (i = 0; pdkim_combined_canons[i].str; i++)
726 if (strcmp(cur_val->str, pdkim_combined_canons[i].str) == 0)
728 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
729 sig->canon_body = pdkim_combined_canons[i].canon_body;
734 for (i = 0; pdkim_querymethods[i]; i++)
735 if (strcmp(cur_val->str, pdkim_querymethods[i]) == 0)
737 sig->querymethod = i;
742 sig->selector = strdup(cur_val->str); break;
744 sig->domain = strdup(cur_val->str); break;
746 sig->identity = pdkim_decode_qp(cur_val->str); break;
748 sig->created = strtoul(cur_val->str, NULL, 10); break;
750 sig->expires = strtoul(cur_val->str, NULL, 10); break;
752 sig->bodylength = strtol(cur_val->str, NULL, 10); break;
754 sig->headernames = strdup(cur_val->str); break;
756 sig->copiedheaders = pdkim_decode_qp(cur_val->str); break;
759 if (ctx->debug_stream)
760 fprintf(ctx->debug_stream, " Unknown tag encountered\n");
765 pdkim_strclear(cur_tag);
766 pdkim_strclear(cur_val);
768 where = PDKIM_HDR_LIMBO;
771 pdkim_strncat(cur_val, p, 1);
782 /* Make sure the most important bits are there. */
783 if (!(sig->domain && (*(sig->domain) != '\0') &&
784 sig->selector && (*(sig->selector) != '\0') &&
785 sig->headernames && (*(sig->headernames) != '\0') &&
795 /* Chomp raw header. The final newline must not be added to the signature. */
797 while (q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
798 *q = '\0'; q--; /*XXX questionable code layout; possible bug */
801 if (ctx->debug_stream)
803 fprintf(ctx->debug_stream,
804 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
805 pdkim_quoteprint(ctx->debug_stream,
806 sig->rawsig_no_b_val,
807 strlen(sig->rawsig_no_b_val), 1);
808 fprintf(ctx->debug_stream,
809 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
813 if ( !(sig->sha1_body = malloc(sizeof(sha1_context)))
814 || !(sig->sha2_body = malloc(sizeof(sha2_context)))
821 sha1_starts(sig->sha1_body);
822 sha2_starts(sig->sha2_body, 0);
828 /* -------------------------------------------------------------------------- */
831 pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record)
835 pdkim_str *cur_tag = NULL;
836 pdkim_str *cur_val = NULL;
837 int where = PDKIM_HDR_LIMBO;
839 if (!(pub = malloc(sizeof(pdkim_pubkey)))) return NULL;
840 memset(pub,0,sizeof(pdkim_pubkey));
842 for (p = raw_record; ; p++)
847 if (c == '\r' || c == '\n')
850 if (where == PDKIM_HDR_LIMBO)
852 /* In limbo, just wait for a tag-char to appear */
853 if (!(c >= 'a' && c <= 'z'))
856 where = PDKIM_HDR_TAG;
859 if (where == PDKIM_HDR_TAG)
862 cur_tag = pdkim_strnew(NULL);
864 if (c >= 'a' && c <= 'z')
865 pdkim_strncat(cur_tag, p, 1);
869 where = PDKIM_HDR_VALUE;
874 if (where == PDKIM_HDR_VALUE)
877 cur_val = pdkim_strnew(NULL);
879 if (c == '\r' || c == '\n')
882 if (c == ';' || c == '\0')
884 if (cur_tag->len > 0)
886 pdkim_strtrim(cur_val);
888 if (ctx->debug_stream)
889 fprintf(ctx->debug_stream, " %s=%s\n", cur_tag->str, cur_val->str);
892 switch (cur_tag->str[0])
895 /* This tag isn't evaluated because:
896 - We only support version DKIM1.
897 - Which is the default for this value (set below)
898 - Other versions are currently not specified. */
901 pub->hashes = strdup(cur_val->str); break;
903 pub->granularity = strdup(cur_val->str); break;
905 pub->notes = pdkim_decode_qp(cur_val->str); break;
907 pub->key = pdkim_decode_base64(cur_val->str, &(pub->key_len)); break;
909 pub->hashes = strdup(cur_val->str); break;
911 pub->srvtype = strdup(cur_val->str); break;
913 if (strchr(cur_val->str,'y') != NULL) pub->testing = 1;
914 if (strchr(cur_val->str,'s') != NULL) pub->no_subdomaining = 1;
918 if (ctx->debug_stream)
919 fprintf(ctx->debug_stream, " Unknown tag encountered\n");
924 pdkim_strclear(cur_tag);
925 pdkim_strclear(cur_val);
926 where = PDKIM_HDR_LIMBO;
929 pdkim_strncat(cur_val, p, 1);
933 if (c == '\0') break;
936 /* Set fallback defaults */
937 if (!pub->version ) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
938 if (!pub->granularity) pub->granularity = strdup("*");
939 if (!pub->keytype ) pub->keytype = strdup("rsa");
940 if (!pub->srvtype ) pub->srvtype = strdup("*");
946 pdkim_free_pubkey(pub);
951 /* -------------------------------------------------------------------------- */
954 pdkim_update_bodyhash(pdkim_ctx *ctx, const char *data, int len)
956 pdkim_signature *sig = ctx->sig;
957 /* Cache relaxed version of data */
958 char *relaxed_data = NULL;
961 /* Traverse all signatures, updating their hashes. */
964 /* Defaults to simple canon (no further treatment necessary) */
965 const char *canon_data = data;
968 if (sig->canon_body == PDKIM_CANON_RELAXED)
970 /* Relax the line if not done already */
973 BOOL seen_wsp = FALSE;
977 if (!(relaxed_data = malloc(len+1)))
978 return PDKIM_ERR_OOM;
980 for (p = data; *p; p++)
985 if (q > 0 && relaxed_data[q-1] == ' ')
988 else if (c == '\t' || c == ' ')
990 c = ' '; /* Turns WSP into SP */
997 relaxed_data[q++] = c;
999 relaxed_data[q] = '\0';
1002 canon_data = relaxed_data;
1003 canon_len = relaxed_len;
1006 /* Make sure we don't exceed the to-be-signed body length */
1007 if ( sig->bodylength >= 0
1008 && sig->signed_body_bytes + (unsigned long)canon_len > sig->bodylength
1010 canon_len = sig->bodylength - sig->signed_body_bytes;
1014 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1015 sha1_update(sig->sha1_body,(unsigned char *)canon_data,canon_len);
1017 sha2_update(sig->sha2_body,(unsigned char *)canon_data,canon_len);
1019 sig->signed_body_bytes += canon_len;
1021 if (ctx->debug_stream)
1022 pdkim_quoteprint(ctx->debug_stream, canon_data, canon_len, 1);
1029 if (relaxed_data) free(relaxed_data);
1034 /* -------------------------------------------------------------------------- */
1037 pdkim_finish_bodyhash(pdkim_ctx *ctx)
1039 pdkim_signature *sig = ctx->sig;
1041 /* Traverse all signatures */
1043 { /* Finish hashes */
1044 unsigned char bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
1046 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1047 sha1_finish(sig->sha1_body,bh);
1049 sha2_finish(sig->sha2_body,bh);
1052 if (ctx->debug_stream)
1054 fprintf(ctx->debug_stream, "PDKIM [%s] Body bytes hashed: %lu\n",
1055 sig->domain, sig->signed_body_bytes);
1056 fprintf(ctx->debug_stream, "PDKIM [%s] bh computed: ", sig->domain);
1057 pdkim_hexprint(ctx->debug_stream, (char *)bh,
1058 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
1062 /* SIGNING -------------------------------------------------------------- */
1063 if (ctx->mode == PDKIM_MODE_SIGN)
1065 sig->bodyhash_len = (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32;
1067 if (!(sig->bodyhash = malloc(sig->bodyhash_len)))
1068 return PDKIM_ERR_OOM;
1069 memcpy(sig->bodyhash, bh, sig->bodyhash_len);
1071 /* If bodylength limit is set, and we have received less bytes
1072 than the requested amount, effectively remove the limit tag. */
1073 if (sig->signed_body_bytes < sig->bodylength)
1074 sig->bodylength = -1;
1077 /* VERIFICATION --------------------------------------------------------- */
1080 /* Compare bodyhash */
1081 if (memcmp(bh, sig->bodyhash,
1082 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0)
1085 if (ctx->debug_stream)
1086 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash verified OK\n",
1093 if (ctx->debug_stream)
1095 fprintf(ctx->debug_stream, "PDKIM [%s] bh signature: ", sig->domain);
1096 pdkim_hexprint(ctx->debug_stream, sig->bodyhash,
1097 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
1098 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash did NOT verify\n",
1102 sig->verify_status = PDKIM_VERIFY_FAIL;
1103 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
1115 /* -------------------------------------------------------------------------- */
1116 /* Callback from pdkim_feed below for processing complete body lines */
1119 pdkim_bodyline_complete(pdkim_ctx *ctx)
1121 char *p = ctx->linebuf;
1122 int n = ctx->linebuf_offset;
1124 /* Ignore extra data if we've seen the end-of-data marker */
1125 if (ctx->seen_eod) goto BAIL;
1127 /* We've always got one extra byte to stuff a zero ... */
1128 ctx->linebuf[(ctx->linebuf_offset)] = '\0';
1130 if (ctx->input_mode == PDKIM_INPUT_SMTP)
1132 /* Terminate on EOD marker */
1133 if (memcmp(p, ".\r\n", 3) == 0)
1135 /* In simple body mode, if any empty lines were buffered,
1136 replace with one. rfc 4871 3.4.3 */
1137 if ( ctx->sig && ctx->sig->canon_body == PDKIM_CANON_SIMPLE
1138 && ctx->num_buffered_crlf > 0
1140 pdkim_update_bodyhash(ctx, "\r\n",2);
1146 if (memcmp(p, "..", 2) == 0)
1153 /* Empty lines need to be buffered until we find a non-empty line */
1154 if (memcmp(p, "\r\n", 2) == 0)
1156 ctx->num_buffered_crlf++;
1161 && ctx->sig->canon_body == PDKIM_CANON_RELAXED
1164 /* Lines with just spaces need to be buffered too */
1166 while (memcmp(check, "\r\n", 2) != 0)
1170 if (c != '\t' && c != ' ')
1175 ctx->num_buffered_crlf++;
1180 /* At this point, we have a non-empty line, so release the buffered ones. */
1181 while (ctx->num_buffered_crlf)
1183 pdkim_update_bodyhash(ctx, "\r\n", 2);
1184 ctx->num_buffered_crlf--;
1187 pdkim_update_bodyhash(ctx, p, n);
1190 ctx->linebuf_offset = 0;
1195 /* -------------------------------------------------------------------------- */
1196 /* Callback from pdkim_feed below for processing complete headers */
1197 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1200 pdkim_header_complete(pdkim_ctx *ctx)
1202 pdkim_signature *sig = ctx->sig;
1204 /* Special case: The last header can have an extra \r appended */
1205 if ( (ctx->cur_header->len > 1) &&
1206 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') )
1208 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
1209 ctx->cur_header->len--;
1213 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
1215 /* SIGNING -------------------------------------------------------------- */
1216 if (ctx->mode == PDKIM_MODE_SIGN)
1217 for ( ; sig; sig = sig->next) /* Traverse all signatures */
1218 if (header_name_match(ctx->cur_header->str,
1221 PDKIM_DEFAULT_SIGN_HEADERS, 0) == PDKIM_OK)
1223 pdkim_stringlist *list;
1225 /* Add header to the signed headers list (in reverse order) */
1226 if (!(list = pdkim_prepend_stringlist(sig->headers,
1227 ctx->cur_header->str)))
1228 return PDKIM_ERR_OOM;
1229 sig->headers = list;
1232 /* DKIM-Signature: headers are added to the verification list */
1233 if (ctx->mode == PDKIM_MODE_VERIFY)
1235 if (strncasecmp(ctx->cur_header->str,
1236 DKIM_SIGNATURE_HEADERNAME,
1237 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
1239 pdkim_signature *new_sig;
1241 /* Create and chain new signature block */
1243 if (ctx->debug_stream)
1244 fprintf(ctx->debug_stream,
1245 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1248 if ((new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str)))
1250 pdkim_signature *last_sig = ctx->sig;
1255 while (last_sig->next) last_sig = last_sig->next;
1256 last_sig->next = new_sig;
1261 if (ctx->debug_stream)
1263 fprintf(ctx->debug_stream,"Error while parsing signature header\n");
1264 fprintf(ctx->debug_stream,
1265 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1270 /* every other header is stored for signature verification */
1273 pdkim_stringlist *list;
1275 if (!(list = pdkim_prepend_stringlist(ctx->headers,
1276 ctx->cur_header->str)))
1277 return PDKIM_ERR_OOM;
1278 ctx->headers = list;
1283 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1289 /* -------------------------------------------------------------------------- */
1290 #define HEADER_BUFFER_FRAG_SIZE 256
1293 pdkim_feed (pdkim_ctx *ctx, char *data, int len)
1297 for (p = 0; p<len; p++)
1301 if (ctx->past_headers)
1303 /* Processing body byte */
1304 ctx->linebuf[(ctx->linebuf_offset)++] = c;
1307 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1308 if (rc != PDKIM_OK) return rc;
1310 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1311 return PDKIM_ERR_LONG_LINE;
1315 /* Processing header byte */
1322 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1323 if (rc != PDKIM_OK) return rc;
1325 ctx->past_headers = 1;
1328 if (ctx->debug_stream)
1329 fprintf(ctx->debug_stream,
1330 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1337 else if (ctx->seen_lf)
1339 if (!(c == '\t' || c == ' '))
1341 int rc = pdkim_header_complete(ctx); /* End of header */
1342 if (rc != PDKIM_OK) return rc;
1348 if (!ctx->cur_header)
1349 if (!(ctx->cur_header = pdkim_strnew(NULL)))
1350 return PDKIM_ERR_OOM;
1352 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1353 if (!pdkim_strncat(ctx->cur_header, &data[p], 1))
1354 return PDKIM_ERR_OOM;
1361 * RFC 5322 specifies that header line length SHOULD be no more than 78
1366 * col: this int holds and receives column number (octets since last '\n')
1367 * str: partial string to append to
1368 * pad: padding, split line or space after before or after eg: ";"
1369 * intro: - must join to payload eg "h=", usually the tag name
1370 * payload: eg base64 data - long data can be split arbitrarily.
1372 * this code doesn't fold the header in some of the places that RFC4871
1373 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1374 * pairs and inside long values. it also always spaces or breaks after the
1377 * no guarantees are made for output given out-of range input. like tag
1378 * names loinger than 78, or bogus col. Input is assumed to be free of line breaks.
1382 pdkim_headcat(int *col, pdkim_str *str, const char * pad,
1383 const char *intro, const char *payload)
1392 pdkim_strcat(str, "\r\n\t");
1395 pdkim_strncat(str, pad, l);
1399 l = (pad?1:0) + (intro?strlen(intro):0);
1402 { /*can't fit intro - start a new line to make room.*/
1403 pdkim_strcat(str, "\r\n\t");
1405 l = intro?strlen(intro):0;
1408 l += payload ? strlen(payload):0 ;
1411 { /* this fragment will not fit on a single line */
1414 pdkim_strcat(str, " ");
1416 pad = NULL; /* only want this once */
1422 size_t sl = strlen(intro);
1424 pdkim_strncat(str, intro,sl);
1427 intro = NULL; /* only want this once */
1432 size_t sl = strlen(payload);
1433 size_t chomp = *col+sl < 77 ? sl : 78-*col;
1435 pdkim_strncat(str, payload,chomp);
1441 /* the while precondition tells us it didn't fit. */
1442 pdkim_strcat(str, "\r\n\t");
1448 pdkim_strcat(str, "\r\n\t");
1455 pdkim_strcat(str, " ");
1462 size_t sl = strlen(intro);
1464 pdkim_strncat(str, intro, sl);
1472 size_t sl = strlen(payload);
1474 pdkim_strncat(str, payload, sl);
1482 /* -------------------------------------------------------------------------- */
1485 pdkim_create_header(pdkim_signature *sig, int final)
1488 char *base64_bh = NULL;
1489 char *base64_b = NULL;
1492 pdkim_str *canon_all;
1494 if (!(hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION)))
1497 if (!(canon_all = pdkim_strnew(pdkim_canons[sig->canon_headers])))
1500 if (!(base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len)))
1503 col = strlen(hdr->str);
1505 /* Required and static bits */
1507 pdkim_headcat(&col,hdr,";","a=",pdkim_algos[sig->algo]) &&
1508 pdkim_headcat(&col,hdr,";","q=",pdkim_querymethods[sig->querymethod]) &&
1509 pdkim_strcat(canon_all,"/") &&
1510 pdkim_strcat(canon_all,pdkim_canons[sig->canon_body]) &&
1511 pdkim_headcat(&col,hdr,";","c=",canon_all->str) &&
1512 pdkim_headcat(&col,hdr,";","d=",sig->domain) &&
1513 pdkim_headcat(&col,hdr,";","s=",sig->selector)
1516 /* list of eader names can be split between items. */
1518 char *n = strdup(sig->headernames);
1526 char *c = strchr(n,':');
1531 if (!pdkim_headcat(&col,hdr,NULL,NULL,":"))
1537 if (!pdkim_headcat(&col,hdr,s,i,n))
1553 if(!pdkim_headcat(&col, hdr, ";", "bh=", base64_bh))
1558 if(!pdkim_headcat(&col, hdr, ";", "i=", sig->identity))
1561 if (sig->created > 0)
1565 snprintf(minibuf,20,"%lu",sig->created);
1566 if(!pdkim_headcat(&col, hdr, ";", "t=", minibuf))
1570 if (sig->expires > 0)
1574 snprintf(minibuf,20,"%lu",sig->expires);
1575 if(!pdkim_headcat(&col, hdr, ";", "x=", minibuf))
1579 if (sig->bodylength >= 0)
1583 snprintf(minibuf,20,"%lu",sig->bodylength);
1584 if(!pdkim_headcat(&col, hdr, ";", "l=", minibuf))
1588 /* Preliminary or final version? */
1591 if (!(base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len)))
1593 if (!pdkim_headcat(&col, hdr, ";", "b=", base64_b))
1597 if(!pdkim_headcat(&col, hdr, ";", "b=", ""))
1600 /* add trailing semicolon: I'm not sure if this is actually needed */
1601 if (!pdkim_headcat(&col,hdr,NULL,";",""))
1605 rc = strdup(hdr->str);
1609 if (canon_all) pdkim_strfree(canon_all);
1610 if (base64_bh) free(base64_bh);
1611 if (base64_b ) free(base64_b);
1616 /* -------------------------------------------------------------------------- */
1619 pdkim_feed_finish(pdkim_ctx *ctx, pdkim_signature **return_signatures)
1621 pdkim_signature *sig = ctx->sig;
1622 pdkim_str *headernames = NULL; /* Collected signed header names */
1624 /* Check if we must still flush a (partial) header. If that is the
1625 case, the message has no body, and we must compute a body hash
1626 out of '<CR><LF>' */
1627 if (ctx->cur_header && ctx->cur_header->len)
1629 int rc = pdkim_header_complete(ctx);
1630 if (rc != PDKIM_OK) return rc;
1631 pdkim_update_bodyhash(ctx, "\r\n", 2);
1635 /* For non-smtp input, check if there's an unfinished line in the
1636 body line buffer. If that is the case, we must add a CRLF to the
1637 hash to properly terminate the message. */
1638 if ((ctx->input_mode == PDKIM_INPUT_NORMAL) && ctx->linebuf_offset)
1640 pdkim_update_bodyhash(ctx, ctx->linebuf, ctx->linebuf_offset);
1641 pdkim_update_bodyhash(ctx, "\r\n", 2);
1644 if (ctx->debug_stream)
1645 fprintf(ctx->debug_stream,
1646 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1650 /* Build (and/or evaluate) body hash */
1651 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK)
1652 return PDKIM_ERR_OOM;
1654 /* SIGNING -------------------------------------------------------------- */
1655 if (ctx->mode == PDKIM_MODE_SIGN)
1656 if (!(headernames = pdkim_strnew(NULL)))
1657 return PDKIM_ERR_OOM;
1658 /* ---------------------------------------------------------------------- */
1662 sha1_context sha1_headers;
1663 sha2_context sha2_headers;
1665 char headerhash[32];
1667 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1668 sha1_starts(&sha1_headers);
1670 sha2_starts(&sha2_headers,0);
1673 if (ctx->debug_stream)
1674 fprintf(ctx->debug_stream,
1675 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1678 /* SIGNING ---------------------------------------------------------------- */
1679 /* When signing, walk through our header list and add them to the hash. As we
1680 go, construct a list of the header's names to use for the h= parameter. */
1682 if (ctx->mode == PDKIM_MODE_SIGN)
1684 pdkim_stringlist *p;
1686 for (p = sig->headers; p; p = p->next)
1689 /* Collect header names (Note: colon presence is guaranteed here) */
1690 char *q = strchr(p->value,':');
1692 if (!(pdkim_strncat(headernames, p->value,
1693 (q-(p->value)) + (p->next ? 1 : 0))))
1694 return PDKIM_ERR_OOM;
1696 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1697 ? pdkim_relax_header(p->value,1) /* cook header for relaxed canon */
1698 : strdup(p->value); /* just copy it for simple canon */
1700 return PDKIM_ERR_OOM;
1702 /* Feed header to the hash algorithm */
1703 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1704 sha1_update(&(sha1_headers), (unsigned char *)rh, strlen(rh));
1706 sha2_update(&(sha2_headers), (unsigned char *)rh, strlen(rh));
1709 if (ctx->debug_stream)
1710 pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1716 /* VERIFICATION ----------------------------------------------------------- */
1717 /* When verifying, walk through the header name list in the h= parameter and
1718 add the headers to the hash in that order. */
1721 char *b = strdup(sig->headernames);
1724 pdkim_stringlist *hdrs;
1726 if (!b) return PDKIM_ERR_OOM;
1729 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1734 if ((q = strchr(p,':')))
1737 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1739 && strncasecmp(hdrs->value,p,strlen(p)) == 0
1740 && (hdrs->value)[strlen(p)] == ':'
1745 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1746 ? pdkim_relax_header(hdrs->value,1) /* cook header for relaxed canon */
1747 : strdup(hdrs->value); /* just copy it for simple canon */
1749 return PDKIM_ERR_OOM;
1751 /* Feed header to the hash algorithm */
1752 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1753 sha1_update(&(sha1_headers), (unsigned char *)rh, strlen(rh));
1755 sha2_update(&(sha2_headers), (unsigned char *)rh, strlen(rh));
1758 if (ctx->debug_stream)
1759 pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1773 if (ctx->debug_stream)
1774 fprintf(ctx->debug_stream,
1775 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1778 /* SIGNING ---------------------------------------------------------------- */
1779 if (ctx->mode == PDKIM_MODE_SIGN)
1781 /* Copy headernames to signature struct */
1782 sig->headernames = strdup(headernames->str);
1783 pdkim_strfree(headernames);
1785 /* Create signature header with b= omitted */
1786 sig_hdr = pdkim_create_header(ctx->sig, 0);
1789 /* VERIFICATION ----------------------------------------------------------- */
1791 sig_hdr = strdup(sig->rawsig_no_b_val);
1792 /* ------------------------------------------------------------------------ */
1795 return PDKIM_ERR_OOM;
1797 /* Relax header if necessary */
1798 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1800 char *relaxed_hdr = pdkim_relax_header(sig_hdr, 0);
1804 return PDKIM_ERR_OOM;
1805 sig_hdr = relaxed_hdr;
1809 if (ctx->debug_stream)
1811 fprintf(ctx->debug_stream,
1812 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1813 pdkim_quoteprint(ctx->debug_stream, sig_hdr, strlen(sig_hdr), 1);
1814 fprintf(ctx->debug_stream,
1815 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1819 /* Finalize header hash */
1820 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1822 sha1_update(&(sha1_headers), (unsigned char *)sig_hdr, strlen(sig_hdr));
1823 sha1_finish(&(sha1_headers), (unsigned char *)headerhash);
1826 if (ctx->debug_stream)
1828 fprintf(ctx->debug_stream, "PDKIM [%s] hh computed: ", sig->domain);
1829 pdkim_hexprint(ctx->debug_stream, headerhash, 20, 1);
1835 sha2_update(&(sha2_headers), (unsigned char *)sig_hdr, strlen(sig_hdr));
1836 sha2_finish(&(sha2_headers), (unsigned char *)headerhash);
1839 if (ctx->debug_stream)
1841 fprintf(ctx->debug_stream, "PDKIM [%s] hh computed: ", sig->domain);
1842 pdkim_hexprint(ctx->debug_stream, headerhash, 32, 1);
1849 /* SIGNING ---------------------------------------------------------------- */
1850 if (ctx->mode == PDKIM_MODE_SIGN)
1854 rsa_init(&rsa, RSA_PKCS_V15, 0);
1856 /* Perform private key operation */
1857 if (rsa_parse_key(&rsa, (unsigned char *)sig->rsa_privkey,
1858 strlen(sig->rsa_privkey), NULL, 0) != 0)
1859 return PDKIM_ERR_RSA_PRIVKEY;
1861 sig->sigdata_len = mpi_size(&(rsa.N));
1862 if (!(sig->sigdata = malloc(sig->sigdata_len)))
1863 return PDKIM_ERR_OOM;
1865 if (rsa_pkcs1_sign( &rsa, RSA_PRIVATE,
1866 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1867 SIG_RSA_SHA1:SIG_RSA_SHA256),
1869 (unsigned char *)headerhash,
1870 (unsigned char *)sig->sigdata ) != 0)
1871 return PDKIM_ERR_RSA_SIGNING;
1876 if (ctx->debug_stream)
1878 fprintf(ctx->debug_stream, "PDKIM [%s] b computed: ", sig->domain);
1879 pdkim_hexprint(ctx->debug_stream, sig->sigdata, sig->sigdata_len, 1);
1883 if (!(sig->signature_header = pdkim_create_header(ctx->sig,1)))
1884 return PDKIM_ERR_OOM;
1887 /* VERIFICATION ----------------------------------------------------------- */
1891 char *dns_txt_name, *dns_txt_reply;
1893 rsa_init(&rsa, RSA_PKCS_V15, 0);
1895 if (!(dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN)))
1896 return PDKIM_ERR_OOM;
1898 if (!(dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN)))
1901 return PDKIM_ERR_OOM;
1904 memset(dns_txt_reply, 0, PDKIM_DNS_TXT_MAX_RECLEN);
1905 memset(dns_txt_name , 0, PDKIM_DNS_TXT_MAX_NAMELEN);
1907 if (snprintf(dns_txt_name,PDKIM_DNS_TXT_MAX_NAMELEN,
1908 "%s._domainkey.%s.",
1909 sig->selector,sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN)
1911 sig->verify_status = PDKIM_VERIFY_INVALID;
1912 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1916 if ( ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK
1917 || dns_txt_reply[0] == '\0')
1919 sig->verify_status = PDKIM_VERIFY_INVALID;
1920 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1925 if (ctx->debug_stream)
1927 fprintf(ctx->debug_stream,
1928 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1929 fprintf(ctx->debug_stream," Raw record: ");
1930 pdkim_quoteprint(ctx->debug_stream, dns_txt_reply, strlen(dns_txt_reply), 1);
1934 if (!(sig->pubkey = pdkim_parse_pubkey_record(ctx,dns_txt_reply)))
1936 sig->verify_status = PDKIM_VERIFY_INVALID;
1937 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1940 if (ctx->debug_stream)
1942 fprintf(ctx->debug_stream," Error while parsing public key record\n");
1943 fprintf(ctx->debug_stream,
1944 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1951 if (ctx->debug_stream)
1952 fprintf(ctx->debug_stream,
1953 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1956 if (rsa_parse_public_key(&rsa,
1957 (unsigned char *)sig->pubkey->key,
1958 sig->pubkey->key_len) != 0)
1960 sig->verify_status = PDKIM_VERIFY_INVALID;
1961 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1965 /* Check the signature */
1966 if (rsa_pkcs1_verify(&rsa,
1968 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1969 SIG_RSA_SHA1:SIG_RSA_SHA256),
1971 (unsigned char *)headerhash,
1972 (unsigned char *)sig->sigdata) != 0)
1974 sig->verify_status = PDKIM_VERIFY_FAIL;
1975 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1979 /* We have a winner! (if bodydhash was correct earlier) */
1980 if (sig->verify_status == PDKIM_VERIFY_NONE)
1981 sig->verify_status = PDKIM_VERIFY_PASS;
1986 if (ctx->debug_stream)
1988 fprintf(ctx->debug_stream, "PDKIM [%s] signature status: %s",
1989 sig->domain, pdkim_verify_status_str(sig->verify_status));
1990 if (sig->verify_ext_status > 0)
1991 fprintf(ctx->debug_stream, " (%s)\n",
1992 pdkim_verify_ext_status_str(sig->verify_ext_status));
1994 fprintf(ctx->debug_stream, "\n");
2000 free(dns_txt_reply);
2006 /* If requested, set return pointer to signature(s) */
2007 if (return_signatures)
2008 *return_signatures = ctx->sig;
2014 /* -------------------------------------------------------------------------- */
2016 DLLEXPORT pdkim_ctx *
2017 pdkim_init_verify(int input_mode, int(*dns_txt_callback)(char *, char *))
2019 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
2023 memset(ctx,0,sizeof(pdkim_ctx));
2025 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2031 ctx->mode = PDKIM_MODE_VERIFY;
2032 ctx->input_mode = input_mode;
2033 ctx->dns_txt_callback = dns_txt_callback;
2039 /* -------------------------------------------------------------------------- */
2041 DLLEXPORT pdkim_ctx *
2042 pdkim_init_sign(int input_mode, char *domain, char *selector, char *rsa_privkey)
2045 pdkim_signature *sig;
2047 if (!domain || !selector || !rsa_privkey)
2050 if (!(ctx = malloc(sizeof(pdkim_ctx))))
2052 memset(ctx,0,sizeof(pdkim_ctx));
2054 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2060 if (!(sig = malloc(sizeof(pdkim_signature))))
2066 memset(sig,0,sizeof(pdkim_signature));
2068 sig->bodylength = -1;
2070 ctx->mode = PDKIM_MODE_SIGN;
2071 ctx->input_mode = input_mode;
2074 ctx->sig->domain = strdup(domain);
2075 ctx->sig->selector = strdup(selector);
2076 ctx->sig->rsa_privkey = strdup(rsa_privkey);
2078 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey)
2081 if (!(ctx->sig->sha1_body = malloc(sizeof(sha1_context))))
2083 sha1_starts(ctx->sig->sha1_body);
2085 if (!(ctx->sig->sha2_body = malloc(sizeof(sha2_context))))
2087 sha2_starts(ctx->sig->sha2_body,0);
2092 pdkim_free_ctx(ctx);
2096 /* -------------------------------------------------------------------------- */
2099 pdkim_set_optional(pdkim_ctx *ctx,
2106 unsigned long created,
2107 unsigned long expires)
2111 if (!(ctx->sig->identity = strdup(identity)))
2112 return PDKIM_ERR_OOM;
2115 if (!(ctx->sig->sign_headers = strdup(sign_headers)))
2116 return PDKIM_ERR_OOM;
2118 ctx->sig->canon_headers = canon_headers;
2119 ctx->sig->canon_body = canon_body;
2120 ctx->sig->bodylength = bodylength;
2121 ctx->sig->algo = algo;
2122 ctx->sig->created = created;
2123 ctx->sig->expires = expires;
2128 /* -------------------------------------------------------------------------- */
2132 pdkim_set_debug_stream(pdkim_ctx *ctx, FILE *debug_stream)
2134 ctx->debug_stream = debug_stream;