2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2009 - 2015 Tom Kistner <tom@duncanthrax.net>
6 * http://duncanthrax.net/pdkim/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 #include "pdkim-rsa.h"
31 #include "polarssl/sha1.h"
32 #include "polarssl/sha2.h"
33 #include "polarssl/rsa.h"
34 #include "polarssl/base64.h"
36 #define PDKIM_SIGNATURE_VERSION "1"
37 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
39 #define PDKIM_MAX_HEADER_LEN 65536
40 #define PDKIM_MAX_HEADERS 512
41 #define PDKIM_MAX_BODY_LINE_LEN 16384
42 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
43 #define PDKIM_DEFAULT_SIGN_HEADERS "From:Sender:Reply-To:Subject:Date:"\
44 "Message-ID:To:Cc:MIME-Version:Content-Type:"\
45 "Content-Transfer-Encoding:Content-ID:"\
46 "Content-Description:Resent-Date:Resent-From:"\
47 "Resent-Sender:Resent-To:Resent-Cc:"\
48 "Resent-Message-ID:In-Reply-To:References:"\
49 "List-Id:List-Help:List-Unsubscribe:"\
50 "List-Subscribe:List-Post:List-Owner:List-Archive"
52 /* -------------------------------------------------------------------------- */
53 struct pdkim_stringlist
{
59 #define PDKIM_STR_ALLOC_FRAG 256
63 unsigned int allocated
;
66 /* -------------------------------------------------------------------------- */
67 /* A bunch of list constants */
68 const char *pdkim_querymethods
[] = {
72 const char *pdkim_algos
[] = {
77 const char *pdkim_canons
[] = {
82 const char *pdkim_hashes
[] = {
87 const char *pdkim_keytypes
[] = {
92 typedef struct pdkim_combined_canon_entry
{
96 } pdkim_combined_canon_entry
;
97 pdkim_combined_canon_entry pdkim_combined_canons
[] = {
98 { "simple/simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
99 { "simple/relaxed", PDKIM_CANON_SIMPLE
, PDKIM_CANON_RELAXED
},
100 { "relaxed/simple", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
101 { "relaxed/relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_RELAXED
},
102 { "simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
103 { "relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
108 const char *pdkim_verify_status_str(int status
) {
110 case PDKIM_VERIFY_NONE
: return "PDKIM_VERIFY_NONE";
111 case PDKIM_VERIFY_INVALID
: return "PDKIM_VERIFY_INVALID";
112 case PDKIM_VERIFY_FAIL
: return "PDKIM_VERIFY_FAIL";
113 case PDKIM_VERIFY_PASS
: return "PDKIM_VERIFY_PASS";
114 default: return "PDKIM_VERIFY_UNKNOWN";
117 const char *pdkim_verify_ext_status_str(int ext_status
) {
119 case PDKIM_VERIFY_FAIL_BODY
: return "PDKIM_VERIFY_FAIL_BODY";
120 case PDKIM_VERIFY_FAIL_MESSAGE
: return "PDKIM_VERIFY_FAIL_MESSAGE";
121 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
122 case PDKIM_VERIFY_INVALID_BUFFER_SIZE
: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
123 case PDKIM_VERIFY_INVALID_PUBKEY_PARSING
: return "PDKIM_VERIFY_INVALID_PUBKEY_PARSING";
124 default: return "PDKIM_VERIFY_UNKNOWN";
129 /* -------------------------------------------------------------------------- */
130 /* Print debugging functions */
132 void pdkim_quoteprint(FILE *stream
, const char *data
, int len
, int lf
) {
134 const unsigned char *p
= (const unsigned char *)data
;
136 for (i
=0;i
<len
;i
++) {
139 case ' ' : fprintf(stream
,"{SP}"); break;
140 case '\t': fprintf(stream
,"{TB}"); break;
141 case '\r': fprintf(stream
,"{CR}"); break;
142 case '\n': fprintf(stream
,"{LF}"); break;
143 case '{' : fprintf(stream
,"{BO}"); break;
144 case '}' : fprintf(stream
,"{BC}"); break;
146 if ( (c
< 32) || (c
> 127) )
147 fprintf(stream
,"{%02x}",c
);
156 void pdkim_hexprint(FILE *stream
, const char *data
, int len
, int lf
) {
158 const unsigned char *p
= (const unsigned char *)data
;
160 for (i
=0;i
<len
;i
++) {
162 fprintf(stream
,"%02x",c
);
170 /* -------------------------------------------------------------------------- */
171 /* Simple string list implementation for convinience */
172 pdkim_stringlist
*pdkim_append_stringlist(pdkim_stringlist
*base
, char *str
) {
173 pdkim_stringlist
*new_entry
= malloc(sizeof(pdkim_stringlist
));
174 if (new_entry
== NULL
) return NULL
;
175 memset(new_entry
,0,sizeof(pdkim_stringlist
));
176 new_entry
->value
= strdup(str
);
177 if (new_entry
->value
== NULL
) return NULL
;
179 pdkim_stringlist
*last
= base
;
180 while (last
->next
!= NULL
) { last
= last
->next
; }
181 last
->next
= new_entry
;
184 else return new_entry
;
186 pdkim_stringlist
*pdkim_prepend_stringlist(pdkim_stringlist
*base
, char *str
) {
187 pdkim_stringlist
*new_entry
= malloc(sizeof(pdkim_stringlist
));
188 if (new_entry
== NULL
) return NULL
;
189 memset(new_entry
,0,sizeof(pdkim_stringlist
));
190 new_entry
->value
= strdup(str
);
191 if (new_entry
->value
== NULL
) return NULL
;
193 new_entry
->next
= base
;
199 /* -------------------------------------------------------------------------- */
200 /* A small "growing string" implementation to escape malloc/realloc hell */
201 pdkim_str
*pdkim_strnew (const char *cstr
) {
202 unsigned int len
= cstr
?strlen(cstr
):0;
203 pdkim_str
*p
= malloc(sizeof(pdkim_str
));
204 if (p
== NULL
) return NULL
;
205 memset(p
,0,sizeof(pdkim_str
));
206 p
->str
= malloc(len
+1);
207 if (p
->str
== NULL
) {
211 p
->allocated
=(len
+1);
213 if (cstr
) strcpy(p
->str
,cstr
);
214 else p
->str
[p
->len
] = '\0';
217 char *pdkim_strncat(pdkim_str
*str
, const char *data
, int len
) {
218 if ((str
->allocated
- str
->len
) < (len
+1)) {
219 /* Extend the buffer */
220 int num_frags
= ((len
+1)/PDKIM_STR_ALLOC_FRAG
)+1;
221 char *n
= realloc(str
->str
,
222 (str
->allocated
+(num_frags
*PDKIM_STR_ALLOC_FRAG
)));
223 if (n
== NULL
) return NULL
;
225 str
->allocated
+= (num_frags
*PDKIM_STR_ALLOC_FRAG
);
227 strncpy(&(str
->str
[str
->len
]),data
,len
);
229 str
->str
[str
->len
] = '\0';
232 char *pdkim_strcat(pdkim_str
*str
, const char *cstr
) {
233 return pdkim_strncat(str
, cstr
, strlen(cstr
));
236 char *pdkim_numcat(pdkim_str
*str
, unsigned long num
) {
238 snprintf(minibuf
,20,"%lu",num
);
239 return pdkim_strcat(str
,minibuf
);
241 char *pdkim_strtrim(pdkim_str
*str
) {
244 while ( (*p
!= '\0') && ((*p
== '\t') || (*p
== ' ')) ) p
++;
245 while (*p
!= '\0') {*q
= *p
; q
++; p
++;}
247 while ( (q
!= str
->str
) && ( (*q
== '\0') || (*q
== '\t') || (*q
== ' ') ) ) {
251 str
->len
= strlen(str
->str
);
254 char *pdkim_strclear(pdkim_str
*str
) {
259 void pdkim_strfree(pdkim_str
*str
) {
260 if (str
== NULL
) return;
261 if (str
->str
!= NULL
) free(str
->str
);
267 /* -------------------------------------------------------------------------- */
268 void pdkim_free_pubkey(pdkim_pubkey
*pub
) {
270 if (pub
->version
!= NULL
) free(pub
->version
);
271 if (pub
->granularity
!= NULL
) free(pub
->granularity
);
272 if (pub
->hashes
!= NULL
) free(pub
->hashes
);
273 if (pub
->keytype
!= NULL
) free(pub
->keytype
);
274 if (pub
->srvtype
!= NULL
) free(pub
->srvtype
);
275 if (pub
->notes
!= NULL
) free(pub
->notes
);
276 if (pub
->key
!= NULL
) free(pub
->key
);
282 /* -------------------------------------------------------------------------- */
283 void pdkim_free_sig(pdkim_signature
*sig
) {
285 pdkim_signature
*next
= (pdkim_signature
*)sig
->next
;
287 pdkim_stringlist
*e
= sig
->headers
;
289 pdkim_stringlist
*c
= e
;
290 if (e
->value
!= NULL
) free(e
->value
);
295 if (sig
->sigdata
!= NULL
) free(sig
->sigdata
);
296 if (sig
->bodyhash
!= NULL
) free(sig
->bodyhash
);
297 if (sig
->selector
!= NULL
) free(sig
->selector
);
298 if (sig
->domain
!= NULL
) free(sig
->domain
);
299 if (sig
->identity
!= NULL
) free(sig
->identity
);
300 if (sig
->headernames
!= NULL
) free(sig
->headernames
);
301 if (sig
->copiedheaders
!= NULL
) free(sig
->copiedheaders
);
302 if (sig
->rsa_privkey
!= NULL
) free(sig
->rsa_privkey
);
303 if (sig
->sign_headers
!= NULL
) free(sig
->sign_headers
);
304 if (sig
->signature_header
!= NULL
) free(sig
->signature_header
);
305 if (sig
->sha1_body
!= NULL
) free(sig
->sha1_body
);
306 if (sig
->sha2_body
!= NULL
) free(sig
->sha2_body
);
308 if (sig
->pubkey
!= NULL
) pdkim_free_pubkey(sig
->pubkey
);
311 if (next
!= NULL
) pdkim_free_sig(next
);
316 /* -------------------------------------------------------------------------- */
317 DLLEXPORT
void pdkim_free_ctx(pdkim_ctx
*ctx
) {
319 pdkim_stringlist
*e
= ctx
->headers
;
321 pdkim_stringlist
*c
= e
;
322 if (e
->value
!= NULL
) free(e
->value
);
326 pdkim_free_sig(ctx
->sig
);
327 pdkim_strfree(ctx
->cur_header
);
333 /* -------------------------------------------------------------------------- */
334 /* Matches the name of the passed raw "header" against
335 the passed colon-separated "list", starting at entry
336 "start". Returns the position of the header name in
338 int header_name_match(const char *header
,
347 /* Get header name */
348 char *hcolon
= strchr(header
,':');
349 if (hcolon
== NULL
) return rc
; /* This isn't a header */
350 hname
= malloc((hcolon
-header
)+1);
351 if (hname
== NULL
) return PDKIM_ERR_OOM
;
352 memset(hname
,0,(hcolon
-header
)+1);
353 strncpy(hname
,header
,(hcolon
-header
));
355 /* Copy tick-off list locally, so we can punch zeroes into it */
356 lcopy
= strdup(tick
);
359 return PDKIM_ERR_OOM
;
366 if (strcasecmp(p
,hname
) == 0) {
368 /* Invalidate header name instance in tick-off list */
369 if (do_tick
) tick
[p
-lcopy
] = '_';
377 if (strcasecmp(p
,hname
) == 0) {
379 /* Invalidate header name instance in tick-off list */
380 if (do_tick
) tick
[p
-lcopy
] = '_';
390 /* -------------------------------------------------------------------------- */
391 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
393 char *pdkim_relax_header (char *header
, int crlf
) {
394 int past_field_name
= 0;
398 char *relaxed
= malloc(strlen(header
)+3);
399 if (relaxed
== NULL
) return NULL
;
404 if ( (c
== '\r') || (c
== '\n') ) {
408 if ( (c
== '\t') || (c
== ' ') ) {
409 c
= ' '; /* Turns WSP into SP */
417 if ( (!past_field_name
) && (c
== ':') ) {
418 if (seen_wsp
) q
--; /* This removes WSP before the colon */
419 seen_wsp
= 1; /* This removes WSP after the colon */
424 /* Lowercase header name */
425 if (!past_field_name
) c
= tolower(c
);
430 if ((q
>relaxed
) && (*(q
-1) == ' ')) q
--; /* Squash eventual trailing SP */
432 if (crlf
) strcat(relaxed
,"\r\n");
437 /* -------------------------------------------------------------------------- */
438 #define PDKIM_QP_ERROR_DECODE -1
439 char *pdkim_decode_qp_char(char *qp_p
, int *c
) {
440 char *initial_pos
= qp_p
;
442 /* Advance one char */
445 /* Check for two hex digits and decode them */
446 if (isxdigit(*qp_p
) && isxdigit(qp_p
[1])) {
447 /* Do hex conversion */
448 if (isdigit(*qp_p
)) {*c
= *qp_p
- '0';}
449 else {*c
= toupper(*qp_p
) - 'A' + 10;}
451 if (isdigit(qp_p
[1])) {*c
|= qp_p
[1] - '0';}
452 else {*c
|= toupper(qp_p
[1]) - 'A' + 10;}
456 /* Illegal char here */
457 *c
= PDKIM_QP_ERROR_DECODE
;
462 /* -------------------------------------------------------------------------- */
463 char *pdkim_decode_qp(char *str
) {
467 char *n
= malloc(strlen(p
)+1);
468 if (n
== NULL
) return NULL
;
473 p
= pdkim_decode_qp_char(p
,&nchar
);
491 /* -------------------------------------------------------------------------- */
492 char *pdkim_decode_base64(char *str
, int *num_decoded
) {
496 base64_decode(NULL
, &dlen
, (unsigned char *)str
, strlen(str
));
497 res
= malloc(dlen
+1);
498 if (res
== NULL
) return NULL
;
499 if (base64_decode((unsigned char *)res
,&dlen
,(unsigned char *)str
,strlen(str
)) != 0) {
503 if (num_decoded
!= NULL
) *num_decoded
= dlen
;
507 /* -------------------------------------------------------------------------- */
508 char *pdkim_encode_base64(char *str
, int num
) {
512 base64_encode(NULL
, &dlen
, (unsigned char *)str
, num
);
513 res
= malloc(dlen
+1);
514 if (res
== NULL
) return NULL
;
515 if (base64_encode((unsigned char *)res
,&dlen
,(unsigned char *)str
,num
) != 0) {
523 /* -------------------------------------------------------------------------- */
524 #define PDKIM_HDR_LIMBO 0
525 #define PDKIM_HDR_TAG 1
526 #define PDKIM_HDR_VALUE 2
527 pdkim_signature
*pdkim_parse_sig_header(pdkim_ctx
*ctx
, char *raw_hdr
) {
528 pdkim_signature
*sig
;
530 pdkim_str
*cur_tag
= NULL
;
531 pdkim_str
*cur_val
= NULL
;
534 int where
= PDKIM_HDR_LIMBO
;
537 sig
= malloc(sizeof(pdkim_signature
));
538 if (sig
== NULL
) return NULL
;
539 memset(sig
,0,sizeof(pdkim_signature
));
540 sig
->bodylength
= -1;
542 sig
->rawsig_no_b_val
= malloc(strlen(raw_hdr
)+1);
543 if (sig
->rawsig_no_b_val
== NULL
) {
549 q
= sig
->rawsig_no_b_val
;
554 if ( (*p
== '\r') || (*p
== '\n') )
557 /* Fast-forward through header name */
559 if (*p
== ':') past_hname
= 1;
563 if (where
== PDKIM_HDR_LIMBO
) {
564 /* In limbo, just wait for a tag-char to appear */
565 if (!((*p
>= 'a') && (*p
<= 'z')))
568 where
= PDKIM_HDR_TAG
;
571 if (where
== PDKIM_HDR_TAG
) {
573 cur_tag
= pdkim_strnew(NULL
);
575 if ((*p
>= 'a') && (*p
<= 'z'))
576 pdkim_strncat(cur_tag
,p
,1);
579 if (strcmp(cur_tag
->str
,"b") == 0) {
583 where
= PDKIM_HDR_VALUE
;
588 if (where
== PDKIM_HDR_VALUE
) {
590 cur_val
= pdkim_strnew(NULL
);
592 if ( (*p
== '\r') || (*p
== '\n') || (*p
== ' ') || (*p
== '\t') )
595 if ( (*p
== ';') || (*p
== '\0') ) {
596 if (cur_tag
->len
> 0) {
597 pdkim_strtrim(cur_val
);
599 if (ctx
->debug_stream
)
600 fprintf(ctx
->debug_stream
, " %s=%s\n", cur_tag
->str
, cur_val
->str
);
602 switch (cur_tag
->str
[0]) {
604 switch (cur_tag
->str
[1]) {
606 sig
->bodyhash
= pdkim_decode_base64(cur_val
->str
,&(sig
->bodyhash_len
));
609 sig
->sigdata
= pdkim_decode_base64(cur_val
->str
,&(sig
->sigdata_len
));
614 if (strcmp(cur_val
->str
,PDKIM_SIGNATURE_VERSION
) == 0) {
615 /* We only support version 1, and that is currently the
616 only version there is. */
622 while (pdkim_algos
[i
] != NULL
) {
623 if (strcmp(cur_val
->str
,pdkim_algos
[i
]) == 0 ) {
632 while (pdkim_combined_canons
[i
].str
!= NULL
) {
633 if (strcmp(cur_val
->str
,pdkim_combined_canons
[i
].str
) == 0 ) {
634 sig
->canon_headers
= pdkim_combined_canons
[i
].canon_headers
;
635 sig
->canon_body
= pdkim_combined_canons
[i
].canon_body
;
643 while (pdkim_querymethods
[i
] != NULL
) {
644 if (strcmp(cur_val
->str
,pdkim_querymethods
[i
]) == 0 ) {
645 sig
->querymethod
= i
;
652 sig
->selector
= strdup(cur_val
->str
);
655 sig
->domain
= strdup(cur_val
->str
);
658 sig
->identity
= pdkim_decode_qp(cur_val
->str
);
661 sig
->created
= strtoul(cur_val
->str
,NULL
,10);
664 sig
->expires
= strtoul(cur_val
->str
,NULL
,10);
667 sig
->bodylength
= strtol(cur_val
->str
,NULL
,10);
670 sig
->headernames
= strdup(cur_val
->str
);
673 sig
->copiedheaders
= pdkim_decode_qp(cur_val
->str
);
677 if (ctx
->debug_stream
)
678 fprintf(ctx
->debug_stream
, " Unknown tag encountered\n");
683 pdkim_strclear(cur_tag
);
684 pdkim_strclear(cur_val
);
686 where
= PDKIM_HDR_LIMBO
;
689 else pdkim_strncat(cur_val
,p
,1);
693 if (*p
== '\0') break;
702 /* Make sure the most important bits are there. */
703 if (!(sig
->domain
&& (*(sig
->domain
) != '\0') &&
704 sig
->selector
&& (*(sig
->selector
) != '\0') &&
705 sig
->headernames
&& (*(sig
->headernames
) != '\0') &&
714 /* Chomp raw header. The final newline must not be added to the signature. */
716 while( (q
> sig
->rawsig_no_b_val
) && ((*q
== '\r') || (*q
== '\n')) ) {
721 if (ctx
->debug_stream
) {
722 fprintf(ctx
->debug_stream
,
723 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
724 pdkim_quoteprint(ctx
->debug_stream
,
725 sig
->rawsig_no_b_val
,
726 strlen(sig
->rawsig_no_b_val
), 1);
727 fprintf(ctx
->debug_stream
,
728 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
732 sig
->sha1_body
= malloc(sizeof(sha1_context
));
733 if (sig
->sha1_body
== NULL
) {
737 sig
->sha2_body
= malloc(sizeof(sha2_context
));
738 if (sig
->sha2_body
== NULL
) {
743 sha1_starts(sig
->sha1_body
);
744 sha2_starts(sig
->sha2_body
,0);
750 /* -------------------------------------------------------------------------- */
751 pdkim_pubkey
*pdkim_parse_pubkey_record(pdkim_ctx
*ctx
, char *raw_record
) {
754 pdkim_str
*cur_tag
= NULL
;
755 pdkim_str
*cur_val
= NULL
;
756 int where
= PDKIM_HDR_LIMBO
;
758 pub
= malloc(sizeof(pdkim_pubkey
));
759 if (pub
== NULL
) return NULL
;
760 memset(pub
,0,sizeof(pdkim_pubkey
));
767 if ( (*p
== '\r') || (*p
== '\n') )
770 if (where
== PDKIM_HDR_LIMBO
) {
771 /* In limbo, just wait for a tag-char to appear */
772 if (!((*p
>= 'a') && (*p
<= 'z')))
775 where
= PDKIM_HDR_TAG
;
778 if (where
== PDKIM_HDR_TAG
) {
780 cur_tag
= pdkim_strnew(NULL
);
782 if ((*p
>= 'a') && (*p
<= 'z'))
783 pdkim_strncat(cur_tag
,p
,1);
786 where
= PDKIM_HDR_VALUE
;
791 if (where
== PDKIM_HDR_VALUE
) {
793 cur_val
= pdkim_strnew(NULL
);
795 if ( (*p
== '\r') || (*p
== '\n') )
798 if ( (*p
== ';') || (*p
== '\0') ) {
799 if (cur_tag
->len
> 0) {
800 pdkim_strtrim(cur_val
);
802 if (ctx
->debug_stream
)
803 fprintf(ctx
->debug_stream
, " %s=%s\n", cur_tag
->str
, cur_val
->str
);
805 switch (cur_tag
->str
[0]) {
807 /* This tag isn't evaluated because:
808 - We only support version DKIM1.
809 - Which is the default for this value (set below)
810 - Other versions are currently not specified. */
813 pub
->hashes
= strdup(cur_val
->str
);
816 pub
->granularity
= strdup(cur_val
->str
);
819 pub
->notes
= pdkim_decode_qp(cur_val
->str
);
822 pub
->key
= pdkim_decode_base64(cur_val
->str
,&(pub
->key_len
));
825 pub
->hashes
= strdup(cur_val
->str
);
828 pub
->srvtype
= strdup(cur_val
->str
);
831 if (strchr(cur_val
->str
,'y') != NULL
) pub
->testing
= 1;
832 if (strchr(cur_val
->str
,'s') != NULL
) pub
->no_subdomaining
= 1;
836 if (ctx
->debug_stream
)
837 fprintf(ctx
->debug_stream
, " Unknown tag encountered\n");
842 pdkim_strclear(cur_tag
);
843 pdkim_strclear(cur_val
);
844 where
= PDKIM_HDR_LIMBO
;
847 else pdkim_strncat(cur_val
,p
,1);
851 if (*p
== '\0') break;
855 /* Set fallback defaults */
856 if (pub
->version
== NULL
) pub
->version
= strdup(PDKIM_PUB_RECORD_VERSION
);
857 if (pub
->granularity
== NULL
) pub
->granularity
= strdup("*");
858 if (pub
->keytype
== NULL
) pub
->keytype
= strdup("rsa");
859 if (pub
->srvtype
== NULL
) pub
->srvtype
= strdup("*");
862 if (pub
->key
== NULL
) {
863 pdkim_free_pubkey(pub
);
871 /* -------------------------------------------------------------------------- */
872 int pdkim_update_bodyhash(pdkim_ctx
*ctx
, const char *data
, int len
) {
873 pdkim_signature
*sig
= ctx
->sig
;
874 /* Cache relaxed version of data */
875 char *relaxed_data
= NULL
;
878 /* Traverse all signatures, updating their hashes. */
879 while (sig
!= NULL
) {
880 /* Defaults to simple canon (no further treatment necessary) */
881 const char *canon_data
= data
;
884 if (sig
->canon_body
== PDKIM_CANON_RELAXED
) {
885 /* Relax the line if not done already */
886 if (relaxed_data
== NULL
) {
888 const char *p
= data
;
890 relaxed_data
= malloc(len
+1);
891 if (relaxed_data
== NULL
) return PDKIM_ERR_OOM
;
895 if ( (q
> 0) && (relaxed_data
[q
-1] == ' ') ) q
--;
897 else if ( (c
== '\t') || (c
== ' ') ) {
898 c
= ' '; /* Turns WSP into SP */
906 relaxed_data
[q
++] = c
;
909 relaxed_data
[q
] = '\0';
912 canon_data
= relaxed_data
;
913 canon_len
= relaxed_len
;
916 /* Make sure we don't exceed the to-be-signed body length */
917 if ((sig
->bodylength
>= 0) &&
918 ((sig
->signed_body_bytes
+(unsigned long)canon_len
) > sig
->bodylength
))
919 canon_len
= (sig
->bodylength
- sig
->signed_body_bytes
);
922 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
923 sha1_update(sig
->sha1_body
,(unsigned char *)canon_data
,canon_len
);
925 sha2_update(sig
->sha2_body
,(unsigned char *)canon_data
,canon_len
);
926 sig
->signed_body_bytes
+= canon_len
;
928 if (ctx
->debug_stream
!=NULL
)
929 pdkim_quoteprint(ctx
->debug_stream
,canon_data
,canon_len
,1);
936 if (relaxed_data
!= NULL
) free(relaxed_data
);
941 /* -------------------------------------------------------------------------- */
942 int pdkim_finish_bodyhash(pdkim_ctx
*ctx
) {
943 pdkim_signature
*sig
= ctx
->sig
;
945 /* Traverse all signatures */
946 while (sig
!= NULL
) {
949 unsigned char bh
[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
950 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
951 sha1_finish(sig
->sha1_body
,bh
);
953 sha2_finish(sig
->sha2_body
,bh
);
956 if (ctx
->debug_stream
) {
957 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body bytes hashed: %lu\n",
958 sig
->domain
, sig
->signed_body_bytes
);
959 fprintf(ctx
->debug_stream
, "PDKIM [%s] bh computed: ", sig
->domain
);
960 pdkim_hexprint(ctx
->debug_stream
, (char *)bh
,
961 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32,1);
965 /* SIGNING -------------------------------------------------------------- */
966 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
967 sig
->bodyhash_len
= (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32;
968 sig
->bodyhash
= malloc(sig
->bodyhash_len
);
969 if (sig
->bodyhash
== NULL
) return PDKIM_ERR_OOM
;
970 memcpy(sig
->bodyhash
,bh
,sig
->bodyhash_len
);
972 /* If bodylength limit is set, and we have received less bytes
973 than the requested amount, effectively remove the limit tag. */
974 if (sig
->signed_body_bytes
< sig
->bodylength
) sig
->bodylength
= -1;
976 /* VERIFICATION --------------------------------------------------------- */
978 /* Compare bodyhash */
979 if (memcmp(bh
,sig
->bodyhash
,
980 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32) == 0) {
982 if (ctx
->debug_stream
)
983 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body hash verified OK\n",
989 if (ctx
->debug_stream
) {
990 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body hash did NOT verify\n",
992 fprintf(ctx
->debug_stream
, "PDKIM [%s] bh signature: ", sig
->domain
);
993 pdkim_hexprint(ctx
->debug_stream
, sig
->bodyhash
,
994 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32,1);
997 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
998 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_BODY
;
1010 /* -------------------------------------------------------------------------- */
1011 /* Callback from pdkim_feed below for processing complete body lines */
1012 int pdkim_bodyline_complete(pdkim_ctx
*ctx
) {
1013 char *p
= ctx
->linebuf
;
1014 int n
= ctx
->linebuf_offset
;
1016 /* Ignore extra data if we've seen the end-of-data marker */
1017 if (ctx
->seen_eod
) goto BAIL
;
1019 /* We've always got one extra byte to stuff a zero ... */
1020 ctx
->linebuf
[(ctx
->linebuf_offset
)] = '\0';
1022 if (ctx
->input_mode
== PDKIM_INPUT_SMTP
) {
1023 /* Terminate on EOD marker */
1024 if (memcmp(p
,".\r\n",3) == 0) {
1029 if (memcmp(p
,"..",2) == 0) {
1035 /* Empty lines need to be buffered until we find a non-empty line */
1036 if (memcmp(p
,"\r\n",2) == 0) {
1037 ctx
->num_buffered_crlf
++;
1042 && ctx
->sig
->canon_body
== PDKIM_CANON_RELAXED
) {
1043 /* Lines with just spaces need to be buffered too */
1045 while(memcmp(check
,"\r\n",2) != 0) {
1048 if (c
!= '\t' && c
!= ' ')
1053 ctx
->num_buffered_crlf
++;
1058 /* At this point, we have a non-empty line, so release the buffered ones. */
1059 while (ctx
->num_buffered_crlf
) {
1060 pdkim_update_bodyhash(ctx
,"\r\n",2);
1061 ctx
->num_buffered_crlf
--;
1064 pdkim_update_bodyhash(ctx
,p
,n
);
1067 ctx
->linebuf_offset
= 0;
1072 /* -------------------------------------------------------------------------- */
1073 /* Callback from pdkim_feed below for processing complete headers */
1074 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1075 int pdkim_header_complete(pdkim_ctx
*ctx
) {
1076 pdkim_signature
*sig
= ctx
->sig
;
1078 /* Special case: The last header can have an extra \r appended */
1079 if ( (ctx
->cur_header
->len
> 1) &&
1080 (ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] == '\r') ) {
1081 ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] = '\0';
1082 ctx
->cur_header
->len
--;
1086 if (ctx
->num_headers
> PDKIM_MAX_HEADERS
) goto BAIL
;
1088 /* SIGNING -------------------------------------------------------------- */
1089 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1090 /* Traverse all signatures */
1091 while (sig
!= NULL
) {
1092 pdkim_stringlist
*list
;
1094 if (header_name_match(ctx
->cur_header
->str
,
1097 PDKIM_DEFAULT_SIGN_HEADERS
, 0) != PDKIM_OK
) goto NEXT_SIG
;
1099 /* Add header to the signed headers list (in reverse order) */
1100 list
= pdkim_prepend_stringlist(sig
->headers
,
1101 ctx
->cur_header
->str
);
1102 if (list
== NULL
) return PDKIM_ERR_OOM
;
1103 sig
->headers
= list
;
1110 /* DKIM-Signature: headers are added to the verification list */
1111 if (ctx
->mode
== PDKIM_MODE_VERIFY
) {
1112 if (strncasecmp(ctx
->cur_header
->str
,
1113 DKIM_SIGNATURE_HEADERNAME
,
1114 strlen(DKIM_SIGNATURE_HEADERNAME
)) == 0) {
1115 pdkim_signature
*new_sig
;
1116 /* Create and chain new signature block */
1118 if (ctx
->debug_stream
)
1119 fprintf(ctx
->debug_stream
,
1120 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1122 new_sig
= pdkim_parse_sig_header(ctx
, ctx
->cur_header
->str
);
1123 if (new_sig
!= NULL
) {
1124 pdkim_signature
*last_sig
= ctx
->sig
;
1125 if (last_sig
== NULL
) {
1129 while (last_sig
->next
!= NULL
) { last_sig
= last_sig
->next
; }
1130 last_sig
->next
= new_sig
;
1135 if (ctx
->debug_stream
) {
1136 fprintf(ctx
->debug_stream
,"Error while parsing signature header\n");
1137 fprintf(ctx
->debug_stream
,
1138 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1143 /* every other header is stored for signature verification */
1145 pdkim_stringlist
*list
;
1147 list
= pdkim_prepend_stringlist(ctx
->headers
,
1148 ctx
->cur_header
->str
);
1149 if (list
== NULL
) return PDKIM_ERR_OOM
;
1150 ctx
->headers
= list
;
1155 pdkim_strclear(ctx
->cur_header
); /* Re-use existing pdkim_str */
1161 /* -------------------------------------------------------------------------- */
1162 #define HEADER_BUFFER_FRAG_SIZE 256
1163 DLLEXPORT
int pdkim_feed (pdkim_ctx
*ctx
,
1167 for (p
=0;p
<len
;p
++) {
1169 if (ctx
->past_headers
) {
1170 /* Processing body byte */
1171 ctx
->linebuf
[(ctx
->linebuf_offset
)++] = c
;
1173 int rc
= pdkim_bodyline_complete(ctx
); /* End of line */
1174 if (rc
!= PDKIM_OK
) return rc
;
1176 if (ctx
->linebuf_offset
== (PDKIM_MAX_BODY_LINE_LEN
-1))
1177 return PDKIM_ERR_LONG_LINE
;
1180 /* Processing header byte */
1184 int rc
= pdkim_header_complete(ctx
); /* Seen last header line */
1185 if (rc
!= PDKIM_OK
) return rc
;
1186 ctx
->past_headers
= 1;
1189 if (ctx
->debug_stream
)
1190 fprintf(ctx
->debug_stream
,
1191 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1195 else ctx
->seen_lf
= 1;
1197 else if (ctx
->seen_lf
) {
1198 if (! ((c
== '\t') || (c
== ' '))) {
1199 int rc
= pdkim_header_complete(ctx
); /* End of header */
1200 if (rc
!= PDKIM_OK
) return rc
;
1205 if (ctx
->cur_header
== NULL
) {
1206 ctx
->cur_header
= pdkim_strnew(NULL
);
1207 if (ctx
->cur_header
== NULL
) return PDKIM_ERR_OOM
;
1209 if (ctx
->cur_header
->len
< PDKIM_MAX_HEADER_LEN
)
1210 if (pdkim_strncat(ctx
->cur_header
,&data
[p
],1) == NULL
)
1211 return PDKIM_ERR_OOM
;
1218 * RFC 5322 specifies that header line length SHOULD be no more than 78
1223 * col: this int holds and receives column number (octets since last '\n')
1224 * str: partial string to append to
1225 * pad: padding, split line or space after before or after eg: ";"
1226 * intro: - must join to payload eg "h=", usually the tag name
1227 * payload: eg base64 data - long data can be split arbitrarily.
1229 * this code doesn't fold the header in some of the places that RFC4871
1230 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1231 * pairs and inside long values. it also always spaces or breaks after the
1234 * no guarantees are made for output given out-of range input. like tag
1235 * names loinger than 78, or bogus col. Input is assumed to be free of line breaks.
1238 static char *pdkim_headcat(int *col
, pdkim_str
*str
, const char*pad
,const char *intro
, const char *payload
) {
1245 pdkim_strcat(str
, "\r\n\t");
1248 pdkim_strncat(str
, pad
,l
);
1252 l
=(pad
?1:0) + (intro
?strlen(intro
):0 );
1255 { /*can't fit intro - start a new line to make room.*/
1256 pdkim_strcat(str
, "\r\n\t");
1258 l
= intro
?strlen(intro
):0;
1261 l
+= payload
? strlen(payload
):0 ;
1264 { /* this fragment will not fit on a single line */
1267 pdkim_strcat(str
, " ");
1269 pad
=NULL
; // only want this once
1274 size_t sl
=strlen(intro
);
1275 pdkim_strncat(str
, intro
,sl
);
1278 intro
=NULL
; // only want this once
1282 size_t sl
=strlen(payload
);
1283 size_t chomp
= *col
+sl
< 77 ? sl
: 78-*col
;
1284 pdkim_strncat(str
, payload
,chomp
);
1289 // the while precondition tells us it didn't fit.
1290 pdkim_strcat(str
, "\r\n\t");
1295 pdkim_strcat(str
, "\r\n\t");
1302 pdkim_strcat(str
, " ");
1309 size_t sl
=strlen(intro
);
1310 pdkim_strncat(str
, intro
,sl
);
1317 size_t sl
=strlen(payload
);
1318 pdkim_strncat(str
, payload
,sl
);
1325 /* -------------------------------------------------------------------------- */
1326 char *pdkim_create_header(pdkim_signature
*sig
, int final
) {
1328 char *base64_bh
= NULL
;
1329 char *base64_b
= NULL
;
1331 pdkim_str
*hdr
= pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION
);
1332 if (hdr
== NULL
) return NULL
;
1333 pdkim_str
*canon_all
= pdkim_strnew(pdkim_canons
[sig
->canon_headers
]);
1334 if (canon_all
== NULL
) goto BAIL
;
1336 base64_bh
= pdkim_encode_base64(sig
->bodyhash
, sig
->bodyhash_len
);
1337 if (base64_bh
== NULL
) goto BAIL
;
1339 col
=strlen(hdr
->str
);
1341 /* Required and static bits */
1343 pdkim_headcat(&col
,hdr
,";","a=",pdkim_algos
[sig
->algo
]) &&
1344 pdkim_headcat(&col
,hdr
,";","q=",pdkim_querymethods
[sig
->querymethod
]) &&
1345 pdkim_strcat(canon_all
,"/") &&
1346 pdkim_strcat(canon_all
,pdkim_canons
[sig
->canon_body
]) &&
1347 pdkim_headcat(&col
,hdr
,";","c=",canon_all
->str
) &&
1348 pdkim_headcat(&col
,hdr
,";","d=",sig
->domain
) &&
1349 pdkim_headcat(&col
,hdr
,";","s=",sig
->selector
)
1351 /* list of eader names can be split between items. */
1353 char *n
=strdup(sig
->headernames
);
1360 char *c
=strchr(n
,':');
1364 if (!pdkim_headcat(&col
,hdr
,NULL
,NULL
,":"))
1370 if( !pdkim_headcat(&col
,hdr
,s
,i
,n
))
1375 if(c
) n
=c
+1 ; else break;
1381 if(!pdkim_headcat(&col
,hdr
,";","bh=",base64_bh
))
1385 if (sig
->identity
!= NULL
) {
1386 if(!pdkim_headcat(&col
,hdr
,";","i=",sig
->identity
)){
1391 if (sig
->created
> 0) {
1393 snprintf(minibuf
,20,"%lu",sig
->created
);
1394 if(!pdkim_headcat(&col
,hdr
,";","t=",minibuf
)) {
1398 if (sig
->expires
> 0) {
1400 snprintf(minibuf
,20,"%lu",sig
->expires
);
1401 if(!pdkim_headcat(&col
,hdr
,";","x=",minibuf
)) {
1405 if (sig
->bodylength
>= 0) {
1407 snprintf(minibuf
,20,"%lu",sig
->bodylength
);
1408 if(!pdkim_headcat(&col
,hdr
,";","l=",minibuf
)) {
1413 /* Preliminary or final version? */
1415 base64_b
= pdkim_encode_base64(sig
->sigdata
, sig
->sigdata_len
);
1416 if (base64_b
== NULL
) goto BAIL
;
1417 if(!pdkim_headcat(&col
,hdr
,";","b=",base64_b
)) goto BAIL
;
1420 if(!pdkim_headcat(&col
,hdr
,";","b=","")) goto BAIL
;
1423 /* add trailing semicolon: I'm not sure if this is actually needed */
1424 if(!pdkim_headcat(&col
,hdr
,NULL
,";","")) goto BAIL
;
1430 rc
= strdup(hdr
->str
);
1434 if (canon_all
!= NULL
) pdkim_strfree(canon_all
);
1435 if (base64_bh
!= NULL
) free(base64_bh
);
1436 if (base64_b
!= NULL
) free(base64_b
);
1441 /* -------------------------------------------------------------------------- */
1442 DLLEXPORT
int pdkim_feed_finish(pdkim_ctx
*ctx
, pdkim_signature
**return_signatures
) {
1443 pdkim_signature
*sig
= ctx
->sig
;
1444 pdkim_str
*headernames
= NULL
; /* Collected signed header names */
1446 /* Check if we must still flush a (partial) header. If that is the
1447 case, the message has no body, and we must compute a body hash
1448 out of '<CR><LF>' */
1449 if (ctx
->cur_header
&& ctx
->cur_header
->len
) {
1450 int rc
= pdkim_header_complete(ctx
);
1451 if (rc
!= PDKIM_OK
) return rc
;
1452 pdkim_update_bodyhash(ctx
,"\r\n",2);
1455 /* For non-smtp input, check if there's an unfinished line in the
1456 body line buffer. If that is the case, we must add a CRLF to the
1457 hash to properly terminate the message. */
1458 if ((ctx
->input_mode
== PDKIM_INPUT_NORMAL
) && ctx
->linebuf_offset
) {
1459 pdkim_update_bodyhash(ctx
, ctx
->linebuf
, ctx
->linebuf_offset
);
1460 pdkim_update_bodyhash(ctx
,"\r\n",2);
1463 if (ctx
->debug_stream
)
1464 fprintf(ctx
->debug_stream
,
1465 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1469 /* Build (and/or evaluate) body hash */
1470 if (pdkim_finish_bodyhash(ctx
) != PDKIM_OK
) return PDKIM_ERR_OOM
;
1472 /* SIGNING -------------------------------------------------------------- */
1473 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1474 headernames
= pdkim_strnew(NULL
);
1475 if (headernames
== NULL
) return PDKIM_ERR_OOM
;
1477 /* ---------------------------------------------------------------------- */
1479 while (sig
!= NULL
) {
1480 sha1_context sha1_headers
;
1481 sha2_context sha2_headers
;
1483 char headerhash
[32];
1485 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1486 sha1_starts(&sha1_headers
);
1488 sha2_starts(&sha2_headers
,0);
1491 if (ctx
->debug_stream
)
1492 fprintf(ctx
->debug_stream
,
1493 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1496 /* SIGNING ---------------------------------------------------------------- */
1497 /* When signing, walk through our header list and add them to the hash. As we
1498 go, construct a list of the header's names to use for the h= parameter. */
1499 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1500 pdkim_stringlist
*p
= sig
->headers
;
1503 /* Collect header names (Note: colon presence is guaranteed here) */
1504 char *q
= strchr(p
->value
,':');
1505 if (pdkim_strncat(headernames
, p
->value
,
1506 (q
-(p
->value
))+((p
->next
==NULL
)?0:1)) == NULL
)
1507 return PDKIM_ERR_OOM
;
1509 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1510 rh
= pdkim_relax_header(p
->value
,1); /* cook header for relaxed canon */
1512 rh
= strdup(p
->value
); /* just copy it for simple canon */
1514 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1516 /* Feed header to the hash algorithm */
1517 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1518 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1520 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1522 if (ctx
->debug_stream
)
1523 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1529 /* VERIFICATION ----------------------------------------------------------- */
1530 /* When verifying, walk through the header name list in the h= parameter and
1531 add the headers to the hash in that order. */
1533 char *b
= strdup(sig
->headernames
);
1536 pdkim_stringlist
*hdrs
= ctx
->headers
;
1538 if (b
== NULL
) return PDKIM_ERR_OOM
;
1541 while (hdrs
!= NULL
) {
1547 hdrs
= ctx
->headers
;
1549 if (q
!= NULL
) *q
= '\0';
1550 while (hdrs
!= NULL
) {
1551 if ( (hdrs
->tag
== 0) &&
1552 (strncasecmp(hdrs
->value
,p
,strlen(p
)) == 0) &&
1553 ((hdrs
->value
)[strlen(p
)] == ':') ) {
1555 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1556 rh
= pdkim_relax_header(hdrs
->value
,1); /* cook header for relaxed canon */
1558 rh
= strdup(hdrs
->value
); /* just copy it for simple canon */
1559 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1560 /* Feed header to the hash algorithm */
1561 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1562 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1564 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1566 if (ctx
->debug_stream
)
1567 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1575 if (q
== NULL
) break;
1582 if (ctx
->debug_stream
)
1583 fprintf(ctx
->debug_stream
,
1584 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1587 /* SIGNING ---------------------------------------------------------------- */
1588 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1589 /* Copy headernames to signature struct */
1590 sig
->headernames
= strdup(headernames
->str
);
1591 pdkim_strfree(headernames
);
1593 /* Create signature header with b= omitted */
1594 sig_hdr
= pdkim_create_header(ctx
->sig
,0);
1596 /* VERIFICATION ----------------------------------------------------------- */
1598 sig_hdr
= strdup(sig
->rawsig_no_b_val
);
1600 /* ------------------------------------------------------------------------ */
1602 if (sig_hdr
== NULL
) return PDKIM_ERR_OOM
;
1604 /* Relax header if necessary */
1605 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
) {
1606 char *relaxed_hdr
= pdkim_relax_header(sig_hdr
,0);
1608 if (relaxed_hdr
== NULL
) return PDKIM_ERR_OOM
;
1609 sig_hdr
= relaxed_hdr
;
1613 if (ctx
->debug_stream
) {
1614 fprintf(ctx
->debug_stream
,
1615 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1616 pdkim_quoteprint(ctx
->debug_stream
, sig_hdr
, strlen(sig_hdr
), 1);
1617 fprintf(ctx
->debug_stream
,
1618 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1622 /* Finalize header hash */
1623 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
) {
1624 sha1_update(&(sha1_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1625 sha1_finish(&(sha1_headers
),(unsigned char *)headerhash
);
1627 if (ctx
->debug_stream
) {
1628 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1629 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 20, 1);
1634 sha2_update(&(sha2_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1635 sha2_finish(&(sha2_headers
),(unsigned char *)headerhash
);
1637 if (ctx
->debug_stream
) {
1638 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1639 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 32, 1);
1646 /* SIGNING ---------------------------------------------------------------- */
1647 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1650 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1652 /* Perform private key operation */
1653 if (rsa_parse_key(&rsa
, (unsigned char *)sig
->rsa_privkey
,
1654 strlen(sig
->rsa_privkey
), NULL
, 0) != 0) {
1655 return PDKIM_ERR_RSA_PRIVKEY
;
1658 sig
->sigdata_len
= mpi_size(&(rsa
.N
));
1659 sig
->sigdata
= malloc(sig
->sigdata_len
);
1660 if (sig
->sigdata
== NULL
) return PDKIM_ERR_OOM
;
1662 if (rsa_pkcs1_sign( &rsa
, RSA_PRIVATE
,
1663 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1664 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1666 (unsigned char *)headerhash
,
1667 (unsigned char *)sig
->sigdata
) != 0) {
1668 return PDKIM_ERR_RSA_SIGNING
;
1674 if (ctx
->debug_stream
) {
1675 fprintf(ctx
->debug_stream
, "PDKIM [%s] b computed: ",
1677 pdkim_hexprint(ctx
->debug_stream
, sig
->sigdata
, sig
->sigdata_len
, 1);
1681 sig
->signature_header
= pdkim_create_header(ctx
->sig
,1);
1682 if (sig
->signature_header
== NULL
) return PDKIM_ERR_OOM
;
1684 /* VERIFICATION ----------------------------------------------------------- */
1687 char *dns_txt_name
, *dns_txt_reply
;
1689 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1691 dns_txt_name
= malloc(PDKIM_DNS_TXT_MAX_NAMELEN
);
1692 if (dns_txt_name
== NULL
) return PDKIM_ERR_OOM
;
1693 dns_txt_reply
= malloc(PDKIM_DNS_TXT_MAX_RECLEN
);
1694 if (dns_txt_reply
== NULL
) {
1696 return PDKIM_ERR_OOM
;
1698 memset(dns_txt_reply
,0,PDKIM_DNS_TXT_MAX_RECLEN
);
1699 memset(dns_txt_name
,0,PDKIM_DNS_TXT_MAX_NAMELEN
);
1701 if (snprintf(dns_txt_name
,PDKIM_DNS_TXT_MAX_NAMELEN
,
1702 "%s._domainkey.%s.",
1703 sig
->selector
,sig
->domain
) >= PDKIM_DNS_TXT_MAX_NAMELEN
) {
1704 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1705 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_BUFFER_SIZE
;
1709 if ((ctx
->dns_txt_callback(dns_txt_name
, dns_txt_reply
) != PDKIM_OK
) ||
1710 (dns_txt_reply
[0] == '\0')) {
1711 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1712 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
;
1717 if (ctx
->debug_stream
) {
1718 fprintf(ctx
->debug_stream
,
1719 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1720 fprintf(ctx
->debug_stream
," Raw record: ");
1721 pdkim_quoteprint(ctx
->debug_stream
, dns_txt_reply
, strlen(dns_txt_reply
), 1);
1725 sig
->pubkey
= pdkim_parse_pubkey_record(ctx
,dns_txt_reply
);
1726 if (sig
->pubkey
== NULL
) {
1727 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1728 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1730 if (ctx
->debug_stream
) {
1731 fprintf(ctx
->debug_stream
," Error while parsing public key record\n");
1732 fprintf(ctx
->debug_stream
,
1733 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1740 if (ctx
->debug_stream
) {
1741 fprintf(ctx
->debug_stream
,
1742 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1746 if (rsa_parse_public_key(&rsa
,
1747 (unsigned char *)sig
->pubkey
->key
,
1748 sig
->pubkey
->key_len
) != 0) {
1749 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1750 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1754 /* Check the signature */
1755 if (rsa_pkcs1_verify(&rsa
,
1757 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1758 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1760 (unsigned char *)headerhash
,
1761 (unsigned char *)sig
->sigdata
) != 0) {
1762 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
1763 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_MESSAGE
;
1767 /* We have a winner! (if bodydhash was correct earlier) */
1768 if (sig
->verify_status
== PDKIM_VERIFY_NONE
) {
1769 sig
->verify_status
= PDKIM_VERIFY_PASS
;
1775 if (ctx
->debug_stream
) {
1776 fprintf(ctx
->debug_stream
, "PDKIM [%s] signature status: %s",
1777 sig
->domain
, pdkim_verify_status_str(sig
->verify_status
));
1778 if (sig
->verify_ext_status
> 0) {
1779 fprintf(ctx
->debug_stream
, " (%s)\n",
1780 pdkim_verify_ext_status_str(sig
->verify_ext_status
));
1783 fprintf(ctx
->debug_stream
, "\n");
1790 free(dns_txt_reply
);
1796 /* If requested, set return pointer to signature(s) */
1797 if (return_signatures
!= NULL
) {
1798 *return_signatures
= ctx
->sig
;
1805 /* -------------------------------------------------------------------------- */
1806 DLLEXPORT pdkim_ctx
*pdkim_init_verify(int input_mode
,
1807 int(*dns_txt_callback
)(char *, char *)
1809 pdkim_ctx
*ctx
= malloc(sizeof(pdkim_ctx
));
1810 if (ctx
== NULL
) return NULL
;
1811 memset(ctx
,0,sizeof(pdkim_ctx
));
1813 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1814 if (ctx
->linebuf
== NULL
) {
1819 ctx
->mode
= PDKIM_MODE_VERIFY
;
1820 ctx
->input_mode
= input_mode
;
1821 ctx
->dns_txt_callback
= dns_txt_callback
;
1827 /* -------------------------------------------------------------------------- */
1828 DLLEXPORT pdkim_ctx
*pdkim_init_sign(int input_mode
,
1831 char *rsa_privkey
) {
1833 pdkim_signature
*sig
;
1835 if (!domain
|| !selector
|| !rsa_privkey
) return NULL
;
1837 ctx
= malloc(sizeof(pdkim_ctx
));
1838 if (ctx
== NULL
) return NULL
;
1839 memset(ctx
,0,sizeof(pdkim_ctx
));
1841 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1842 if (ctx
->linebuf
== NULL
) {
1847 sig
= malloc(sizeof(pdkim_signature
));
1853 memset(sig
,0,sizeof(pdkim_signature
));
1854 sig
->bodylength
= -1;
1856 ctx
->mode
= PDKIM_MODE_SIGN
;
1857 ctx
->input_mode
= input_mode
;
1860 ctx
->sig
->domain
= strdup(domain
);
1861 ctx
->sig
->selector
= strdup(selector
);
1862 ctx
->sig
->rsa_privkey
= strdup(rsa_privkey
);
1864 if (!ctx
->sig
->domain
|| !ctx
->sig
->selector
|| !ctx
->sig
->rsa_privkey
) {
1865 pdkim_free_ctx(ctx
);
1869 ctx
->sig
->sha1_body
= malloc(sizeof(sha1_context
));
1870 if (ctx
->sig
->sha1_body
== NULL
) {
1871 pdkim_free_ctx(ctx
);
1874 sha1_starts(ctx
->sig
->sha1_body
);
1876 ctx
->sig
->sha2_body
= malloc(sizeof(sha2_context
));
1877 if (ctx
->sig
->sha2_body
== NULL
) {
1878 pdkim_free_ctx(ctx
);
1881 sha2_starts(ctx
->sig
->sha2_body
,0);
1887 /* -------------------------------------------------------------------------- */
1888 DLLEXPORT
void pdkim_set_debug_stream(pdkim_ctx
*ctx
,
1889 FILE *debug_stream
) {
1890 ctx
->debug_stream
= debug_stream
;
1894 /* -------------------------------------------------------------------------- */
1895 DLLEXPORT
int pdkim_set_optional(pdkim_ctx
*ctx
,
1902 unsigned long created
,
1903 unsigned long expires
) {
1905 if (identity
!= NULL
) {
1906 ctx
->sig
->identity
= strdup(identity
);
1907 if (ctx
->sig
->identity
== NULL
) return PDKIM_ERR_OOM
;
1910 if (sign_headers
!= NULL
) {
1911 ctx
->sig
->sign_headers
= strdup(sign_headers
);
1912 if (ctx
->sig
->sign_headers
== NULL
) return PDKIM_ERR_OOM
;
1915 ctx
->sig
->canon_headers
= canon_headers
;
1916 ctx
->sig
->canon_body
= canon_body
;
1917 ctx
->sig
->bodylength
= bodylength
;
1918 ctx
->sig
->algo
= algo
;
1919 ctx
->sig
->created
= created
;
1920 ctx
->sig
->expires
= expires
;