2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2009 - 2016 Tom Kistner <tom@duncanthrax.net>
5 * Copyright (C) 2016 Jeremy Harris <jgh@exim.org>
7 * http://duncanthrax.net/pdkim/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #ifndef DISABLE_DKIM /* entire file */
30 # error Need SUPPORT_TLS for DKIM
35 # include <gnutls/gnutls.h>
36 # include <gnutls/x509.h>
37 # include <gnutls/abstract.h>
38 # include <gnutls/crypto.h>
40 # include <openssl/rsa.h>
41 # include <openssl/ssl.h>
42 # include <openssl/err.h>
47 #define PDKIM_SIGNATURE_VERSION "1"
48 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
50 #define PDKIM_MAX_HEADER_LEN 65536
51 #define PDKIM_MAX_HEADERS 512
52 #define PDKIM_MAX_BODY_LINE_LEN 16384
53 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
54 #define PDKIM_DEFAULT_SIGN_HEADERS "From:Sender:Reply-To:Subject:Date:"\
55 "Message-ID:To:Cc:MIME-Version:Content-Type:"\
56 "Content-Transfer-Encoding:Content-ID:"\
57 "Content-Description:Resent-Date:Resent-From:"\
58 "Resent-Sender:Resent-To:Resent-Cc:"\
59 "Resent-Message-ID:In-Reply-To:References:"\
60 "List-Id:List-Help:List-Unsubscribe:"\
61 "List-Subscribe:List-Post:List-Owner:List-Archive"
63 /* -------------------------------------------------------------------------- */
64 struct pdkim_stringlist
{
70 #define PDKIM_STR_ALLOC_FRAG 256
74 unsigned int allocated
;
77 /* -------------------------------------------------------------------------- */
78 /* A bunch of list constants */
79 const char *pdkim_querymethods
[] = {
83 const char *pdkim_algos
[] = {
88 const char *pdkim_canons
[] = {
93 const char *pdkim_hashes
[] = {
98 const char *pdkim_keytypes
[] = {
103 typedef struct pdkim_combined_canon_entry
{
107 } pdkim_combined_canon_entry
;
109 pdkim_combined_canon_entry pdkim_combined_canons
[] = {
110 { "simple/simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
111 { "simple/relaxed", PDKIM_CANON_SIMPLE
, PDKIM_CANON_RELAXED
},
112 { "relaxed/simple", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
113 { "relaxed/relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_RELAXED
},
114 { "simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
115 { "relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
120 /* -------------------------------------------------------------------------- */
123 pdkim_verify_status_str(int status
)
126 case PDKIM_VERIFY_NONE
: return "PDKIM_VERIFY_NONE";
127 case PDKIM_VERIFY_INVALID
: return "PDKIM_VERIFY_INVALID";
128 case PDKIM_VERIFY_FAIL
: return "PDKIM_VERIFY_FAIL";
129 case PDKIM_VERIFY_PASS
: return "PDKIM_VERIFY_PASS";
130 default: return "PDKIM_VERIFY_UNKNOWN";
135 pdkim_verify_ext_status_str(int ext_status
)
138 case PDKIM_VERIFY_FAIL_BODY
: return "PDKIM_VERIFY_FAIL_BODY";
139 case PDKIM_VERIFY_FAIL_MESSAGE
: return "PDKIM_VERIFY_FAIL_MESSAGE";
140 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
141 case PDKIM_VERIFY_INVALID_BUFFER_SIZE
: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
142 case PDKIM_VERIFY_INVALID_PUBKEY_PARSING
: return "PDKIM_VERIFY_INVALID_PUBKEY_PARSING";
143 default: return "PDKIM_VERIFY_UNKNOWN";
148 /* -------------------------------------------------------------------------- */
149 /* Print debugging functions */
151 pdkim_quoteprint(const char *data
, int len
, int lf
)
154 const unsigned char *p
= (const unsigned char *)data
;
156 for (i
= 0; i
< len
; i
++)
161 case ' ' : debug_printf("{SP}"); break;
162 case '\t': debug_printf("{TB}"); break;
163 case '\r': debug_printf("{CR}"); break;
164 case '\n': debug_printf("{LF}"); break;
165 case '{' : debug_printf("{BO}"); break;
166 case '}' : debug_printf("{BC}"); break;
168 if ( (c
< 32) || (c
> 127) )
169 debug_printf("{%02x}", c
);
171 debug_printf("%c", c
);
180 pdkim_hexprint(const char *data
, int len
, int lf
)
183 const unsigned char *p
= (const unsigned char *)data
;
185 for (i
= 0 ; i
< len
; i
++)
186 debug_printf("%02x", p
[i
]);
193 /* String package: should be replaced by Exim standard ones */
195 static pdkim_stringlist
*
196 pdkim_prepend_stringlist(pdkim_stringlist
*base
, char *str
)
198 pdkim_stringlist
*new_entry
= malloc(sizeof(pdkim_stringlist
));
200 if (!new_entry
) return NULL
;
201 memset(new_entry
, 0, sizeof(pdkim_stringlist
));
202 if (!(new_entry
->value
= strdup(str
))) return NULL
;
205 pdkim_stringlist
*last
= base
;
206 while (last
->next
!= NULL
) { last
= last
->next
; }
207 last
->next
= new_entry
;
215 /* -------------------------------------------------------------------------- */
216 /* A small "growing string" implementation to escape malloc/realloc hell */
219 pdkim_strnew (const char *cstr
)
221 unsigned int len
= cstr
? strlen(cstr
) : 0;
222 pdkim_str
*p
= malloc(sizeof(pdkim_str
));
225 memset(p
, 0, sizeof(pdkim_str
));
226 if (!(p
->str
= malloc(len
+1)))
231 p
->allocated
= len
+1;
234 strcpy(p
->str
, cstr
);
236 p
->str
[p
->len
] = '\0';
241 pdkim_strncat(pdkim_str
*str
, const char *data
, int len
)
243 if ((str
->allocated
- str
->len
) < (len
+1))
245 /* Extend the buffer */
246 int num_frags
= ((len
+1)/PDKIM_STR_ALLOC_FRAG
)+1;
247 char *n
= realloc(str
->str
,
248 (str
->allocated
+(num_frags
*PDKIM_STR_ALLOC_FRAG
)));
249 if (n
== NULL
) return NULL
;
251 str
->allocated
+= (num_frags
*PDKIM_STR_ALLOC_FRAG
);
253 strncpy(&(str
->str
[str
->len
]), data
, len
);
255 str
->str
[str
->len
] = '\0';
260 pdkim_strcat(pdkim_str
*str
, const char *cstr
)
262 return pdkim_strncat(str
, cstr
, strlen(cstr
));
266 pdkim_strtrim(pdkim_str
*str
)
270 while ( (*p
!= '\0') && ((*p
== '\t') || (*p
== ' ')) ) p
++;
271 while (*p
!= '\0') {*q
= *p
; q
++; p
++;}
273 while ( (q
!= str
->str
) && ( (*q
== '\0') || (*q
== '\t') || (*q
== ' ') ) )
278 str
->len
= strlen(str
->str
);
283 pdkim_strclear(pdkim_str
*str
)
291 pdkim_strfree(pdkim_str
*str
)
294 if (str
->str
) free(str
->str
);
300 /* -------------------------------------------------------------------------- */
303 pdkim_free_pubkey(pdkim_pubkey
*pub
)
307 if (pub
->version
) free(pub
->version
);
308 if (pub
->granularity
) free(pub
->granularity
);
309 if (pub
->hashes
) free(pub
->hashes
);
310 if (pub
->keytype
) free(pub
->keytype
);
311 if (pub
->srvtype
) free(pub
->srvtype
);
312 if (pub
->notes
) free(pub
->notes
);
313 /* if (pub->key ) free(pub->key); */
319 /* -------------------------------------------------------------------------- */
322 pdkim_free_sig(pdkim_signature
*sig
)
326 pdkim_signature
*next
= (pdkim_signature
*)sig
->next
;
328 pdkim_stringlist
*e
= sig
->headers
;
331 pdkim_stringlist
*c
= e
;
332 if (e
->value
) free(e
->value
);
337 if (sig
->selector
) free(sig
->selector
);
338 if (sig
->domain
) free(sig
->domain
);
339 if (sig
->identity
) free(sig
->identity
);
340 if (sig
->headernames
) free(sig
->headernames
);
341 if (sig
->copiedheaders
) free(sig
->copiedheaders
);
342 if (sig
->rsa_privkey
) free(sig
->rsa_privkey
);
343 if (sig
->sign_headers
) free(sig
->sign_headers
);
344 if (sig
->signature_header
) free(sig
->signature_header
);
346 if (sig
->pubkey
) pdkim_free_pubkey(sig
->pubkey
);
349 if (next
) pdkim_free_sig(next
);
354 /* -------------------------------------------------------------------------- */
357 pdkim_free_ctx(pdkim_ctx
*ctx
)
361 pdkim_stringlist
*e
= ctx
->headers
;
364 pdkim_stringlist
*c
= e
;
365 if (e
->value
) free(e
->value
);
369 pdkim_free_sig(ctx
->sig
);
370 pdkim_strfree(ctx
->cur_header
);
376 /* -------------------------------------------------------------------------- */
377 /* Matches the name of the passed raw "header" against
378 the passed colon-separated "list", starting at entry
379 "start". Returns the position of the header name in
383 header_name_match(const char *header
,
393 /* Get header name */
394 char *hcolon
= strchr(header
, ':');
396 if (!hcolon
) return rc
; /* This isn't a header */
398 if (!(hname
= malloc((hcolon
-header
)+1)))
399 return PDKIM_ERR_OOM
;
400 memset(hname
, 0, (hcolon
-header
)+1);
401 strncpy(hname
, header
, (hcolon
-header
));
403 /* Copy tick-off list locally, so we can punch zeroes into it */
404 if (!(lcopy
= strdup(tick
)))
407 return PDKIM_ERR_OOM
;
415 if (strcasecmp(p
, hname
) == 0)
418 /* Invalidate header name instance in tick-off list */
419 if (do_tick
) tick
[p
-lcopy
] = '_';
427 if (strcasecmp(p
, hname
) == 0)
430 /* Invalidate header name instance in tick-off list */
431 if (do_tick
) tick
[p
-lcopy
] = '_';
441 /* -------------------------------------------------------------------------- */
442 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
446 pdkim_relax_header (char *header
, int crlf
)
448 BOOL past_field_name
= FALSE
;
449 BOOL seen_wsp
= FALSE
;
452 char *relaxed
= malloc(strlen(header
)+3);
454 if (!relaxed
) return NULL
;
457 for (p
= header
; *p
!= '\0'; p
++)
461 if (c
== '\r' || c
== '\n')
463 if (c
== '\t' || c
== ' ')
467 c
= ' '; /* Turns WSP into SP */
471 if (!past_field_name
&& c
== ':')
473 if (seen_wsp
) q
--; /* This removes WSP before the colon */
474 seen_wsp
= TRUE
; /* This removes WSP after the colon */
475 past_field_name
= TRUE
;
480 /* Lowercase header name */
481 if (!past_field_name
) c
= tolower(c
);
485 if (q
> relaxed
&& q
[-1] == ' ') q
--; /* Squash eventual trailing SP */
488 if (crlf
) strcat(relaxed
, "\r\n");
493 /* -------------------------------------------------------------------------- */
494 #define PDKIM_QP_ERROR_DECODE -1
497 pdkim_decode_qp_char(char *qp_p
, int *c
)
499 char *initial_pos
= qp_p
;
501 /* Advance one char */
504 /* Check for two hex digits and decode them */
505 if (isxdigit(*qp_p
) && isxdigit(qp_p
[1]))
507 /* Do hex conversion */
508 *c
= (isdigit(*qp_p
) ? *qp_p
- '0' : toupper(*qp_p
) - 'A' + 10) << 4;
509 *c
|= isdigit(qp_p
[1]) ? qp_p
[1] - '0' : toupper(qp_p
[1]) - 'A' + 10;
513 /* Illegal char here */
514 *c
= PDKIM_QP_ERROR_DECODE
;
519 /* -------------------------------------------------------------------------- */
522 pdkim_decode_qp(char *str
)
527 char *n
= malloc(strlen(p
)+1);
537 p
= pdkim_decode_qp_char(p
, &nchar
);
553 /* -------------------------------------------------------------------------- */
556 pdkim_decode_base64(char *str
, int *num_decoded
)
560 int old_pool
= store_pool
;
562 /* There is a store-reset between header & body reception
563 so cannot use the main pool */
565 store_pool
= POOL_PERM
;
566 dlen
= b64decode(US str
, USS
&res
);
567 store_pool
= old_pool
;
569 if (dlen
< 0) return NULL
;
571 if (num_decoded
) *num_decoded
= dlen
;
576 /* -------------------------------------------------------------------------- */
579 pdkim_encode_base64(char *str
, int num
)
582 int old_pool
= store_pool
;
584 store_pool
= POOL_PERM
;
585 ret
= CS
b64encode(US str
, num
);
586 store_pool
= old_pool
;
591 /* -------------------------------------------------------------------------- */
592 #define PDKIM_HDR_LIMBO 0
593 #define PDKIM_HDR_TAG 1
594 #define PDKIM_HDR_VALUE 2
596 static pdkim_signature
*
597 pdkim_parse_sig_header(pdkim_ctx
*ctx
, char *raw_hdr
)
599 pdkim_signature
*sig
;
601 pdkim_str
*cur_tag
= NULL
;
602 pdkim_str
*cur_val
= NULL
;
603 BOOL past_hname
= FALSE
;
604 BOOL in_b_val
= FALSE
;
605 int where
= PDKIM_HDR_LIMBO
;
608 if (!(sig
= malloc(sizeof(pdkim_signature
)))) return NULL
;
609 memset(sig
, 0, sizeof(pdkim_signature
));
610 sig
->bodylength
= -1;
612 if (!(sig
->rawsig_no_b_val
= malloc(strlen(raw_hdr
)+1)))
618 q
= sig
->rawsig_no_b_val
;
620 for (p
= raw_hdr
; ; p
++)
625 if (c
== '\r' || c
== '\n')
628 /* Fast-forward through header name */
631 if (c
== ':') past_hname
= TRUE
;
635 if (where
== PDKIM_HDR_LIMBO
)
637 /* In limbo, just wait for a tag-char to appear */
638 if (!(c
>= 'a' && c
<= 'z'))
641 where
= PDKIM_HDR_TAG
;
644 if (where
== PDKIM_HDR_TAG
)
647 cur_tag
= pdkim_strnew(NULL
);
649 if (c
>= 'a' && c
<= 'z')
650 pdkim_strncat(cur_tag
, p
, 1);
654 if (strcmp(cur_tag
->str
, "b") == 0)
659 where
= PDKIM_HDR_VALUE
;
664 if (where
== PDKIM_HDR_VALUE
)
667 cur_val
= pdkim_strnew(NULL
);
669 if (c
== '\r' || c
== '\n' || c
== ' ' || c
== '\t')
672 if (c
== ';' || c
== '\0')
674 if (cur_tag
->len
> 0)
676 pdkim_strtrim(cur_val
);
678 DEBUG(D_acl
) debug_printf(" %s=%s\n", cur_tag
->str
, cur_val
->str
);
680 switch (cur_tag
->str
[0])
683 if (cur_tag
->str
[1] == 'h')
684 sig
->bodyhash
= pdkim_decode_base64(cur_val
->str
,
687 sig
->sigdata
= pdkim_decode_base64(cur_val
->str
,
691 /* We only support version 1, and that is currently the
692 only version there is. */
693 if (strcmp(cur_val
->str
, PDKIM_SIGNATURE_VERSION
) == 0)
697 for (i
= 0; pdkim_algos
[i
]; i
++)
698 if (strcmp(cur_val
->str
, pdkim_algos
[i
]) == 0)
705 for (i
= 0; pdkim_combined_canons
[i
].str
; i
++)
706 if (strcmp(cur_val
->str
, pdkim_combined_canons
[i
].str
) == 0)
708 sig
->canon_headers
= pdkim_combined_canons
[i
].canon_headers
;
709 sig
->canon_body
= pdkim_combined_canons
[i
].canon_body
;
714 for (i
= 0; pdkim_querymethods
[i
]; i
++)
715 if (strcmp(cur_val
->str
, pdkim_querymethods
[i
]) == 0)
717 sig
->querymethod
= i
;
722 sig
->selector
= strdup(cur_val
->str
); break;
724 sig
->domain
= strdup(cur_val
->str
); break;
726 sig
->identity
= pdkim_decode_qp(cur_val
->str
); break;
728 sig
->created
= strtoul(cur_val
->str
, NULL
, 10); break;
730 sig
->expires
= strtoul(cur_val
->str
, NULL
, 10); break;
732 sig
->bodylength
= strtol(cur_val
->str
, NULL
, 10); break;
734 sig
->headernames
= strdup(cur_val
->str
); break;
736 sig
->copiedheaders
= pdkim_decode_qp(cur_val
->str
); break;
738 DEBUG(D_acl
) debug_printf(" Unknown tag encountered\n");
742 pdkim_strclear(cur_tag
);
743 pdkim_strclear(cur_val
);
745 where
= PDKIM_HDR_LIMBO
;
748 pdkim_strncat(cur_val
, p
, 1);
759 /* Make sure the most important bits are there. */
760 if (!(sig
->domain
&& (*(sig
->domain
) != '\0') &&
761 sig
->selector
&& (*(sig
->selector
) != '\0') &&
762 sig
->headernames
&& (*(sig
->headernames
) != '\0') &&
772 /* Chomp raw header. The final newline must not be added to the signature. */
774 while (q
> sig
->rawsig_no_b_val
&& (*q
== '\r' || *q
== '\n'))
775 *q
= '\0'; q
--; /*XXX questionable code layout; possible bug */
780 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
781 pdkim_quoteprint(sig
->rawsig_no_b_val
, strlen(sig
->rawsig_no_b_val
), 1);
783 "PDKIM >> Sig size: %4d bits\n", sig
->sigdata_len
*8);
785 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
789 gnutls_hash_init(&sig
->sha_body
,
790 sig
->algo
== PDKIM_ALGO_RSA_SHA1
? GNUTLS_DIG_SHA1
: GNUTLS_DIG_SHA256
);
793 SHA1_Init (&sig
->sha1_body
);
794 SHA256_Init(&sig
->sha2_body
);
801 /* -------------------------------------------------------------------------- */
803 static pdkim_pubkey
*
804 pdkim_parse_pubkey_record(pdkim_ctx
*ctx
, char *raw_record
)
808 pdkim_str
*cur_tag
= NULL
;
809 pdkim_str
*cur_val
= NULL
;
810 int where
= PDKIM_HDR_LIMBO
;
812 if (!(pub
= malloc(sizeof(pdkim_pubkey
)))) return NULL
;
813 memset(pub
, 0, sizeof(pdkim_pubkey
));
815 for (p
= raw_record
; ; p
++)
820 if (c
== '\r' || c
== '\n')
823 if (where
== PDKIM_HDR_LIMBO
)
825 /* In limbo, just wait for a tag-char to appear */
826 if (!(c
>= 'a' && c
<= 'z'))
829 where
= PDKIM_HDR_TAG
;
832 if (where
== PDKIM_HDR_TAG
)
835 cur_tag
= pdkim_strnew(NULL
);
837 if (c
>= 'a' && c
<= 'z')
838 pdkim_strncat(cur_tag
, p
, 1);
842 where
= PDKIM_HDR_VALUE
;
847 if (where
== PDKIM_HDR_VALUE
)
850 cur_val
= pdkim_strnew(NULL
);
852 if (c
== '\r' || c
== '\n')
855 if (c
== ';' || c
== '\0')
857 if (cur_tag
->len
> 0)
859 pdkim_strtrim(cur_val
);
860 DEBUG(D_acl
) debug_printf(" %s=%s\n", cur_tag
->str
, cur_val
->str
);
862 switch (cur_tag
->str
[0])
865 /* This tag isn't evaluated because:
866 - We only support version DKIM1.
867 - Which is the default for this value (set below)
868 - Other versions are currently not specified. */
871 pub
->hashes
= strdup(cur_val
->str
); break;
873 pub
->granularity
= strdup(cur_val
->str
); break;
875 pub
->notes
= pdkim_decode_qp(cur_val
->str
); break;
877 pub
->key
= pdkim_decode_base64(cur_val
->str
, &(pub
->key_len
)); break;
879 pub
->hashes
= strdup(cur_val
->str
); break;
881 pub
->srvtype
= strdup(cur_val
->str
); break;
883 if (strchr(cur_val
->str
, 'y') != NULL
) pub
->testing
= 1;
884 if (strchr(cur_val
->str
, 's') != NULL
) pub
->no_subdomaining
= 1;
887 DEBUG(D_acl
) debug_printf(" Unknown tag encountered\n");
891 pdkim_strclear(cur_tag
);
892 pdkim_strclear(cur_val
);
893 where
= PDKIM_HDR_LIMBO
;
896 pdkim_strncat(cur_val
, p
, 1);
900 if (c
== '\0') break;
903 /* Set fallback defaults */
904 if (!pub
->version
) pub
->version
= strdup(PDKIM_PUB_RECORD_VERSION
);
905 if (!pub
->granularity
) pub
->granularity
= strdup("*");
906 if (!pub
->keytype
) pub
->keytype
= strdup("rsa");
907 if (!pub
->srvtype
) pub
->srvtype
= strdup("*");
913 pdkim_free_pubkey(pub
);
918 /* -------------------------------------------------------------------------- */
921 pdkim_update_bodyhash(pdkim_ctx
*ctx
, const char *data
, int len
)
923 pdkim_signature
*sig
= ctx
->sig
;
924 /* Cache relaxed version of data */
925 char *relaxed_data
= NULL
;
928 /* Traverse all signatures, updating their hashes. */
931 /* Defaults to simple canon (no further treatment necessary) */
932 const char *canon_data
= data
;
935 if (sig
->canon_body
== PDKIM_CANON_RELAXED
)
937 /* Relax the line if not done already */
940 BOOL seen_wsp
= FALSE
;
944 if (!(relaxed_data
= malloc(len
+1)))
945 return PDKIM_ERR_OOM
;
947 for (p
= data
; *p
; p
++)
952 if (q
> 0 && relaxed_data
[q
-1] == ' ')
955 else if (c
== '\t' || c
== ' ')
957 c
= ' '; /* Turns WSP into SP */
964 relaxed_data
[q
++] = c
;
966 relaxed_data
[q
] = '\0';
969 canon_data
= relaxed_data
;
970 canon_len
= relaxed_len
;
973 /* Make sure we don't exceed the to-be-signed body length */
974 if ( sig
->bodylength
>= 0
975 && sig
->signed_body_bytes
+ (unsigned long)canon_len
> sig
->bodylength
977 canon_len
= sig
->bodylength
- sig
->signed_body_bytes
;
982 gnutls_hash(sig
->sha_body
, canon_data
, canon_len
);
984 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
985 SHA1_Update (&sig
->sha1_body
, canon_data
, canon_len
);
987 SHA256_Update(&sig
->sha2_body
, canon_data
, canon_len
);
990 sig
->signed_body_bytes
+= canon_len
;
991 DEBUG(D_acl
) pdkim_quoteprint(canon_data
, canon_len
, 1);
997 if (relaxed_data
) free(relaxed_data
);
1002 /* -------------------------------------------------------------------------- */
1005 pdkim_finish_bodyhash(pdkim_ctx
*ctx
)
1007 pdkim_signature
*sig
;
1009 /* Traverse all signatures */
1010 for (sig
= ctx
->sig
; sig
; sig
= sig
->next
)
1011 { /* Finish hashes */
1012 uschar bh
[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
1015 gnutls_hash_output(sig
->sha_body
, bh
);
1017 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1018 SHA1_Final (bh
, &sig
->sha1_body
);
1020 SHA256_Final(bh
, &sig
->sha2_body
);
1025 debug_printf("PDKIM [%s] Body bytes hashed: %lu\n"
1026 "PDKIM [%s] bh computed: ",
1027 sig
->domain
, sig
->signed_body_bytes
, sig
->domain
);
1028 pdkim_hexprint((char *)bh
, sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20 : 32, 1);
1031 /* SIGNING -------------------------------------------------------------- */
1032 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1034 sig
->bodyhash_len
= sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20:32;
1035 sig
->bodyhash
= string_copyn(US bh
, sig
->bodyhash_len
);
1037 /* If bodylength limit is set, and we have received less bytes
1038 than the requested amount, effectively remove the limit tag. */
1039 if (sig
->signed_body_bytes
< sig
->bodylength
)
1040 sig
->bodylength
= -1;
1043 /* VERIFICATION --------------------------------------------------------- */
1046 /* Compare bodyhash */
1047 if (memcmp(bh
, sig
->bodyhash
,
1048 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32) == 0)
1050 DEBUG(D_acl
) debug_printf("PDKIM [%s] Body hash verified OK\n", sig
->domain
);
1056 debug_printf("PDKIM [%s] bh signature: ", sig
->domain
);
1057 pdkim_hexprint(sig
->bodyhash
,
1058 sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20 : 32, 1);
1059 debug_printf("PDKIM [%s] Body hash did NOT verify\n", sig
->domain
);
1061 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
1062 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_BODY
;
1072 /* -------------------------------------------------------------------------- */
1073 /* Callback from pdkim_feed below for processing complete body lines */
1076 pdkim_bodyline_complete(pdkim_ctx
*ctx
)
1078 char *p
= ctx
->linebuf
;
1079 int n
= ctx
->linebuf_offset
;
1080 pdkim_signature
*sig
= ctx
->sig
; /*XXX assumes only one sig */
1082 /* Ignore extra data if we've seen the end-of-data marker */
1083 if (ctx
->seen_eod
) goto BAIL
;
1085 /* We've always got one extra byte to stuff a zero ... */
1086 ctx
->linebuf
[ctx
->linebuf_offset
] = '\0';
1088 /* Terminate on EOD marker */
1089 if (memcmp(p
, ".\r\n", 3) == 0)
1091 /* In simple body mode, if any empty lines were buffered,
1092 replace with one. rfc 4871 3.4.3 */
1093 /*XXX checking the signed-body-bytes is a gross hack; I think
1094 it indicates that all linebreaks should be buffered, including
1095 the one terminating a text line */
1096 if ( sig
&& sig
->canon_body
== PDKIM_CANON_SIMPLE
1097 && sig
->signed_body_bytes
== 0
1098 && ctx
->num_buffered_crlf
> 0
1100 pdkim_update_bodyhash(ctx
, "\r\n", 2);
1102 ctx
->seen_eod
= TRUE
;
1106 if (memcmp(p
, "..", 2) == 0)
1112 /* Empty lines need to be buffered until we find a non-empty line */
1113 if (memcmp(p
, "\r\n", 2) == 0)
1115 ctx
->num_buffered_crlf
++;
1119 if (sig
&& sig
->canon_body
== PDKIM_CANON_RELAXED
)
1121 /* Lines with just spaces need to be buffered too */
1123 while (memcmp(check
, "\r\n", 2) != 0)
1127 if (c
!= '\t' && c
!= ' ')
1132 ctx
->num_buffered_crlf
++;
1137 /* At this point, we have a non-empty line, so release the buffered ones. */
1138 while (ctx
->num_buffered_crlf
)
1140 pdkim_update_bodyhash(ctx
, "\r\n", 2);
1141 ctx
->num_buffered_crlf
--;
1144 pdkim_update_bodyhash(ctx
, p
, n
);
1147 ctx
->linebuf_offset
= 0;
1152 /* -------------------------------------------------------------------------- */
1153 /* Callback from pdkim_feed below for processing complete headers */
1154 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1157 pdkim_header_complete(pdkim_ctx
*ctx
)
1159 /* Special case: The last header can have an extra \r appended */
1160 if ( (ctx
->cur_header
->len
> 1) &&
1161 (ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] == '\r') )
1163 ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] = '\0';
1164 ctx
->cur_header
->len
--;
1168 if (ctx
->num_headers
> PDKIM_MAX_HEADERS
) goto BAIL
;
1170 /* SIGNING -------------------------------------------------------------- */
1171 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1173 pdkim_signature
*sig
;
1175 for (sig
= ctx
->sig
; sig
; sig
= sig
->next
) /* Traverse all signatures */
1176 if (header_name_match(ctx
->cur_header
->str
,
1179 PDKIM_DEFAULT_SIGN_HEADERS
, 0) == PDKIM_OK
)
1181 pdkim_stringlist
*list
;
1183 /* Add header to the signed headers list (in reverse order) */
1184 if (!(list
= pdkim_prepend_stringlist(sig
->headers
,
1185 ctx
->cur_header
->str
)))
1186 return PDKIM_ERR_OOM
;
1187 sig
->headers
= list
;
1191 /* VERIFICATION ----------------------------------------------------------- */
1192 /* DKIM-Signature: headers are added to the verification list */
1193 if (ctx
->mode
== PDKIM_MODE_VERIFY
)
1195 if (strncasecmp(ctx
->cur_header
->str
,
1196 DKIM_SIGNATURE_HEADERNAME
,
1197 strlen(DKIM_SIGNATURE_HEADERNAME
)) == 0)
1199 pdkim_signature
*new_sig
;
1201 /* Create and chain new signature block */
1202 DEBUG(D_acl
) debug_printf(
1203 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1205 if ((new_sig
= pdkim_parse_sig_header(ctx
, ctx
->cur_header
->str
)))
1207 pdkim_signature
*last_sig
= ctx
->sig
;
1212 while (last_sig
->next
) last_sig
= last_sig
->next
;
1213 last_sig
->next
= new_sig
;
1217 DEBUG(D_acl
) debug_printf(
1218 "Error while parsing signature header\n"
1219 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1222 /* every other header is stored for signature verification */
1225 pdkim_stringlist
*list
;
1227 if (!(list
= pdkim_prepend_stringlist(ctx
->headers
, ctx
->cur_header
->str
)))
1228 return PDKIM_ERR_OOM
;
1229 ctx
->headers
= list
;
1234 pdkim_strclear(ctx
->cur_header
); /* Re-use existing pdkim_str */
1240 /* -------------------------------------------------------------------------- */
1241 #define HEADER_BUFFER_FRAG_SIZE 256
1244 pdkim_feed (pdkim_ctx
*ctx
, char *data
, int len
)
1248 for (p
= 0; p
<len
; p
++)
1252 if (ctx
->past_headers
)
1254 /* Processing body byte */
1255 ctx
->linebuf
[ctx
->linebuf_offset
++] = c
;
1258 int rc
= pdkim_bodyline_complete(ctx
); /* End of line */
1259 if (rc
!= PDKIM_OK
) return rc
;
1261 if (ctx
->linebuf_offset
== (PDKIM_MAX_BODY_LINE_LEN
-1))
1262 return PDKIM_ERR_LONG_LINE
;
1266 /* Processing header byte */
1273 int rc
= pdkim_header_complete(ctx
); /* Seen last header line */
1274 if (rc
!= PDKIM_OK
) return rc
;
1276 ctx
->past_headers
= TRUE
;
1278 DEBUG(D_acl
) debug_printf(
1279 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1283 ctx
->seen_lf
= TRUE
;
1285 else if (ctx
->seen_lf
)
1287 if (!(c
== '\t' || c
== ' '))
1289 int rc
= pdkim_header_complete(ctx
); /* End of header */
1290 if (rc
!= PDKIM_OK
) return rc
;
1292 ctx
->seen_lf
= FALSE
;
1296 if (!ctx
->cur_header
)
1297 if (!(ctx
->cur_header
= pdkim_strnew(NULL
)))
1298 return PDKIM_ERR_OOM
;
1300 if (ctx
->cur_header
->len
< PDKIM_MAX_HEADER_LEN
)
1301 if (!pdkim_strncat(ctx
->cur_header
, &data
[p
], 1))
1302 return PDKIM_ERR_OOM
;
1309 * RFC 5322 specifies that header line length SHOULD be no more than 78
1314 * col: this int holds and receives column number (octets since last '\n')
1315 * str: partial string to append to
1316 * pad: padding, split line or space after before or after eg: ";"
1317 * intro: - must join to payload eg "h=", usually the tag name
1318 * payload: eg base64 data - long data can be split arbitrarily.
1320 * this code doesn't fold the header in some of the places that RFC4871
1321 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1322 * pairs and inside long values. it also always spaces or breaks after the
1325 * no guarantees are made for output given out-of range input. like tag
1326 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1330 pdkim_headcat(int *col
, pdkim_str
*str
, const char * pad
,
1331 const char *intro
, const char *payload
)
1340 pdkim_strcat(str
, "\r\n\t");
1343 pdkim_strncat(str
, pad
, l
);
1347 l
= (pad
?1:0) + (intro
?strlen(intro
):0);
1350 { /*can't fit intro - start a new line to make room.*/
1351 pdkim_strcat(str
, "\r\n\t");
1353 l
= intro
?strlen(intro
):0;
1356 l
+= payload
? strlen(payload
):0 ;
1359 { /* this fragment will not fit on a single line */
1362 pdkim_strcat(str
, " ");
1364 pad
= NULL
; /* only want this once */
1370 size_t sl
= strlen(intro
);
1372 pdkim_strncat(str
, intro
, sl
);
1375 intro
= NULL
; /* only want this once */
1380 size_t sl
= strlen(payload
);
1381 size_t chomp
= *col
+sl
< 77 ? sl
: 78-*col
;
1383 pdkim_strncat(str
, payload
, chomp
);
1389 /* the while precondition tells us it didn't fit. */
1390 pdkim_strcat(str
, "\r\n\t");
1396 pdkim_strcat(str
, "\r\n\t");
1403 pdkim_strcat(str
, " ");
1410 size_t sl
= strlen(intro
);
1412 pdkim_strncat(str
, intro
, sl
);
1420 size_t sl
= strlen(payload
);
1422 pdkim_strncat(str
, payload
, sl
);
1430 /* -------------------------------------------------------------------------- */
1433 pdkim_create_header(pdkim_signature
*sig
, int final
)
1436 char *base64_bh
= NULL
;
1437 char *base64_b
= NULL
;
1440 pdkim_str
*canon_all
;
1442 if (!(hdr
= pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION
)))
1445 if (!(canon_all
= pdkim_strnew(pdkim_canons
[sig
->canon_headers
])))
1448 if (!(base64_bh
= pdkim_encode_base64(sig
->bodyhash
, sig
->bodyhash_len
)))
1451 col
= strlen(hdr
->str
);
1453 /* Required and static bits */
1454 if ( pdkim_headcat(&col
, hdr
, ";", "a=", pdkim_algos
[sig
->algo
])
1455 && pdkim_headcat(&col
, hdr
, ";", "q=", pdkim_querymethods
[sig
->querymethod
])
1456 && pdkim_strcat(canon_all
, "/")
1457 && pdkim_strcat(canon_all
, pdkim_canons
[sig
->canon_body
])
1458 && pdkim_headcat(&col
, hdr
, ";", "c=", canon_all
->str
)
1459 && pdkim_headcat(&col
, hdr
, ";", "d=", sig
->domain
)
1460 && pdkim_headcat(&col
, hdr
, ";", "s=", sig
->selector
)
1463 /* list of eader names can be split between items. */
1465 char *n
= strdup(sig
->headernames
);
1473 char *c
= strchr(n
, ':');
1478 if (!pdkim_headcat(&col
, hdr
, NULL
, NULL
, ":"))
1484 if (!pdkim_headcat(&col
, hdr
, s
, i
, n
))
1500 if(!pdkim_headcat(&col
, hdr
, ";", "bh=", base64_bh
))
1505 if(!pdkim_headcat(&col
, hdr
, ";", "i=", sig
->identity
))
1508 if (sig
->created
> 0)
1512 snprintf(minibuf
, 20, "%lu", sig
->created
);
1513 if(!pdkim_headcat(&col
, hdr
, ";", "t=", minibuf
))
1517 if (sig
->expires
> 0)
1521 snprintf(minibuf
, 20, "%lu", sig
->expires
);
1522 if(!pdkim_headcat(&col
, hdr
, ";", "x=", minibuf
))
1526 if (sig
->bodylength
>= 0)
1530 snprintf(minibuf
, 20, "%lu", sig
->bodylength
);
1531 if(!pdkim_headcat(&col
, hdr
, ";", "l=", minibuf
))
1535 /* Preliminary or final version? */
1538 if (!(base64_b
= pdkim_encode_base64(sig
->sigdata
, sig
->sigdata_len
)))
1540 if (!pdkim_headcat(&col
, hdr
, ";", "b=", base64_b
))
1544 if(!pdkim_headcat(&col
, hdr
, ";", "b=", ""))
1547 /* add trailing semicolon: I'm not sure if this is actually needed */
1548 if (!pdkim_headcat(&col
, hdr
, NULL
, ";", ""))
1552 rc
= strdup(hdr
->str
);
1556 if (canon_all
) pdkim_strfree(canon_all
);
1561 /* -------------------------------------------------------------------------- */
1564 pdkim_feed_finish(pdkim_ctx
*ctx
, pdkim_signature
**return_signatures
)
1566 pdkim_signature
*sig
= ctx
->sig
;
1567 pdkim_str
*headernames
= NULL
; /* Collected signed header names */
1569 /* Check if we must still flush a (partial) header. If that is the
1570 case, the message has no body, and we must compute a body hash
1571 out of '<CR><LF>' */
1572 if (ctx
->cur_header
&& ctx
->cur_header
->len
)
1574 int rc
= pdkim_header_complete(ctx
);
1575 if (rc
!= PDKIM_OK
) return rc
;
1576 pdkim_update_bodyhash(ctx
, "\r\n", 2);
1579 DEBUG(D_acl
) debug_printf(
1580 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1582 /* Build (and/or evaluate) body hash */
1583 if (pdkim_finish_bodyhash(ctx
) != PDKIM_OK
)
1584 return PDKIM_ERR_OOM
;
1586 /* SIGNING -------------------------------------------------------------- */
1587 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1588 if (!(headernames
= pdkim_strnew(NULL
)))
1589 return PDKIM_ERR_OOM
;
1590 /* ---------------------------------------------------------------------- */
1595 gnutls_hash_hd_t sha_headers
;
1596 uschar
* hdata
= NULL
;
1597 int hdata_alloc
= 0;
1600 SHA_CTX sha1_headers
;
1601 SHA256_CTX sha2_headers
;
1604 char headerhash
[32];
1607 gnutls_hash_init(&sha_headers
,
1608 sig
->algo
== PDKIM_ALGO_RSA_SHA1
? GNUTLS_DIG_SHA1
: GNUTLS_DIG_SHA256
);
1610 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1611 SHA1_Init(&sha1_headers
);
1613 SHA256_Init(&sha2_headers
);
1616 DEBUG(D_acl
) debug_printf(
1617 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1619 /* SIGNING ---------------------------------------------------------------- */
1620 /* When signing, walk through our header list and add them to the hash. As we
1621 go, construct a list of the header's names to use for the h= parameter. */
1623 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1625 pdkim_stringlist
*p
;
1627 for (p
= sig
->headers
; p
; p
= p
->next
)
1630 /* Collect header names (Note: colon presence is guaranteed here) */
1631 char *q
= strchr(p
->value
, ':');
1633 if (!(pdkim_strncat(headernames
, p
->value
,
1634 (q
-(p
->value
)) + (p
->next
? 1 : 0))))
1635 return PDKIM_ERR_OOM
;
1637 rh
= sig
->canon_headers
== PDKIM_CANON_RELAXED
1638 ? pdkim_relax_header(p
->value
, 1) /* cook header for relaxed canon */
1639 : strdup(p
->value
); /* just copy it for simple canon */
1641 return PDKIM_ERR_OOM
;
1643 /* Feed header to the hash algorithm */
1645 gnutls_hash(sha_headers
, rh
, strlen(rh
));
1647 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1648 SHA1_Update (&sha1_headers
, rh
, strlen(rh
));
1650 SHA256_Update(&sha2_headers
, rh
, strlen(rh
));
1654 /* Remember headers block for signing */
1655 hdata
= string_append(hdata
, &hdata_alloc
, &hdata_size
, 1, rh
);
1658 DEBUG(D_acl
) pdkim_quoteprint(rh
, strlen(rh
), 1);
1663 /* VERIFICATION ----------------------------------------------------------- */
1664 /* When verifying, walk through the header name list in the h= parameter and
1665 add the headers to the hash in that order. */
1668 char *b
= strdup(sig
->headernames
);
1671 pdkim_stringlist
*hdrs
;
1673 if (!b
) return PDKIM_ERR_OOM
;
1676 for (hdrs
= ctx
->headers
; hdrs
; hdrs
= hdrs
->next
)
1681 if ((q
= strchr(p
, ':')))
1684 for (hdrs
= ctx
->headers
; hdrs
; hdrs
= hdrs
->next
)
1686 && strncasecmp(hdrs
->value
, p
, strlen(p
)) == 0
1687 && (hdrs
->value
)[strlen(p
)] == ':'
1692 rh
= sig
->canon_headers
== PDKIM_CANON_RELAXED
1693 ? pdkim_relax_header(hdrs
->value
, 1) /* cook header for relaxed canon */
1694 : strdup(hdrs
->value
); /* just copy it for simple canon */
1696 return PDKIM_ERR_OOM
;
1698 /* Feed header to the hash algorithm */
1700 gnutls_hash(sha_headers
, rh
, strlen(rh
));
1702 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1703 SHA1_Update (&sha1_headers
, rh
, strlen(rh
));
1705 SHA256_Update(&sha2_headers
, rh
, strlen(rh
));
1708 DEBUG(D_acl
) pdkim_quoteprint(rh
, strlen(rh
), 1);
1720 DEBUG(D_acl
) debug_printf(
1721 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1723 /* SIGNING ---------------------------------------------------------------- */
1724 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1726 /* Copy headernames to signature struct */
1727 sig
->headernames
= strdup(headernames
->str
);
1728 pdkim_strfree(headernames
);
1730 /* Create signature header with b= omitted */
1731 sig_hdr
= pdkim_create_header(ctx
->sig
, 0);
1734 /* VERIFICATION ----------------------------------------------------------- */
1736 sig_hdr
= strdup(sig
->rawsig_no_b_val
);
1737 /* ------------------------------------------------------------------------ */
1740 return PDKIM_ERR_OOM
;
1742 /* Relax header if necessary */
1743 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1745 char *relaxed_hdr
= pdkim_relax_header(sig_hdr
, 0);
1749 return PDKIM_ERR_OOM
;
1750 sig_hdr
= relaxed_hdr
;
1756 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1757 pdkim_quoteprint(sig_hdr
, strlen(sig_hdr
), 1);
1759 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1762 /* Finalize header hash */
1764 gnutls_hash(sha_headers
, sig_hdr
, strlen(sig_hdr
));
1765 gnutls_hash_output(sha_headers
, headerhash
);
1767 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1769 SHA1_Update(&sha1_headers
, sig_hdr
, strlen(sig_hdr
));
1770 SHA1_Final(US headerhash
, &sha1_headers
);
1774 SHA256_Update(&sha2_headers
, sig_hdr
, strlen(sig_hdr
));
1775 SHA256_Final(US headerhash
, &sha2_headers
);
1781 debug_printf("PDKIM [%s] hh computed: ", sig
->domain
);
1782 pdkim_hexprint(headerhash
, sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20:32, 1);
1786 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1787 hdata
= string_append(hdata
, &hdata_alloc
, &hdata_size
, 1, sig_hdr
);
1792 /* SIGNING ---------------------------------------------------------------- */
1793 if (ctx
->mode
== PDKIM_MODE_SIGN
)
1796 gnutls_x509_privkey_t rsa
;
1806 /* Import private key */
1809 k
.data
= sig
->rsa_privkey
;
1810 k
.size
= strlen(sig
->rsa_privkey
);
1811 if ( (rc
= gnutls_x509_privkey_init(&rsa
)) != GNUTLS_E_SUCCESS
1812 || (rc
= gnutls_x509_privkey_import2(rsa
, &k
,
1813 GNUTLS_X509_FMT_PEM
, NULL
, GNUTLS_PKCS_PLAIN
)) != GNUTLS_E_SUCCESS
1816 DEBUG(D_acl
) debug_printf("gnutls_x509_privkey_import2: %s\n",
1817 gnutls_strerror(rc
));
1818 return PDKIM_ERR_RSA_PRIVKEY
;
1823 if ( !(p
= Ustrstr(sig
->rsa_privkey
, "-----BEGIN RSA PRIVATE KEY-----"))
1824 || !(q
= Ustrstr(p
+=31, "-----END RSA PRIVATE KEY-----"))
1826 return PDKIM_ERR_RSA_PRIVKEY
;
1828 if ( (len
= b64decode(p
, &p
)) < 0
1829 || !(rsa
= d2i_RSAPrivateKey(NULL
, CUSS
&p
, len
))
1831 /*XXX todo: get errstring from library */
1832 return PDKIM_ERR_RSA_PRIVKEY
;
1837 /* Allocate mem for signature */
1840 k
.size
= hdata_size
;
1841 (void) gnutls_x509_privkey_sign_data(rsa
,
1842 sig
->algo
== PDKIM_ALGO_RSA_SHA1
? GNUTLS_DIG_SHA1
: GNUTLS_DIG_SHA256
,
1843 0, &k
, NULL
, &sigsize
);
1844 sig
->sigdata
= store_get(sig
->sigdata_len
= sigsize
);
1846 sig
->sigdata
= store_get(RSA_size(rsa
));
1852 if ((rc
= gnutls_x509_privkey_sign_data(rsa
,
1853 sig
->algo
== PDKIM_ALGO_RSA_SHA1
? GNUTLS_DIG_SHA1
: GNUTLS_DIG_SHA256
,
1854 0, &k
, sig
->sigdata
, &sigsize
)) != GNUTLS_E_SUCCESS
1857 DEBUG(D_acl
) debug_printf("gnutls_x509_privkey_sign_data: %s\n",
1858 gnutls_strerror(rc
));
1859 return PDKIM_ERR_RSA_SIGNING
;
1861 gnutls_x509_privkey_deinit(rsa
);
1865 if (RSA_sign(sig
->algo
== PDKIM_ALGO_RSA_SHA1
? NID_sha1
: NID_sha256
,
1866 CUS headerhash
, sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20 : 32,
1867 US sig
->sigdata
, (unsigned int *)&sig
->sigdata_len
,
1869 return PDKIM_ERR_RSA_SIGNING
;
1877 debug_printf( "PDKIM [%s] b computed: ", sig
->domain
);
1878 pdkim_hexprint(sig
->sigdata
, sig
->sigdata_len
, 1);
1881 if (!(sig
->signature_header
= pdkim_create_header(ctx
->sig
, 1)))
1882 return PDKIM_ERR_OOM
;
1885 /* VERIFICATION ----------------------------------------------------------- */
1889 gnutls_pubkey_t rsa
;
1890 gnutls_datum_t k
, s
;
1894 const unsigned char * p
;
1896 char *dns_txt_name
, *dns_txt_reply
;
1899 gnutls_pubkey_init(&rsa
);
1902 /* Fetch public key for signing domain, from DNS */
1904 if (!(dns_txt_name
= malloc(PDKIM_DNS_TXT_MAX_NAMELEN
)))
1905 return PDKIM_ERR_OOM
;
1907 if (!(dns_txt_reply
= malloc(PDKIM_DNS_TXT_MAX_RECLEN
)))
1910 return PDKIM_ERR_OOM
;
1913 memset(dns_txt_reply
, 0, PDKIM_DNS_TXT_MAX_RECLEN
);
1914 memset(dns_txt_name
, 0, PDKIM_DNS_TXT_MAX_NAMELEN
);
1916 if (snprintf(dns_txt_name
, PDKIM_DNS_TXT_MAX_NAMELEN
,
1917 "%s._domainkey.%s.",
1918 sig
->selector
, sig
->domain
) >= PDKIM_DNS_TXT_MAX_NAMELEN
)
1920 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1921 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_BUFFER_SIZE
;
1925 if ( ctx
->dns_txt_callback(dns_txt_name
, dns_txt_reply
) != PDKIM_OK
1926 || dns_txt_reply
[0] == '\0')
1928 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1929 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
;
1936 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
1938 pdkim_quoteprint(dns_txt_reply
, strlen(dns_txt_reply
), 1);
1941 if (!(sig
->pubkey
= pdkim_parse_pubkey_record(ctx
, dns_txt_reply
)))
1943 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1944 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1946 DEBUG(D_acl
) debug_printf(
1947 " Error while parsing public key record\n"
1948 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1952 DEBUG(D_acl
) debug_printf(
1953 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1955 /* Import public key */
1958 k
.data
= sig
->pubkey
->key
;
1959 k
.size
= sig
->pubkey
->key_len
;
1960 if ((rc
= gnutls_pubkey_import(rsa
, &k
, GNUTLS_X509_FMT_DER
))
1961 != GNUTLS_E_SUCCESS
)
1965 p
= CUS sig
->pubkey
->key
;
1966 if (!(rsa
= d2i_RSA_PUBKEY(NULL
, &p
, (long) sig
->pubkey
->key_len
)))
1973 debug_printf("gnutls_pubkey_import: %s\n", gnutls_strerror(rc
));
1976 ERR_load_crypto_strings(); /*XXX move to a startup routine */
1977 while ((e
= ERR_get_error()))
1978 debug_printf("Az: %.120s\n", ERR_error_string(e
, NULL
));
1982 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1983 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1987 /* Check the signature */
1990 k
.data
= headerhash
;
1991 k
.size
= sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20 : 32;
1992 s
.data
= sig
->sigdata
;
1993 s
.size
= sig
->sigdata_len
;
1994 if ((rc
= gnutls_pubkey_verify_hash2(rsa
,
1995 sig
->algo
== PDKIM_ALGO_RSA_SHA1
1996 ? GNUTLS_SIGN_RSA_SHA1
: GNUTLS_SIGN_RSA_SHA256
,
2001 if (RSA_verify(sig
->algo
== PDKIM_ALGO_RSA_SHA1
? NID_sha1
: NID_sha256
,
2002 CUS headerhash
, sig
->algo
== PDKIM_ALGO_RSA_SHA1
? 20 : 32,
2003 US sig
->sigdata
, (unsigned int)sig
->sigdata_len
,
2009 debug_printf("gnutls_pubkey_verify_hash2: %s\n", gnutls_strerror(rc
));
2011 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
2012 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_MESSAGE
;
2016 /* We have a winner! (if bodydhash was correct earlier) */
2017 if (sig
->verify_status
== PDKIM_VERIFY_NONE
)
2018 sig
->verify_status
= PDKIM_VERIFY_PASS
;
2024 debug_printf("PDKIM [%s] signature status: %s",
2025 sig
->domain
, pdkim_verify_status_str(sig
->verify_status
));
2026 if (sig
->verify_ext_status
> 0)
2027 debug_printf(" (%s)\n",
2028 pdkim_verify_ext_status_str(sig
->verify_ext_status
));
2034 gnutls_pubkey_deinit(rsa
);
2037 free(dns_txt_reply
);
2043 /* If requested, set return pointer to signature(s) */
2044 if (return_signatures
)
2045 *return_signatures
= ctx
->sig
;
2051 /* -------------------------------------------------------------------------- */
2053 DLLEXPORT pdkim_ctx
*
2054 pdkim_init_verify(int(*dns_txt_callback
)(char *, char *))
2056 pdkim_ctx
*ctx
= malloc(sizeof(pdkim_ctx
));
2060 memset(ctx
, 0, sizeof(pdkim_ctx
));
2062 if (!(ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
)))
2068 ctx
->mode
= PDKIM_MODE_VERIFY
;
2069 ctx
->dns_txt_callback
= dns_txt_callback
;
2075 /* -------------------------------------------------------------------------- */
2077 DLLEXPORT pdkim_ctx
*
2078 pdkim_init_sign(char *domain
, char *selector
, char *rsa_privkey
, int algo
)
2081 pdkim_signature
*sig
;
2083 if (!domain
|| !selector
|| !rsa_privkey
)
2086 if (!(ctx
= malloc(sizeof(pdkim_ctx
))))
2088 memset(ctx
, 0, sizeof(pdkim_ctx
));
2090 if (!(ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
)))
2096 if (!(sig
= malloc(sizeof(pdkim_signature
))))
2102 memset(sig
, 0, sizeof(pdkim_signature
));
2104 sig
->bodylength
= -1;
2106 ctx
->mode
= PDKIM_MODE_SIGN
;
2109 ctx
->sig
->domain
= strdup(domain
);
2110 ctx
->sig
->selector
= strdup(selector
);
2111 ctx
->sig
->rsa_privkey
= strdup(rsa_privkey
);
2112 ctx
->sig
->algo
= algo
;
2114 if (!ctx
->sig
->domain
|| !ctx
->sig
->selector
|| !ctx
->sig
->rsa_privkey
)
2118 gnutls_hash_init(&ctx
->sig
->sha_body
,
2119 algo
== PDKIM_ALGO_RSA_SHA1
? GNUTLS_DIG_SHA1
: GNUTLS_DIG_SHA256
);
2122 SHA1_Init (&ctx
->sig
->sha1_body
);
2123 SHA256_Init(&ctx
->sig
->sha2_body
);
2130 pdkim_free_ctx(ctx
);
2135 /* -------------------------------------------------------------------------- */
2138 pdkim_set_optional(pdkim_ctx
*ctx
,
2144 unsigned long created
,
2145 unsigned long expires
)
2148 if (!(ctx
->sig
->identity
= strdup(identity
)))
2149 return PDKIM_ERR_OOM
;
2152 if (!(ctx
->sig
->sign_headers
= strdup(sign_headers
)))
2153 return PDKIM_ERR_OOM
;
2155 ctx
->sig
->canon_headers
= canon_headers
;
2156 ctx
->sig
->canon_body
= canon_body
;
2157 ctx
->sig
->bodylength
= bodylength
;
2158 ctx
->sig
->created
= created
;
2159 ctx
->sig
->expires
= expires
;
2165 #endif /*DISABLE_DKIM*/