2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2009 - 2016 Tom Kistner <tom@duncanthrax.net>
5 * Copyright (C) 2016 Jeremy Harris <jgh@exim.org>
7 * http://duncanthrax.net/pdkim/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #ifndef DISABLE_DKIM /* entire file */
30 # error Need SUPPORT_TLS for DKIM
33 #include "crypt_ver.h"
36 # include <openssl/rsa.h>
37 # include <openssl/ssl.h>
38 # include <openssl/err.h>
39 #elif defined(RSA_GNUTLS)
40 # include <gnutls/gnutls.h>
41 # include <gnutls/x509.h>
42 # include <gnutls/abstract.h>
46 # include <gnutls/crypto.h>
47 #elif defined(SHA_POLARSSL)
48 # include "polarssl/sha1.h"
49 # include "polarssl/sha2.h"
54 #define PDKIM_SIGNATURE_VERSION "1"
55 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
57 #define PDKIM_MAX_HEADER_LEN 65536
58 #define PDKIM_MAX_HEADERS 512
59 #define PDKIM_MAX_BODY_LINE_LEN 16384
60 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
61 #define PDKIM_DEFAULT_SIGN_HEADERS "From:Sender:Reply-To:Subject:Date:"\
62 "Message-ID:To:Cc:MIME-Version:Content-Type:"\
63 "Content-Transfer-Encoding:Content-ID:"\
64 "Content-Description:Resent-Date:Resent-From:"\
65 "Resent-Sender:Resent-To:Resent-Cc:"\
66 "Resent-Message-ID:In-Reply-To:References:"\
67 "List-Id:List-Help:List-Unsubscribe:"\
68 "List-Subscribe:List-Post:List-Owner:List-Archive"
70 /* -------------------------------------------------------------------------- */
71 struct pdkim_stringlist {
77 #define PDKIM_STR_ALLOC_FRAG 256
81 unsigned int allocated;
84 /* -------------------------------------------------------------------------- */
85 /* A bunch of list constants */
86 const char *pdkim_querymethods[] = {
90 const char *pdkim_algos[] = {
95 const char *pdkim_canons[] = {
100 const char *pdkim_hashes[] = {
105 const char *pdkim_keytypes[] = {
110 typedef struct pdkim_combined_canon_entry {
114 } pdkim_combined_canon_entry;
116 pdkim_combined_canon_entry pdkim_combined_canons[] = {
117 { "simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
118 { "simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
119 { "relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
120 { "relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
121 { "simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
122 { "relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
127 /* -------------------------------------------------------------------------- */
130 pdkim_verify_status_str(int status)
133 case PDKIM_VERIFY_NONE: return "PDKIM_VERIFY_NONE";
134 case PDKIM_VERIFY_INVALID: return "PDKIM_VERIFY_INVALID";
135 case PDKIM_VERIFY_FAIL: return "PDKIM_VERIFY_FAIL";
136 case PDKIM_VERIFY_PASS: return "PDKIM_VERIFY_PASS";
137 default: return "PDKIM_VERIFY_UNKNOWN";
142 pdkim_verify_ext_status_str(int ext_status)
145 case PDKIM_VERIFY_FAIL_BODY: return "PDKIM_VERIFY_FAIL_BODY";
146 case PDKIM_VERIFY_FAIL_MESSAGE: return "PDKIM_VERIFY_FAIL_MESSAGE";
147 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
148 case PDKIM_VERIFY_INVALID_BUFFER_SIZE: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
149 case PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD: return "PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD";
150 case PDKIM_VERIFY_INVALID_PUBKEY_IMPORT: return "PDKIM_VERIFY_INVALID_PUBKEY_IMPORT";
151 default: return "PDKIM_VERIFY_UNKNOWN";
156 /* -------------------------------------------------------------------------- */
157 /* Print debugging functions */
159 pdkim_quoteprint(const char *data, int len, int lf)
162 const unsigned char *p = (const unsigned char *)data;
164 for (i = 0; i < len; i++)
169 case ' ' : debug_printf("{SP}"); break;
170 case '\t': debug_printf("{TB}"); break;
171 case '\r': debug_printf("{CR}"); break;
172 case '\n': debug_printf("{LF}"); break;
173 case '{' : debug_printf("{BO}"); break;
174 case '}' : debug_printf("{BC}"); break;
176 if ( (c < 32) || (c > 127) )
177 debug_printf("{%02x}", c);
179 debug_printf("%c", c);
188 pdkim_hexprint(const char *data, int len, int lf)
191 const unsigned char *p = (const unsigned char *)data;
193 for (i = 0 ; i < len; i++)
194 debug_printf("%02x", p[i]);
201 /* String package: should be replaced by Exim standard ones */
203 static pdkim_stringlist *
204 pdkim_prepend_stringlist(pdkim_stringlist *base, char *str)
206 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
208 if (!new_entry) return NULL;
209 memset(new_entry, 0, sizeof(pdkim_stringlist));
210 if (!(new_entry->value = strdup(str))) return NULL;
213 pdkim_stringlist *last = base;
214 while (last->next != NULL) { last = last->next; }
215 last->next = new_entry;
223 /* -------------------------------------------------------------------------- */
224 /* A small "growing string" implementation to escape malloc/realloc hell */
227 pdkim_strnew (const char *cstr)
229 unsigned int len = cstr ? strlen(cstr) : 0;
230 pdkim_str *p = malloc(sizeof(pdkim_str));
233 memset(p, 0, sizeof(pdkim_str));
234 if (!(p->str = malloc(len+1)))
239 p->allocated = len+1;
242 strcpy(p->str, cstr);
244 p->str[p->len] = '\0';
249 pdkim_strncat(pdkim_str *str, const char *data, int len)
251 if ((str->allocated - str->len) < (len+1))
253 /* Extend the buffer */
254 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
255 char *n = realloc(str->str,
256 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
257 if (n == NULL) return NULL;
259 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
261 strncpy(&(str->str[str->len]), data, len);
263 str->str[str->len] = '\0';
268 pdkim_strcat(pdkim_str *str, const char *cstr)
270 return pdkim_strncat(str, cstr, strlen(cstr));
274 pdkim_strtrim(pdkim_str *str)
278 while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
279 while (*p != '\0') {*q = *p; q++; p++;}
281 while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) )
286 str->len = strlen(str->str);
291 pdkim_strclear(pdkim_str *str)
299 pdkim_strfree(pdkim_str *str)
302 if (str->str) free(str->str);
308 /* -------------------------------------------------------------------------- */
311 pdkim_free_pubkey(pdkim_pubkey *pub)
315 if (pub->version ) free(pub->version);
316 if (pub->granularity) free(pub->granularity);
317 if (pub->hashes ) free(pub->hashes);
318 if (pub->keytype ) free(pub->keytype);
319 if (pub->srvtype ) free(pub->srvtype);
320 if (pub->notes ) free(pub->notes);
321 /* if (pub->key ) free(pub->key); */
327 /* -------------------------------------------------------------------------- */
330 pdkim_free_sig(pdkim_signature *sig)
334 pdkim_signature *next = (pdkim_signature *)sig->next;
336 pdkim_stringlist *e = sig->headers;
339 pdkim_stringlist *c = e;
340 if (e->value) free(e->value);
345 if (sig->selector ) free(sig->selector);
346 if (sig->domain ) free(sig->domain);
347 if (sig->identity ) free(sig->identity);
348 if (sig->headernames ) free(sig->headernames);
349 if (sig->copiedheaders ) free(sig->copiedheaders);
350 if (sig->rsa_privkey ) free(sig->rsa_privkey);
351 if (sig->sign_headers ) free(sig->sign_headers);
352 if (sig->signature_header) free(sig->signature_header);
354 if (sig->pubkey) pdkim_free_pubkey(sig->pubkey);
357 if (next) pdkim_free_sig(next);
362 /* -------------------------------------------------------------------------- */
365 pdkim_free_ctx(pdkim_ctx *ctx)
369 pdkim_stringlist *e = ctx->headers;
372 pdkim_stringlist *c = e;
373 if (e->value) free(e->value);
377 pdkim_free_sig(ctx->sig);
378 pdkim_strfree(ctx->cur_header);
384 /* -------------------------------------------------------------------------- */
385 /* Matches the name of the passed raw "header" against
386 the passed colon-separated "list", starting at entry
387 "start". Returns the position of the header name in
391 header_name_match(const char *header,
401 /* Get header name */
402 char *hcolon = strchr(header, ':');
404 if (!hcolon) return rc; /* This isn't a header */
406 if (!(hname = malloc((hcolon-header)+1)))
407 return PDKIM_ERR_OOM;
408 memset(hname, 0, (hcolon-header)+1);
409 strncpy(hname, header, (hcolon-header));
411 /* Copy tick-off list locally, so we can punch zeroes into it */
412 if (!(lcopy = strdup(tick)))
415 return PDKIM_ERR_OOM;
423 if (strcasecmp(p, hname) == 0)
426 /* Invalidate header name instance in tick-off list */
427 if (do_tick) tick[p-lcopy] = '_';
435 if (strcasecmp(p, hname) == 0)
438 /* Invalidate header name instance in tick-off list */
439 if (do_tick) tick[p-lcopy] = '_';
449 /* -------------------------------------------------------------------------- */
450 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
454 pdkim_relax_header (char *header, int crlf)
456 BOOL past_field_name = FALSE;
457 BOOL seen_wsp = FALSE;
460 char *relaxed = malloc(strlen(header)+3);
462 if (!relaxed) return NULL;
465 for (p = header; *p != '\0'; p++)
469 if (c == '\r' || c == '\n')
471 if (c == '\t' || c == ' ')
475 c = ' '; /* Turns WSP into SP */
479 if (!past_field_name && c == ':')
481 if (seen_wsp) q--; /* This removes WSP before the colon */
482 seen_wsp = TRUE; /* This removes WSP after the colon */
483 past_field_name = TRUE;
488 /* Lowercase header name */
489 if (!past_field_name) c = tolower(c);
493 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
496 if (crlf) strcat(relaxed, "\r\n");
501 /* -------------------------------------------------------------------------- */
502 #define PDKIM_QP_ERROR_DECODE -1
505 pdkim_decode_qp_char(char *qp_p, int *c)
507 char *initial_pos = qp_p;
509 /* Advance one char */
512 /* Check for two hex digits and decode them */
513 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
515 /* Do hex conversion */
516 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
517 *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
521 /* Illegal char here */
522 *c = PDKIM_QP_ERROR_DECODE;
527 /* -------------------------------------------------------------------------- */
530 pdkim_decode_qp(char *str)
535 char *n = malloc(strlen(p)+1);
545 p = pdkim_decode_qp_char(p, &nchar);
561 /* -------------------------------------------------------------------------- */
564 pdkim_decode_base64(char *str, int *num_decoded)
568 int old_pool = store_pool;
570 /* There is a store-reset between header & body reception
571 so cannot use the main pool */
573 store_pool = POOL_PERM;
574 dlen = b64decode(US str, USS &res);
575 store_pool = old_pool;
577 if (dlen < 0) return NULL;
579 if (num_decoded) *num_decoded = dlen;
584 /* -------------------------------------------------------------------------- */
587 pdkim_encode_base64(char *str, int num)
590 int old_pool = store_pool;
592 store_pool = POOL_PERM;
593 ret = CS b64encode(US str, num);
594 store_pool = old_pool;
599 /* -------------------------------------------------------------------------- */
600 #define PDKIM_HDR_LIMBO 0
601 #define PDKIM_HDR_TAG 1
602 #define PDKIM_HDR_VALUE 2
604 static pdkim_signature *
605 pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr)
607 pdkim_signature *sig ;
609 pdkim_str *cur_tag = NULL;
610 pdkim_str *cur_val = NULL;
611 BOOL past_hname = FALSE;
612 BOOL in_b_val = FALSE;
613 int where = PDKIM_HDR_LIMBO;
616 if (!(sig = malloc(sizeof(pdkim_signature)))) return NULL;
617 memset(sig, 0, sizeof(pdkim_signature));
618 sig->bodylength = -1;
620 if (!(sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1)))
626 q = sig->rawsig_no_b_val;
628 for (p = raw_hdr; ; p++)
633 if (c == '\r' || c == '\n')
636 /* Fast-forward through header name */
639 if (c == ':') past_hname = TRUE;
643 if (where == PDKIM_HDR_LIMBO)
645 /* In limbo, just wait for a tag-char to appear */
646 if (!(c >= 'a' && c <= 'z'))
649 where = PDKIM_HDR_TAG;
652 if (where == PDKIM_HDR_TAG)
655 cur_tag = pdkim_strnew(NULL);
657 if (c >= 'a' && c <= 'z')
658 pdkim_strncat(cur_tag, p, 1);
662 if (strcmp(cur_tag->str, "b") == 0)
667 where = PDKIM_HDR_VALUE;
672 if (where == PDKIM_HDR_VALUE)
675 cur_val = pdkim_strnew(NULL);
677 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
680 if (c == ';' || c == '\0')
682 if (cur_tag->len > 0)
684 pdkim_strtrim(cur_val);
686 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
688 switch (cur_tag->str[0])
691 if (cur_tag->str[1] == 'h')
692 sig->bodyhash = pdkim_decode_base64(cur_val->str,
695 sig->sigdata = pdkim_decode_base64(cur_val->str,
699 /* We only support version 1, and that is currently the
700 only version there is. */
701 if (strcmp(cur_val->str, PDKIM_SIGNATURE_VERSION) == 0)
705 for (i = 0; pdkim_algos[i]; i++)
706 if (strcmp(cur_val->str, pdkim_algos[i]) == 0)
713 for (i = 0; pdkim_combined_canons[i].str; i++)
714 if (strcmp(cur_val->str, pdkim_combined_canons[i].str) == 0)
716 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
717 sig->canon_body = pdkim_combined_canons[i].canon_body;
722 for (i = 0; pdkim_querymethods[i]; i++)
723 if (strcmp(cur_val->str, pdkim_querymethods[i]) == 0)
725 sig->querymethod = i;
730 sig->selector = strdup(cur_val->str); break;
732 sig->domain = strdup(cur_val->str); break;
734 sig->identity = pdkim_decode_qp(cur_val->str); break;
736 sig->created = strtoul(cur_val->str, NULL, 10); break;
738 sig->expires = strtoul(cur_val->str, NULL, 10); break;
740 sig->bodylength = strtol(cur_val->str, NULL, 10); break;
742 sig->headernames = strdup(cur_val->str); break;
744 sig->copiedheaders = pdkim_decode_qp(cur_val->str); break;
746 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
750 pdkim_strclear(cur_tag);
751 pdkim_strclear(cur_val);
753 where = PDKIM_HDR_LIMBO;
756 pdkim_strncat(cur_val, p, 1);
767 /* Make sure the most important bits are there. */
768 if (!(sig->domain && (*(sig->domain) != '\0') &&
769 sig->selector && (*(sig->selector) != '\0') &&
770 sig->headernames && (*(sig->headernames) != '\0') &&
780 /* Chomp raw header. The final newline must not be added to the signature. */
782 while (q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
783 *q = '\0'; q--; /*XXX questionable code layout; possible bug */
788 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
789 pdkim_quoteprint(sig->rawsig_no_b_val, strlen(sig->rawsig_no_b_val), 1);
791 "PDKIM >> Sig size: %4d bits\n", sig->sigdata_len*8);
793 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
798 SHA1_Init (&sig->sha1_body);
799 SHA256_Init(&sig->sha2_body);
801 #elif defined(SHA_GNUTLS)
803 gnutls_hash_init(&sig->sha_body,
804 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
806 #elif defined(SHA_POLARSSL)
808 if ( !(sig->sha1_body = malloc(sizeof(sha1_context)))
809 || !(sig->sha2_body = malloc(sizeof(sha2_context)))
816 sha1_starts(sig->sha1_body);
817 sha2_starts(sig->sha2_body, 0);
819 #endif /* SHA impl */
825 /* -------------------------------------------------------------------------- */
827 static pdkim_pubkey *
828 pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record)
832 pdkim_str *cur_tag = NULL;
833 pdkim_str *cur_val = NULL;
834 int where = PDKIM_HDR_LIMBO;
836 if (!(pub = malloc(sizeof(pdkim_pubkey)))) return NULL;
837 memset(pub, 0, sizeof(pdkim_pubkey));
839 for (p = raw_record; ; p++)
844 if (c == '\r' || c == '\n')
847 if (where == PDKIM_HDR_LIMBO)
849 /* In limbo, just wait for a tag-char to appear */
850 if (!(c >= 'a' && c <= 'z'))
853 where = PDKIM_HDR_TAG;
856 if (where == PDKIM_HDR_TAG)
859 cur_tag = pdkim_strnew(NULL);
861 if (c >= 'a' && c <= 'z')
862 pdkim_strncat(cur_tag, p, 1);
866 where = PDKIM_HDR_VALUE;
871 if (where == PDKIM_HDR_VALUE)
874 cur_val = pdkim_strnew(NULL);
876 if (c == '\r' || c == '\n')
879 if (c == ';' || c == '\0')
881 if (cur_tag->len > 0)
883 pdkim_strtrim(cur_val);
884 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
886 switch (cur_tag->str[0])
889 /* This tag isn't evaluated because:
890 - We only support version DKIM1.
891 - Which is the default for this value (set below)
892 - Other versions are currently not specified. */
895 pub->hashes = strdup(cur_val->str); break;
897 pub->granularity = strdup(cur_val->str); break;
899 pub->notes = pdkim_decode_qp(cur_val->str); break;
901 pub->key = pdkim_decode_base64(cur_val->str, &(pub->key_len)); break;
903 pub->hashes = strdup(cur_val->str); break;
905 pub->srvtype = strdup(cur_val->str); break;
907 if (strchr(cur_val->str, 'y') != NULL) pub->testing = 1;
908 if (strchr(cur_val->str, 's') != NULL) pub->no_subdomaining = 1;
911 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
915 pdkim_strclear(cur_tag);
916 pdkim_strclear(cur_val);
917 where = PDKIM_HDR_LIMBO;
920 pdkim_strncat(cur_val, p, 1);
924 if (c == '\0') break;
927 /* Set fallback defaults */
928 if (!pub->version ) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
929 if (!pub->granularity) pub->granularity = strdup("*");
930 if (!pub->keytype ) pub->keytype = strdup("rsa");
931 if (!pub->srvtype ) pub->srvtype = strdup("*");
937 pdkim_free_pubkey(pub);
942 /* -------------------------------------------------------------------------- */
945 pdkim_update_bodyhash(pdkim_ctx *ctx, const char *data, int len)
947 pdkim_signature *sig = ctx->sig;
948 /* Cache relaxed version of data */
949 char *relaxed_data = NULL;
952 /* Traverse all signatures, updating their hashes. */
955 /* Defaults to simple canon (no further treatment necessary) */
956 const char *canon_data = data;
959 if (sig->canon_body == PDKIM_CANON_RELAXED)
961 /* Relax the line if not done already */
964 BOOL seen_wsp = FALSE;
968 if (!(relaxed_data = malloc(len+1)))
969 return PDKIM_ERR_OOM;
971 for (p = data; *p; p++)
976 if (q > 0 && relaxed_data[q-1] == ' ')
979 else if (c == '\t' || c == ' ')
981 c = ' '; /* Turns WSP into SP */
988 relaxed_data[q++] = c;
990 relaxed_data[q] = '\0';
993 canon_data = relaxed_data;
994 canon_len = relaxed_len;
997 /* Make sure we don't exceed the to-be-signed body length */
998 if ( sig->bodylength >= 0
999 && sig->signed_body_bytes + (unsigned long)canon_len > sig->bodylength
1001 canon_len = sig->bodylength - sig->signed_body_bytes;
1006 gnutls_hash(sig->sha_body, canon_data, canon_len);
1008 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1010 SHA1_Update (&sig->sha1_body, canon_data, canon_len);
1012 SHA256_Update(&sig->sha2_body, canon_data, canon_len);
1013 # elif defined(SHA_POLARSSL)
1014 sha1_update(sig->sha1_body, US canon_data, canon_len);
1016 sha2_update(sig->sha2_body, US canon_data, canon_len);
1020 sig->signed_body_bytes += canon_len;
1021 DEBUG(D_acl) pdkim_quoteprint(canon_data, canon_len, 1);
1027 if (relaxed_data) free(relaxed_data);
1032 /* -------------------------------------------------------------------------- */
1035 pdkim_finish_bodyhash(pdkim_ctx *ctx)
1037 pdkim_signature *sig;
1039 /* Traverse all signatures */
1040 for (sig = ctx->sig; sig; sig = sig->next)
1041 { /* Finish hashes */
1042 uschar bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
1045 gnutls_hash_output(sig->sha_body, bh);
1047 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1049 SHA1_Final (bh, &sig->sha1_body);
1051 SHA256_Final(bh, &sig->sha2_body);
1052 # elif defined(SHA_POLARSSL)
1053 sha1_finish(sig->sha1_body, bh);
1055 sha2_finish(sig->sha2_body, bh);
1061 debug_printf("PDKIM [%s] Body bytes hashed: %lu\n"
1062 "PDKIM [%s] bh computed: ",
1063 sig->domain, sig->signed_body_bytes, sig->domain);
1064 pdkim_hexprint((char *)bh, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32, 1);
1067 /* SIGNING -------------------------------------------------------------- */
1068 if (ctx->mode == PDKIM_MODE_SIGN)
1070 sig->bodyhash_len = sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32;
1071 sig->bodyhash = CS string_copyn(US bh, sig->bodyhash_len);
1073 /* If bodylength limit is set, and we have received less bytes
1074 than the requested amount, effectively remove the limit tag. */
1075 if (sig->signed_body_bytes < sig->bodylength)
1076 sig->bodylength = -1;
1079 /* VERIFICATION --------------------------------------------------------- */
1082 /* Compare bodyhash */
1083 if (memcmp(bh, sig->bodyhash,
1084 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0)
1086 DEBUG(D_acl) debug_printf("PDKIM [%s] Body hash verified OK\n", sig->domain);
1092 debug_printf("PDKIM [%s] bh signature: ", sig->domain);
1093 pdkim_hexprint(sig->bodyhash,
1094 sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32, 1);
1095 debug_printf("PDKIM [%s] Body hash did NOT verify\n", sig->domain);
1097 sig->verify_status = PDKIM_VERIFY_FAIL;
1098 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
1108 /* -------------------------------------------------------------------------- */
1109 /* Callback from pdkim_feed below for processing complete body lines */
1112 pdkim_bodyline_complete(pdkim_ctx *ctx)
1114 char *p = ctx->linebuf;
1115 int n = ctx->linebuf_offset;
1116 pdkim_signature *sig = ctx->sig; /*XXX assumes only one sig */
1118 /* Ignore extra data if we've seen the end-of-data marker */
1119 if (ctx->seen_eod) goto BAIL;
1121 /* We've always got one extra byte to stuff a zero ... */
1122 ctx->linebuf[ctx->linebuf_offset] = '\0';
1124 /* Terminate on EOD marker */
1125 if (memcmp(p, ".\r\n", 3) == 0)
1127 /* In simple body mode, if any empty lines were buffered,
1128 replace with one. rfc 4871 3.4.3 */
1129 /*XXX checking the signed-body-bytes is a gross hack; I think
1130 it indicates that all linebreaks should be buffered, including
1131 the one terminating a text line */
1132 if ( sig && sig->canon_body == PDKIM_CANON_SIMPLE
1133 && sig->signed_body_bytes == 0
1134 && ctx->num_buffered_crlf > 0
1136 pdkim_update_bodyhash(ctx, "\r\n", 2);
1138 ctx->seen_eod = TRUE;
1142 if (memcmp(p, "..", 2) == 0)
1148 /* Empty lines need to be buffered until we find a non-empty line */
1149 if (memcmp(p, "\r\n", 2) == 0)
1151 ctx->num_buffered_crlf++;
1155 if (sig && sig->canon_body == PDKIM_CANON_RELAXED)
1157 /* Lines with just spaces need to be buffered too */
1159 while (memcmp(check, "\r\n", 2) != 0)
1163 if (c != '\t' && c != ' ')
1168 ctx->num_buffered_crlf++;
1173 /* At this point, we have a non-empty line, so release the buffered ones. */
1174 while (ctx->num_buffered_crlf)
1176 pdkim_update_bodyhash(ctx, "\r\n", 2);
1177 ctx->num_buffered_crlf--;
1180 pdkim_update_bodyhash(ctx, p, n);
1183 ctx->linebuf_offset = 0;
1188 /* -------------------------------------------------------------------------- */
1189 /* Callback from pdkim_feed below for processing complete headers */
1190 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1193 pdkim_header_complete(pdkim_ctx *ctx)
1195 /* Special case: The last header can have an extra \r appended */
1196 if ( (ctx->cur_header->len > 1) &&
1197 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') )
1199 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
1200 ctx->cur_header->len--;
1204 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
1206 /* SIGNING -------------------------------------------------------------- */
1207 if (ctx->mode == PDKIM_MODE_SIGN)
1209 pdkim_signature *sig;
1211 for (sig = ctx->sig; sig; sig = sig->next) /* Traverse all signatures */
1212 if (header_name_match(ctx->cur_header->str,
1215 PDKIM_DEFAULT_SIGN_HEADERS, 0) == PDKIM_OK)
1217 pdkim_stringlist *list;
1219 /* Add header to the signed headers list (in reverse order) */
1220 if (!(list = pdkim_prepend_stringlist(sig->headers,
1221 ctx->cur_header->str)))
1222 return PDKIM_ERR_OOM;
1223 sig->headers = list;
1227 /* VERIFICATION ----------------------------------------------------------- */
1228 /* DKIM-Signature: headers are added to the verification list */
1229 if (ctx->mode == PDKIM_MODE_VERIFY)
1231 if (strncasecmp(ctx->cur_header->str,
1232 DKIM_SIGNATURE_HEADERNAME,
1233 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
1235 pdkim_signature *new_sig;
1237 /* Create and chain new signature block */
1238 DEBUG(D_acl) debug_printf(
1239 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1241 if ((new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str)))
1243 pdkim_signature *last_sig = ctx->sig;
1248 while (last_sig->next) last_sig = last_sig->next;
1249 last_sig->next = new_sig;
1253 DEBUG(D_acl) debug_printf(
1254 "Error while parsing signature header\n"
1255 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1258 /* every other header is stored for signature verification */
1261 pdkim_stringlist *list;
1263 if (!(list = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->str)))
1264 return PDKIM_ERR_OOM;
1265 ctx->headers = list;
1270 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1276 /* -------------------------------------------------------------------------- */
1277 #define HEADER_BUFFER_FRAG_SIZE 256
1280 pdkim_feed (pdkim_ctx *ctx, char *data, int len)
1284 for (p = 0; p<len; p++)
1288 if (ctx->past_headers)
1290 /* Processing body byte */
1291 ctx->linebuf[ctx->linebuf_offset++] = c;
1294 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1295 if (rc != PDKIM_OK) return rc;
1297 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1298 return PDKIM_ERR_LONG_LINE;
1302 /* Processing header byte */
1309 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1310 if (rc != PDKIM_OK) return rc;
1312 ctx->past_headers = TRUE;
1314 DEBUG(D_acl) debug_printf(
1315 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1319 ctx->seen_lf = TRUE;
1321 else if (ctx->seen_lf)
1323 if (!(c == '\t' || c == ' '))
1325 int rc = pdkim_header_complete(ctx); /* End of header */
1326 if (rc != PDKIM_OK) return rc;
1328 ctx->seen_lf = FALSE;
1332 if (!ctx->cur_header)
1333 if (!(ctx->cur_header = pdkim_strnew(NULL)))
1334 return PDKIM_ERR_OOM;
1336 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1337 if (!pdkim_strncat(ctx->cur_header, &data[p], 1))
1338 return PDKIM_ERR_OOM;
1345 * RFC 5322 specifies that header line length SHOULD be no more than 78
1350 * col: this int holds and receives column number (octets since last '\n')
1351 * str: partial string to append to
1352 * pad: padding, split line or space after before or after eg: ";"
1353 * intro: - must join to payload eg "h=", usually the tag name
1354 * payload: eg base64 data - long data can be split arbitrarily.
1356 * this code doesn't fold the header in some of the places that RFC4871
1357 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1358 * pairs and inside long values. it also always spaces or breaks after the
1361 * no guarantees are made for output given out-of range input. like tag
1362 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1366 pdkim_headcat(int *col, pdkim_str *str, const char * pad,
1367 const char *intro, const char *payload)
1376 pdkim_strcat(str, "\r\n\t");
1379 pdkim_strncat(str, pad, l);
1383 l = (pad?1:0) + (intro?strlen(intro):0);
1386 { /*can't fit intro - start a new line to make room.*/
1387 pdkim_strcat(str, "\r\n\t");
1389 l = intro?strlen(intro):0;
1392 l += payload ? strlen(payload):0 ;
1395 { /* this fragment will not fit on a single line */
1398 pdkim_strcat(str, " ");
1400 pad = NULL; /* only want this once */
1406 size_t sl = strlen(intro);
1408 pdkim_strncat(str, intro, sl);
1411 intro = NULL; /* only want this once */
1416 size_t sl = strlen(payload);
1417 size_t chomp = *col+sl < 77 ? sl : 78-*col;
1419 pdkim_strncat(str, payload, chomp);
1425 /* the while precondition tells us it didn't fit. */
1426 pdkim_strcat(str, "\r\n\t");
1432 pdkim_strcat(str, "\r\n\t");
1439 pdkim_strcat(str, " ");
1446 size_t sl = strlen(intro);
1448 pdkim_strncat(str, intro, sl);
1456 size_t sl = strlen(payload);
1458 pdkim_strncat(str, payload, sl);
1466 /* -------------------------------------------------------------------------- */
1469 pdkim_create_header(pdkim_signature *sig, int final)
1472 char *base64_bh = NULL;
1473 char *base64_b = NULL;
1476 pdkim_str *canon_all;
1478 if (!(hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION)))
1481 if (!(canon_all = pdkim_strnew(pdkim_canons[sig->canon_headers])))
1484 if (!(base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len)))
1487 col = strlen(hdr->str);
1489 /* Required and static bits */
1490 if ( pdkim_headcat(&col, hdr, ";", "a=", pdkim_algos[sig->algo])
1491 && pdkim_headcat(&col, hdr, ";", "q=", pdkim_querymethods[sig->querymethod])
1492 && pdkim_strcat(canon_all, "/")
1493 && pdkim_strcat(canon_all, pdkim_canons[sig->canon_body])
1494 && pdkim_headcat(&col, hdr, ";", "c=", canon_all->str)
1495 && pdkim_headcat(&col, hdr, ";", "d=", sig->domain)
1496 && pdkim_headcat(&col, hdr, ";", "s=", sig->selector)
1499 /* list of eader names can be split between items. */
1501 char *n = strdup(sig->headernames);
1509 char *c = strchr(n, ':');
1514 if (!pdkim_headcat(&col, hdr, NULL, NULL, ":"))
1520 if (!pdkim_headcat(&col, hdr, s, i, n))
1536 if(!pdkim_headcat(&col, hdr, ";", "bh=", base64_bh))
1541 if(!pdkim_headcat(&col, hdr, ";", "i=", sig->identity))
1544 if (sig->created > 0)
1548 snprintf(minibuf, 20, "%lu", sig->created);
1549 if(!pdkim_headcat(&col, hdr, ";", "t=", minibuf))
1553 if (sig->expires > 0)
1557 snprintf(minibuf, 20, "%lu", sig->expires);
1558 if(!pdkim_headcat(&col, hdr, ";", "x=", minibuf))
1562 if (sig->bodylength >= 0)
1566 snprintf(minibuf, 20, "%lu", sig->bodylength);
1567 if(!pdkim_headcat(&col, hdr, ";", "l=", minibuf))
1571 /* Preliminary or final version? */
1574 if (!(base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len)))
1576 if (!pdkim_headcat(&col, hdr, ";", "b=", base64_b))
1580 if(!pdkim_headcat(&col, hdr, ";", "b=", ""))
1583 /* add trailing semicolon: I'm not sure if this is actually needed */
1584 if (!pdkim_headcat(&col, hdr, NULL, ";", ""))
1588 rc = strdup(hdr->str);
1592 if (canon_all) pdkim_strfree(canon_all);
1597 /* -------------------------------------------------------------------------- */
1600 pdkim_feed_finish(pdkim_ctx *ctx, pdkim_signature **return_signatures)
1602 pdkim_signature *sig = ctx->sig;
1603 pdkim_str *headernames = NULL; /* Collected signed header names */
1605 /* Check if we must still flush a (partial) header. If that is the
1606 case, the message has no body, and we must compute a body hash
1607 out of '<CR><LF>' */
1608 if (ctx->cur_header && ctx->cur_header->len)
1610 int rc = pdkim_header_complete(ctx);
1611 if (rc != PDKIM_OK) return rc;
1612 pdkim_update_bodyhash(ctx, "\r\n", 2);
1615 DEBUG(D_acl) debug_printf(
1616 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1618 /* Build (and/or evaluate) body hash */
1619 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK)
1620 return PDKIM_ERR_OOM;
1622 /* SIGNING -------------------------------------------------------------- */
1623 if (ctx->mode == PDKIM_MODE_SIGN)
1624 if (!(headernames = pdkim_strnew(NULL)))
1625 return PDKIM_ERR_OOM;
1626 /* ---------------------------------------------------------------------- */
1631 SHA_CTX sha1_headers;
1632 SHA256_CTX sha2_headers;
1633 #elif defined(SHA_GNUTLS)
1634 gnutls_hash_hd_t sha_headers;
1635 #elif defined(SHA_POLARSSL)
1636 sha1_context sha1_headers;
1637 sha2_context sha2_headers;
1641 char headerhash[32];
1644 uschar * hdata = NULL;
1645 int hdata_alloc = 0;
1650 gnutls_hash_init(&sha_headers,
1651 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
1653 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1655 SHA1_Init(&sha1_headers);
1657 SHA256_Init(&sha2_headers);
1658 # elif defined(SHA_POLARSSL)
1659 sha1_starts(&sha1_headers);
1661 sha2_starts(&sha2_headers, 0);
1665 DEBUG(D_acl) debug_printf(
1666 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1668 /* SIGNING ---------------------------------------------------------------- */
1669 /* When signing, walk through our header list and add them to the hash. As we
1670 go, construct a list of the header's names to use for the h= parameter. */
1672 if (ctx->mode == PDKIM_MODE_SIGN)
1674 pdkim_stringlist *p;
1676 for (p = sig->headers; p; p = p->next)
1679 /* Collect header names (Note: colon presence is guaranteed here) */
1680 char *q = strchr(p->value, ':');
1682 if (!(pdkim_strncat(headernames, p->value,
1683 (q-(p->value)) + (p->next ? 1 : 0))))
1684 return PDKIM_ERR_OOM;
1686 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1687 ? pdkim_relax_header(p->value, 1) /* cook header for relaxed canon */
1688 : strdup(p->value); /* just copy it for simple canon */
1690 return PDKIM_ERR_OOM;
1692 /* Feed header to the hash algorithm */
1694 gnutls_hash(sha_headers, rh, strlen(rh));
1696 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1698 SHA1_Update (&sha1_headers, rh, strlen(rh));
1700 SHA256_Update(&sha2_headers, rh, strlen(rh));
1701 # elif defined(SHA_POLARSSL)
1702 sha1_update(&sha1_headers, US rh, strlen(rh));
1704 sha2_update(&sha2_headers, US rh, strlen(rh));
1709 /* Remember headers block for signing */
1710 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, rh);
1713 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
1718 /* VERIFICATION ----------------------------------------------------------- */
1719 /* When verifying, walk through the header name list in the h= parameter and
1720 add the headers to the hash in that order. */
1723 char *b = strdup(sig->headernames);
1726 pdkim_stringlist *hdrs;
1728 if (!b) return PDKIM_ERR_OOM;
1731 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1736 if ((q = strchr(p, ':')))
1739 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1741 && strncasecmp(hdrs->value, p, strlen(p)) == 0
1742 && (hdrs->value)[strlen(p)] == ':'
1747 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1748 ? pdkim_relax_header(hdrs->value, 1) /* cook header for relaxed canon */
1749 : strdup(hdrs->value); /* just copy it for simple canon */
1751 return PDKIM_ERR_OOM;
1753 /* Feed header to the hash algorithm */
1755 gnutls_hash(sha_headers, rh, strlen(rh));
1757 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1759 SHA1_Update (&sha1_headers, rh, strlen(rh));
1761 SHA256_Update(&sha2_headers, rh, strlen(rh));
1762 # elif defined(SHA_POLARSSL)
1763 sha1_update(&sha1_headers, US rh, strlen(rh));
1765 sha2_update(&sha2_headers, US rh, strlen(rh));
1769 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
1781 DEBUG(D_acl) debug_printf(
1782 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1784 /* SIGNING ---------------------------------------------------------------- */
1785 if (ctx->mode == PDKIM_MODE_SIGN)
1787 /* Copy headernames to signature struct */
1788 sig->headernames = strdup(headernames->str);
1789 pdkim_strfree(headernames);
1791 /* Create signature header with b= omitted */
1792 sig_hdr = pdkim_create_header(ctx->sig, 0);
1795 /* VERIFICATION ----------------------------------------------------------- */
1797 sig_hdr = strdup(sig->rawsig_no_b_val);
1798 /* ------------------------------------------------------------------------ */
1801 return PDKIM_ERR_OOM;
1803 /* Relax header if necessary */
1804 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1806 char *relaxed_hdr = pdkim_relax_header(sig_hdr, 0);
1810 return PDKIM_ERR_OOM;
1811 sig_hdr = relaxed_hdr;
1817 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1818 pdkim_quoteprint(sig_hdr, strlen(sig_hdr), 1);
1820 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1823 /* Finalize header hash */
1825 gnutls_hash(sha_headers, sig_hdr, strlen(sig_hdr));
1826 gnutls_hash_output(sha_headers, headerhash);
1828 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1831 SHA1_Update(&sha1_headers, sig_hdr, strlen(sig_hdr));
1832 SHA1_Final(US headerhash, &sha1_headers);
1836 SHA256_Update(&sha2_headers, sig_hdr, strlen(sig_hdr));
1837 SHA256_Final(US headerhash, &sha2_headers);
1839 # elif defined(SHA_POLARSSL)
1841 sha1_update(&sha1_headers, US sig_hdr, strlen(sig_hdr));
1842 sha1_finish(&sha1_headers, US headerhash);
1846 sha2_update(&sha2_headers, US sig_hdr, strlen(sig_hdr));
1847 sha2_finish(&sha2_headers, US headerhash);
1854 debug_printf("PDKIM [%s] hh computed: ", sig->domain);
1855 pdkim_hexprint(headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32, 1);
1859 if (ctx->mode == PDKIM_MODE_SIGN)
1860 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, sig_hdr);
1865 /* SIGNING ---------------------------------------------------------------- */
1866 if (ctx->mode == PDKIM_MODE_SIGN)
1872 #elif defined(RSA_GNUTLS)
1873 gnutls_x509_privkey_t rsa;
1879 /* Import private key */
1882 if ( !(p = Ustrstr(sig->rsa_privkey, "-----BEGIN RSA PRIVATE KEY-----"))
1883 || !(q = Ustrstr(p+=31, "-----END RSA PRIVATE KEY-----"))
1885 return PDKIM_SIGN_PRIVKEY_WRAP;
1887 if ((len = b64decode(p, &p)) < 0)
1889 DEBUG(D_acl) debug_printf("b64decode failed\n");
1890 return PDKIM_SIGN_PRIVKEY_B64D;
1892 if (!(rsa = d2i_RSAPrivateKey(NULL, CUSS &p, len)))
1896 char ssl_errstring[256];
1897 ERR_error_string(ERR_get_error(), ssl_errstring);
1898 debug_printf("d2i_RSAPrivateKey: %s\n", ssl_errstring);
1900 return PDKIM_ERR_RSA_PRIVKEY;
1903 #elif defined(RSA_GNUTLS)
1905 k.data = sig->rsa_privkey;
1906 k.size = strlen(sig->rsa_privkey);
1907 if ( (rc = gnutls_x509_privkey_init(&rsa)) != GNUTLS_E_SUCCESS
1908 || (rc = gnutls_x509_privkey_import2(rsa, &k,
1909 GNUTLS_X509_FMT_PEM, NULL, GNUTLS_PKCS_PLAIN)) != GNUTLS_E_SUCCESS
1912 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_import2: %s\n",
1913 gnutls_strerror(rc));
1914 return PDKIM_ERR_RSA_PRIVKEY;
1920 /* Allocate mem for signature */
1922 sig->sigdata = store_get(RSA_size(rsa));
1923 #elif defined(RSA_GNUTLS)
1925 k.size = hdata_size;
1926 (void) gnutls_x509_privkey_sign_data(rsa,
1927 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256,
1928 0, &k, NULL, &sigsize);
1929 sig->sigdata = store_get(sig->sigdata_len = sigsize);
1935 if (RSA_sign(sig->algo == PDKIM_ALGO_RSA_SHA1 ? NID_sha1 : NID_sha256,
1936 CUS headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32,
1937 US sig->sigdata, (unsigned int *)&sig->sigdata_len,
1939 return PDKIM_ERR_RSA_SIGNING;
1942 #elif defined(RSA_GNUTLS)
1944 if ((rc = gnutls_x509_privkey_sign_data(rsa,
1945 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256,
1946 0, &k, sig->sigdata, &sigsize)) != GNUTLS_E_SUCCESS
1949 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_sign_data: %s\n",
1950 gnutls_strerror(rc));
1951 return PDKIM_ERR_RSA_SIGNING;
1953 gnutls_x509_privkey_deinit(rsa);
1960 debug_printf( "PDKIM [%s] b computed: ", sig->domain);
1961 pdkim_hexprint(sig->sigdata, sig->sigdata_len, 1);
1964 if (!(sig->signature_header = pdkim_create_header(ctx->sig, 1)))
1965 return PDKIM_ERR_OOM;
1968 /* VERIFICATION ----------------------------------------------------------- */
1973 const unsigned char * p;
1974 #elif defined(RSA_GNUTLS)
1975 gnutls_pubkey_t rsa;
1976 gnutls_datum_t k, s;
1979 char *dns_txt_name, *dns_txt_reply;
1982 gnutls_pubkey_init(&rsa);
1985 /* Fetch public key for signing domain, from DNS */
1987 if (!(dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN)))
1988 return PDKIM_ERR_OOM;
1990 if (!(dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN)))
1993 return PDKIM_ERR_OOM;
1996 memset(dns_txt_reply, 0, PDKIM_DNS_TXT_MAX_RECLEN);
1997 memset(dns_txt_name , 0, PDKIM_DNS_TXT_MAX_NAMELEN);
1999 if (snprintf(dns_txt_name, PDKIM_DNS_TXT_MAX_NAMELEN,
2000 "%s._domainkey.%s.",
2001 sig->selector, sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN)
2003 sig->verify_status = PDKIM_VERIFY_INVALID;
2004 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
2008 if ( ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK
2009 || dns_txt_reply[0] == '\0')
2011 sig->verify_status = PDKIM_VERIFY_INVALID;
2012 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
2019 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
2021 pdkim_quoteprint(dns_txt_reply, strlen(dns_txt_reply), 1);
2024 if (!(sig->pubkey = pdkim_parse_pubkey_record(ctx, dns_txt_reply)))
2026 sig->verify_status = PDKIM_VERIFY_INVALID;
2027 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD;
2029 DEBUG(D_acl) debug_printf(
2030 " Error while parsing public key record\n"
2031 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
2035 DEBUG(D_acl) debug_printf(
2036 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
2038 /* Import public key */
2041 p = CUS sig->pubkey->key;
2042 if (!(rsa = d2i_RSA_PUBKEY(NULL, &p, (long) sig->pubkey->key_len)))
2044 #elif defined(RSA_GNUTLS)
2046 k.data = sig->pubkey->key;
2047 k.size = sig->pubkey->key_len;
2048 if ((rc = gnutls_pubkey_import(rsa, &k, GNUTLS_X509_FMT_DER))
2049 != GNUTLS_E_SUCCESS)
2057 ERR_load_crypto_strings(); /*XXX move to a startup routine */
2058 while ((e = ERR_get_error()))
2059 debug_printf("Az: %.120s\n", ERR_error_string(e, NULL));
2060 #elif defined(RSA_GNUTLS)
2061 debug_printf("gnutls_pubkey_import: %s\n", gnutls_strerror(rc));
2065 sig->verify_status = PDKIM_VERIFY_INVALID;
2066 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
2070 /* Check the signature */
2073 if (RSA_verify(sig->algo == PDKIM_ALGO_RSA_SHA1 ? NID_sha1 : NID_sha256,
2074 CUS headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32,
2075 US sig->sigdata, (unsigned int)sig->sigdata_len,
2078 #elif defined(RSA_GNUTLS)
2080 k.data = headerhash;
2081 k.size = sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32;
2082 s.data = sig->sigdata;
2083 s.size = sig->sigdata_len;
2084 if ((rc = gnutls_pubkey_verify_hash2(rsa,
2085 sig->algo == PDKIM_ALGO_RSA_SHA1
2086 ? GNUTLS_SIGN_RSA_SHA1 : GNUTLS_SIGN_RSA_SHA256,
2091 #if defined(RSA_GNUTLS)
2092 debug_printf("gnutls_pubkey_verify_hash2: %s\n", gnutls_strerror(rc));
2094 sig->verify_status = PDKIM_VERIFY_FAIL;
2095 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
2099 /* We have a winner! (if bodydhash was correct earlier) */
2100 if (sig->verify_status == PDKIM_VERIFY_NONE)
2101 sig->verify_status = PDKIM_VERIFY_PASS;
2107 debug_printf("PDKIM [%s] signature status: %s",
2108 sig->domain, pdkim_verify_status_str(sig->verify_status));
2109 if (sig->verify_ext_status > 0)
2110 debug_printf(" (%s)\n",
2111 pdkim_verify_ext_status_str(sig->verify_ext_status));
2117 gnutls_pubkey_deinit(rsa);
2120 free(dns_txt_reply);
2126 /* If requested, set return pointer to signature(s) */
2127 if (return_signatures)
2128 *return_signatures = ctx->sig;
2134 /* -------------------------------------------------------------------------- */
2136 DLLEXPORT pdkim_ctx *
2137 pdkim_init_verify(int(*dns_txt_callback)(char *, char *))
2139 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
2143 memset(ctx, 0, sizeof(pdkim_ctx));
2145 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2151 ctx->mode = PDKIM_MODE_VERIFY;
2152 ctx->dns_txt_callback = dns_txt_callback;
2158 /* -------------------------------------------------------------------------- */
2160 DLLEXPORT pdkim_ctx *
2161 pdkim_init_sign(char *domain, char *selector, char *rsa_privkey, int algo)
2164 pdkim_signature *sig;
2166 if (!domain || !selector || !rsa_privkey)
2169 if (!(ctx = malloc(sizeof(pdkim_ctx))))
2171 memset(ctx, 0, sizeof(pdkim_ctx));
2173 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2179 if (!(sig = malloc(sizeof(pdkim_signature))))
2185 memset(sig, 0, sizeof(pdkim_signature));
2187 sig->bodylength = -1;
2189 ctx->mode = PDKIM_MODE_SIGN;
2192 ctx->sig->domain = strdup(domain);
2193 ctx->sig->selector = strdup(selector);
2194 ctx->sig->rsa_privkey = strdup(rsa_privkey);
2195 ctx->sig->algo = algo;
2197 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey)
2201 SHA1_Init (&ctx->sig->sha1_body);
2202 SHA256_Init(&ctx->sig->sha2_body);
2204 #elif defined(SHA_GNUTLS)
2205 gnutls_hash_init(&ctx->sig->sha_body,
2206 algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
2208 #elif defined(SHA_POLARSSL)
2209 if (!(ctx->sig->sha1_body = malloc(sizeof(sha1_context))))
2211 sha1_starts(ctx->sig->sha1_body);
2213 if (!(ctx->sig->sha2_body = malloc(sizeof(sha2_context))))
2215 sha2_starts(ctx->sig->sha2_body, 0);
2222 pdkim_free_ctx(ctx);
2227 /* -------------------------------------------------------------------------- */
2230 pdkim_set_optional(pdkim_ctx *ctx,
2236 unsigned long created,
2237 unsigned long expires)
2240 if (!(ctx->sig->identity = strdup(identity)))
2241 return PDKIM_ERR_OOM;
2244 if (!(ctx->sig->sign_headers = strdup(sign_headers)))
2245 return PDKIM_ERR_OOM;
2247 ctx->sig->canon_headers = canon_headers;
2248 ctx->sig->canon_body = canon_body;
2249 ctx->sig->bodylength = bodylength;
2250 ctx->sig->created = created;
2251 ctx->sig->expires = expires;
2257 #endif /*DISABLE_DKIM*/