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_PARSING: return "PDKIM_VERIFY_INVALID_PUBKEY_PARSING";
150 default: return "PDKIM_VERIFY_UNKNOWN";
155 /* -------------------------------------------------------------------------- */
156 /* Print debugging functions */
158 pdkim_quoteprint(const char *data, int len, int lf)
161 const unsigned char *p = (const unsigned char *)data;
163 for (i = 0; i < len; i++)
168 case ' ' : debug_printf("{SP}"); break;
169 case '\t': debug_printf("{TB}"); break;
170 case '\r': debug_printf("{CR}"); break;
171 case '\n': debug_printf("{LF}"); break;
172 case '{' : debug_printf("{BO}"); break;
173 case '}' : debug_printf("{BC}"); break;
175 if ( (c < 32) || (c > 127) )
176 debug_printf("{%02x}", c);
178 debug_printf("%c", c);
187 pdkim_hexprint(const char *data, int len, int lf)
190 const unsigned char *p = (const unsigned char *)data;
192 for (i = 0 ; i < len; i++)
193 debug_printf("%02x", p[i]);
200 /* String package: should be replaced by Exim standard ones */
202 static pdkim_stringlist *
203 pdkim_prepend_stringlist(pdkim_stringlist *base, char *str)
205 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
207 if (!new_entry) return NULL;
208 memset(new_entry, 0, sizeof(pdkim_stringlist));
209 if (!(new_entry->value = strdup(str))) return NULL;
212 pdkim_stringlist *last = base;
213 while (last->next != NULL) { last = last->next; }
214 last->next = new_entry;
222 /* -------------------------------------------------------------------------- */
223 /* A small "growing string" implementation to escape malloc/realloc hell */
226 pdkim_strnew (const char *cstr)
228 unsigned int len = cstr ? strlen(cstr) : 0;
229 pdkim_str *p = malloc(sizeof(pdkim_str));
232 memset(p, 0, sizeof(pdkim_str));
233 if (!(p->str = malloc(len+1)))
238 p->allocated = len+1;
241 strcpy(p->str, cstr);
243 p->str[p->len] = '\0';
248 pdkim_strncat(pdkim_str *str, const char *data, int len)
250 if ((str->allocated - str->len) < (len+1))
252 /* Extend the buffer */
253 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
254 char *n = realloc(str->str,
255 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
256 if (n == NULL) return NULL;
258 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
260 strncpy(&(str->str[str->len]), data, len);
262 str->str[str->len] = '\0';
267 pdkim_strcat(pdkim_str *str, const char *cstr)
269 return pdkim_strncat(str, cstr, strlen(cstr));
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->selector ) free(sig->selector);
345 if (sig->domain ) free(sig->domain);
346 if (sig->identity ) free(sig->identity);
347 if (sig->headernames ) free(sig->headernames);
348 if (sig->copiedheaders ) free(sig->copiedheaders);
349 if (sig->rsa_privkey ) free(sig->rsa_privkey);
350 if (sig->sign_headers ) free(sig->sign_headers);
351 if (sig->signature_header) free(sig->signature_header);
353 if (sig->pubkey) pdkim_free_pubkey(sig->pubkey);
356 if (next) pdkim_free_sig(next);
361 /* -------------------------------------------------------------------------- */
364 pdkim_free_ctx(pdkim_ctx *ctx)
368 pdkim_stringlist *e = ctx->headers;
371 pdkim_stringlist *c = e;
372 if (e->value) free(e->value);
376 pdkim_free_sig(ctx->sig);
377 pdkim_strfree(ctx->cur_header);
383 /* -------------------------------------------------------------------------- */
384 /* Matches the name of the passed raw "header" against
385 the passed colon-separated "list", starting at entry
386 "start". Returns the position of the header name in
390 header_name_match(const char *header,
400 /* Get header name */
401 char *hcolon = strchr(header, ':');
403 if (!hcolon) return rc; /* This isn't a header */
405 if (!(hname = malloc((hcolon-header)+1)))
406 return PDKIM_ERR_OOM;
407 memset(hname, 0, (hcolon-header)+1);
408 strncpy(hname, header, (hcolon-header));
410 /* Copy tick-off list locally, so we can punch zeroes into it */
411 if (!(lcopy = strdup(tick)))
414 return PDKIM_ERR_OOM;
422 if (strcasecmp(p, hname) == 0)
425 /* Invalidate header name instance in tick-off list */
426 if (do_tick) tick[p-lcopy] = '_';
434 if (strcasecmp(p, hname) == 0)
437 /* Invalidate header name instance in tick-off list */
438 if (do_tick) tick[p-lcopy] = '_';
448 /* -------------------------------------------------------------------------- */
449 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
453 pdkim_relax_header (char *header, int crlf)
455 BOOL past_field_name = FALSE;
456 BOOL seen_wsp = FALSE;
459 char *relaxed = malloc(strlen(header)+3);
461 if (!relaxed) return NULL;
464 for (p = header; *p != '\0'; p++)
468 if (c == '\r' || c == '\n')
470 if (c == '\t' || c == ' ')
474 c = ' '; /* Turns WSP into SP */
478 if (!past_field_name && c == ':')
480 if (seen_wsp) q--; /* This removes WSP before the colon */
481 seen_wsp = TRUE; /* This removes WSP after the colon */
482 past_field_name = TRUE;
487 /* Lowercase header name */
488 if (!past_field_name) c = tolower(c);
492 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
495 if (crlf) strcat(relaxed, "\r\n");
500 /* -------------------------------------------------------------------------- */
501 #define PDKIM_QP_ERROR_DECODE -1
504 pdkim_decode_qp_char(char *qp_p, int *c)
506 char *initial_pos = qp_p;
508 /* Advance one char */
511 /* Check for two hex digits and decode them */
512 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
514 /* Do hex conversion */
515 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
516 *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
520 /* Illegal char here */
521 *c = PDKIM_QP_ERROR_DECODE;
526 /* -------------------------------------------------------------------------- */
529 pdkim_decode_qp(char *str)
534 char *n = malloc(strlen(p)+1);
544 p = pdkim_decode_qp_char(p, &nchar);
560 /* -------------------------------------------------------------------------- */
563 pdkim_decode_base64(char *str, int *num_decoded)
567 int old_pool = store_pool;
569 /* There is a store-reset between header & body reception
570 so cannot use the main pool */
572 store_pool = POOL_PERM;
573 dlen = b64decode(US str, USS &res);
574 store_pool = old_pool;
576 if (dlen < 0) return NULL;
578 if (num_decoded) *num_decoded = dlen;
583 /* -------------------------------------------------------------------------- */
586 pdkim_encode_base64(char *str, int num)
589 int old_pool = store_pool;
591 store_pool = POOL_PERM;
592 ret = CS b64encode(US str, num);
593 store_pool = old_pool;
598 /* -------------------------------------------------------------------------- */
599 #define PDKIM_HDR_LIMBO 0
600 #define PDKIM_HDR_TAG 1
601 #define PDKIM_HDR_VALUE 2
603 static pdkim_signature *
604 pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr)
606 pdkim_signature *sig ;
608 pdkim_str *cur_tag = NULL;
609 pdkim_str *cur_val = NULL;
610 BOOL past_hname = FALSE;
611 BOOL in_b_val = FALSE;
612 int where = PDKIM_HDR_LIMBO;
615 if (!(sig = malloc(sizeof(pdkim_signature)))) return NULL;
616 memset(sig, 0, sizeof(pdkim_signature));
617 sig->bodylength = -1;
619 if (!(sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1)))
625 q = sig->rawsig_no_b_val;
627 for (p = raw_hdr; ; p++)
632 if (c == '\r' || c == '\n')
635 /* Fast-forward through header name */
638 if (c == ':') past_hname = TRUE;
642 if (where == PDKIM_HDR_LIMBO)
644 /* In limbo, just wait for a tag-char to appear */
645 if (!(c >= 'a' && c <= 'z'))
648 where = PDKIM_HDR_TAG;
651 if (where == PDKIM_HDR_TAG)
654 cur_tag = pdkim_strnew(NULL);
656 if (c >= 'a' && c <= 'z')
657 pdkim_strncat(cur_tag, p, 1);
661 if (strcmp(cur_tag->str, "b") == 0)
666 where = PDKIM_HDR_VALUE;
671 if (where == PDKIM_HDR_VALUE)
674 cur_val = pdkim_strnew(NULL);
676 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
679 if (c == ';' || c == '\0')
681 if (cur_tag->len > 0)
683 pdkim_strtrim(cur_val);
685 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
687 switch (cur_tag->str[0])
690 if (cur_tag->str[1] == 'h')
691 sig->bodyhash = pdkim_decode_base64(cur_val->str,
694 sig->sigdata = pdkim_decode_base64(cur_val->str,
698 /* We only support version 1, and that is currently the
699 only version there is. */
700 if (strcmp(cur_val->str, PDKIM_SIGNATURE_VERSION) == 0)
704 for (i = 0; pdkim_algos[i]; i++)
705 if (strcmp(cur_val->str, pdkim_algos[i]) == 0)
712 for (i = 0; pdkim_combined_canons[i].str; i++)
713 if (strcmp(cur_val->str, pdkim_combined_canons[i].str) == 0)
715 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
716 sig->canon_body = pdkim_combined_canons[i].canon_body;
721 for (i = 0; pdkim_querymethods[i]; i++)
722 if (strcmp(cur_val->str, pdkim_querymethods[i]) == 0)
724 sig->querymethod = i;
729 sig->selector = strdup(cur_val->str); break;
731 sig->domain = strdup(cur_val->str); break;
733 sig->identity = pdkim_decode_qp(cur_val->str); break;
735 sig->created = strtoul(cur_val->str, NULL, 10); break;
737 sig->expires = strtoul(cur_val->str, NULL, 10); break;
739 sig->bodylength = strtol(cur_val->str, NULL, 10); break;
741 sig->headernames = strdup(cur_val->str); break;
743 sig->copiedheaders = pdkim_decode_qp(cur_val->str); break;
745 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
749 pdkim_strclear(cur_tag);
750 pdkim_strclear(cur_val);
752 where = PDKIM_HDR_LIMBO;
755 pdkim_strncat(cur_val, p, 1);
766 /* Make sure the most important bits are there. */
767 if (!(sig->domain && (*(sig->domain) != '\0') &&
768 sig->selector && (*(sig->selector) != '\0') &&
769 sig->headernames && (*(sig->headernames) != '\0') &&
779 /* Chomp raw header. The final newline must not be added to the signature. */
781 while (q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
782 *q = '\0'; q--; /*XXX questionable code layout; possible bug */
787 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
788 pdkim_quoteprint(sig->rawsig_no_b_val, strlen(sig->rawsig_no_b_val), 1);
790 "PDKIM >> Sig size: %4d bits\n", sig->sigdata_len*8);
792 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
797 SHA1_Init (&sig->sha1_body);
798 SHA256_Init(&sig->sha2_body);
800 #elif defined(SHA_GNUTLS)
802 gnutls_hash_init(&sig->sha_body,
803 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
805 #elif defined(SHA_POLARSSL)
807 if ( !(sig->sha1_body = malloc(sizeof(sha1_context)))
808 || !(sig->sha2_body = malloc(sizeof(sha2_context)))
815 sha1_starts(sig->sha1_body);
816 sha2_starts(sig->sha2_body, 0);
818 #endif /* SHA impl */
824 /* -------------------------------------------------------------------------- */
826 static pdkim_pubkey *
827 pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record)
831 pdkim_str *cur_tag = NULL;
832 pdkim_str *cur_val = NULL;
833 int where = PDKIM_HDR_LIMBO;
835 if (!(pub = malloc(sizeof(pdkim_pubkey)))) return NULL;
836 memset(pub, 0, sizeof(pdkim_pubkey));
838 for (p = raw_record; ; p++)
843 if (c == '\r' || c == '\n')
846 if (where == PDKIM_HDR_LIMBO)
848 /* In limbo, just wait for a tag-char to appear */
849 if (!(c >= 'a' && c <= 'z'))
852 where = PDKIM_HDR_TAG;
855 if (where == PDKIM_HDR_TAG)
858 cur_tag = pdkim_strnew(NULL);
860 if (c >= 'a' && c <= 'z')
861 pdkim_strncat(cur_tag, p, 1);
865 where = PDKIM_HDR_VALUE;
870 if (where == PDKIM_HDR_VALUE)
873 cur_val = pdkim_strnew(NULL);
875 if (c == '\r' || c == '\n')
878 if (c == ';' || c == '\0')
880 if (cur_tag->len > 0)
882 pdkim_strtrim(cur_val);
883 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
885 switch (cur_tag->str[0])
888 /* This tag isn't evaluated because:
889 - We only support version DKIM1.
890 - Which is the default for this value (set below)
891 - Other versions are currently not specified. */
894 pub->hashes = strdup(cur_val->str); break;
896 pub->granularity = strdup(cur_val->str); break;
898 pub->notes = pdkim_decode_qp(cur_val->str); break;
900 pub->key = pdkim_decode_base64(cur_val->str, &(pub->key_len)); break;
902 pub->hashes = strdup(cur_val->str); break;
904 pub->srvtype = strdup(cur_val->str); break;
906 if (strchr(cur_val->str, 'y') != NULL) pub->testing = 1;
907 if (strchr(cur_val->str, 's') != NULL) pub->no_subdomaining = 1;
910 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
914 pdkim_strclear(cur_tag);
915 pdkim_strclear(cur_val);
916 where = PDKIM_HDR_LIMBO;
919 pdkim_strncat(cur_val, p, 1);
923 if (c == '\0') break;
926 /* Set fallback defaults */
927 if (!pub->version ) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
928 if (!pub->granularity) pub->granularity = strdup("*");
929 if (!pub->keytype ) pub->keytype = strdup("rsa");
930 if (!pub->srvtype ) pub->srvtype = strdup("*");
936 pdkim_free_pubkey(pub);
941 /* -------------------------------------------------------------------------- */
944 pdkim_update_bodyhash(pdkim_ctx *ctx, const char *data, int len)
946 pdkim_signature *sig = ctx->sig;
947 /* Cache relaxed version of data */
948 char *relaxed_data = NULL;
951 /* Traverse all signatures, updating their hashes. */
954 /* Defaults to simple canon (no further treatment necessary) */
955 const char *canon_data = data;
958 if (sig->canon_body == PDKIM_CANON_RELAXED)
960 /* Relax the line if not done already */
963 BOOL seen_wsp = FALSE;
967 if (!(relaxed_data = malloc(len+1)))
968 return PDKIM_ERR_OOM;
970 for (p = data; *p; p++)
975 if (q > 0 && relaxed_data[q-1] == ' ')
978 else if (c == '\t' || c == ' ')
980 c = ' '; /* Turns WSP into SP */
987 relaxed_data[q++] = c;
989 relaxed_data[q] = '\0';
992 canon_data = relaxed_data;
993 canon_len = relaxed_len;
996 /* Make sure we don't exceed the to-be-signed body length */
997 if ( sig->bodylength >= 0
998 && sig->signed_body_bytes + (unsigned long)canon_len > sig->bodylength
1000 canon_len = sig->bodylength - sig->signed_body_bytes;
1005 gnutls_hash(sig->sha_body, canon_data, canon_len);
1007 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1009 SHA1_Update (&sig->sha1_body, canon_data, canon_len);
1011 SHA256_Update(&sig->sha2_body, canon_data, canon_len);
1012 # elif defined(SHA_POLARSSL)
1013 sha1_update(sig->sha1_body, US canon_data, canon_len);
1015 sha2_update(sig->sha2_body, US canon_data, canon_len);
1019 sig->signed_body_bytes += canon_len;
1020 DEBUG(D_acl) pdkim_quoteprint(canon_data, canon_len, 1);
1026 if (relaxed_data) free(relaxed_data);
1031 /* -------------------------------------------------------------------------- */
1034 pdkim_finish_bodyhash(pdkim_ctx *ctx)
1036 pdkim_signature *sig;
1038 /* Traverse all signatures */
1039 for (sig = ctx->sig; sig; sig = sig->next)
1040 { /* Finish hashes */
1041 uschar bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
1044 gnutls_hash_output(sig->sha_body, bh);
1046 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1048 SHA1_Final (bh, &sig->sha1_body);
1050 SHA256_Final(bh, &sig->sha2_body);
1051 # elif defined(SHA_POLARSSL)
1052 sha1_finish(sig->sha1_body, bh);
1054 sha2_finish(sig->sha2_body, bh);
1060 debug_printf("PDKIM [%s] Body bytes hashed: %lu\n"
1061 "PDKIM [%s] bh computed: ",
1062 sig->domain, sig->signed_body_bytes, sig->domain);
1063 pdkim_hexprint((char *)bh, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32, 1);
1066 /* SIGNING -------------------------------------------------------------- */
1067 if (ctx->mode == PDKIM_MODE_SIGN)
1069 sig->bodyhash_len = sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32;
1070 sig->bodyhash = string_copyn(US bh, sig->bodyhash_len);
1072 /* If bodylength limit is set, and we have received less bytes
1073 than the requested amount, effectively remove the limit tag. */
1074 if (sig->signed_body_bytes < sig->bodylength)
1075 sig->bodylength = -1;
1078 /* VERIFICATION --------------------------------------------------------- */
1081 /* Compare bodyhash */
1082 if (memcmp(bh, sig->bodyhash,
1083 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0)
1085 DEBUG(D_acl) debug_printf("PDKIM [%s] Body hash verified OK\n", sig->domain);
1091 debug_printf("PDKIM [%s] bh signature: ", sig->domain);
1092 pdkim_hexprint(sig->bodyhash,
1093 sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32, 1);
1094 debug_printf("PDKIM [%s] Body hash did NOT verify\n", sig->domain);
1096 sig->verify_status = PDKIM_VERIFY_FAIL;
1097 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
1107 /* -------------------------------------------------------------------------- */
1108 /* Callback from pdkim_feed below for processing complete body lines */
1111 pdkim_bodyline_complete(pdkim_ctx *ctx)
1113 char *p = ctx->linebuf;
1114 int n = ctx->linebuf_offset;
1115 pdkim_signature *sig = ctx->sig; /*XXX assumes only one sig */
1117 /* Ignore extra data if we've seen the end-of-data marker */
1118 if (ctx->seen_eod) goto BAIL;
1120 /* We've always got one extra byte to stuff a zero ... */
1121 ctx->linebuf[ctx->linebuf_offset] = '\0';
1123 /* Terminate on EOD marker */
1124 if (memcmp(p, ".\r\n", 3) == 0)
1126 /* In simple body mode, if any empty lines were buffered,
1127 replace with one. rfc 4871 3.4.3 */
1128 /*XXX checking the signed-body-bytes is a gross hack; I think
1129 it indicates that all linebreaks should be buffered, including
1130 the one terminating a text line */
1131 if ( sig && sig->canon_body == PDKIM_CANON_SIMPLE
1132 && sig->signed_body_bytes == 0
1133 && ctx->num_buffered_crlf > 0
1135 pdkim_update_bodyhash(ctx, "\r\n", 2);
1137 ctx->seen_eod = TRUE;
1141 if (memcmp(p, "..", 2) == 0)
1147 /* Empty lines need to be buffered until we find a non-empty line */
1148 if (memcmp(p, "\r\n", 2) == 0)
1150 ctx->num_buffered_crlf++;
1154 if (sig && sig->canon_body == PDKIM_CANON_RELAXED)
1156 /* Lines with just spaces need to be buffered too */
1158 while (memcmp(check, "\r\n", 2) != 0)
1162 if (c != '\t' && c != ' ')
1167 ctx->num_buffered_crlf++;
1172 /* At this point, we have a non-empty line, so release the buffered ones. */
1173 while (ctx->num_buffered_crlf)
1175 pdkim_update_bodyhash(ctx, "\r\n", 2);
1176 ctx->num_buffered_crlf--;
1179 pdkim_update_bodyhash(ctx, p, n);
1182 ctx->linebuf_offset = 0;
1187 /* -------------------------------------------------------------------------- */
1188 /* Callback from pdkim_feed below for processing complete headers */
1189 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1192 pdkim_header_complete(pdkim_ctx *ctx)
1194 /* Special case: The last header can have an extra \r appended */
1195 if ( (ctx->cur_header->len > 1) &&
1196 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') )
1198 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
1199 ctx->cur_header->len--;
1203 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
1205 /* SIGNING -------------------------------------------------------------- */
1206 if (ctx->mode == PDKIM_MODE_SIGN)
1208 pdkim_signature *sig;
1210 for (sig = ctx->sig; sig; sig = sig->next) /* Traverse all signatures */
1211 if (header_name_match(ctx->cur_header->str,
1214 PDKIM_DEFAULT_SIGN_HEADERS, 0) == PDKIM_OK)
1216 pdkim_stringlist *list;
1218 /* Add header to the signed headers list (in reverse order) */
1219 if (!(list = pdkim_prepend_stringlist(sig->headers,
1220 ctx->cur_header->str)))
1221 return PDKIM_ERR_OOM;
1222 sig->headers = list;
1226 /* VERIFICATION ----------------------------------------------------------- */
1227 /* DKIM-Signature: headers are added to the verification list */
1228 if (ctx->mode == PDKIM_MODE_VERIFY)
1230 if (strncasecmp(ctx->cur_header->str,
1231 DKIM_SIGNATURE_HEADERNAME,
1232 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
1234 pdkim_signature *new_sig;
1236 /* Create and chain new signature block */
1237 DEBUG(D_acl) debug_printf(
1238 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1240 if ((new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str)))
1242 pdkim_signature *last_sig = ctx->sig;
1247 while (last_sig->next) last_sig = last_sig->next;
1248 last_sig->next = new_sig;
1252 DEBUG(D_acl) debug_printf(
1253 "Error while parsing signature header\n"
1254 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1257 /* every other header is stored for signature verification */
1260 pdkim_stringlist *list;
1262 if (!(list = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->str)))
1263 return PDKIM_ERR_OOM;
1264 ctx->headers = list;
1269 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1275 /* -------------------------------------------------------------------------- */
1276 #define HEADER_BUFFER_FRAG_SIZE 256
1279 pdkim_feed (pdkim_ctx *ctx, char *data, int len)
1283 for (p = 0; p<len; p++)
1287 if (ctx->past_headers)
1289 /* Processing body byte */
1290 ctx->linebuf[ctx->linebuf_offset++] = c;
1293 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1294 if (rc != PDKIM_OK) return rc;
1296 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1297 return PDKIM_ERR_LONG_LINE;
1301 /* Processing header byte */
1308 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1309 if (rc != PDKIM_OK) return rc;
1311 ctx->past_headers = TRUE;
1313 DEBUG(D_acl) debug_printf(
1314 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1318 ctx->seen_lf = TRUE;
1320 else if (ctx->seen_lf)
1322 if (!(c == '\t' || c == ' '))
1324 int rc = pdkim_header_complete(ctx); /* End of header */
1325 if (rc != PDKIM_OK) return rc;
1327 ctx->seen_lf = FALSE;
1331 if (!ctx->cur_header)
1332 if (!(ctx->cur_header = pdkim_strnew(NULL)))
1333 return PDKIM_ERR_OOM;
1335 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1336 if (!pdkim_strncat(ctx->cur_header, &data[p], 1))
1337 return PDKIM_ERR_OOM;
1344 * RFC 5322 specifies that header line length SHOULD be no more than 78
1349 * col: this int holds and receives column number (octets since last '\n')
1350 * str: partial string to append to
1351 * pad: padding, split line or space after before or after eg: ";"
1352 * intro: - must join to payload eg "h=", usually the tag name
1353 * payload: eg base64 data - long data can be split arbitrarily.
1355 * this code doesn't fold the header in some of the places that RFC4871
1356 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1357 * pairs and inside long values. it also always spaces or breaks after the
1360 * no guarantees are made for output given out-of range input. like tag
1361 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1365 pdkim_headcat(int *col, pdkim_str *str, const char * pad,
1366 const char *intro, const char *payload)
1375 pdkim_strcat(str, "\r\n\t");
1378 pdkim_strncat(str, pad, l);
1382 l = (pad?1:0) + (intro?strlen(intro):0);
1385 { /*can't fit intro - start a new line to make room.*/
1386 pdkim_strcat(str, "\r\n\t");
1388 l = intro?strlen(intro):0;
1391 l += payload ? strlen(payload):0 ;
1394 { /* this fragment will not fit on a single line */
1397 pdkim_strcat(str, " ");
1399 pad = NULL; /* only want this once */
1405 size_t sl = strlen(intro);
1407 pdkim_strncat(str, intro, sl);
1410 intro = NULL; /* only want this once */
1415 size_t sl = strlen(payload);
1416 size_t chomp = *col+sl < 77 ? sl : 78-*col;
1418 pdkim_strncat(str, payload, chomp);
1424 /* the while precondition tells us it didn't fit. */
1425 pdkim_strcat(str, "\r\n\t");
1431 pdkim_strcat(str, "\r\n\t");
1438 pdkim_strcat(str, " ");
1445 size_t sl = strlen(intro);
1447 pdkim_strncat(str, intro, sl);
1455 size_t sl = strlen(payload);
1457 pdkim_strncat(str, payload, sl);
1465 /* -------------------------------------------------------------------------- */
1468 pdkim_create_header(pdkim_signature *sig, int final)
1471 char *base64_bh = NULL;
1472 char *base64_b = NULL;
1475 pdkim_str *canon_all;
1477 if (!(hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION)))
1480 if (!(canon_all = pdkim_strnew(pdkim_canons[sig->canon_headers])))
1483 if (!(base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len)))
1486 col = strlen(hdr->str);
1488 /* Required and static bits */
1489 if ( pdkim_headcat(&col, hdr, ";", "a=", pdkim_algos[sig->algo])
1490 && pdkim_headcat(&col, hdr, ";", "q=", pdkim_querymethods[sig->querymethod])
1491 && pdkim_strcat(canon_all, "/")
1492 && pdkim_strcat(canon_all, pdkim_canons[sig->canon_body])
1493 && pdkim_headcat(&col, hdr, ";", "c=", canon_all->str)
1494 && pdkim_headcat(&col, hdr, ";", "d=", sig->domain)
1495 && pdkim_headcat(&col, hdr, ";", "s=", sig->selector)
1498 /* list of eader names can be split between items. */
1500 char *n = strdup(sig->headernames);
1508 char *c = strchr(n, ':');
1513 if (!pdkim_headcat(&col, hdr, NULL, NULL, ":"))
1519 if (!pdkim_headcat(&col, hdr, s, i, n))
1535 if(!pdkim_headcat(&col, hdr, ";", "bh=", base64_bh))
1540 if(!pdkim_headcat(&col, hdr, ";", "i=", sig->identity))
1543 if (sig->created > 0)
1547 snprintf(minibuf, 20, "%lu", sig->created);
1548 if(!pdkim_headcat(&col, hdr, ";", "t=", minibuf))
1552 if (sig->expires > 0)
1556 snprintf(minibuf, 20, "%lu", sig->expires);
1557 if(!pdkim_headcat(&col, hdr, ";", "x=", minibuf))
1561 if (sig->bodylength >= 0)
1565 snprintf(minibuf, 20, "%lu", sig->bodylength);
1566 if(!pdkim_headcat(&col, hdr, ";", "l=", minibuf))
1570 /* Preliminary or final version? */
1573 if (!(base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len)))
1575 if (!pdkim_headcat(&col, hdr, ";", "b=", base64_b))
1579 if(!pdkim_headcat(&col, hdr, ";", "b=", ""))
1582 /* add trailing semicolon: I'm not sure if this is actually needed */
1583 if (!pdkim_headcat(&col, hdr, NULL, ";", ""))
1587 rc = strdup(hdr->str);
1591 if (canon_all) pdkim_strfree(canon_all);
1596 /* -------------------------------------------------------------------------- */
1599 pdkim_feed_finish(pdkim_ctx *ctx, pdkim_signature **return_signatures)
1601 pdkim_signature *sig = ctx->sig;
1602 pdkim_str *headernames = NULL; /* Collected signed header names */
1604 /* Check if we must still flush a (partial) header. If that is the
1605 case, the message has no body, and we must compute a body hash
1606 out of '<CR><LF>' */
1607 if (ctx->cur_header && ctx->cur_header->len)
1609 int rc = pdkim_header_complete(ctx);
1610 if (rc != PDKIM_OK) return rc;
1611 pdkim_update_bodyhash(ctx, "\r\n", 2);
1614 DEBUG(D_acl) debug_printf(
1615 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1617 /* Build (and/or evaluate) body hash */
1618 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK)
1619 return PDKIM_ERR_OOM;
1621 /* SIGNING -------------------------------------------------------------- */
1622 if (ctx->mode == PDKIM_MODE_SIGN)
1623 if (!(headernames = pdkim_strnew(NULL)))
1624 return PDKIM_ERR_OOM;
1625 /* ---------------------------------------------------------------------- */
1630 SHA_CTX sha1_headers;
1631 SHA256_CTX sha2_headers;
1632 #elif defined(SHA_GNUTLS)
1633 gnutls_hash_hd_t sha_headers;
1634 #elif defined(SHA_POLARSSL)
1635 sha1_context sha1_headers;
1636 sha2_context sha2_headers;
1640 char headerhash[32];
1643 uschar * hdata = NULL;
1644 int hdata_alloc = 0;
1649 gnutls_hash_init(&sha_headers,
1650 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
1652 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1654 SHA1_Init(&sha1_headers);
1656 SHA256_Init(&sha2_headers);
1657 # elif defined(SHA_POLARSSL)
1658 sha1_starts(&sha1_headers);
1660 sha2_starts(&sha2_headers, 0);
1664 DEBUG(D_acl) debug_printf(
1665 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1667 /* SIGNING ---------------------------------------------------------------- */
1668 /* When signing, walk through our header list and add them to the hash. As we
1669 go, construct a list of the header's names to use for the h= parameter. */
1671 if (ctx->mode == PDKIM_MODE_SIGN)
1673 pdkim_stringlist *p;
1675 for (p = sig->headers; p; p = p->next)
1678 /* Collect header names (Note: colon presence is guaranteed here) */
1679 char *q = strchr(p->value, ':');
1681 if (!(pdkim_strncat(headernames, p->value,
1682 (q-(p->value)) + (p->next ? 1 : 0))))
1683 return PDKIM_ERR_OOM;
1685 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1686 ? pdkim_relax_header(p->value, 1) /* cook header for relaxed canon */
1687 : strdup(p->value); /* just copy it for simple canon */
1689 return PDKIM_ERR_OOM;
1691 /* Feed header to the hash algorithm */
1693 gnutls_hash(sha_headers, rh, strlen(rh));
1695 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1697 SHA1_Update (&sha1_headers, rh, strlen(rh));
1699 SHA256_Update(&sha2_headers, rh, strlen(rh));
1700 # elif defined(SHA_POLARSSL)
1701 sha1_update(&sha1_headers, US rh, strlen(rh));
1703 sha2_update(&sha2_headers, US rh, strlen(rh));
1708 /* Remember headers block for signing */
1709 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, rh);
1712 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
1717 /* VERIFICATION ----------------------------------------------------------- */
1718 /* When verifying, walk through the header name list in the h= parameter and
1719 add the headers to the hash in that order. */
1722 char *b = strdup(sig->headernames);
1725 pdkim_stringlist *hdrs;
1727 if (!b) return PDKIM_ERR_OOM;
1730 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1735 if ((q = strchr(p, ':')))
1738 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1740 && strncasecmp(hdrs->value, p, strlen(p)) == 0
1741 && (hdrs->value)[strlen(p)] == ':'
1746 rh = sig->canon_headers == PDKIM_CANON_RELAXED
1747 ? pdkim_relax_header(hdrs->value, 1) /* cook header for relaxed canon */
1748 : strdup(hdrs->value); /* just copy it for simple canon */
1750 return PDKIM_ERR_OOM;
1752 /* Feed header to the hash algorithm */
1754 gnutls_hash(sha_headers, rh, strlen(rh));
1756 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1758 SHA1_Update (&sha1_headers, rh, strlen(rh));
1760 SHA256_Update(&sha2_headers, rh, strlen(rh));
1761 # elif defined(SHA_POLARSSL)
1762 sha1_update(&sha1_headers, US rh, strlen(rh));
1764 sha2_update(&sha2_headers, US rh, strlen(rh));
1768 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
1780 DEBUG(D_acl) debug_printf(
1781 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1783 /* SIGNING ---------------------------------------------------------------- */
1784 if (ctx->mode == PDKIM_MODE_SIGN)
1786 /* Copy headernames to signature struct */
1787 sig->headernames = strdup(headernames->str);
1788 pdkim_strfree(headernames);
1790 /* Create signature header with b= omitted */
1791 sig_hdr = pdkim_create_header(ctx->sig, 0);
1794 /* VERIFICATION ----------------------------------------------------------- */
1796 sig_hdr = strdup(sig->rawsig_no_b_val);
1797 /* ------------------------------------------------------------------------ */
1800 return PDKIM_ERR_OOM;
1802 /* Relax header if necessary */
1803 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1805 char *relaxed_hdr = pdkim_relax_header(sig_hdr, 0);
1809 return PDKIM_ERR_OOM;
1810 sig_hdr = relaxed_hdr;
1816 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1817 pdkim_quoteprint(sig_hdr, strlen(sig_hdr), 1);
1819 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1822 /* Finalize header hash */
1824 gnutls_hash(sha_headers, sig_hdr, strlen(sig_hdr));
1825 gnutls_hash_output(sha_headers, headerhash);
1827 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1830 SHA1_Update(&sha1_headers, sig_hdr, strlen(sig_hdr));
1831 SHA1_Final(US headerhash, &sha1_headers);
1835 SHA256_Update(&sha2_headers, sig_hdr, strlen(sig_hdr));
1836 SHA256_Final(US headerhash, &sha2_headers);
1838 # elif defined(SHA_POLARSSL)
1840 sha1_update(&sha1_headers, US sig_hdr, strlen(sig_hdr));
1841 sha1_finish(&sha1_headers, US headerhash);
1845 sha2_update(&sha2_headers, US sig_hdr, strlen(sig_hdr));
1846 sha2_finish(&sha2_headers, US headerhash);
1853 debug_printf("PDKIM [%s] hh computed: ", sig->domain);
1854 pdkim_hexprint(headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32, 1);
1858 if (ctx->mode == PDKIM_MODE_SIGN)
1859 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, sig_hdr);
1864 /* SIGNING ---------------------------------------------------------------- */
1865 if (ctx->mode == PDKIM_MODE_SIGN)
1871 #elif defined(RSA_GNUTLS)
1872 gnutls_x509_privkey_t rsa;
1878 /* Import private key */
1881 if ( !(p = Ustrstr(sig->rsa_privkey, "-----BEGIN RSA PRIVATE KEY-----"))
1882 || !(q = Ustrstr(p+=31, "-----END RSA PRIVATE KEY-----"))
1884 return PDKIM_ERR_RSA_PRIVKEY;
1886 if ( (len = b64decode(p, &p)) < 0
1887 || !(rsa = d2i_RSAPrivateKey(NULL, CUSS &p, len))
1889 /*XXX todo: get errstring from library */
1890 return PDKIM_ERR_RSA_PRIVKEY;
1892 #elif defined(RSA_GNUTLS)
1894 k.data = sig->rsa_privkey;
1895 k.size = strlen(sig->rsa_privkey);
1896 if ( (rc = gnutls_x509_privkey_init(&rsa)) != GNUTLS_E_SUCCESS
1897 || (rc = gnutls_x509_privkey_import2(rsa, &k,
1898 GNUTLS_X509_FMT_PEM, NULL, GNUTLS_PKCS_PLAIN)) != GNUTLS_E_SUCCESS
1901 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_import2: %s\n",
1902 gnutls_strerror(rc));
1903 return PDKIM_ERR_RSA_PRIVKEY;
1909 /* Allocate mem for signature */
1911 sig->sigdata = store_get(RSA_size(rsa));
1912 #elif defined(RSA_GNUTLS)
1914 k.size = hdata_size;
1915 (void) gnutls_x509_privkey_sign_data(rsa,
1916 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256,
1917 0, &k, NULL, &sigsize);
1918 sig->sigdata = store_get(sig->sigdata_len = sigsize);
1924 if (RSA_sign(sig->algo == PDKIM_ALGO_RSA_SHA1 ? NID_sha1 : NID_sha256,
1925 CUS headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32,
1926 US sig->sigdata, (unsigned int *)&sig->sigdata_len,
1928 return PDKIM_ERR_RSA_SIGNING;
1931 #elif defined(RSA_GNUTLS)
1933 if ((rc = gnutls_x509_privkey_sign_data(rsa,
1934 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256,
1935 0, &k, sig->sigdata, &sigsize)) != GNUTLS_E_SUCCESS
1938 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_sign_data: %s\n",
1939 gnutls_strerror(rc));
1940 return PDKIM_ERR_RSA_SIGNING;
1942 gnutls_x509_privkey_deinit(rsa);
1949 debug_printf( "PDKIM [%s] b computed: ", sig->domain);
1950 pdkim_hexprint(sig->sigdata, sig->sigdata_len, 1);
1953 if (!(sig->signature_header = pdkim_create_header(ctx->sig, 1)))
1954 return PDKIM_ERR_OOM;
1957 /* VERIFICATION ----------------------------------------------------------- */
1962 const unsigned char * p;
1963 #elif defined(RSA_GNUTLS)
1964 gnutls_pubkey_t rsa;
1965 gnutls_datum_t k, s;
1968 char *dns_txt_name, *dns_txt_reply;
1971 gnutls_pubkey_init(&rsa);
1974 /* Fetch public key for signing domain, from DNS */
1976 if (!(dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN)))
1977 return PDKIM_ERR_OOM;
1979 if (!(dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN)))
1982 return PDKIM_ERR_OOM;
1985 memset(dns_txt_reply, 0, PDKIM_DNS_TXT_MAX_RECLEN);
1986 memset(dns_txt_name , 0, PDKIM_DNS_TXT_MAX_NAMELEN);
1988 if (snprintf(dns_txt_name, PDKIM_DNS_TXT_MAX_NAMELEN,
1989 "%s._domainkey.%s.",
1990 sig->selector, sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN)
1992 sig->verify_status = PDKIM_VERIFY_INVALID;
1993 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1997 if ( ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK
1998 || dns_txt_reply[0] == '\0')
2000 sig->verify_status = PDKIM_VERIFY_INVALID;
2001 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
2008 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
2010 pdkim_quoteprint(dns_txt_reply, strlen(dns_txt_reply), 1);
2013 if (!(sig->pubkey = pdkim_parse_pubkey_record(ctx, dns_txt_reply)))
2015 sig->verify_status = PDKIM_VERIFY_INVALID;
2016 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
2018 DEBUG(D_acl) debug_printf(
2019 " Error while parsing public key record\n"
2020 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
2024 DEBUG(D_acl) debug_printf(
2025 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
2027 /* Import public key */
2030 p = CUS sig->pubkey->key;
2031 if (!(rsa = d2i_RSA_PUBKEY(NULL, &p, (long) sig->pubkey->key_len)))
2033 #elif defined(RSA_GNUTLS)
2035 k.data = sig->pubkey->key;
2036 k.size = sig->pubkey->key_len;
2037 if ((rc = gnutls_pubkey_import(rsa, &k, GNUTLS_X509_FMT_DER))
2038 != GNUTLS_E_SUCCESS)
2046 ERR_load_crypto_strings(); /*XXX move to a startup routine */
2047 while ((e = ERR_get_error()))
2048 debug_printf("Az: %.120s\n", ERR_error_string(e, NULL));
2049 #elif defined(RSA_GNUTLS)
2050 debug_printf("gnutls_pubkey_import: %s\n", gnutls_strerror(rc));
2054 sig->verify_status = PDKIM_VERIFY_INVALID;
2055 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
2059 /* Check the signature */
2062 if (RSA_verify(sig->algo == PDKIM_ALGO_RSA_SHA1 ? NID_sha1 : NID_sha256,
2063 CUS headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32,
2064 US sig->sigdata, (unsigned int)sig->sigdata_len,
2067 #elif defined(RSA_GNUTLS)
2069 k.data = headerhash;
2070 k.size = sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20 : 32;
2071 s.data = sig->sigdata;
2072 s.size = sig->sigdata_len;
2073 if ((rc = gnutls_pubkey_verify_hash2(rsa,
2074 sig->algo == PDKIM_ALGO_RSA_SHA1
2075 ? GNUTLS_SIGN_RSA_SHA1 : GNUTLS_SIGN_RSA_SHA256,
2080 #if defined(RSA_GNUTLS)
2081 debug_printf("gnutls_pubkey_verify_hash2: %s\n", gnutls_strerror(rc));
2083 sig->verify_status = PDKIM_VERIFY_FAIL;
2084 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
2088 /* We have a winner! (if bodydhash was correct earlier) */
2089 if (sig->verify_status == PDKIM_VERIFY_NONE)
2090 sig->verify_status = PDKIM_VERIFY_PASS;
2096 debug_printf("PDKIM [%s] signature status: %s",
2097 sig->domain, pdkim_verify_status_str(sig->verify_status));
2098 if (sig->verify_ext_status > 0)
2099 debug_printf(" (%s)\n",
2100 pdkim_verify_ext_status_str(sig->verify_ext_status));
2106 gnutls_pubkey_deinit(rsa);
2109 free(dns_txt_reply);
2115 /* If requested, set return pointer to signature(s) */
2116 if (return_signatures)
2117 *return_signatures = ctx->sig;
2123 /* -------------------------------------------------------------------------- */
2125 DLLEXPORT pdkim_ctx *
2126 pdkim_init_verify(int(*dns_txt_callback)(char *, char *))
2128 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
2132 memset(ctx, 0, sizeof(pdkim_ctx));
2134 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2140 ctx->mode = PDKIM_MODE_VERIFY;
2141 ctx->dns_txt_callback = dns_txt_callback;
2147 /* -------------------------------------------------------------------------- */
2149 DLLEXPORT pdkim_ctx *
2150 pdkim_init_sign(char *domain, char *selector, char *rsa_privkey, int algo)
2153 pdkim_signature *sig;
2155 if (!domain || !selector || !rsa_privkey)
2158 if (!(ctx = malloc(sizeof(pdkim_ctx))))
2160 memset(ctx, 0, sizeof(pdkim_ctx));
2162 if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2168 if (!(sig = malloc(sizeof(pdkim_signature))))
2174 memset(sig, 0, sizeof(pdkim_signature));
2176 sig->bodylength = -1;
2178 ctx->mode = PDKIM_MODE_SIGN;
2181 ctx->sig->domain = strdup(domain);
2182 ctx->sig->selector = strdup(selector);
2183 ctx->sig->rsa_privkey = strdup(rsa_privkey);
2184 ctx->sig->algo = algo;
2186 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey)
2190 SHA1_Init (&ctx->sig->sha1_body);
2191 SHA256_Init(&ctx->sig->sha2_body);
2193 #elif defined(SHA_GNUTLS)
2194 gnutls_hash_init(&ctx->sig->sha_body,
2195 algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
2197 #elif defined(SHA_POLARSSL)
2198 if (!(ctx->sig->sha1_body = malloc(sizeof(sha1_context))))
2200 sha1_starts(ctx->sig->sha1_body);
2202 if (!(ctx->sig->sha2_body = malloc(sizeof(sha2_context))))
2204 sha2_starts(ctx->sig->sha2_body, 0);
2211 pdkim_free_ctx(ctx);
2216 /* -------------------------------------------------------------------------- */
2219 pdkim_set_optional(pdkim_ctx *ctx,
2225 unsigned long created,
2226 unsigned long expires)
2229 if (!(ctx->sig->identity = strdup(identity)))
2230 return PDKIM_ERR_OOM;
2233 if (!(ctx->sig->sign_headers = strdup(sign_headers)))
2234 return PDKIM_ERR_OOM;
2236 ctx->sig->canon_headers = canon_headers;
2237 ctx->sig->canon_body = canon_body;
2238 ctx->sig->bodylength = bodylength;
2239 ctx->sig->created = created;
2240 ctx->sig->expires = expires;
2246 #endif /*DISABLE_DKIM*/