DKIM: reinstate embedded Polarssl SHA routines under older GnuTLS. Bug 1772
[exim.git] / src / src / pdkim / pdkim.c
CommitLineData
80a47a2c
TK
1/*
2 * PDKIM - a RFC4871 (DKIM) implementation
3 *
f444c2c7
JH
4 * Copyright (C) 2009 - 2016 Tom Kistner <tom@duncanthrax.net>
5 * Copyright (C) 2016 Jeremy Harris <jgh@exim.org>
80a47a2c
TK
6 *
7 * http://duncanthrax.net/pdkim/
8 *
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.
13 *
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.
18 *
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.
22 */
23
0d04a285 24#include "../exim.h"
80a47a2c 25
f444c2c7
JH
26
27#ifndef DISABLE_DKIM /* entire file */
28
29#ifndef SUPPORT_TLS
30# error Need SUPPORT_TLS for DKIM
31#endif
32
cb224393 33#include "crypt_ver.h"
f444c2c7 34
cb224393
JH
35#ifdef RSA_OPENSSL
36# include <openssl/rsa.h>
37# include <openssl/ssl.h>
38# include <openssl/err.h>
39#elif defined(RSA_GNUTLS)
f444c2c7
JH
40# include <gnutls/gnutls.h>
41# include <gnutls/x509.h>
42# include <gnutls/abstract.h>
cb224393
JH
43#endif
44
45#ifdef SHA_GNUTLS
f444c2c7 46# include <gnutls/crypto.h>
cb224393
JH
47#elif defined(SHA_POLARSSL)
48# include "polarssl/sha1.h"
49# include "polarssl/sha2.h"
f444c2c7
JH
50#endif
51
52#include "pdkim.h"
80a47a2c
TK
53
54#define PDKIM_SIGNATURE_VERSION "1"
55#define PDKIM_PUB_RECORD_VERSION "DKIM1"
56
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"
69
70/* -------------------------------------------------------------------------- */
71struct pdkim_stringlist {
72 char *value;
37f8b554 73 int tag;
80a47a2c
TK
74 void *next;
75};
76
77#define PDKIM_STR_ALLOC_FRAG 256
78struct pdkim_str {
79 char *str;
80 unsigned int len;
81 unsigned int allocated;
82};
83
84/* -------------------------------------------------------------------------- */
85/* A bunch of list constants */
1ba28e2b 86const char *pdkim_querymethods[] = {
80a47a2c
TK
87 "dns/txt",
88 NULL
89};
1ba28e2b 90const char *pdkim_algos[] = {
80a47a2c
TK
91 "rsa-sha256",
92 "rsa-sha1",
93 NULL
94};
1ba28e2b 95const char *pdkim_canons[] = {
80a47a2c
TK
96 "simple",
97 "relaxed",
98 NULL
99};
1ba28e2b 100const char *pdkim_hashes[] = {
80a47a2c
TK
101 "sha256",
102 "sha1",
103 NULL
104};
1ba28e2b 105const char *pdkim_keytypes[] = {
80a47a2c
TK
106 "rsa",
107 NULL
108};
109
110typedef struct pdkim_combined_canon_entry {
1ba28e2b 111 const char *str;
80a47a2c
TK
112 int canon_headers;
113 int canon_body;
114} pdkim_combined_canon_entry;
f444c2c7 115
80a47a2c
TK
116pdkim_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 },
123 { NULL, 0, 0 }
124};
125
126
f444c2c7
JH
127/* -------------------------------------------------------------------------- */
128
129const char *
130pdkim_verify_status_str(int status)
131{
ff7ddfd7
TK
132 switch(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";
138 }
139}
f444c2c7
JH
140
141const char *
142pdkim_verify_ext_status_str(int ext_status)
143{
ff7ddfd7
TK
144 switch(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";
151 }
152}
153
154
80a47a2c
TK
155/* -------------------------------------------------------------------------- */
156/* Print debugging functions */
3045f050 157void
0d04a285 158pdkim_quoteprint(const char *data, int len, int lf)
3045f050
JH
159{
160int i;
161const unsigned char *p = (const unsigned char *)data;
162
0d04a285 163for (i = 0; i < len; i++)
3045f050
JH
164 {
165 const int c = p[i];
166 switch (c)
167 {
0d04a285
JH
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;
3045f050
JH
174 default:
175 if ( (c < 32) || (c > 127) )
0d04a285 176 debug_printf("{%02x}", c);
3045f050 177 else
0d04a285 178 debug_printf("%c", c);
80a47a2c
TK
179 break;
180 }
181 }
3045f050 182if (lf)
0d04a285 183 debug_printf("\n");
80a47a2c 184}
80a47a2c 185
3045f050 186void
0d04a285 187pdkim_hexprint(const char *data, int len, int lf)
3045f050
JH
188{
189int i;
190const unsigned char *p = (const unsigned char *)data;
191
0d04a285
JH
192for (i = 0 ; i < len; i++)
193 debug_printf("%02x", p[i]);
3045f050 194if (lf)
0d04a285 195 debug_printf("\n");
80a47a2c 196}
80a47a2c
TK
197
198
f444c2c7
JH
199
200/* String package: should be replaced by Exim standard ones */
201
202static pdkim_stringlist *
203pdkim_prepend_stringlist(pdkim_stringlist *base, char *str)
3045f050
JH
204{
205pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
206
207if (!new_entry) return NULL;
abe1010c 208memset(new_entry, 0, sizeof(pdkim_stringlist));
3045f050
JH
209if (!(new_entry->value = strdup(str))) return NULL;
210if (base)
211 {
212 pdkim_stringlist *last = base;
213 while (last->next != NULL) { last = last->next; }
214 last->next = new_entry;
215 return base;
97713345 216 }
3045f050 217else
97713345 218 return new_entry;
6ab02e3f 219}
80a47a2c
TK
220
221
222/* -------------------------------------------------------------------------- */
223/* A small "growing string" implementation to escape malloc/realloc hell */
3045f050 224
f444c2c7 225static pdkim_str *
3045f050
JH
226pdkim_strnew (const char *cstr)
227{
228unsigned int len = cstr ? strlen(cstr) : 0;
229pdkim_str *p = malloc(sizeof(pdkim_str));
230
231if (!p) return NULL;
abe1010c 232memset(p, 0, sizeof(pdkim_str));
3045f050
JH
233if (!(p->str = malloc(len+1)))
234 {
235 free(p);
236 return NULL;
80a47a2c 237 }
3045f050
JH
238p->allocated = len+1;
239p->len = len;
240if (cstr)
abe1010c 241 strcpy(p->str, cstr);
3045f050
JH
242else
243 p->str[p->len] = '\0';
244return p;
6ab02e3f 245}
3045f050 246
f444c2c7 247static char *
3045f050
JH
248pdkim_strncat(pdkim_str *str, const char *data, int len)
249{
250if ((str->allocated - str->len) < (len+1))
251 {
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;
257 str->str = n;
258 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
80a47a2c 259 }
3045f050
JH
260strncpy(&(str->str[str->len]), data, len);
261str->len += len;
262str->str[str->len] = '\0';
263return str->str;
6ab02e3f 264}
3045f050 265
f444c2c7 266static char *
3045f050
JH
267pdkim_strcat(pdkim_str *str, const char *cstr)
268{
269return pdkim_strncat(str, cstr, strlen(cstr));
6ab02e3f 270}
05b7d6de 271
f444c2c7 272static char *
3045f050
JH
273pdkim_strtrim(pdkim_str *str)
274{
275char *p = str->str;
276char *q = str->str;
277while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
278while (*p != '\0') {*q = *p; q++; p++;}
279*q = '\0';
280while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) )
281 {
80a47a2c 282 *q = '\0';
3045f050 283 q--;
80a47a2c 284 }
3045f050
JH
285str->len = strlen(str->str);
286return str->str;
6ab02e3f 287}
3045f050 288
f444c2c7 289static char *
3045f050
JH
290pdkim_strclear(pdkim_str *str)
291{
292str->str[0] = '\0';
293str->len = 0;
294return str->str;
6ab02e3f 295}
3045f050 296
f444c2c7 297static void
3045f050
JH
298pdkim_strfree(pdkim_str *str)
299{
300if (!str) return;
301if (str->str) free(str->str);
302free(str);
6ab02e3f 303}
80a47a2c
TK
304
305
306
307/* -------------------------------------------------------------------------- */
3045f050 308
f444c2c7 309static void
3045f050
JH
310pdkim_free_pubkey(pdkim_pubkey *pub)
311{
312if (pub)
313 {
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);
f4d091fb 320/* if (pub->key ) free(pub->key); */
3045f050 321 free(pub);
80a47a2c
TK
322 }
323}
324
325
326/* -------------------------------------------------------------------------- */
3045f050 327
f444c2c7 328static void
3045f050
JH
329pdkim_free_sig(pdkim_signature *sig)
330{
331if (sig)
332 {
333 pdkim_signature *next = (pdkim_signature *)sig->next;
334
335 pdkim_stringlist *e = sig->headers;
336 while(e)
337 {
338 pdkim_stringlist *c = e;
339 if (e->value) free(e->value);
340 e = e->next;
341 free(c);
80a47a2c
TK
342 }
343
3045f050
JH
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);
3045f050
JH
352
353 if (sig->pubkey) pdkim_free_pubkey(sig->pubkey);
354
355 free(sig);
356 if (next) pdkim_free_sig(next);
80a47a2c 357 }
6ab02e3f 358}
80a47a2c
TK
359
360
361/* -------------------------------------------------------------------------- */
3045f050
JH
362
363DLLEXPORT void
364pdkim_free_ctx(pdkim_ctx *ctx)
365{
366if (ctx)
367 {
368 pdkim_stringlist *e = ctx->headers;
369 while(e)
370 {
371 pdkim_stringlist *c = e;
372 if (e->value) free(e->value);
373 e = e->next;
374 free(c);
37f8b554 375 }
3045f050
JH
376 pdkim_free_sig(ctx->sig);
377 pdkim_strfree(ctx->cur_header);
378 free(ctx);
80a47a2c 379 }
6ab02e3f 380}
80a47a2c
TK
381
382
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
387 the list. */
3045f050 388
f444c2c7 389static int
3045f050 390header_name_match(const char *header,
1ba28e2b 391 char *tick,
3045f050
JH
392 int do_tick)
393{
394char *hname;
395char *lcopy;
396char *p;
397char *q;
398int rc = PDKIM_FAIL;
399
400/* Get header name */
abe1010c 401char *hcolon = strchr(header, ':');
3045f050
JH
402
403if (!hcolon) return rc; /* This isn't a header */
404
405if (!(hname = malloc((hcolon-header)+1)))
406 return PDKIM_ERR_OOM;
abe1010c
JH
407memset(hname, 0, (hcolon-header)+1);
408strncpy(hname, header, (hcolon-header));
3045f050
JH
409
410/* Copy tick-off list locally, so we can punch zeroes into it */
411if (!(lcopy = strdup(tick)))
412 {
413 free(hname);
414 return PDKIM_ERR_OOM;
80a47a2c 415 }
3045f050 416p = lcopy;
abe1010c 417q = strchr(p, ':');
3045f050
JH
418while (q)
419 {
420 *q = '\0';
80a47a2c 421
abe1010c 422 if (strcasecmp(p, hname) == 0)
3045f050
JH
423 {
424 rc = PDKIM_OK;
425 /* Invalidate header name instance in tick-off list */
426 if (do_tick) tick[p-lcopy] = '_';
427 goto BAIL;
80a47a2c
TK
428 }
429
3045f050 430 p = q+1;
abe1010c 431 q = strchr(p, ':');
80a47a2c
TK
432 }
433
abe1010c 434if (strcasecmp(p, hname) == 0)
3045f050
JH
435 {
436 rc = PDKIM_OK;
437 /* Invalidate header name instance in tick-off list */
438 if (do_tick) tick[p-lcopy] = '_';
80a47a2c
TK
439 }
440
3045f050
JH
441BAIL:
442free(hname);
443free(lcopy);
444return rc;
80a47a2c
TK
445}
446
447
448/* -------------------------------------------------------------------------- */
449/* Performs "relaxed" canonicalization of a header. The returned pointer needs
450 to be free()d. */
3045f050 451
f444c2c7 452static char *
3045f050
JH
453pdkim_relax_header (char *header, int crlf)
454{
455BOOL past_field_name = FALSE;
456BOOL seen_wsp = FALSE;
457char *p;
458char *q;
459char *relaxed = malloc(strlen(header)+3);
460
461if (!relaxed) return NULL;
462
463q = relaxed;
464for (p = header; *p != '\0'; p++)
465 {
466 int c = *p;
467 /* Ignore CR & LF */
468 if (c == '\r' || c == '\n')
469 continue;
470 if (c == '\t' || c == ' ')
471 {
472 if (seen_wsp)
80a47a2c 473 continue;
3045f050
JH
474 c = ' '; /* Turns WSP into SP */
475 seen_wsp = TRUE;
80a47a2c 476 }
3045f050
JH
477 else
478 if (!past_field_name && c == ':')
479 {
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;
80a47a2c 483 }
3045f050
JH
484 else
485 seen_wsp = FALSE;
486
487 /* Lowercase header name */
488 if (!past_field_name) c = tolower(c);
489 *q++ = c;
80a47a2c 490 }
3045f050
JH
491
492if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
493*q = '\0';
494
abe1010c 495if (crlf) strcat(relaxed, "\r\n");
3045f050 496return relaxed;
6ab02e3f 497}
80a47a2c
TK
498
499
500/* -------------------------------------------------------------------------- */
501#define PDKIM_QP_ERROR_DECODE -1
3045f050 502
a5840e10 503static char *
3045f050
JH
504pdkim_decode_qp_char(char *qp_p, int *c)
505{
506char *initial_pos = qp_p;
507
508/* Advance one char */
509qp_p++;
510
511/* Check for two hex digits and decode them */
512if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
513 {
514 /* Do hex conversion */
515 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
a5840e10 516 *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
3045f050 517 return qp_p + 2;
6ab02e3f 518 }
80a47a2c 519
3045f050
JH
520/* Illegal char here */
521*c = PDKIM_QP_ERROR_DECODE;
522return initial_pos;
80a47a2c
TK
523}
524
525
526/* -------------------------------------------------------------------------- */
3045f050 527
f444c2c7 528static char *
3045f050
JH
529pdkim_decode_qp(char *str)
530{
531int nchar = 0;
532char *q;
533char *p = str;
534char *n = malloc(strlen(p)+1);
535
536if (!n) return NULL;
537
538*n = '\0';
539q = n;
540while (*p != '\0')
541 {
542 if (*p == '=')
543 {
544 p = pdkim_decode_qp_char(p, &nchar);
545 if (nchar >= 0)
546 {
547 *q++ = nchar;
548 continue;
80a47a2c
TK
549 }
550 }
3045f050
JH
551 else
552 *q++ = *p;
553 p++;
80a47a2c 554 }
3045f050
JH
555*q = '\0';
556return n;
80a47a2c
TK
557}
558
559
560/* -------------------------------------------------------------------------- */
3045f050 561
f444c2c7 562static char *
3045f050
JH
563pdkim_decode_base64(char *str, int *num_decoded)
564{
565int dlen = 0;
566char *res;
f4d091fb 567int old_pool = store_pool;
3045f050 568
f4d091fb
JH
569/* There is a store-reset between header & body reception
570so cannot use the main pool */
3045f050 571
f4d091fb
JH
572store_pool = POOL_PERM;
573dlen = b64decode(US str, USS &res);
574store_pool = old_pool;
575
576if (dlen < 0) return NULL;
3045f050
JH
577
578if (num_decoded) *num_decoded = dlen;
579return res;
80a47a2c
TK
580}
581
3045f050 582
80a47a2c 583/* -------------------------------------------------------------------------- */
3045f050 584
f444c2c7 585static char *
3045f050
JH
586pdkim_encode_base64(char *str, int num)
587{
f4d091fb
JH
588char * ret;
589int old_pool = store_pool;
3045f050 590
f4d091fb
JH
591store_pool = POOL_PERM;
592ret = CS b64encode(US str, num);
593store_pool = old_pool;
594return ret;
80a47a2c
TK
595}
596
597
598/* -------------------------------------------------------------------------- */
599#define PDKIM_HDR_LIMBO 0
600#define PDKIM_HDR_TAG 1
601#define PDKIM_HDR_VALUE 2
3045f050 602
f444c2c7 603static pdkim_signature *
3045f050
JH
604pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr)
605{
606pdkim_signature *sig ;
abe1010c 607char *p, *q;
3045f050
JH
608pdkim_str *cur_tag = NULL;
609pdkim_str *cur_val = NULL;
610BOOL past_hname = FALSE;
611BOOL in_b_val = FALSE;
612int where = PDKIM_HDR_LIMBO;
613int i;
614
615if (!(sig = malloc(sizeof(pdkim_signature)))) return NULL;
abe1010c 616memset(sig, 0, sizeof(pdkim_signature));
3045f050
JH
617sig->bodylength = -1;
618
619if (!(sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1)))
620 {
621 free(sig);
622 return NULL;
80a47a2c
TK
623 }
624
3045f050 625q = sig->rawsig_no_b_val;
80a47a2c 626
3045f050
JH
627for (p = raw_hdr; ; p++)
628 {
629 char c = *p;
80a47a2c 630
3045f050
JH
631 /* Ignore FWS */
632 if (c == '\r' || c == '\n')
633 goto NEXT_CHAR;
80a47a2c 634
3045f050
JH
635 /* Fast-forward through header name */
636 if (!past_hname)
637 {
638 if (c == ':') past_hname = TRUE;
639 goto NEXT_CHAR;
80a47a2c
TK
640 }
641
3045f050
JH
642 if (where == PDKIM_HDR_LIMBO)
643 {
644 /* In limbo, just wait for a tag-char to appear */
645 if (!(c >= 'a' && c <= 'z'))
646 goto NEXT_CHAR;
80a47a2c 647
3045f050 648 where = PDKIM_HDR_TAG;
80a47a2c
TK
649 }
650
3045f050
JH
651 if (where == PDKIM_HDR_TAG)
652 {
653 if (!cur_tag)
654 cur_tag = pdkim_strnew(NULL);
80a47a2c 655
3045f050
JH
656 if (c >= 'a' && c <= 'z')
657 pdkim_strncat(cur_tag, p, 1);
80a47a2c 658
3045f050
JH
659 if (c == '=')
660 {
661 if (strcmp(cur_tag->str, "b") == 0)
662 {
663 *q = '='; q++;
664 in_b_val = TRUE;
665 }
666 where = PDKIM_HDR_VALUE;
667 goto NEXT_CHAR;
80a47a2c
TK
668 }
669 }
670
3045f050
JH
671 if (where == PDKIM_HDR_VALUE)
672 {
673 if (!cur_val)
674 cur_val = pdkim_strnew(NULL);
675
676 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
677 goto NEXT_CHAR;
678
679 if (c == ';' || c == '\0')
680 {
681 if (cur_tag->len > 0)
682 {
683 pdkim_strtrim(cur_val);
684
0d04a285 685 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
3045f050
JH
686
687 switch (cur_tag->str[0])
688 {
689 case 'b':
690 if (cur_tag->str[1] == 'h')
691 sig->bodyhash = pdkim_decode_base64(cur_val->str,
692 &sig->bodyhash_len);
693 else
694 sig->sigdata = pdkim_decode_base64(cur_val->str,
695 &sig->sigdata_len);
696 break;
697 case 'v':
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)
701 sig->version = 1;
702 break;
703 case 'a':
704 for (i = 0; pdkim_algos[i]; i++)
705 if (strcmp(cur_val->str, pdkim_algos[i]) == 0)
706 {
707 sig->algo = i;
708 break;
709 }
710 break;
711 case 'c':
712 for (i = 0; pdkim_combined_canons[i].str; i++)
713 if (strcmp(cur_val->str, pdkim_combined_canons[i].str) == 0)
714 {
715 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
716 sig->canon_body = pdkim_combined_canons[i].canon_body;
717 break;
718 }
719 break;
720 case 'q':
721 for (i = 0; pdkim_querymethods[i]; i++)
722 if (strcmp(cur_val->str, pdkim_querymethods[i]) == 0)
723 {
724 sig->querymethod = i;
725 break;
726 }
727 break;
728 case 's':
729 sig->selector = strdup(cur_val->str); break;
730 case 'd':
731 sig->domain = strdup(cur_val->str); break;
732 case 'i':
733 sig->identity = pdkim_decode_qp(cur_val->str); break;
734 case 't':
735 sig->created = strtoul(cur_val->str, NULL, 10); break;
736 case 'x':
737 sig->expires = strtoul(cur_val->str, NULL, 10); break;
738 case 'l':
739 sig->bodylength = strtol(cur_val->str, NULL, 10); break;
740 case 'h':
741 sig->headernames = strdup(cur_val->str); break;
742 case 'z':
743 sig->copiedheaders = pdkim_decode_qp(cur_val->str); break;
744 default:
0d04a285 745 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
3045f050
JH
746 break;
747 }
748 }
749 pdkim_strclear(cur_tag);
750 pdkim_strclear(cur_val);
751 in_b_val = FALSE;
752 where = PDKIM_HDR_LIMBO;
80a47a2c 753 }
3045f050
JH
754 else
755 pdkim_strncat(cur_val, p, 1);
80a47a2c
TK
756 }
757
3045f050
JH
758NEXT_CHAR:
759 if (c == '\0')
760 break;
80a47a2c 761
3045f050
JH
762 if (!in_b_val)
763 *q++ = c;
80a47a2c
TK
764 }
765
3045f050
JH
766/* Make sure the most important bits are there. */
767if (!(sig->domain && (*(sig->domain) != '\0') &&
768 sig->selector && (*(sig->selector) != '\0') &&
769 sig->headernames && (*(sig->headernames) != '\0') &&
770 sig->bodyhash &&
771 sig->sigdata &&
772 sig->version))
773 {
774 pdkim_free_sig(sig);
775 return NULL;
80a47a2c
TK
776 }
777
3045f050
JH
778*q = '\0';
779/* Chomp raw header. The final newline must not be added to the signature. */
780q--;
781while (q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
782 *q = '\0'; q--; /*XXX questionable code layout; possible bug */
80a47a2c 783
0d04a285 784DEBUG(D_acl)
3045f050 785 {
0d04a285 786 debug_printf(
3045f050 787 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
0d04a285
JH
788 pdkim_quoteprint(sig->rawsig_no_b_val, strlen(sig->rawsig_no_b_val), 1);
789 debug_printf(
abe1010c 790 "PDKIM >> Sig size: %4d bits\n", sig->sigdata_len*8);
0d04a285 791 debug_printf(
3045f050 792 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
80a47a2c 793 }
80a47a2c 794
cb224393 795#ifdef SHA_OPENSSL
80a47a2c 796
f444c2c7
JH
797SHA1_Init (&sig->sha1_body);
798SHA256_Init(&sig->sha2_body);
cb224393
JH
799
800#elif defined(SHA_GNUTLS)
801
802gnutls_hash_init(&sig->sha_body,
803 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
804
805#elif defined(SHA_POLARSSL)
806
807if ( !(sig->sha1_body = malloc(sizeof(sha1_context)))
808 || !(sig->sha2_body = malloc(sizeof(sha2_context)))
809 )
810 {
811 pdkim_free_sig(sig);
812 return NULL;
813 }
814
815sha1_starts(sig->sha1_body);
816sha2_starts(sig->sha2_body, 0);
817
818#endif /* SHA impl */
80a47a2c 819
3045f050 820return sig;
80a47a2c
TK
821}
822
823
824/* -------------------------------------------------------------------------- */
80a47a2c 825
f444c2c7 826static pdkim_pubkey *
3045f050
JH
827pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record)
828{
829pdkim_pubkey *pub;
830char *p;
831pdkim_str *cur_tag = NULL;
832pdkim_str *cur_val = NULL;
833int where = PDKIM_HDR_LIMBO;
80a47a2c 834
3045f050 835if (!(pub = malloc(sizeof(pdkim_pubkey)))) return NULL;
abe1010c 836memset(pub, 0, sizeof(pdkim_pubkey));
80a47a2c 837
3045f050
JH
838for (p = raw_record; ; p++)
839 {
840 char c = *p;
80a47a2c 841
3045f050
JH
842 /* Ignore FWS */
843 if (c == '\r' || c == '\n')
844 goto NEXT_CHAR;
80a47a2c 845
3045f050
JH
846 if (where == PDKIM_HDR_LIMBO)
847 {
848 /* In limbo, just wait for a tag-char to appear */
849 if (!(c >= 'a' && c <= 'z'))
850 goto NEXT_CHAR;
80a47a2c 851
3045f050 852 where = PDKIM_HDR_TAG;
80a47a2c
TK
853 }
854
3045f050
JH
855 if (where == PDKIM_HDR_TAG)
856 {
857 if (!cur_tag)
858 cur_tag = pdkim_strnew(NULL);
80a47a2c 859
3045f050
JH
860 if (c >= 'a' && c <= 'z')
861 pdkim_strncat(cur_tag, p, 1);
80a47a2c 862
3045f050
JH
863 if (c == '=')
864 {
865 where = PDKIM_HDR_VALUE;
866 goto NEXT_CHAR;
80a47a2c
TK
867 }
868 }
869
3045f050
JH
870 if (where == PDKIM_HDR_VALUE)
871 {
872 if (!cur_val)
873 cur_val = pdkim_strnew(NULL);
874
875 if (c == '\r' || c == '\n')
876 goto NEXT_CHAR;
877
878 if (c == ';' || c == '\0')
879 {
880 if (cur_tag->len > 0)
881 {
882 pdkim_strtrim(cur_val);
0d04a285 883 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->str, cur_val->str);
3045f050
JH
884
885 switch (cur_tag->str[0])
886 {
887 case 'v':
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. */
892 break;
893 case 'h':
894 pub->hashes = strdup(cur_val->str); break;
895 case 'g':
896 pub->granularity = strdup(cur_val->str); break;
897 case 'n':
898 pub->notes = pdkim_decode_qp(cur_val->str); break;
899 case 'p':
900 pub->key = pdkim_decode_base64(cur_val->str, &(pub->key_len)); break;
901 case 'k':
902 pub->hashes = strdup(cur_val->str); break;
903 case 's':
904 pub->srvtype = strdup(cur_val->str); break;
905 case 't':
abe1010c
JH
906 if (strchr(cur_val->str, 'y') != NULL) pub->testing = 1;
907 if (strchr(cur_val->str, 's') != NULL) pub->no_subdomaining = 1;
3045f050
JH
908 break;
909 default:
0d04a285 910 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
3045f050
JH
911 break;
912 }
913 }
914 pdkim_strclear(cur_tag);
915 pdkim_strclear(cur_val);
916 where = PDKIM_HDR_LIMBO;
80a47a2c 917 }
3045f050
JH
918 else
919 pdkim_strncat(cur_val, p, 1);
80a47a2c
TK
920 }
921
3045f050
JH
922NEXT_CHAR:
923 if (c == '\0') break;
80a47a2c
TK
924 }
925
3045f050
JH
926/* Set fallback defaults */
927if (!pub->version ) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
928if (!pub->granularity) pub->granularity = strdup("*");
929if (!pub->keytype ) pub->keytype = strdup("rsa");
930if (!pub->srvtype ) pub->srvtype = strdup("*");
80a47a2c 931
3045f050
JH
932/* p= is required */
933if (pub->key)
80a47a2c 934 return pub;
3045f050
JH
935
936pdkim_free_pubkey(pub);
937return NULL;
80a47a2c
TK
938}
939
940
941/* -------------------------------------------------------------------------- */
3045f050 942
f444c2c7 943static int
3045f050
JH
944pdkim_update_bodyhash(pdkim_ctx *ctx, const char *data, int len)
945{
946pdkim_signature *sig = ctx->sig;
947/* Cache relaxed version of data */
948char *relaxed_data = NULL;
949int relaxed_len = 0;
950
951/* Traverse all signatures, updating their hashes. */
952while (sig)
953 {
954 /* Defaults to simple canon (no further treatment necessary) */
955 const char *canon_data = data;
956 int canon_len = len;
957
958 if (sig->canon_body == PDKIM_CANON_RELAXED)
959 {
960 /* Relax the line if not done already */
961 if (!relaxed_data)
962 {
963 BOOL seen_wsp = FALSE;
964 const char *p;
965 int q = 0;
966
967 if (!(relaxed_data = malloc(len+1)))
968 return PDKIM_ERR_OOM;
969
970 for (p = data; *p; p++)
971 {
972 char c = *p;
973 if (c == '\r')
974 {
975 if (q > 0 && relaxed_data[q-1] == ' ')
976 q--;
977 }
978 else if (c == '\t' || c == ' ')
979 {
980 c = ' '; /* Turns WSP into SP */
981 if (seen_wsp)
982 continue;
983 seen_wsp = TRUE;
984 }
985 else
986 seen_wsp = FALSE;
987 relaxed_data[q++] = c;
988 }
989 relaxed_data[q] = '\0';
990 relaxed_len = q;
80a47a2c 991 }
3045f050
JH
992 canon_data = relaxed_data;
993 canon_len = relaxed_len;
80a47a2c
TK
994 }
995
3045f050
JH
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
999 )
1000 canon_len = sig->bodylength - sig->signed_body_bytes;
80a47a2c 1001
3045f050
JH
1002 if (canon_len > 0)
1003 {
cb224393 1004#ifdef SHA_GNUTLS
f444c2c7
JH
1005 gnutls_hash(sig->sha_body, canon_data, canon_len);
1006#else
3045f050 1007 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1008# ifdef SHA_OPENSSL
f444c2c7 1009 SHA1_Update (&sig->sha1_body, canon_data, canon_len);
3045f050 1010 else
f444c2c7 1011 SHA256_Update(&sig->sha2_body, canon_data, canon_len);
cb224393
JH
1012# elif defined(SHA_POLARSSL)
1013 sha1_update(sig->sha1_body, US canon_data, canon_len);
1014 else
1015 sha2_update(sig->sha2_body, US canon_data, canon_len);
1016# endif
f444c2c7 1017#endif
3045f050
JH
1018
1019 sig->signed_body_bytes += canon_len;
0d04a285 1020 DEBUG(D_acl) pdkim_quoteprint(canon_data, canon_len, 1);
80a47a2c
TK
1021 }
1022
3045f050 1023 sig = sig->next;
80a47a2c
TK
1024 }
1025
3045f050
JH
1026if (relaxed_data) free(relaxed_data);
1027return PDKIM_OK;
6ab02e3f 1028}
80a47a2c
TK
1029
1030
1031/* -------------------------------------------------------------------------- */
80a47a2c 1032
f444c2c7 1033static int
3045f050
JH
1034pdkim_finish_bodyhash(pdkim_ctx *ctx)
1035{
f4d091fb 1036pdkim_signature *sig;
80a47a2c 1037
3045f050 1038/* Traverse all signatures */
f4d091fb 1039for (sig = ctx->sig; sig; sig = sig->next)
3045f050 1040 { /* Finish hashes */
f444c2c7 1041 uschar bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
3045f050 1042
cb224393 1043#ifdef SHA_GNUTLS
f444c2c7
JH
1044 gnutls_hash_output(sig->sha_body, bh);
1045#else
3045f050 1046 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1047# ifdef SHA_OPENSSL
f444c2c7 1048 SHA1_Final (bh, &sig->sha1_body);
3045f050 1049 else
f444c2c7 1050 SHA256_Final(bh, &sig->sha2_body);
cb224393
JH
1051# elif defined(SHA_POLARSSL)
1052 sha1_finish(sig->sha1_body, bh);
1053 else
1054 sha2_finish(sig->sha2_body, bh);
1055# endif
f444c2c7 1056#endif
3045f050 1057
0d04a285 1058 DEBUG(D_acl)
3045f050 1059 {
0d04a285
JH
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);
80a47a2c 1064 }
3045f050
JH
1065
1066 /* SIGNING -------------------------------------------------------------- */
1067 if (ctx->mode == PDKIM_MODE_SIGN)
1068 {
f444c2c7 1069 sig->bodyhash_len = sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32;
f4d091fb 1070 sig->bodyhash = string_copyn(US bh, sig->bodyhash_len);
3045f050
JH
1071
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;
80a47a2c 1076 }
3045f050
JH
1077
1078 /* VERIFICATION --------------------------------------------------------- */
1079 else
1080 {
1081 /* Compare bodyhash */
1082 if (memcmp(bh, sig->bodyhash,
1083 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0)
1084 {
0d04a285 1085 DEBUG(D_acl) debug_printf("PDKIM [%s] Body hash verified OK\n", sig->domain);
80a47a2c 1086 }
3045f050
JH
1087 else
1088 {
0d04a285 1089 DEBUG(D_acl)
3045f050 1090 {
0d04a285
JH
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);
3045f050 1095 }
3045f050
JH
1096 sig->verify_status = PDKIM_VERIFY_FAIL;
1097 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
80a47a2c
TK
1098 }
1099 }
80a47a2c
TK
1100 }
1101
3045f050 1102return PDKIM_OK;
6ab02e3f 1103}
80a47a2c
TK
1104
1105
1106
1107/* -------------------------------------------------------------------------- */
1108/* Callback from pdkim_feed below for processing complete body lines */
3045f050 1109
0d04a285 1110static int
3045f050
JH
1111pdkim_bodyline_complete(pdkim_ctx *ctx)
1112{
1113char *p = ctx->linebuf;
1114int n = ctx->linebuf_offset;
c14470c3 1115pdkim_signature *sig = ctx->sig; /*XXX assumes only one sig */
3045f050
JH
1116
1117/* Ignore extra data if we've seen the end-of-data marker */
1118if (ctx->seen_eod) goto BAIL;
1119
1120/* We've always got one extra byte to stuff a zero ... */
0d04a285 1121ctx->linebuf[ctx->linebuf_offset] = '\0';
3045f050 1122
0d04a285
JH
1123/* Terminate on EOD marker */
1124if (memcmp(p, ".\r\n", 3) == 0)
3045f050 1125 {
0d04a285
JH
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
1134 )
1135 pdkim_update_bodyhash(ctx, "\r\n", 2);
1136
1137 ctx->seen_eod = TRUE;
1138 goto BAIL;
1139 }
1140/* Unstuff dots */
1141if (memcmp(p, "..", 2) == 0)
1142 {
1143 p++;
1144 n--;
80a47a2c
TK
1145 }
1146
3045f050
JH
1147/* Empty lines need to be buffered until we find a non-empty line */
1148if (memcmp(p, "\r\n", 2) == 0)
1149 {
1150 ctx->num_buffered_crlf++;
1151 goto BAIL;
80a47a2c
TK
1152 }
1153
c14470c3 1154if (sig && sig->canon_body == PDKIM_CANON_RELAXED)
3045f050
JH
1155 {
1156 /* Lines with just spaces need to be buffered too */
1157 char *check = p;
1158 while (memcmp(check, "\r\n", 2) != 0)
1159 {
1160 char c = *check;
6a11a9e6 1161
3045f050
JH
1162 if (c != '\t' && c != ' ')
1163 goto PROCESS;
1164 check++;
6a11a9e6
JH
1165 }
1166
3045f050
JH
1167 ctx->num_buffered_crlf++;
1168 goto BAIL;
1169}
6a11a9e6 1170
3045f050
JH
1171PROCESS:
1172/* At this point, we have a non-empty line, so release the buffered ones. */
1173while (ctx->num_buffered_crlf)
1174 {
1175 pdkim_update_bodyhash(ctx, "\r\n", 2);
1176 ctx->num_buffered_crlf--;
80a47a2c
TK
1177 }
1178
3045f050 1179pdkim_update_bodyhash(ctx, p, n);
80a47a2c 1180
3045f050
JH
1181BAIL:
1182ctx->linebuf_offset = 0;
1183return PDKIM_OK;
80a47a2c
TK
1184}
1185
1186
1187/* -------------------------------------------------------------------------- */
1188/* Callback from pdkim_feed below for processing complete headers */
1189#define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
3045f050 1190
f444c2c7 1191static int
3045f050
JH
1192pdkim_header_complete(pdkim_ctx *ctx)
1193{
3045f050
JH
1194/* Special case: The last header can have an extra \r appended */
1195if ( (ctx->cur_header->len > 1) &&
1196 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') )
1197 {
1198 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
1199 ctx->cur_header->len--;
80a47a2c
TK
1200 }
1201
3045f050
JH
1202ctx->num_headers++;
1203if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
80a47a2c 1204
3045f050
JH
1205/* SIGNING -------------------------------------------------------------- */
1206if (ctx->mode == PDKIM_MODE_SIGN)
0d04a285
JH
1207 {
1208 pdkim_signature *sig;
1209
1210 for (sig = ctx->sig; sig; sig = sig->next) /* Traverse all signatures */
3045f050
JH
1211 if (header_name_match(ctx->cur_header->str,
1212 sig->sign_headers?
1213 sig->sign_headers:
1214 PDKIM_DEFAULT_SIGN_HEADERS, 0) == PDKIM_OK)
1215 {
37f8b554 1216 pdkim_stringlist *list;
80a47a2c 1217
37f8b554 1218 /* Add header to the signed headers list (in reverse order) */
3045f050
JH
1219 if (!(list = pdkim_prepend_stringlist(sig->headers,
1220 ctx->cur_header->str)))
1221 return PDKIM_ERR_OOM;
37f8b554 1222 sig->headers = list;
3045f050 1223 }
0d04a285 1224 }
94431adb 1225
0d04a285 1226/* VERIFICATION ----------------------------------------------------------- */
3045f050
JH
1227/* DKIM-Signature: headers are added to the verification list */
1228if (ctx->mode == PDKIM_MODE_VERIFY)
1229 {
1230 if (strncasecmp(ctx->cur_header->str,
1231 DKIM_SIGNATURE_HEADERNAME,
1232 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
1233 {
1234 pdkim_signature *new_sig;
80a47a2c 1235
3045f050 1236 /* Create and chain new signature block */
0d04a285 1237 DEBUG(D_acl) debug_printf(
3045f050 1238 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
3045f050
JH
1239
1240 if ((new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str)))
1241 {
1242 pdkim_signature *last_sig = ctx->sig;
1243 if (!last_sig)
1244 ctx->sig = new_sig;
1245 else
1246 {
1247 while (last_sig->next) last_sig = last_sig->next;
1248 last_sig->next = new_sig;
1249 }
80a47a2c 1250 }
abe1010c 1251 else
0d04a285
JH
1252 DEBUG(D_acl) debug_printf(
1253 "Error while parsing signature header\n"
3045f050 1254 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
80a47a2c 1255 }
37f8b554 1256
3045f050
JH
1257 /* every other header is stored for signature verification */
1258 else
1259 {
1260 pdkim_stringlist *list;
1261
abe1010c 1262 if (!(list = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->str)))
3045f050
JH
1263 return PDKIM_ERR_OOM;
1264 ctx->headers = list;
80a47a2c
TK
1265 }
1266 }
1267
3045f050
JH
1268BAIL:
1269pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1270return PDKIM_OK;
6ab02e3f 1271}
80a47a2c
TK
1272
1273
1274
1275/* -------------------------------------------------------------------------- */
1276#define HEADER_BUFFER_FRAG_SIZE 256
3045f050
JH
1277
1278DLLEXPORT int
1279pdkim_feed (pdkim_ctx *ctx, char *data, int len)
1280{
1281int p;
1282
1283for (p = 0; p<len; p++)
1284 {
1285 char c = data[p];
1286
1287 if (ctx->past_headers)
1288 {
1289 /* Processing body byte */
0d04a285 1290 ctx->linebuf[ctx->linebuf_offset++] = c;
3045f050
JH
1291 if (c == '\n')
1292 {
1293 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1294 if (rc != PDKIM_OK) return rc;
80a47a2c 1295 }
3045f050
JH
1296 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1297 return PDKIM_ERR_LONG_LINE;
80a47a2c 1298 }
3045f050
JH
1299 else
1300 {
1301 /* Processing header byte */
1302 if (c != '\r')
1303 {
1304 if (c == '\n')
1305 {
1306 if (ctx->seen_lf)
1307 {
1308 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1309 if (rc != PDKIM_OK) return rc;
1310
0d04a285 1311 ctx->past_headers = TRUE;
3045f050 1312 ctx->seen_lf = 0;
0d04a285 1313 DEBUG(D_acl) debug_printf(
3045f050 1314 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
3045f050
JH
1315 continue;
1316 }
1317 else
0d04a285 1318 ctx->seen_lf = TRUE;
3045f050
JH
1319 }
1320 else if (ctx->seen_lf)
1321 {
1322 if (!(c == '\t' || c == ' '))
1323 {
1324 int rc = pdkim_header_complete(ctx); /* End of header */
1325 if (rc != PDKIM_OK) return rc;
1326 }
0d04a285 1327 ctx->seen_lf = FALSE;
3045f050 1328 }
80a47a2c 1329 }
3045f050
JH
1330
1331 if (!ctx->cur_header)
1332 if (!(ctx->cur_header = pdkim_strnew(NULL)))
1333 return PDKIM_ERR_OOM;
1334
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;
80a47a2c
TK
1338 }
1339 }
3045f050 1340return PDKIM_OK;
6ab02e3f 1341}
80a47a2c 1342
05b7d6de
JB
1343/*
1344 * RFC 5322 specifies that header line length SHOULD be no more than 78
1345 * lets make it so!
1346 * pdkim_headcat
1347 * returns char*
1348 *
1349 * col: this int holds and receives column number (octets since last '\n')
1350 * str: partial string to append to
94431adb 1351 * pad: padding, split line or space after before or after eg: ";"
05b7d6de
JB
1352 * intro: - must join to payload eg "h=", usually the tag name
1353 * payload: eg base64 data - long data can be split arbitrarily.
1354 *
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
94431adb 1358 * "pad"
05b7d6de
JB
1359 *
1360 * no guarantees are made for output given out-of range input. like tag
f444c2c7 1361 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
05b7d6de
JB
1362 */
1363
3045f050
JH
1364static char *
1365pdkim_headcat(int *col, pdkim_str *str, const char * pad,
1366 const char *intro, const char *payload)
1367{
1368size_t l;
1369
1370if (pad)
05b7d6de 1371 {
3045f050
JH
1372 l = strlen(pad);
1373 if (*col + l > 78)
05b7d6de 1374 {
3045f050
JH
1375 pdkim_strcat(str, "\r\n\t");
1376 *col = 1;
05b7d6de 1377 }
3045f050
JH
1378 pdkim_strncat(str, pad, l);
1379 *col += l;
05b7d6de
JB
1380 }
1381
3045f050 1382l = (pad?1:0) + (intro?strlen(intro):0);
05b7d6de 1383
3045f050 1384if (*col + l > 78)
05b7d6de 1385 { /*can't fit intro - start a new line to make room.*/
3045f050
JH
1386 pdkim_strcat(str, "\r\n\t");
1387 *col = 1;
1388 l = intro?strlen(intro):0;
05b7d6de
JB
1389 }
1390
3045f050 1391l += payload ? strlen(payload):0 ;
05b7d6de 1392
3045f050 1393while (l>77)
05b7d6de 1394 { /* this fragment will not fit on a single line */
3045f050 1395 if (pad)
05b7d6de 1396 {
3045f050
JH
1397 pdkim_strcat(str, " ");
1398 *col += 1;
1399 pad = NULL; /* only want this once */
1400 l--;
05b7d6de 1401 }
3045f050
JH
1402
1403 if (intro)
05b7d6de 1404 {
3045f050
JH
1405 size_t sl = strlen(intro);
1406
abe1010c 1407 pdkim_strncat(str, intro, sl);
3045f050
JH
1408 *col += sl;
1409 l -= sl;
1410 intro = NULL; /* only want this once */
05b7d6de 1411 }
3045f050
JH
1412
1413 if (payload)
05b7d6de 1414 {
3045f050
JH
1415 size_t sl = strlen(payload);
1416 size_t chomp = *col+sl < 77 ? sl : 78-*col;
1417
abe1010c 1418 pdkim_strncat(str, payload, chomp);
3045f050
JH
1419 *col += chomp;
1420 payload += chomp;
1421 l -= chomp-1;
05b7d6de 1422 }
3045f050
JH
1423
1424 /* the while precondition tells us it didn't fit. */
1425 pdkim_strcat(str, "\r\n\t");
1426 *col = 1;
05b7d6de 1427 }
3045f050
JH
1428
1429if (*col + l > 78)
05b7d6de 1430 {
3045f050
JH
1431 pdkim_strcat(str, "\r\n\t");
1432 *col = 1;
1433 pad = NULL;
05b7d6de
JB
1434 }
1435
3045f050 1436if (pad)
05b7d6de 1437 {
3045f050
JH
1438 pdkim_strcat(str, " ");
1439 *col += 1;
1440 pad = NULL;
05b7d6de
JB
1441 }
1442
3045f050 1443if (intro)
05b7d6de 1444 {
3045f050
JH
1445 size_t sl = strlen(intro);
1446
1447 pdkim_strncat(str, intro, sl);
1448 *col += sl;
1449 l -= sl;
1450 intro = NULL;
05b7d6de 1451 }
3045f050
JH
1452
1453if (payload)
05b7d6de 1454 {
3045f050
JH
1455 size_t sl = strlen(payload);
1456
1457 pdkim_strncat(str, payload, sl);
1458 *col += sl;
05b7d6de
JB
1459 }
1460
3045f050 1461return str->str;
05b7d6de 1462}
80a47a2c 1463
3045f050 1464
80a47a2c 1465/* -------------------------------------------------------------------------- */
3045f050 1466
f444c2c7 1467static char *
3045f050
JH
1468pdkim_create_header(pdkim_signature *sig, int final)
1469{
1470char *rc = NULL;
1471char *base64_bh = NULL;
1472char *base64_b = NULL;
1473int col = 0;
1474pdkim_str *hdr;
1475pdkim_str *canon_all;
1476
1477if (!(hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION)))
1478 return NULL;
1479
1480if (!(canon_all = pdkim_strnew(pdkim_canons[sig->canon_headers])))
1481 goto BAIL;
1482
1483if (!(base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len)))
1484 goto BAIL;
1485
1486col = strlen(hdr->str);
1487
1488/* Required and static bits */
abe1010c
JH
1489if ( 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)
3045f050
JH
1496 )
1497 {
1498 /* list of eader names can be split between items. */
05b7d6de 1499 {
3045f050
JH
1500 char *n = strdup(sig->headernames);
1501 char *f = n;
1502 char *i = "h=";
1503 char *s = ";";
1504
1505 if (!n) goto BAIL;
1506 while (*n)
05b7d6de 1507 {
abe1010c 1508 char *c = strchr(n, ':');
05b7d6de 1509
3045f050 1510 if (c) *c ='\0';
05b7d6de 1511
3045f050 1512 if (!i)
abe1010c 1513 if (!pdkim_headcat(&col, hdr, NULL, NULL, ":"))
3045f050
JH
1514 {
1515 free(f);
1516 goto BAIL;
1517 }
1518
abe1010c 1519 if (!pdkim_headcat(&col, hdr, s, i, n))
3045f050
JH
1520 {
1521 free(f);
1522 goto BAIL;
1523 }
1524
1525 if (!c)
1526 break;
1527
1528 n = c+1;
1529 s = NULL;
1530 i = NULL;
80a47a2c 1531 }
3045f050 1532 free(f);
80a47a2c 1533 }
05b7d6de 1534
3045f050
JH
1535 if(!pdkim_headcat(&col, hdr, ";", "bh=", base64_bh))
1536 goto BAIL;
1537
1538 /* Optional bits */
1539 if (sig->identity)
1540 if(!pdkim_headcat(&col, hdr, ";", "i=", sig->identity))
1541 goto BAIL;
1542
1543 if (sig->created > 0)
1544 {
1545 char minibuf[20];
1546
abe1010c 1547 snprintf(minibuf, 20, "%lu", sig->created);
3045f050
JH
1548 if(!pdkim_headcat(&col, hdr, ";", "t=", minibuf))
1549 goto BAIL;
1550 }
1551
1552 if (sig->expires > 0)
1553 {
1554 char minibuf[20];
1555
abe1010c 1556 snprintf(minibuf, 20, "%lu", sig->expires);
3045f050
JH
1557 if(!pdkim_headcat(&col, hdr, ";", "x=", minibuf))
1558 goto BAIL;
80a47a2c 1559 }
3045f050
JH
1560
1561 if (sig->bodylength >= 0)
1562 {
1563 char minibuf[20];
1564
abe1010c 1565 snprintf(minibuf, 20, "%lu", sig->bodylength);
3045f050
JH
1566 if(!pdkim_headcat(&col, hdr, ";", "l=", minibuf))
1567 goto BAIL;
80a47a2c
TK
1568 }
1569
3045f050
JH
1570 /* Preliminary or final version? */
1571 if (final)
1572 {
1573 if (!(base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len)))
1574 goto BAIL;
1575 if (!pdkim_headcat(&col, hdr, ";", "b=", base64_b))
1576 goto BAIL;
1577 }
1578 else
1579 if(!pdkim_headcat(&col, hdr, ";", "b=", ""))
1580 goto BAIL;
05b7d6de 1581
3045f050 1582 /* add trailing semicolon: I'm not sure if this is actually needed */
abe1010c 1583 if (!pdkim_headcat(&col, hdr, NULL, ";", ""))
3045f050 1584 goto BAIL;
80a47a2c
TK
1585 }
1586
3045f050 1587rc = strdup(hdr->str);
80a47a2c 1588
3045f050
JH
1589BAIL:
1590pdkim_strfree(hdr);
1591if (canon_all) pdkim_strfree(canon_all);
3045f050 1592return rc;
80a47a2c
TK
1593}
1594
1595
1596/* -------------------------------------------------------------------------- */
3045f050
JH
1597
1598DLLEXPORT int
1599pdkim_feed_finish(pdkim_ctx *ctx, pdkim_signature **return_signatures)
1600{
1601pdkim_signature *sig = ctx->sig;
1602pdkim_str *headernames = NULL; /* Collected signed header names */
1603
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>' */
1607if (ctx->cur_header && ctx->cur_header->len)
1608 {
1609 int rc = pdkim_header_complete(ctx);
1610 if (rc != PDKIM_OK) return rc;
1611 pdkim_update_bodyhash(ctx, "\r\n", 2);
80a47a2c 1612 }
3045f050 1613else
0d04a285 1614 DEBUG(D_acl) debug_printf(
3045f050 1615 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
80a47a2c 1616
3045f050
JH
1617/* Build (and/or evaluate) body hash */
1618if (pdkim_finish_bodyhash(ctx) != PDKIM_OK)
1619 return PDKIM_ERR_OOM;
80a47a2c 1620
3045f050
JH
1621/* SIGNING -------------------------------------------------------------- */
1622if (ctx->mode == PDKIM_MODE_SIGN)
1623 if (!(headernames = pdkim_strnew(NULL)))
1624 return PDKIM_ERR_OOM;
1625/* ---------------------------------------------------------------------- */
80a47a2c 1626
3045f050
JH
1627while (sig)
1628 {
cb224393 1629#ifdef SHA_OPENSSL
f444c2c7
JH
1630 SHA_CTX sha1_headers;
1631 SHA256_CTX sha2_headers;
cb224393
JH
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;
f444c2c7 1637#endif
cb224393 1638
3045f050
JH
1639 char *sig_hdr;
1640 char headerhash[32];
80a47a2c 1641
cb224393
JH
1642#ifdef RSA_GNUTLS
1643 uschar * hdata = NULL;
1644 int hdata_alloc = 0;
1645 int hdata_size = 0;
1646#endif
1647
1648#ifdef SHA_GNUTLS
f444c2c7
JH
1649 gnutls_hash_init(&sha_headers,
1650 sig->algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
1651#else
3045f050 1652 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1653# ifdef SHA_OPENSSL
f444c2c7 1654 SHA1_Init(&sha1_headers);
3045f050 1655 else
f444c2c7 1656 SHA256_Init(&sha2_headers);
cb224393
JH
1657# elif defined(SHA_POLARSSL)
1658 sha1_starts(&sha1_headers);
1659 else
1660 sha2_starts(&sha2_headers, 0);
1661# endif
f444c2c7 1662#endif
80a47a2c 1663
0d04a285
JH
1664 DEBUG(D_acl) debug_printf(
1665 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
3045f050
JH
1666
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. */
1670
1671 if (ctx->mode == PDKIM_MODE_SIGN)
1672 {
1673 pdkim_stringlist *p;
1674
1675 for (p = sig->headers; p; p = p->next)
1676 {
1677 char *rh = NULL;
1678 /* Collect header names (Note: colon presence is guaranteed here) */
abe1010c 1679 char *q = strchr(p->value, ':');
3045f050
JH
1680
1681 if (!(pdkim_strncat(headernames, p->value,
1682 (q-(p->value)) + (p->next ? 1 : 0))))
1683 return PDKIM_ERR_OOM;
1684
1685 rh = sig->canon_headers == PDKIM_CANON_RELAXED
abe1010c 1686 ? pdkim_relax_header(p->value, 1) /* cook header for relaxed canon */
3045f050
JH
1687 : strdup(p->value); /* just copy it for simple canon */
1688 if (!rh)
1689 return PDKIM_ERR_OOM;
1690
1691 /* Feed header to the hash algorithm */
cb224393 1692#ifdef SHA_GNUTLS
f444c2c7
JH
1693 gnutls_hash(sha_headers, rh, strlen(rh));
1694#else
3045f050 1695 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1696# ifdef SHA_OPENSSL
f444c2c7 1697 SHA1_Update (&sha1_headers, rh, strlen(rh));
3045f050 1698 else
f444c2c7 1699 SHA256_Update(&sha2_headers, rh, strlen(rh));
cb224393
JH
1700# elif defined(SHA_POLARSSL)
1701 sha1_update(&sha1_headers, US rh, strlen(rh));
1702 else
1703 sha2_update(&sha2_headers, US rh, strlen(rh));
1704# endif
f444c2c7
JH
1705#endif
1706
cb224393 1707#ifdef RSA_GNUTLS
f444c2c7
JH
1708 /* Remember headers block for signing */
1709 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, rh);
1710#endif
3045f050 1711
0d04a285 1712 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
3045f050 1713 free(rh);
80a47a2c
TK
1714 }
1715 }
37f8b554 1716
3045f050
JH
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. */
1720 else
1721 {
1722 char *b = strdup(sig->headernames);
1723 char *p = b;
1724 char *q = NULL;
1725 pdkim_stringlist *hdrs;
1726
1727 if (!b) return PDKIM_ERR_OOM;
1728
1729 /* clear tags */
1730 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1731 hdrs->tag = 0;
1732
1733 while(1)
1734 {
abe1010c 1735 if ((q = strchr(p, ':')))
3045f050
JH
1736 *q = '\0';
1737
1738 for (hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1739 if ( hdrs->tag == 0
abe1010c 1740 && strncasecmp(hdrs->value, p, strlen(p)) == 0
3045f050
JH
1741 && (hdrs->value)[strlen(p)] == ':'
1742 )
1743 {
1744 char *rh;
1745
1746 rh = sig->canon_headers == PDKIM_CANON_RELAXED
abe1010c 1747 ? pdkim_relax_header(hdrs->value, 1) /* cook header for relaxed canon */
3045f050
JH
1748 : strdup(hdrs->value); /* just copy it for simple canon */
1749 if (!rh)
1750 return PDKIM_ERR_OOM;
1751
1752 /* Feed header to the hash algorithm */
cb224393 1753#ifdef SHA_GNUTLS
f444c2c7
JH
1754 gnutls_hash(sha_headers, rh, strlen(rh));
1755#else
3045f050 1756 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1757# ifdef SHA_OPENSSL
f444c2c7 1758 SHA1_Update (&sha1_headers, rh, strlen(rh));
3045f050 1759 else
f444c2c7 1760 SHA256_Update(&sha2_headers, rh, strlen(rh));
cb224393
JH
1761# elif defined(SHA_POLARSSL)
1762 sha1_update(&sha1_headers, US rh, strlen(rh));
1763 else
1764 sha2_update(&sha2_headers, US rh, strlen(rh));
1765# endif
f444c2c7 1766#endif
3045f050 1767
0d04a285 1768 DEBUG(D_acl) pdkim_quoteprint(rh, strlen(rh), 1);
3045f050
JH
1769 free(rh);
1770 hdrs->tag = 1;
1771 break;
1772 }
1773
1774 if (!q) break;
1775 p = q+1;
80a47a2c 1776 }
3045f050 1777 free(b);
80a47a2c
TK
1778 }
1779
0d04a285 1780 DEBUG(D_acl) debug_printf(
3045f050 1781 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
80a47a2c 1782
3045f050
JH
1783 /* SIGNING ---------------------------------------------------------------- */
1784 if (ctx->mode == PDKIM_MODE_SIGN)
1785 {
1786 /* Copy headernames to signature struct */
1787 sig->headernames = strdup(headernames->str);
1788 pdkim_strfree(headernames);
80a47a2c 1789
3045f050
JH
1790 /* Create signature header with b= omitted */
1791 sig_hdr = pdkim_create_header(ctx->sig, 0);
80a47a2c 1792 }
80a47a2c 1793
3045f050
JH
1794 /* VERIFICATION ----------------------------------------------------------- */
1795 else
1796 sig_hdr = strdup(sig->rawsig_no_b_val);
1797 /* ------------------------------------------------------------------------ */
1798
1799 if (!sig_hdr)
1800 return PDKIM_ERR_OOM;
80a47a2c 1801
3045f050
JH
1802 /* Relax header if necessary */
1803 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1804 {
1805 char *relaxed_hdr = pdkim_relax_header(sig_hdr, 0);
1806
1807 free(sig_hdr);
1808 if (!relaxed_hdr)
1809 return PDKIM_ERR_OOM;
1810 sig_hdr = relaxed_hdr;
80a47a2c
TK
1811 }
1812
0d04a285 1813 DEBUG(D_acl)
3045f050 1814 {
0d04a285 1815 debug_printf(
3045f050 1816 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
0d04a285
JH
1817 pdkim_quoteprint(sig_hdr, strlen(sig_hdr), 1);
1818 debug_printf(
3045f050 1819 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
80a47a2c 1820 }
3045f050
JH
1821
1822 /* Finalize header hash */
cb224393 1823#ifdef SHA_GNUTLS
f444c2c7
JH
1824 gnutls_hash(sha_headers, sig_hdr, strlen(sig_hdr));
1825 gnutls_hash_output(sha_headers, headerhash);
1826#else
3045f050 1827 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
cb224393 1828# ifdef SHA_OPENSSL
3045f050 1829 {
f444c2c7
JH
1830 SHA1_Update(&sha1_headers, sig_hdr, strlen(sig_hdr));
1831 SHA1_Final(US headerhash, &sha1_headers);
80a47a2c 1832 }
3045f050
JH
1833 else
1834 {
f444c2c7
JH
1835 SHA256_Update(&sha2_headers, sig_hdr, strlen(sig_hdr));
1836 SHA256_Final(US headerhash, &sha2_headers);
1837 }
cb224393
JH
1838# elif defined(SHA_POLARSSL)
1839 {
1840 sha1_update(&sha1_headers, US sig_hdr, strlen(sig_hdr));
1841 sha1_finish(&sha1_headers, US headerhash);
1842 }
1843 else
1844 {
1845 sha2_update(&sha2_headers, US sig_hdr, strlen(sig_hdr));
1846 sha2_finish(&sha2_headers, US headerhash);
1847 }
1848# endif
f444c2c7 1849#endif
3045f050 1850
f444c2c7
JH
1851 DEBUG(D_acl)
1852 {
1853 debug_printf("PDKIM [%s] hh computed: ", sig->domain);
1854 pdkim_hexprint(headerhash, sig->algo == PDKIM_ALGO_RSA_SHA1 ? 20:32, 1);
80a47a2c
TK
1855 }
1856
cb224393 1857#ifdef RSA_GNUTLS
f444c2c7
JH
1858 if (ctx->mode == PDKIM_MODE_SIGN)
1859 hdata = string_append(hdata, &hdata_alloc, &hdata_size, 1, sig_hdr);
1860#endif
1861
3045f050 1862 free(sig_hdr);
80a47a2c 1863
3045f050
JH
1864 /* SIGNING ---------------------------------------------------------------- */
1865 if (ctx->mode == PDKIM_MODE_SIGN)
1866 {
cb224393
JH
1867#ifdef RSA_OPENSSL
1868 RSA * rsa;
1869 uschar * p, * q;
1870 int len;
1871#elif defined(RSA_GNUTLS)
f444c2c7
JH
1872 gnutls_x509_privkey_t rsa;
1873 gnutls_datum_t k;
1874 int rc;
1875 size_t sigsize;
f444c2c7
JH
1876#endif
1877
1878 /* Import private key */
cb224393
JH
1879#ifdef RSA_OPENSSL
1880
1881 if ( !(p = Ustrstr(sig->rsa_privkey, "-----BEGIN RSA PRIVATE KEY-----"))
1882 || !(q = Ustrstr(p+=31, "-----END RSA PRIVATE KEY-----"))
1883 )
1884 return PDKIM_ERR_RSA_PRIVKEY;
1885 *q = '\0';
1886 if ( (len = b64decode(p, &p)) < 0
1887 || !(rsa = d2i_RSAPrivateKey(NULL, CUSS &p, len))
1888 )
1889 /*XXX todo: get errstring from library */
1890 return PDKIM_ERR_RSA_PRIVKEY;
1891
1892#elif defined(RSA_GNUTLS)
f444c2c7
JH
1893
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
1899 )
1900 {
1901 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_import2: %s\n",
1902 gnutls_strerror(rc));
1903 return PDKIM_ERR_RSA_PRIVKEY;
1904 }
80a47a2c 1905
f444c2c7
JH
1906#endif
1907
1908
1909 /* Allocate mem for signature */
cb224393
JH
1910#ifdef RSA_OPENSSL
1911 sig->sigdata = store_get(RSA_size(rsa));
1912#elif defined(RSA_GNUTLS)
f444c2c7
JH
1913 k.data = hdata;
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);
f444c2c7
JH
1919#endif
1920
1921 /* Do signing */
cb224393
JH
1922#ifdef RSA_OPENSSL
1923
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,
1927 rsa) != 1)
1928 return PDKIM_ERR_RSA_SIGNING;
1929 RSA_free(rsa);
1930
1931#elif defined(RSA_GNUTLS)
80a47a2c 1932
f444c2c7
JH
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
1936 )
1937 {
1938 DEBUG(D_acl) debug_printf("gnutls_x509_privkey_sign_data: %s\n",
1939 gnutls_strerror(rc));
1940 return PDKIM_ERR_RSA_SIGNING;
1941 }
1942 gnutls_x509_privkey_deinit(rsa);
1943
f444c2c7 1944#endif
80a47a2c 1945
80a47a2c 1946
0d04a285 1947 DEBUG(D_acl)
3045f050 1948 {
0d04a285
JH
1949 debug_printf( "PDKIM [%s] b computed: ", sig->domain);
1950 pdkim_hexprint(sig->sigdata, sig->sigdata_len, 1);
80a47a2c 1951 }
80a47a2c 1952
abe1010c 1953 if (!(sig->signature_header = pdkim_create_header(ctx->sig, 1)))
3045f050 1954 return PDKIM_ERR_OOM;
80a47a2c 1955 }
80a47a2c 1956
3045f050
JH
1957 /* VERIFICATION ----------------------------------------------------------- */
1958 else
1959 {
cb224393
JH
1960#ifdef RSA_OPENSSL
1961 RSA * rsa;
1962 const unsigned char * p;
1963#elif defined(RSA_GNUTLS)
f444c2c7
JH
1964 gnutls_pubkey_t rsa;
1965 gnutls_datum_t k, s;
1966 int rc;
f444c2c7 1967#endif
3045f050
JH
1968 char *dns_txt_name, *dns_txt_reply;
1969
cb224393 1970#ifdef RSA_GNUTLS
f444c2c7
JH
1971 gnutls_pubkey_init(&rsa);
1972#endif
1973
1974 /* Fetch public key for signing domain, from DNS */
3045f050
JH
1975
1976 if (!(dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN)))
1977 return PDKIM_ERR_OOM;
1978
1979 if (!(dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN)))
1980 {
1981 free(dns_txt_name);
1982 return PDKIM_ERR_OOM;
80a47a2c
TK
1983 }
1984
3045f050
JH
1985 memset(dns_txt_reply, 0, PDKIM_DNS_TXT_MAX_RECLEN);
1986 memset(dns_txt_name , 0, PDKIM_DNS_TXT_MAX_NAMELEN);
1987
abe1010c 1988 if (snprintf(dns_txt_name, PDKIM_DNS_TXT_MAX_NAMELEN,
3045f050 1989 "%s._domainkey.%s.",
abe1010c 1990 sig->selector, sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN)
3045f050
JH
1991 {
1992 sig->verify_status = PDKIM_VERIFY_INVALID;
1993 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1994 goto NEXT_VERIFY;
80a47a2c 1995 }
3045f050
JH
1996
1997 if ( ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK
1998 || dns_txt_reply[0] == '\0')
1999 {
2000 sig->verify_status = PDKIM_VERIFY_INVALID;
2001 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
2002 goto NEXT_VERIFY;
80a47a2c
TK
2003 }
2004
0d04a285 2005 DEBUG(D_acl)
3045f050 2006 {
0d04a285
JH
2007 debug_printf(
2008 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
2009 " Raw record: ");
2010 pdkim_quoteprint(dns_txt_reply, strlen(dns_txt_reply), 1);
80a47a2c 2011 }
3045f050 2012
abe1010c 2013 if (!(sig->pubkey = pdkim_parse_pubkey_record(ctx, dns_txt_reply)))
3045f050
JH
2014 {
2015 sig->verify_status = PDKIM_VERIFY_INVALID;
2016 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
2017
0d04a285
JH
2018 DEBUG(D_acl) debug_printf(
2019 " Error while parsing public key record\n"
3045f050 2020 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
3045f050 2021 goto NEXT_VERIFY;
80a47a2c
TK
2022 }
2023
0d04a285 2024 DEBUG(D_acl) debug_printf(
3045f050 2025 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
3045f050 2026
f444c2c7 2027 /* Import public key */
cb224393
JH
2028#ifdef RSA_OPENSSL
2029
2030 p = CUS sig->pubkey->key;
2031 if (!(rsa = d2i_RSA_PUBKEY(NULL, &p, (long) sig->pubkey->key_len)))
2032
2033#elif defined(RSA_GNUTLS)
f444c2c7
JH
2034
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)
2039
f444c2c7 2040#endif
3045f050 2041 {
f444c2c7
JH
2042 DEBUG(D_acl)
2043 {
cb224393 2044#ifdef RSA_OPENSSL
f444c2c7
JH
2045 long e;
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));
cb224393
JH
2049#elif defined(RSA_GNUTLS)
2050 debug_printf("gnutls_pubkey_import: %s\n", gnutls_strerror(rc));
f444c2c7
JH
2051#endif
2052 }
2053
3045f050
JH
2054 sig->verify_status = PDKIM_VERIFY_INVALID;
2055 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
2056 goto NEXT_VERIFY;
80a47a2c
TK
2057 }
2058
3045f050 2059 /* Check the signature */
cb224393
JH
2060#ifdef RSA_OPENSSL
2061
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,
2065 rsa) != 1)
2066
2067#elif defined(RSA_GNUTLS)
f444c2c7
JH
2068
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,
2076 0, &k, &s)) < 0)
2077
f444c2c7 2078#endif
3045f050 2079 {
cb224393 2080#if defined(RSA_GNUTLS)
f444c2c7
JH
2081 debug_printf("gnutls_pubkey_verify_hash2: %s\n", gnutls_strerror(rc));
2082#endif
3045f050
JH
2083 sig->verify_status = PDKIM_VERIFY_FAIL;
2084 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
2085 goto NEXT_VERIFY;
ff7ddfd7
TK
2086 }
2087
3045f050
JH
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;
2091
2092NEXT_VERIFY:
2093
0d04a285 2094 DEBUG(D_acl)
3045f050 2095 {
0d04a285 2096 debug_printf("PDKIM [%s] signature status: %s",
3045f050
JH
2097 sig->domain, pdkim_verify_status_str(sig->verify_status));
2098 if (sig->verify_ext_status > 0)
0d04a285 2099 debug_printf(" (%s)\n",
3045f050
JH
2100 pdkim_verify_ext_status_str(sig->verify_ext_status));
2101 else
0d04a285 2102 debug_printf("\n");
80a47a2c 2103 }
80a47a2c 2104
cb224393 2105#ifdef RSA_GNUTLS
f444c2c7
JH
2106 gnutls_pubkey_deinit(rsa);
2107#endif
3045f050
JH
2108 free(dns_txt_name);
2109 free(dns_txt_reply);
80a47a2c
TK
2110 }
2111
3045f050 2112 sig = sig->next;
80a47a2c
TK
2113 }
2114
3045f050
JH
2115/* If requested, set return pointer to signature(s) */
2116if (return_signatures)
2117 *return_signatures = ctx->sig;
80a47a2c 2118
3045f050 2119return PDKIM_OK;
80a47a2c
TK
2120}
2121
2122
2123/* -------------------------------------------------------------------------- */
3045f050
JH
2124
2125DLLEXPORT pdkim_ctx *
0d04a285 2126pdkim_init_verify(int(*dns_txt_callback)(char *, char *))
3045f050
JH
2127{
2128pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
2129
2130if (!ctx)
2131 return NULL;
abe1010c 2132memset(ctx, 0, sizeof(pdkim_ctx));
3045f050
JH
2133
2134if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2135 {
2136 free(ctx);
2137 return NULL;
80a47a2c
TK
2138 }
2139
3045f050 2140ctx->mode = PDKIM_MODE_VERIFY;
3045f050 2141ctx->dns_txt_callback = dns_txt_callback;
80a47a2c 2142
3045f050 2143return ctx;
80a47a2c
TK
2144}
2145
2146
2147/* -------------------------------------------------------------------------- */
80a47a2c 2148
3045f050 2149DLLEXPORT pdkim_ctx *
f444c2c7 2150pdkim_init_sign(char *domain, char *selector, char *rsa_privkey, int algo)
3045f050
JH
2151{
2152pdkim_ctx *ctx;
2153pdkim_signature *sig;
80a47a2c 2154
3045f050
JH
2155if (!domain || !selector || !rsa_privkey)
2156 return NULL;
80a47a2c 2157
3045f050
JH
2158if (!(ctx = malloc(sizeof(pdkim_ctx))))
2159 return NULL;
abe1010c 2160memset(ctx, 0, sizeof(pdkim_ctx));
80a47a2c 2161
3045f050
JH
2162if (!(ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN)))
2163 {
2164 free(ctx);
2165 return NULL;
80a47a2c
TK
2166 }
2167
3045f050
JH
2168if (!(sig = malloc(sizeof(pdkim_signature))))
2169 {
2170 free(ctx->linebuf);
2171 free(ctx);
2172 return NULL;
80a47a2c 2173 }
abe1010c 2174memset(sig, 0, sizeof(pdkim_signature));
80a47a2c 2175
3045f050 2176sig->bodylength = -1;
80a47a2c 2177
3045f050 2178ctx->mode = PDKIM_MODE_SIGN;
3045f050 2179ctx->sig = sig;
80a47a2c 2180
3045f050
JH
2181ctx->sig->domain = strdup(domain);
2182ctx->sig->selector = strdup(selector);
2183ctx->sig->rsa_privkey = strdup(rsa_privkey);
f444c2c7 2184ctx->sig->algo = algo;
3045f050
JH
2185
2186if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey)
2187 goto BAIL;
2188
cb224393
JH
2189#ifdef SHA_OPENSSL
2190SHA1_Init (&ctx->sig->sha1_body);
2191SHA256_Init(&ctx->sig->sha2_body);
2192
2193#elif defined(SHA_GNUTLS)
f444c2c7
JH
2194gnutls_hash_init(&ctx->sig->sha_body,
2195 algo == PDKIM_ALGO_RSA_SHA1 ? GNUTLS_DIG_SHA1 : GNUTLS_DIG_SHA256);
3045f050 2196
cb224393
JH
2197#elif defined(SHA_POLARSSL)
2198if (!(ctx->sig->sha1_body = malloc(sizeof(sha1_context))))
2199 goto BAIL;
2200sha1_starts(ctx->sig->sha1_body);
2201
2202if (!(ctx->sig->sha2_body = malloc(sizeof(sha2_context))))
2203 goto BAIL;
2204sha2_starts(ctx->sig->sha2_body, 0);
f444c2c7
JH
2205
2206#endif
3045f050
JH
2207
2208return ctx;
2209
2210BAIL:
2211 pdkim_free_ctx(ctx);
2212 return NULL;
6ab02e3f 2213}
80a47a2c 2214
f444c2c7 2215
80a47a2c 2216/* -------------------------------------------------------------------------- */
3045f050
JH
2217
2218DLLEXPORT int
2219pdkim_set_optional(pdkim_ctx *ctx,
80a47a2c
TK
2220 char *sign_headers,
2221 char *identity,
2222 int canon_headers,
2223 int canon_body,
2224 long bodylength,
80a47a2c 2225 unsigned long created,
3045f050
JH
2226 unsigned long expires)
2227{
3045f050
JH
2228if (identity)
2229 if (!(ctx->sig->identity = strdup(identity)))
2230 return PDKIM_ERR_OOM;
80a47a2c 2231
3045f050
JH
2232if (sign_headers)
2233 if (!(ctx->sig->sign_headers = strdup(sign_headers)))
2234 return PDKIM_ERR_OOM;
80a47a2c 2235
3045f050
JH
2236ctx->sig->canon_headers = canon_headers;
2237ctx->sig->canon_body = canon_body;
2238ctx->sig->bodylength = bodylength;
3045f050
JH
2239ctx->sig->created = created;
2240ctx->sig->expires = expires;
80a47a2c 2241
3045f050 2242return PDKIM_OK;
6ab02e3f 2243}
3045f050 2244
3045f050 2245
f444c2c7 2246#endif /*DISABLE_DKIM*/