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] bh signature: ", sig
->domain
);
991 pdkim_hexprint(ctx
->debug_stream
, sig
->bodyhash
,
992 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32,1);
993 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body hash did NOT verify\n",
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) {
1025 /* In simple body mode, if any empty lines were buffered,
1026 replace with one. rfc 4871 3.4.3 */
1027 if (ctx
->sig
&& ctx
->sig
->canon_body
== PDKIM_CANON_SIMPLE
1028 && ctx
->num_buffered_crlf
> 0)
1029 pdkim_update_bodyhash(ctx
,"\r\n",2);
1035 if (memcmp(p
,"..",2) == 0) {
1041 /* Empty lines need to be buffered until we find a non-empty line */
1042 if (memcmp(p
,"\r\n",2) == 0) {
1043 ctx
->num_buffered_crlf
++;
1048 && ctx
->sig
->canon_body
== PDKIM_CANON_RELAXED
) {
1049 /* Lines with just spaces need to be buffered too */
1051 while(memcmp(check
,"\r\n",2) != 0) {
1054 if (c
!= '\t' && c
!= ' ')
1059 ctx
->num_buffered_crlf
++;
1064 /* At this point, we have a non-empty line, so release the buffered ones. */
1065 while (ctx
->num_buffered_crlf
) {
1066 pdkim_update_bodyhash(ctx
,"\r\n",2);
1067 ctx
->num_buffered_crlf
--;
1070 pdkim_update_bodyhash(ctx
,p
,n
);
1073 ctx
->linebuf_offset
= 0;
1078 /* -------------------------------------------------------------------------- */
1079 /* Callback from pdkim_feed below for processing complete headers */
1080 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1081 int pdkim_header_complete(pdkim_ctx
*ctx
) {
1082 pdkim_signature
*sig
= ctx
->sig
;
1084 /* Special case: The last header can have an extra \r appended */
1085 if ( (ctx
->cur_header
->len
> 1) &&
1086 (ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] == '\r') ) {
1087 ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] = '\0';
1088 ctx
->cur_header
->len
--;
1092 if (ctx
->num_headers
> PDKIM_MAX_HEADERS
) goto BAIL
;
1094 /* SIGNING -------------------------------------------------------------- */
1095 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1096 /* Traverse all signatures */
1097 while (sig
!= NULL
) {
1098 pdkim_stringlist
*list
;
1100 if (header_name_match(ctx
->cur_header
->str
,
1103 PDKIM_DEFAULT_SIGN_HEADERS
, 0) != PDKIM_OK
) goto NEXT_SIG
;
1105 /* Add header to the signed headers list (in reverse order) */
1106 list
= pdkim_prepend_stringlist(sig
->headers
,
1107 ctx
->cur_header
->str
);
1108 if (list
== NULL
) return PDKIM_ERR_OOM
;
1109 sig
->headers
= list
;
1116 /* DKIM-Signature: headers are added to the verification list */
1117 if (ctx
->mode
== PDKIM_MODE_VERIFY
) {
1118 if (strncasecmp(ctx
->cur_header
->str
,
1119 DKIM_SIGNATURE_HEADERNAME
,
1120 strlen(DKIM_SIGNATURE_HEADERNAME
)) == 0) {
1121 pdkim_signature
*new_sig
;
1122 /* Create and chain new signature block */
1124 if (ctx
->debug_stream
)
1125 fprintf(ctx
->debug_stream
,
1126 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1128 new_sig
= pdkim_parse_sig_header(ctx
, ctx
->cur_header
->str
);
1129 if (new_sig
!= NULL
) {
1130 pdkim_signature
*last_sig
= ctx
->sig
;
1131 if (last_sig
== NULL
) {
1135 while (last_sig
->next
!= NULL
) { last_sig
= last_sig
->next
; }
1136 last_sig
->next
= new_sig
;
1141 if (ctx
->debug_stream
) {
1142 fprintf(ctx
->debug_stream
,"Error while parsing signature header\n");
1143 fprintf(ctx
->debug_stream
,
1144 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1149 /* every other header is stored for signature verification */
1151 pdkim_stringlist
*list
;
1153 list
= pdkim_prepend_stringlist(ctx
->headers
,
1154 ctx
->cur_header
->str
);
1155 if (list
== NULL
) return PDKIM_ERR_OOM
;
1156 ctx
->headers
= list
;
1161 pdkim_strclear(ctx
->cur_header
); /* Re-use existing pdkim_str */
1167 /* -------------------------------------------------------------------------- */
1168 #define HEADER_BUFFER_FRAG_SIZE 256
1169 DLLEXPORT
int pdkim_feed (pdkim_ctx
*ctx
,
1173 for (p
=0;p
<len
;p
++) {
1175 if (ctx
->past_headers
) {
1176 /* Processing body byte */
1177 ctx
->linebuf
[(ctx
->linebuf_offset
)++] = c
;
1179 int rc
= pdkim_bodyline_complete(ctx
); /* End of line */
1180 if (rc
!= PDKIM_OK
) return rc
;
1182 if (ctx
->linebuf_offset
== (PDKIM_MAX_BODY_LINE_LEN
-1))
1183 return PDKIM_ERR_LONG_LINE
;
1186 /* Processing header byte */
1190 int rc
= pdkim_header_complete(ctx
); /* Seen last header line */
1191 if (rc
!= PDKIM_OK
) return rc
;
1192 ctx
->past_headers
= 1;
1195 if (ctx
->debug_stream
)
1196 fprintf(ctx
->debug_stream
,
1197 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1201 else ctx
->seen_lf
= 1;
1203 else if (ctx
->seen_lf
) {
1204 if (! ((c
== '\t') || (c
== ' '))) {
1205 int rc
= pdkim_header_complete(ctx
); /* End of header */
1206 if (rc
!= PDKIM_OK
) return rc
;
1211 if (ctx
->cur_header
== NULL
) {
1212 ctx
->cur_header
= pdkim_strnew(NULL
);
1213 if (ctx
->cur_header
== NULL
) return PDKIM_ERR_OOM
;
1215 if (ctx
->cur_header
->len
< PDKIM_MAX_HEADER_LEN
)
1216 if (pdkim_strncat(ctx
->cur_header
,&data
[p
],1) == NULL
)
1217 return PDKIM_ERR_OOM
;
1224 * RFC 5322 specifies that header line length SHOULD be no more than 78
1229 * col: this int holds and receives column number (octets since last '\n')
1230 * str: partial string to append to
1231 * pad: padding, split line or space after before or after eg: ";"
1232 * intro: - must join to payload eg "h=", usually the tag name
1233 * payload: eg base64 data - long data can be split arbitrarily.
1235 * this code doesn't fold the header in some of the places that RFC4871
1236 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1237 * pairs and inside long values. it also always spaces or breaks after the
1240 * no guarantees are made for output given out-of range input. like tag
1241 * names loinger than 78, or bogus col. Input is assumed to be free of line breaks.
1244 static char *pdkim_headcat(int *col
, pdkim_str
*str
, const char*pad
,const char *intro
, const char *payload
) {
1251 pdkim_strcat(str
, "\r\n\t");
1254 pdkim_strncat(str
, pad
,l
);
1258 l
=(pad
?1:0) + (intro
?strlen(intro
):0 );
1261 { /*can't fit intro - start a new line to make room.*/
1262 pdkim_strcat(str
, "\r\n\t");
1264 l
= intro
?strlen(intro
):0;
1267 l
+= payload
? strlen(payload
):0 ;
1270 { /* this fragment will not fit on a single line */
1273 pdkim_strcat(str
, " ");
1275 pad
=NULL
; // only want this once
1280 size_t sl
=strlen(intro
);
1281 pdkim_strncat(str
, intro
,sl
);
1284 intro
=NULL
; // only want this once
1288 size_t sl
=strlen(payload
);
1289 size_t chomp
= *col
+sl
< 77 ? sl
: 78-*col
;
1290 pdkim_strncat(str
, payload
,chomp
);
1295 // the while precondition tells us it didn't fit.
1296 pdkim_strcat(str
, "\r\n\t");
1301 pdkim_strcat(str
, "\r\n\t");
1308 pdkim_strcat(str
, " ");
1315 size_t sl
=strlen(intro
);
1316 pdkim_strncat(str
, intro
,sl
);
1323 size_t sl
=strlen(payload
);
1324 pdkim_strncat(str
, payload
,sl
);
1331 /* -------------------------------------------------------------------------- */
1332 char *pdkim_create_header(pdkim_signature
*sig
, int final
) {
1334 char *base64_bh
= NULL
;
1335 char *base64_b
= NULL
;
1337 pdkim_str
*hdr
= pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION
);
1338 if (hdr
== NULL
) return NULL
;
1339 pdkim_str
*canon_all
= pdkim_strnew(pdkim_canons
[sig
->canon_headers
]);
1340 if (canon_all
== NULL
) goto BAIL
;
1342 base64_bh
= pdkim_encode_base64(sig
->bodyhash
, sig
->bodyhash_len
);
1343 if (base64_bh
== NULL
) goto BAIL
;
1345 col
=strlen(hdr
->str
);
1347 /* Required and static bits */
1349 pdkim_headcat(&col
,hdr
,";","a=",pdkim_algos
[sig
->algo
]) &&
1350 pdkim_headcat(&col
,hdr
,";","q=",pdkim_querymethods
[sig
->querymethod
]) &&
1351 pdkim_strcat(canon_all
,"/") &&
1352 pdkim_strcat(canon_all
,pdkim_canons
[sig
->canon_body
]) &&
1353 pdkim_headcat(&col
,hdr
,";","c=",canon_all
->str
) &&
1354 pdkim_headcat(&col
,hdr
,";","d=",sig
->domain
) &&
1355 pdkim_headcat(&col
,hdr
,";","s=",sig
->selector
)
1357 /* list of eader names can be split between items. */
1359 char *n
=strdup(sig
->headernames
);
1366 char *c
=strchr(n
,':');
1370 if (!pdkim_headcat(&col
,hdr
,NULL
,NULL
,":"))
1376 if( !pdkim_headcat(&col
,hdr
,s
,i
,n
))
1381 if(c
) n
=c
+1 ; else break;
1387 if(!pdkim_headcat(&col
,hdr
,";","bh=",base64_bh
))
1391 if (sig
->identity
!= NULL
) {
1392 if(!pdkim_headcat(&col
,hdr
,";","i=",sig
->identity
)){
1397 if (sig
->created
> 0) {
1399 snprintf(minibuf
,20,"%lu",sig
->created
);
1400 if(!pdkim_headcat(&col
,hdr
,";","t=",minibuf
)) {
1404 if (sig
->expires
> 0) {
1406 snprintf(minibuf
,20,"%lu",sig
->expires
);
1407 if(!pdkim_headcat(&col
,hdr
,";","x=",minibuf
)) {
1411 if (sig
->bodylength
>= 0) {
1413 snprintf(minibuf
,20,"%lu",sig
->bodylength
);
1414 if(!pdkim_headcat(&col
,hdr
,";","l=",minibuf
)) {
1419 /* Preliminary or final version? */
1421 base64_b
= pdkim_encode_base64(sig
->sigdata
, sig
->sigdata_len
);
1422 if (base64_b
== NULL
) goto BAIL
;
1423 if(!pdkim_headcat(&col
,hdr
,";","b=",base64_b
)) goto BAIL
;
1426 if(!pdkim_headcat(&col
,hdr
,";","b=","")) goto BAIL
;
1429 /* add trailing semicolon: I'm not sure if this is actually needed */
1430 if(!pdkim_headcat(&col
,hdr
,NULL
,";","")) goto BAIL
;
1436 rc
= strdup(hdr
->str
);
1440 if (canon_all
!= NULL
) pdkim_strfree(canon_all
);
1441 if (base64_bh
!= NULL
) free(base64_bh
);
1442 if (base64_b
!= NULL
) free(base64_b
);
1447 /* -------------------------------------------------------------------------- */
1448 DLLEXPORT
int pdkim_feed_finish(pdkim_ctx
*ctx
, pdkim_signature
**return_signatures
) {
1449 pdkim_signature
*sig
= ctx
->sig
;
1450 pdkim_str
*headernames
= NULL
; /* Collected signed header names */
1452 /* Check if we must still flush a (partial) header. If that is the
1453 case, the message has no body, and we must compute a body hash
1454 out of '<CR><LF>' */
1455 if (ctx
->cur_header
&& ctx
->cur_header
->len
) {
1456 int rc
= pdkim_header_complete(ctx
);
1457 if (rc
!= PDKIM_OK
) return rc
;
1458 pdkim_update_bodyhash(ctx
,"\r\n",2);
1461 /* For non-smtp input, check if there's an unfinished line in the
1462 body line buffer. If that is the case, we must add a CRLF to the
1463 hash to properly terminate the message. */
1464 if ((ctx
->input_mode
== PDKIM_INPUT_NORMAL
) && ctx
->linebuf_offset
) {
1465 pdkim_update_bodyhash(ctx
, ctx
->linebuf
, ctx
->linebuf_offset
);
1466 pdkim_update_bodyhash(ctx
,"\r\n",2);
1469 if (ctx
->debug_stream
)
1470 fprintf(ctx
->debug_stream
,
1471 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1475 /* Build (and/or evaluate) body hash */
1476 if (pdkim_finish_bodyhash(ctx
) != PDKIM_OK
) return PDKIM_ERR_OOM
;
1478 /* SIGNING -------------------------------------------------------------- */
1479 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1480 headernames
= pdkim_strnew(NULL
);
1481 if (headernames
== NULL
) return PDKIM_ERR_OOM
;
1483 /* ---------------------------------------------------------------------- */
1485 while (sig
!= NULL
) {
1486 sha1_context sha1_headers
;
1487 sha2_context sha2_headers
;
1489 char headerhash
[32];
1491 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1492 sha1_starts(&sha1_headers
);
1494 sha2_starts(&sha2_headers
,0);
1497 if (ctx
->debug_stream
)
1498 fprintf(ctx
->debug_stream
,
1499 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1502 /* SIGNING ---------------------------------------------------------------- */
1503 /* When signing, walk through our header list and add them to the hash. As we
1504 go, construct a list of the header's names to use for the h= parameter. */
1505 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1506 pdkim_stringlist
*p
= sig
->headers
;
1509 /* Collect header names (Note: colon presence is guaranteed here) */
1510 char *q
= strchr(p
->value
,':');
1511 if (pdkim_strncat(headernames
, p
->value
,
1512 (q
-(p
->value
))+((p
->next
==NULL
)?0:1)) == NULL
)
1513 return PDKIM_ERR_OOM
;
1515 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1516 rh
= pdkim_relax_header(p
->value
,1); /* cook header for relaxed canon */
1518 rh
= strdup(p
->value
); /* just copy it for simple canon */
1520 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1522 /* Feed header to the hash algorithm */
1523 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1524 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1526 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1528 if (ctx
->debug_stream
)
1529 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1535 /* VERIFICATION ----------------------------------------------------------- */
1536 /* When verifying, walk through the header name list in the h= parameter and
1537 add the headers to the hash in that order. */
1539 char *b
= strdup(sig
->headernames
);
1542 pdkim_stringlist
*hdrs
= ctx
->headers
;
1544 if (b
== NULL
) return PDKIM_ERR_OOM
;
1547 while (hdrs
!= NULL
) {
1553 hdrs
= ctx
->headers
;
1555 if (q
!= NULL
) *q
= '\0';
1556 while (hdrs
!= NULL
) {
1557 if ( (hdrs
->tag
== 0) &&
1558 (strncasecmp(hdrs
->value
,p
,strlen(p
)) == 0) &&
1559 ((hdrs
->value
)[strlen(p
)] == ':') ) {
1561 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1562 rh
= pdkim_relax_header(hdrs
->value
,1); /* cook header for relaxed canon */
1564 rh
= strdup(hdrs
->value
); /* just copy it for simple canon */
1565 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1566 /* Feed header to the hash algorithm */
1567 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1568 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1570 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1572 if (ctx
->debug_stream
)
1573 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1581 if (q
== NULL
) break;
1588 if (ctx
->debug_stream
)
1589 fprintf(ctx
->debug_stream
,
1590 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1593 /* SIGNING ---------------------------------------------------------------- */
1594 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1595 /* Copy headernames to signature struct */
1596 sig
->headernames
= strdup(headernames
->str
);
1597 pdkim_strfree(headernames
);
1599 /* Create signature header with b= omitted */
1600 sig_hdr
= pdkim_create_header(ctx
->sig
,0);
1602 /* VERIFICATION ----------------------------------------------------------- */
1604 sig_hdr
= strdup(sig
->rawsig_no_b_val
);
1606 /* ------------------------------------------------------------------------ */
1608 if (sig_hdr
== NULL
) return PDKIM_ERR_OOM
;
1610 /* Relax header if necessary */
1611 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
) {
1612 char *relaxed_hdr
= pdkim_relax_header(sig_hdr
,0);
1614 if (relaxed_hdr
== NULL
) return PDKIM_ERR_OOM
;
1615 sig_hdr
= relaxed_hdr
;
1619 if (ctx
->debug_stream
) {
1620 fprintf(ctx
->debug_stream
,
1621 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1622 pdkim_quoteprint(ctx
->debug_stream
, sig_hdr
, strlen(sig_hdr
), 1);
1623 fprintf(ctx
->debug_stream
,
1624 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1628 /* Finalize header hash */
1629 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
) {
1630 sha1_update(&(sha1_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1631 sha1_finish(&(sha1_headers
),(unsigned char *)headerhash
);
1633 if (ctx
->debug_stream
) {
1634 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1635 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 20, 1);
1640 sha2_update(&(sha2_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1641 sha2_finish(&(sha2_headers
),(unsigned char *)headerhash
);
1643 if (ctx
->debug_stream
) {
1644 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1645 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 32, 1);
1652 /* SIGNING ---------------------------------------------------------------- */
1653 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1656 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1658 /* Perform private key operation */
1659 if (rsa_parse_key(&rsa
, (unsigned char *)sig
->rsa_privkey
,
1660 strlen(sig
->rsa_privkey
), NULL
, 0) != 0) {
1661 return PDKIM_ERR_RSA_PRIVKEY
;
1664 sig
->sigdata_len
= mpi_size(&(rsa
.N
));
1665 sig
->sigdata
= malloc(sig
->sigdata_len
);
1666 if (sig
->sigdata
== NULL
) return PDKIM_ERR_OOM
;
1668 if (rsa_pkcs1_sign( &rsa
, RSA_PRIVATE
,
1669 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1670 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1672 (unsigned char *)headerhash
,
1673 (unsigned char *)sig
->sigdata
) != 0) {
1674 return PDKIM_ERR_RSA_SIGNING
;
1680 if (ctx
->debug_stream
) {
1681 fprintf(ctx
->debug_stream
, "PDKIM [%s] b computed: ",
1683 pdkim_hexprint(ctx
->debug_stream
, sig
->sigdata
, sig
->sigdata_len
, 1);
1687 sig
->signature_header
= pdkim_create_header(ctx
->sig
,1);
1688 if (sig
->signature_header
== NULL
) return PDKIM_ERR_OOM
;
1690 /* VERIFICATION ----------------------------------------------------------- */
1693 char *dns_txt_name
, *dns_txt_reply
;
1695 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1697 dns_txt_name
= malloc(PDKIM_DNS_TXT_MAX_NAMELEN
);
1698 if (dns_txt_name
== NULL
) return PDKIM_ERR_OOM
;
1699 dns_txt_reply
= malloc(PDKIM_DNS_TXT_MAX_RECLEN
);
1700 if (dns_txt_reply
== NULL
) {
1702 return PDKIM_ERR_OOM
;
1704 memset(dns_txt_reply
,0,PDKIM_DNS_TXT_MAX_RECLEN
);
1705 memset(dns_txt_name
,0,PDKIM_DNS_TXT_MAX_NAMELEN
);
1707 if (snprintf(dns_txt_name
,PDKIM_DNS_TXT_MAX_NAMELEN
,
1708 "%s._domainkey.%s.",
1709 sig
->selector
,sig
->domain
) >= PDKIM_DNS_TXT_MAX_NAMELEN
) {
1710 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1711 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_BUFFER_SIZE
;
1715 if ((ctx
->dns_txt_callback(dns_txt_name
, dns_txt_reply
) != PDKIM_OK
) ||
1716 (dns_txt_reply
[0] == '\0')) {
1717 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1718 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
;
1723 if (ctx
->debug_stream
) {
1724 fprintf(ctx
->debug_stream
,
1725 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1726 fprintf(ctx
->debug_stream
," Raw record: ");
1727 pdkim_quoteprint(ctx
->debug_stream
, dns_txt_reply
, strlen(dns_txt_reply
), 1);
1731 sig
->pubkey
= pdkim_parse_pubkey_record(ctx
,dns_txt_reply
);
1732 if (sig
->pubkey
== NULL
) {
1733 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1734 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1736 if (ctx
->debug_stream
) {
1737 fprintf(ctx
->debug_stream
," Error while parsing public key record\n");
1738 fprintf(ctx
->debug_stream
,
1739 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1746 if (ctx
->debug_stream
) {
1747 fprintf(ctx
->debug_stream
,
1748 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1752 if (rsa_parse_public_key(&rsa
,
1753 (unsigned char *)sig
->pubkey
->key
,
1754 sig
->pubkey
->key_len
) != 0) {
1755 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1756 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1760 /* Check the signature */
1761 if (rsa_pkcs1_verify(&rsa
,
1763 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1764 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1766 (unsigned char *)headerhash
,
1767 (unsigned char *)sig
->sigdata
) != 0) {
1768 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
1769 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_MESSAGE
;
1773 /* We have a winner! (if bodydhash was correct earlier) */
1774 if (sig
->verify_status
== PDKIM_VERIFY_NONE
) {
1775 sig
->verify_status
= PDKIM_VERIFY_PASS
;
1781 if (ctx
->debug_stream
) {
1782 fprintf(ctx
->debug_stream
, "PDKIM [%s] signature status: %s",
1783 sig
->domain
, pdkim_verify_status_str(sig
->verify_status
));
1784 if (sig
->verify_ext_status
> 0) {
1785 fprintf(ctx
->debug_stream
, " (%s)\n",
1786 pdkim_verify_ext_status_str(sig
->verify_ext_status
));
1789 fprintf(ctx
->debug_stream
, "\n");
1796 free(dns_txt_reply
);
1802 /* If requested, set return pointer to signature(s) */
1803 if (return_signatures
!= NULL
) {
1804 *return_signatures
= ctx
->sig
;
1811 /* -------------------------------------------------------------------------- */
1812 DLLEXPORT pdkim_ctx
*pdkim_init_verify(int input_mode
,
1813 int(*dns_txt_callback
)(char *, char *)
1815 pdkim_ctx
*ctx
= malloc(sizeof(pdkim_ctx
));
1816 if (ctx
== NULL
) return NULL
;
1817 memset(ctx
,0,sizeof(pdkim_ctx
));
1819 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1820 if (ctx
->linebuf
== NULL
) {
1825 ctx
->mode
= PDKIM_MODE_VERIFY
;
1826 ctx
->input_mode
= input_mode
;
1827 ctx
->dns_txt_callback
= dns_txt_callback
;
1833 /* -------------------------------------------------------------------------- */
1834 DLLEXPORT pdkim_ctx
*pdkim_init_sign(int input_mode
,
1837 char *rsa_privkey
) {
1839 pdkim_signature
*sig
;
1841 if (!domain
|| !selector
|| !rsa_privkey
) return NULL
;
1843 ctx
= malloc(sizeof(pdkim_ctx
));
1844 if (ctx
== NULL
) return NULL
;
1845 memset(ctx
,0,sizeof(pdkim_ctx
));
1847 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1848 if (ctx
->linebuf
== NULL
) {
1853 sig
= malloc(sizeof(pdkim_signature
));
1859 memset(sig
,0,sizeof(pdkim_signature
));
1860 sig
->bodylength
= -1;
1862 ctx
->mode
= PDKIM_MODE_SIGN
;
1863 ctx
->input_mode
= input_mode
;
1866 ctx
->sig
->domain
= strdup(domain
);
1867 ctx
->sig
->selector
= strdup(selector
);
1868 ctx
->sig
->rsa_privkey
= strdup(rsa_privkey
);
1870 if (!ctx
->sig
->domain
|| !ctx
->sig
->selector
|| !ctx
->sig
->rsa_privkey
) {
1871 pdkim_free_ctx(ctx
);
1875 ctx
->sig
->sha1_body
= malloc(sizeof(sha1_context
));
1876 if (ctx
->sig
->sha1_body
== NULL
) {
1877 pdkim_free_ctx(ctx
);
1880 sha1_starts(ctx
->sig
->sha1_body
);
1882 ctx
->sig
->sha2_body
= malloc(sizeof(sha2_context
));
1883 if (ctx
->sig
->sha2_body
== NULL
) {
1884 pdkim_free_ctx(ctx
);
1887 sha2_starts(ctx
->sig
->sha2_body
,0);
1893 /* -------------------------------------------------------------------------- */
1894 DLLEXPORT
void pdkim_set_debug_stream(pdkim_ctx
*ctx
,
1895 FILE *debug_stream
) {
1896 ctx
->debug_stream
= debug_stream
;
1900 /* -------------------------------------------------------------------------- */
1901 DLLEXPORT
int pdkim_set_optional(pdkim_ctx
*ctx
,
1908 unsigned long created
,
1909 unsigned long expires
) {
1911 if (identity
!= NULL
) {
1912 ctx
->sig
->identity
= strdup(identity
);
1913 if (ctx
->sig
->identity
== NULL
) return PDKIM_ERR_OOM
;
1916 if (sign_headers
!= NULL
) {
1917 ctx
->sig
->sign_headers
= strdup(sign_headers
);
1918 if (ctx
->sig
->sign_headers
== NULL
) return PDKIM_ERR_OOM
;
1921 ctx
->sig
->canon_headers
= canon_headers
;
1922 ctx
->sig
->canon_body
= canon_body
;
1923 ctx
->sig
->bodylength
= bodylength
;
1924 ctx
->sig
->algo
= algo
;
1925 ctx
->sig
->created
= created
;
1926 ctx
->sig
->expires
= expires
;