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