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.
35 #define PDKIM_SIGNATURE_VERSION "1"
36 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
38 #define PDKIM_MAX_HEADER_LEN 65536
39 #define PDKIM_MAX_HEADERS 512
40 #define PDKIM_MAX_BODY_LINE_LEN 16384
41 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
42 #define PDKIM_DEFAULT_SIGN_HEADERS "From:Sender:Reply-To:Subject:Date:"\
43 "Message-ID:To:Cc:MIME-Version:Content-Type:"\
44 "Content-Transfer-Encoding:Content-ID:"\
45 "Content-Description:Resent-Date:Resent-From:"\
46 "Resent-Sender:Resent-To:Resent-Cc:"\
47 "Resent-Message-ID:In-Reply-To:References:"\
48 "List-Id:List-Help:List-Unsubscribe:"\
49 "List-Subscribe:List-Post:List-Owner:List-Archive"
51 /* -------------------------------------------------------------------------- */
52 struct pdkim_stringlist
{
58 #define PDKIM_STR_ALLOC_FRAG 256
62 unsigned int allocated
;
65 /* -------------------------------------------------------------------------- */
66 /* A bunch of list constants */
67 const char *pdkim_querymethods
[] = {
71 const char *pdkim_algos
[] = {
76 const char *pdkim_canons
[] = {
81 const char *pdkim_hashes
[] = {
86 const char *pdkim_keytypes
[] = {
91 typedef struct pdkim_combined_canon_entry
{
95 } pdkim_combined_canon_entry
;
96 pdkim_combined_canon_entry pdkim_combined_canons
[] = {
97 { "simple/simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
98 { "simple/relaxed", PDKIM_CANON_SIMPLE
, PDKIM_CANON_RELAXED
},
99 { "relaxed/simple", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
100 { "relaxed/relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_RELAXED
},
101 { "simple", PDKIM_CANON_SIMPLE
, PDKIM_CANON_SIMPLE
},
102 { "relaxed", PDKIM_CANON_RELAXED
, PDKIM_CANON_SIMPLE
},
107 const char *pdkim_verify_status_str(int status
) {
109 case PDKIM_VERIFY_NONE
: return "PDKIM_VERIFY_NONE";
110 case PDKIM_VERIFY_INVALID
: return "PDKIM_VERIFY_INVALID";
111 case PDKIM_VERIFY_FAIL
: return "PDKIM_VERIFY_FAIL";
112 case PDKIM_VERIFY_PASS
: return "PDKIM_VERIFY_PASS";
113 default: return "PDKIM_VERIFY_UNKNOWN";
116 const char *pdkim_verify_ext_status_str(int ext_status
) {
118 case PDKIM_VERIFY_FAIL_BODY
: return "PDKIM_VERIFY_FAIL_BODY";
119 case PDKIM_VERIFY_FAIL_MESSAGE
: return "PDKIM_VERIFY_FAIL_MESSAGE";
120 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
121 case PDKIM_VERIFY_INVALID_BUFFER_SIZE
: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
122 case PDKIM_VERIFY_INVALID_PUBKEY_PARSING
: return "PDKIM_VERIFY_INVALID_PUBKEY_PARSING";
123 default: return "PDKIM_VERIFY_UNKNOWN";
128 /* -------------------------------------------------------------------------- */
129 /* Print debugging functions */
131 void pdkim_quoteprint(FILE *stream
, const char *data
, int len
, int lf
) {
133 const unsigned char *p
= (const unsigned char *)data
;
135 for (i
=0;i
<len
;i
++) {
138 case ' ' : fprintf(stream
,"{SP}"); break;
139 case '\t': fprintf(stream
,"{TB}"); break;
140 case '\r': fprintf(stream
,"{CR}"); break;
141 case '\n': fprintf(stream
,"{LF}"); break;
142 case '{' : fprintf(stream
,"{BO}"); break;
143 case '}' : fprintf(stream
,"{BC}"); break;
145 if ( (c
< 32) || (c
> 127) )
146 fprintf(stream
,"{%02x}",c
);
155 void pdkim_hexprint(FILE *stream
, const char *data
, int len
, int lf
) {
157 const unsigned char *p
= (const unsigned char *)data
;
159 for (i
=0;i
<len
;i
++) {
161 fprintf(stream
,"%02x",c
);
169 /* -------------------------------------------------------------------------- */
170 /* Simple string list implementation for convinience */
171 pdkim_stringlist
*pdkim_append_stringlist(pdkim_stringlist
*base
, char *str
) {
172 pdkim_stringlist
*new_entry
= malloc(sizeof(pdkim_stringlist
));
173 if (new_entry
== NULL
) return NULL
;
174 memset(new_entry
,0,sizeof(pdkim_stringlist
));
175 new_entry
->value
= strdup(str
);
176 if (new_entry
->value
== NULL
) return NULL
;
178 pdkim_stringlist
*last
= base
;
179 while (last
->next
!= NULL
) { last
= last
->next
; }
180 last
->next
= new_entry
;
183 else return new_entry
;
185 pdkim_stringlist
*pdkim_prepend_stringlist(pdkim_stringlist
*base
, char *str
) {
186 pdkim_stringlist
*new_entry
= malloc(sizeof(pdkim_stringlist
));
187 if (new_entry
== NULL
) return NULL
;
188 memset(new_entry
,0,sizeof(pdkim_stringlist
));
189 new_entry
->value
= strdup(str
);
190 if (new_entry
->value
== NULL
) return NULL
;
192 new_entry
->next
= base
;
198 /* -------------------------------------------------------------------------- */
199 /* A small "growing string" implementation to escape malloc/realloc hell */
200 pdkim_str
*pdkim_strnew (const char *cstr
) {
201 unsigned int len
= cstr
?strlen(cstr
):0;
202 pdkim_str
*p
= malloc(sizeof(pdkim_str
));
203 if (p
== NULL
) return NULL
;
204 memset(p
,0,sizeof(pdkim_str
));
205 p
->str
= malloc(len
+1);
206 if (p
->str
== NULL
) {
210 p
->allocated
=(len
+1);
212 if (cstr
) strcpy(p
->str
,cstr
);
213 else p
->str
[p
->len
] = '\0';
216 char *pdkim_strncat(pdkim_str
*str
, const char *data
, int len
) {
217 if ((str
->allocated
- str
->len
) < (len
+1)) {
218 /* Extend the buffer */
219 int num_frags
= ((len
+1)/PDKIM_STR_ALLOC_FRAG
)+1;
220 char *n
= realloc(str
->str
,
221 (str
->allocated
+(num_frags
*PDKIM_STR_ALLOC_FRAG
)));
222 if (n
== NULL
) return NULL
;
224 str
->allocated
+= (num_frags
*PDKIM_STR_ALLOC_FRAG
);
226 strncpy(&(str
->str
[str
->len
]),data
,len
);
228 str
->str
[str
->len
] = '\0';
231 char *pdkim_strcat(pdkim_str
*str
, const char *cstr
) {
232 return pdkim_strncat(str
, cstr
, strlen(cstr
));
235 char *pdkim_numcat(pdkim_str
*str
, unsigned long num
) {
237 snprintf(minibuf
,20,"%lu",num
);
238 return pdkim_strcat(str
,minibuf
);
240 char *pdkim_strtrim(pdkim_str
*str
) {
243 while ( (*p
!= '\0') && ((*p
== '\t') || (*p
== ' ')) ) p
++;
244 while (*p
!= '\0') {*q
= *p
; q
++; p
++;}
246 while ( (q
!= str
->str
) && ( (*q
== '\0') || (*q
== '\t') || (*q
== ' ') ) ) {
250 str
->len
= strlen(str
->str
);
253 char *pdkim_strclear(pdkim_str
*str
) {
258 void pdkim_strfree(pdkim_str
*str
) {
259 if (str
== NULL
) return;
260 if (str
->str
!= NULL
) free(str
->str
);
266 /* -------------------------------------------------------------------------- */
267 void pdkim_free_pubkey(pdkim_pubkey
*pub
) {
269 if (pub
->version
!= NULL
) free(pub
->version
);
270 if (pub
->granularity
!= NULL
) free(pub
->granularity
);
271 if (pub
->hashes
!= NULL
) free(pub
->hashes
);
272 if (pub
->keytype
!= NULL
) free(pub
->keytype
);
273 if (pub
->srvtype
!= NULL
) free(pub
->srvtype
);
274 if (pub
->notes
!= NULL
) free(pub
->notes
);
275 if (pub
->key
!= NULL
) free(pub
->key
);
281 /* -------------------------------------------------------------------------- */
282 void pdkim_free_sig(pdkim_signature
*sig
) {
284 pdkim_signature
*next
= (pdkim_signature
*)sig
->next
;
286 pdkim_stringlist
*e
= sig
->headers
;
288 pdkim_stringlist
*c
= e
;
289 if (e
->value
!= NULL
) free(e
->value
);
294 if (sig
->sigdata
!= NULL
) free(sig
->sigdata
);
295 if (sig
->bodyhash
!= NULL
) free(sig
->bodyhash
);
296 if (sig
->selector
!= NULL
) free(sig
->selector
);
297 if (sig
->domain
!= NULL
) free(sig
->domain
);
298 if (sig
->identity
!= NULL
) free(sig
->identity
);
299 if (sig
->headernames
!= NULL
) free(sig
->headernames
);
300 if (sig
->copiedheaders
!= NULL
) free(sig
->copiedheaders
);
301 if (sig
->rsa_privkey
!= NULL
) free(sig
->rsa_privkey
);
302 if (sig
->sign_headers
!= NULL
) free(sig
->sign_headers
);
303 if (sig
->signature_header
!= NULL
) free(sig
->signature_header
);
304 if (sig
->sha1_body
!= NULL
) free(sig
->sha1_body
);
305 if (sig
->sha2_body
!= NULL
) free(sig
->sha2_body
);
307 if (sig
->pubkey
!= NULL
) pdkim_free_pubkey(sig
->pubkey
);
310 if (next
!= NULL
) pdkim_free_sig(next
);
315 /* -------------------------------------------------------------------------- */
316 DLLEXPORT
void pdkim_free_ctx(pdkim_ctx
*ctx
) {
318 pdkim_stringlist
*e
= ctx
->headers
;
320 pdkim_stringlist
*c
= e
;
321 if (e
->value
!= NULL
) free(e
->value
);
325 pdkim_free_sig(ctx
->sig
);
326 pdkim_strfree(ctx
->cur_header
);
332 /* -------------------------------------------------------------------------- */
333 /* Matches the name of the passed raw "header" against
334 the passed colon-separated "list", starting at entry
335 "start". Returns the position of the header name in
337 int header_name_match(const char *header
,
346 /* Get header name */
347 char *hcolon
= strchr(header
,':');
348 if (hcolon
== NULL
) return rc
; /* This isn't a header */
349 hname
= malloc((hcolon
-header
)+1);
350 if (hname
== NULL
) return PDKIM_ERR_OOM
;
351 memset(hname
,0,(hcolon
-header
)+1);
352 strncpy(hname
,header
,(hcolon
-header
));
354 /* Copy tick-off list locally, so we can punch zeroes into it */
355 lcopy
= strdup(tick
);
358 return PDKIM_ERR_OOM
;
365 if (strcasecmp(p
,hname
) == 0) {
367 /* Invalidate header name instance in tick-off list */
368 if (do_tick
) tick
[p
-lcopy
] = '_';
376 if (strcasecmp(p
,hname
) == 0) {
378 /* Invalidate header name instance in tick-off list */
379 if (do_tick
) tick
[p
-lcopy
] = '_';
389 /* -------------------------------------------------------------------------- */
390 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
392 char *pdkim_relax_header (char *header
, int crlf
) {
393 int past_field_name
= 0;
397 char *relaxed
= malloc(strlen(header
)+3);
398 if (relaxed
== NULL
) return NULL
;
403 if ( (c
== '\r') || (c
== '\n') ) {
407 if ( (c
== '\t') || (c
== ' ') ) {
408 c
= ' '; /* Turns WSP into SP */
416 if ( (!past_field_name
) && (c
== ':') ) {
417 if (seen_wsp
) q
--; /* This removes WSP before the colon */
418 seen_wsp
= 1; /* This removes WSP after the colon */
423 /* Lowercase header name */
424 if (!past_field_name
) c
= tolower(c
);
429 if ((q
>relaxed
) && (*(q
-1) == ' ')) q
--; /* Squash eventual trailing SP */
431 if (crlf
) strcat(relaxed
,"\r\n");
436 /* -------------------------------------------------------------------------- */
437 #define PDKIM_QP_ERROR_DECODE -1
438 char *pdkim_decode_qp_char(char *qp_p
, int *c
) {
439 char *initial_pos
= qp_p
;
441 /* Advance one char */
444 /* Check for two hex digits and decode them */
445 if (isxdigit(*qp_p
) && isxdigit(qp_p
[1])) {
446 /* Do hex conversion */
447 if (isdigit(*qp_p
)) {*c
= *qp_p
- '0';}
448 else {*c
= toupper(*qp_p
) - 'A' + 10;}
450 if (isdigit(qp_p
[1])) {*c
|= qp_p
[1] - '0';}
451 else {*c
|= toupper(qp_p
[1]) - 'A' + 10;}
455 /* Illegal char here */
456 *c
= PDKIM_QP_ERROR_DECODE
;
461 /* -------------------------------------------------------------------------- */
462 char *pdkim_decode_qp(char *str
) {
466 char *n
= malloc(strlen(p
)+1);
467 if (n
== NULL
) return NULL
;
472 p
= pdkim_decode_qp_char(p
,&nchar
);
490 /* -------------------------------------------------------------------------- */
491 char *pdkim_decode_base64(char *str
, int *num_decoded
) {
495 base64_decode(NULL
, &dlen
, (unsigned char *)str
, strlen(str
));
496 res
= malloc(dlen
+1);
497 if (res
== NULL
) return NULL
;
498 if (base64_decode((unsigned char *)res
,&dlen
,(unsigned char *)str
,strlen(str
)) != 0) {
502 if (num_decoded
!= NULL
) *num_decoded
= dlen
;
506 /* -------------------------------------------------------------------------- */
507 char *pdkim_encode_base64(char *str
, int num
) {
511 base64_encode(NULL
, &dlen
, (unsigned char *)str
, num
);
512 res
= malloc(dlen
+1);
513 if (res
== NULL
) return NULL
;
514 if (base64_encode((unsigned char *)res
,&dlen
,(unsigned char *)str
,num
) != 0) {
522 /* -------------------------------------------------------------------------- */
523 #define PDKIM_HDR_LIMBO 0
524 #define PDKIM_HDR_TAG 1
525 #define PDKIM_HDR_VALUE 2
526 pdkim_signature
*pdkim_parse_sig_header(pdkim_ctx
*ctx
, char *raw_hdr
) {
527 pdkim_signature
*sig
;
529 pdkim_str
*cur_tag
= NULL
;
530 pdkim_str
*cur_val
= NULL
;
533 int where
= PDKIM_HDR_LIMBO
;
536 sig
= malloc(sizeof(pdkim_signature
));
537 if (sig
== NULL
) return NULL
;
538 memset(sig
,0,sizeof(pdkim_signature
));
539 sig
->bodylength
= -1;
541 sig
->rawsig_no_b_val
= malloc(strlen(raw_hdr
)+1);
542 if (sig
->rawsig_no_b_val
== NULL
) {
548 q
= sig
->rawsig_no_b_val
;
553 if ( (*p
== '\r') || (*p
== '\n') )
556 /* Fast-forward through header name */
558 if (*p
== ':') past_hname
= 1;
562 if (where
== PDKIM_HDR_LIMBO
) {
563 /* In limbo, just wait for a tag-char to appear */
564 if (!((*p
>= 'a') && (*p
<= 'z')))
567 where
= PDKIM_HDR_TAG
;
570 if (where
== PDKIM_HDR_TAG
) {
572 cur_tag
= pdkim_strnew(NULL
);
574 if ((*p
>= 'a') && (*p
<= 'z'))
575 pdkim_strncat(cur_tag
,p
,1);
578 if (strcmp(cur_tag
->str
,"b") == 0) {
582 where
= PDKIM_HDR_VALUE
;
587 if (where
== PDKIM_HDR_VALUE
) {
589 cur_val
= pdkim_strnew(NULL
);
591 if ( (*p
== '\r') || (*p
== '\n') || (*p
== ' ') || (*p
== '\t') )
594 if ( (*p
== ';') || (*p
== '\0') ) {
595 if (cur_tag
->len
> 0) {
596 pdkim_strtrim(cur_val
);
598 if (ctx
->debug_stream
)
599 fprintf(ctx
->debug_stream
, "%s=%s\n", cur_tag
->str
, cur_val
->str
);
601 switch (cur_tag
->str
[0]) {
603 switch (cur_tag
->str
[1]) {
605 sig
->bodyhash
= pdkim_decode_base64(cur_val
->str
,&(sig
->bodyhash_len
));
608 sig
->sigdata
= pdkim_decode_base64(cur_val
->str
,&(sig
->sigdata_len
));
613 if (strcmp(cur_val
->str
,PDKIM_SIGNATURE_VERSION
) == 0) {
614 /* We only support version 1, and that is currently the
615 only version there is. */
621 while (pdkim_algos
[i
] != NULL
) {
622 if (strcmp(cur_val
->str
,pdkim_algos
[i
]) == 0 ) {
631 while (pdkim_combined_canons
[i
].str
!= NULL
) {
632 if (strcmp(cur_val
->str
,pdkim_combined_canons
[i
].str
) == 0 ) {
633 sig
->canon_headers
= pdkim_combined_canons
[i
].canon_headers
;
634 sig
->canon_body
= pdkim_combined_canons
[i
].canon_body
;
642 while (pdkim_querymethods
[i
] != NULL
) {
643 if (strcmp(cur_val
->str
,pdkim_querymethods
[i
]) == 0 ) {
644 sig
->querymethod
= i
;
651 sig
->selector
= strdup(cur_val
->str
);
654 sig
->domain
= strdup(cur_val
->str
);
657 sig
->identity
= pdkim_decode_qp(cur_val
->str
);
660 sig
->created
= strtoul(cur_val
->str
,NULL
,10);
663 sig
->expires
= strtoul(cur_val
->str
,NULL
,10);
666 sig
->bodylength
= strtol(cur_val
->str
,NULL
,10);
669 sig
->headernames
= strdup(cur_val
->str
);
672 sig
->copiedheaders
= pdkim_decode_qp(cur_val
->str
);
676 if (ctx
->debug_stream
)
677 fprintf(ctx
->debug_stream
, "Unknown tag encountered\n");
682 pdkim_strclear(cur_tag
);
683 pdkim_strclear(cur_val
);
685 where
= PDKIM_HDR_LIMBO
;
688 else pdkim_strncat(cur_val
,p
,1);
692 if (*p
== '\0') break;
701 /* Make sure the most important bits are there. */
702 if (!(sig
->domain
&& (*(sig
->domain
) != '\0') &&
703 sig
->selector
&& (*(sig
->selector
) != '\0') &&
704 sig
->headernames
&& (*(sig
->headernames
) != '\0') &&
713 /* Chomp raw header. The final newline must not be added to the signature. */
715 while( (q
> sig
->rawsig_no_b_val
) && ((*q
== '\r') || (*q
== '\n')) ) {
720 if (ctx
->debug_stream
) {
721 fprintf(ctx
->debug_stream
,
722 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
723 pdkim_quoteprint(ctx
->debug_stream
,
724 sig
->rawsig_no_b_val
,
725 strlen(sig
->rawsig_no_b_val
), 1);
726 fprintf(ctx
->debug_stream
,
727 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
731 sig
->sha1_body
= malloc(sizeof(sha1_context
));
732 if (sig
->sha1_body
== NULL
) {
736 sig
->sha2_body
= malloc(sizeof(sha2_context
));
737 if (sig
->sha2_body
== NULL
) {
742 sha1_starts(sig
->sha1_body
);
743 sha2_starts(sig
->sha2_body
,0);
749 /* -------------------------------------------------------------------------- */
750 pdkim_pubkey
*pdkim_parse_pubkey_record(pdkim_ctx
*ctx
, char *raw_record
) {
753 pdkim_str
*cur_tag
= NULL
;
754 pdkim_str
*cur_val
= NULL
;
755 int where
= PDKIM_HDR_LIMBO
;
757 pub
= malloc(sizeof(pdkim_pubkey
));
758 if (pub
== NULL
) return NULL
;
759 memset(pub
,0,sizeof(pdkim_pubkey
));
766 if ( (*p
== '\r') || (*p
== '\n') )
769 if (where
== PDKIM_HDR_LIMBO
) {
770 /* In limbo, just wait for a tag-char to appear */
771 if (!((*p
>= 'a') && (*p
<= 'z')))
774 where
= PDKIM_HDR_TAG
;
777 if (where
== PDKIM_HDR_TAG
) {
779 cur_tag
= pdkim_strnew(NULL
);
781 if ((*p
>= 'a') && (*p
<= 'z'))
782 pdkim_strncat(cur_tag
,p
,1);
785 where
= PDKIM_HDR_VALUE
;
790 if (where
== PDKIM_HDR_VALUE
) {
792 cur_val
= pdkim_strnew(NULL
);
794 if ( (*p
== '\r') || (*p
== '\n') )
797 if ( (*p
== ';') || (*p
== '\0') ) {
798 if (cur_tag
->len
> 0) {
799 pdkim_strtrim(cur_val
);
801 if (ctx
->debug_stream
)
802 fprintf(ctx
->debug_stream
, "%s=%s\n", cur_tag
->str
, cur_val
->str
);
804 switch (cur_tag
->str
[0]) {
806 /* This tag isn't evaluated because:
807 - We only support version DKIM1.
808 - Which is the default for this value (set below)
809 - Other versions are currently not specified. */
812 pub
->hashes
= strdup(cur_val
->str
);
815 pub
->granularity
= strdup(cur_val
->str
);
818 pub
->notes
= pdkim_decode_qp(cur_val
->str
);
821 pub
->key
= pdkim_decode_base64(cur_val
->str
,&(pub
->key_len
));
824 pub
->hashes
= strdup(cur_val
->str
);
827 pub
->srvtype
= strdup(cur_val
->str
);
830 if (strchr(cur_val
->str
,'y') != NULL
) pub
->testing
= 1;
831 if (strchr(cur_val
->str
,'s') != NULL
) pub
->no_subdomaining
= 1;
835 if (ctx
->debug_stream
)
836 fprintf(ctx
->debug_stream
, "Unknown tag encountered\n");
841 pdkim_strclear(cur_tag
);
842 pdkim_strclear(cur_val
);
843 where
= PDKIM_HDR_LIMBO
;
846 else pdkim_strncat(cur_val
,p
,1);
850 if (*p
== '\0') break;
854 /* Set fallback defaults */
855 if (pub
->version
== NULL
) pub
->version
= strdup(PDKIM_PUB_RECORD_VERSION
);
856 if (pub
->granularity
== NULL
) pub
->granularity
= strdup("*");
857 if (pub
->keytype
== NULL
) pub
->keytype
= strdup("rsa");
858 if (pub
->srvtype
== NULL
) pub
->srvtype
= strdup("*");
861 if (pub
->key
== NULL
) {
862 pdkim_free_pubkey(pub
);
870 /* -------------------------------------------------------------------------- */
871 int pdkim_update_bodyhash(pdkim_ctx
*ctx
, const char *data
, int len
) {
872 pdkim_signature
*sig
= ctx
->sig
;
873 /* Cache relaxed version of data */
874 char *relaxed_data
= NULL
;
877 /* Traverse all signatures, updating their hashes. */
878 while (sig
!= NULL
) {
879 /* Defaults to simple canon (no further treatment necessary) */
880 const char *canon_data
= data
;
883 if (sig
->canon_body
== PDKIM_CANON_RELAXED
) {
884 /* Relax the line if not done already */
885 if (relaxed_data
== NULL
) {
887 const char *p
= data
;
889 relaxed_data
= malloc(len
+1);
890 if (relaxed_data
== NULL
) return PDKIM_ERR_OOM
;
894 if ( (q
> 0) && (relaxed_data
[q
-1] == ' ') ) q
--;
896 else if ( (c
== '\t') || (c
== ' ') ) {
897 c
= ' '; /* Turns WSP into SP */
905 relaxed_data
[q
++] = c
;
908 relaxed_data
[q
] = '\0';
911 canon_data
= relaxed_data
;
912 canon_len
= relaxed_len
;
915 /* Make sure we don't exceed the to-be-signed body length */
916 if ((sig
->bodylength
>= 0) &&
917 ((sig
->signed_body_bytes
+(unsigned long)canon_len
) > sig
->bodylength
))
918 canon_len
= (sig
->bodylength
- sig
->signed_body_bytes
);
921 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
922 sha1_update(sig
->sha1_body
,(unsigned char *)canon_data
,canon_len
);
924 sha2_update(sig
->sha2_body
,(unsigned char *)canon_data
,canon_len
);
925 sig
->signed_body_bytes
+= canon_len
;
927 if (ctx
->debug_stream
!=NULL
)
928 pdkim_quoteprint(ctx
->debug_stream
,canon_data
,canon_len
,0);
935 if (relaxed_data
!= NULL
) free(relaxed_data
);
940 /* -------------------------------------------------------------------------- */
941 int pdkim_finish_bodyhash(pdkim_ctx
*ctx
) {
942 pdkim_signature
*sig
= ctx
->sig
;
944 /* Traverse all signatures */
945 while (sig
!= NULL
) {
948 unsigned char bh
[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
949 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
950 sha1_finish(sig
->sha1_body
,bh
);
952 sha2_finish(sig
->sha2_body
,bh
);
955 if (ctx
->debug_stream
) {
956 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body bytes hashed: %lu\n",
957 sig
->domain
, sig
->signed_body_bytes
);
958 fprintf(ctx
->debug_stream
, "PDKIM [%s] bh computed: ", sig
->domain
);
959 pdkim_hexprint(ctx
->debug_stream
, (char *)bh
,
960 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32,1);
964 /* SIGNING -------------------------------------------------------------- */
965 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
966 sig
->bodyhash_len
= (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32;
967 sig
->bodyhash
= malloc(sig
->bodyhash_len
);
968 if (sig
->bodyhash
== NULL
) return PDKIM_ERR_OOM
;
969 memcpy(sig
->bodyhash
,bh
,sig
->bodyhash_len
);
971 /* If bodylength limit is set, and we have received less bytes
972 than the requested amount, effectively remove the limit tag. */
973 if (sig
->signed_body_bytes
< sig
->bodylength
) sig
->bodylength
= -1;
975 /* VERIFICATION --------------------------------------------------------- */
977 /* Compare bodyhash */
978 if (memcmp(bh
,sig
->bodyhash
,
979 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32) == 0) {
981 if (ctx
->debug_stream
)
982 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body hash verified OK\n",
988 if (ctx
->debug_stream
) {
989 fprintf(ctx
->debug_stream
, "PDKIM [%s] Body hash did NOT verify\n",
991 fprintf(ctx
->debug_stream
, "PDKIM [%s] bh signature: ", sig
->domain
);
992 pdkim_hexprint(ctx
->debug_stream
, sig
->bodyhash
,
993 (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?20:32,1);
996 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
997 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_BODY
;
1009 /* -------------------------------------------------------------------------- */
1010 /* Callback from pdkim_feed below for processing complete body lines */
1011 int pdkim_bodyline_complete(pdkim_ctx
*ctx
) {
1012 char *p
= ctx
->linebuf
;
1013 int n
= ctx
->linebuf_offset
;
1015 /* Ignore extra data if we've seen the end-of-data marker */
1016 if (ctx
->seen_eod
) goto BAIL
;
1018 /* We've always got one extra byte to stuff a zero ... */
1019 ctx
->linebuf
[(ctx
->linebuf_offset
)] = '\0';
1021 if (ctx
->input_mode
== PDKIM_INPUT_SMTP
) {
1022 /* Terminate on EOD marker */
1023 if (memcmp(p
,".\r\n",3) == 0) {
1028 if (memcmp(p
,"..",2) == 0) {
1034 /* Empty lines need to be buffered until we find a non-empty line */
1035 if (memcmp(p
,"\r\n",2) == 0) {
1036 ctx
->num_buffered_crlf
++;
1040 /* At this point, we have a non-empty line, so release the buffered ones. */
1041 while (ctx
->num_buffered_crlf
) {
1042 pdkim_update_bodyhash(ctx
,"\r\n",2);
1043 ctx
->num_buffered_crlf
--;
1046 pdkim_update_bodyhash(ctx
,p
,n
);
1049 ctx
->linebuf_offset
= 0;
1054 /* -------------------------------------------------------------------------- */
1055 /* Callback from pdkim_feed below for processing complete headers */
1056 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
1057 int pdkim_header_complete(pdkim_ctx
*ctx
) {
1058 pdkim_signature
*sig
= ctx
->sig
;
1060 /* Special case: The last header can have an extra \r appended */
1061 if ( (ctx
->cur_header
->len
> 1) &&
1062 (ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] == '\r') ) {
1063 ctx
->cur_header
->str
[(ctx
->cur_header
->len
)-1] = '\0';
1064 ctx
->cur_header
->len
--;
1068 if (ctx
->num_headers
> PDKIM_MAX_HEADERS
) goto BAIL
;
1070 /* SIGNING -------------------------------------------------------------- */
1071 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1072 /* Traverse all signatures */
1073 while (sig
!= NULL
) {
1074 pdkim_stringlist
*list
;
1076 if (header_name_match(ctx
->cur_header
->str
,
1079 PDKIM_DEFAULT_SIGN_HEADERS
, 0) != PDKIM_OK
) goto NEXT_SIG
;
1081 /* Add header to the signed headers list (in reverse order) */
1082 list
= pdkim_prepend_stringlist(sig
->headers
,
1083 ctx
->cur_header
->str
);
1084 if (list
== NULL
) return PDKIM_ERR_OOM
;
1085 sig
->headers
= list
;
1092 /* DKIM-Signature: headers are added to the verification list */
1093 if (ctx
->mode
== PDKIM_MODE_VERIFY
) {
1094 if (strncasecmp(ctx
->cur_header
->str
,
1095 DKIM_SIGNATURE_HEADERNAME
,
1096 strlen(DKIM_SIGNATURE_HEADERNAME
)) == 0) {
1097 pdkim_signature
*new_sig
;
1098 /* Create and chain new signature block */
1100 if (ctx
->debug_stream
)
1101 fprintf(ctx
->debug_stream
,
1102 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1104 new_sig
= pdkim_parse_sig_header(ctx
, ctx
->cur_header
->str
);
1105 if (new_sig
!= NULL
) {
1106 pdkim_signature
*last_sig
= ctx
->sig
;
1107 if (last_sig
== NULL
) {
1111 while (last_sig
->next
!= NULL
) { last_sig
= last_sig
->next
; }
1112 last_sig
->next
= new_sig
;
1117 if (ctx
->debug_stream
) {
1118 fprintf(ctx
->debug_stream
,"Error while parsing signature header\n");
1119 fprintf(ctx
->debug_stream
,
1120 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1125 /* every other header is stored for signature verification */
1127 pdkim_stringlist
*list
;
1129 list
= pdkim_prepend_stringlist(ctx
->headers
,
1130 ctx
->cur_header
->str
);
1131 if (list
== NULL
) return PDKIM_ERR_OOM
;
1132 ctx
->headers
= list
;
1137 pdkim_strclear(ctx
->cur_header
); /* Re-use existing pdkim_str */
1143 /* -------------------------------------------------------------------------- */
1144 #define HEADER_BUFFER_FRAG_SIZE 256
1145 DLLEXPORT
int pdkim_feed (pdkim_ctx
*ctx
,
1149 for (p
=0;p
<len
;p
++) {
1151 if (ctx
->past_headers
) {
1152 /* Processing body byte */
1153 ctx
->linebuf
[(ctx
->linebuf_offset
)++] = c
;
1155 int rc
= pdkim_bodyline_complete(ctx
); /* End of line */
1156 if (rc
!= PDKIM_OK
) return rc
;
1158 if (ctx
->linebuf_offset
== (PDKIM_MAX_BODY_LINE_LEN
-1))
1159 return PDKIM_ERR_LONG_LINE
;
1162 /* Processing header byte */
1166 int rc
= pdkim_header_complete(ctx
); /* Seen last header line */
1167 if (rc
!= PDKIM_OK
) return rc
;
1168 ctx
->past_headers
= 1;
1171 if (ctx
->debug_stream
)
1172 fprintf(ctx
->debug_stream
,
1173 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1177 else ctx
->seen_lf
= 1;
1179 else if (ctx
->seen_lf
) {
1180 if (! ((c
== '\t') || (c
== ' '))) {
1181 int rc
= pdkim_header_complete(ctx
); /* End of header */
1182 if (rc
!= PDKIM_OK
) return rc
;
1187 if (ctx
->cur_header
== NULL
) {
1188 ctx
->cur_header
= pdkim_strnew(NULL
);
1189 if (ctx
->cur_header
== NULL
) return PDKIM_ERR_OOM
;
1191 if (ctx
->cur_header
->len
< PDKIM_MAX_HEADER_LEN
)
1192 if (pdkim_strncat(ctx
->cur_header
,&data
[p
],1) == NULL
)
1193 return PDKIM_ERR_OOM
;
1200 * RFC 5322 specifies that header line length SHOULD be no more than 78
1205 * col: this int holds and receives column number (octets since last '\n')
1206 * str: partial string to append to
1207 * pad: padding, split line or space after before or after eg: ";"
1208 * intro: - must join to payload eg "h=", usually the tag name
1209 * payload: eg base64 data - long data can be split arbitrarily.
1211 * this code doesn't fold the header in some of the places that RFC4871
1212 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1213 * pairs and inside long values. it also always spaces or breaks after the
1216 * no guarantees are made for output given out-of range input. like tag
1217 * names loinger than 78, or bogus col. Input is assumed to be free of line breaks.
1220 static char *pdkim_headcat(int *col
, pdkim_str
*str
, const char*pad
,const char *intro
, const char *payload
) {
1227 pdkim_strcat(str
, "\r\n\t");
1230 pdkim_strncat(str
, pad
,l
);
1234 l
=(pad
?1:0) + (intro
?strlen(intro
):0 );
1237 { /*can't fit intro - start a new line to make room.*/
1238 pdkim_strcat(str
, "\r\n\t");
1240 l
= intro
?strlen(intro
):0;
1243 l
+= payload
? strlen(payload
):0 ;
1246 { /* this fragment will not fit on a single line */
1249 pdkim_strcat(str
, " ");
1251 pad
=NULL
; // only want this once
1256 size_t sl
=strlen(intro
);
1257 pdkim_strncat(str
, intro
,sl
);
1260 intro
=NULL
; // only want this once
1264 size_t sl
=strlen(payload
);
1265 size_t chomp
= *col
+sl
< 77 ? sl
: 78-*col
;
1266 pdkim_strncat(str
, payload
,chomp
);
1271 // the while precondition tells us it didn't fit.
1272 pdkim_strcat(str
, "\r\n\t");
1277 pdkim_strcat(str
, "\r\n\t");
1284 pdkim_strcat(str
, " ");
1291 size_t sl
=strlen(intro
);
1292 pdkim_strncat(str
, intro
,sl
);
1299 size_t sl
=strlen(payload
);
1300 pdkim_strncat(str
, payload
,sl
);
1307 /* -------------------------------------------------------------------------- */
1308 char *pdkim_create_header(pdkim_signature
*sig
, int final
) {
1310 char *base64_bh
= NULL
;
1311 char *base64_b
= NULL
;
1313 pdkim_str
*hdr
= pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION
);
1314 if (hdr
== NULL
) return NULL
;
1315 pdkim_str
*canon_all
= pdkim_strnew(pdkim_canons
[sig
->canon_headers
]);
1316 if (canon_all
== NULL
) goto BAIL
;
1318 base64_bh
= pdkim_encode_base64(sig
->bodyhash
, sig
->bodyhash_len
);
1319 if (base64_bh
== NULL
) goto BAIL
;
1321 col
=strlen(hdr
->str
);
1323 /* Required and static bits */
1325 pdkim_headcat(&col
,hdr
,";","a=",pdkim_algos
[sig
->algo
]) &&
1326 pdkim_headcat(&col
,hdr
,";","q=",pdkim_querymethods
[sig
->querymethod
]) &&
1327 pdkim_strcat(canon_all
,"/") &&
1328 pdkim_strcat(canon_all
,pdkim_canons
[sig
->canon_body
]) &&
1329 pdkim_headcat(&col
,hdr
,";","c=",canon_all
->str
) &&
1330 pdkim_headcat(&col
,hdr
,";","d=",sig
->domain
) &&
1331 pdkim_headcat(&col
,hdr
,";","s=",sig
->selector
)
1333 /* list of eader names can be split between items. */
1335 char *n
=strdup(sig
->headernames
);
1342 char *c
=strchr(n
,':');
1346 if (!pdkim_headcat(&col
,hdr
,NULL
,NULL
,":"))
1352 if( !pdkim_headcat(&col
,hdr
,s
,i
,n
))
1357 if(c
) n
=c
+1 ; else break;
1363 if(!pdkim_headcat(&col
,hdr
,";","bh=",base64_bh
))
1367 if (sig
->identity
!= NULL
) {
1368 if(!pdkim_headcat(&col
,hdr
,";","i=",sig
->identity
)){
1373 if (sig
->created
> 0) {
1375 snprintf(minibuf
,20,"%lu",sig
->created
);
1376 if(!pdkim_headcat(&col
,hdr
,";","t=",minibuf
)) {
1380 if (sig
->expires
> 0) {
1382 snprintf(minibuf
,20,"%lu",sig
->expires
);
1383 if(!pdkim_headcat(&col
,hdr
,";","x=",minibuf
)) {
1387 if (sig
->bodylength
>= 0) {
1389 snprintf(minibuf
,20,"%lu",sig
->bodylength
);
1390 if(!pdkim_headcat(&col
,hdr
,";","l=",minibuf
)) {
1395 /* Preliminary or final version? */
1397 base64_b
= pdkim_encode_base64(sig
->sigdata
, sig
->sigdata_len
);
1398 if (base64_b
== NULL
) goto BAIL
;
1399 if(!pdkim_headcat(&col
,hdr
,";","b=",base64_b
)) goto BAIL
;
1402 if(!pdkim_headcat(&col
,hdr
,";","b=","")) goto BAIL
;
1405 /* add trailing semicolon: I'm not sure if this is actually needed */
1406 if(!pdkim_headcat(&col
,hdr
,NULL
,";","")) goto BAIL
;
1412 rc
= strdup(hdr
->str
);
1416 if (canon_all
!= NULL
) pdkim_strfree(canon_all
);
1417 if (base64_bh
!= NULL
) free(base64_bh
);
1418 if (base64_b
!= NULL
) free(base64_b
);
1423 /* -------------------------------------------------------------------------- */
1424 DLLEXPORT
int pdkim_feed_finish(pdkim_ctx
*ctx
, pdkim_signature
**return_signatures
) {
1425 pdkim_signature
*sig
= ctx
->sig
;
1426 pdkim_str
*headernames
= NULL
; /* Collected signed header names */
1428 /* Check if we must still flush a (partial) header. If that is the
1429 case, the message has no body, and we must compute a body hash
1430 out of '<CR><LF>' */
1431 if (ctx
->cur_header
&& ctx
->cur_header
->len
) {
1432 int rc
= pdkim_header_complete(ctx
);
1433 if (rc
!= PDKIM_OK
) return rc
;
1434 pdkim_update_bodyhash(ctx
,"\r\n",2);
1437 /* For non-smtp input, check if there's an unfinished line in the
1438 body line buffer. If that is the case, we must add a CRLF to the
1439 hash to properly terminate the message. */
1440 if ((ctx
->input_mode
== PDKIM_INPUT_NORMAL
) && ctx
->linebuf_offset
) {
1441 pdkim_update_bodyhash(ctx
, ctx
->linebuf
, ctx
->linebuf_offset
);
1442 pdkim_update_bodyhash(ctx
,"\r\n",2);
1445 if (ctx
->debug_stream
)
1446 fprintf(ctx
->debug_stream
,
1447 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1451 /* Build (and/or evaluate) body hash */
1452 if (pdkim_finish_bodyhash(ctx
) != PDKIM_OK
) return PDKIM_ERR_OOM
;
1454 /* SIGNING -------------------------------------------------------------- */
1455 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1456 headernames
= pdkim_strnew(NULL
);
1457 if (headernames
== NULL
) return PDKIM_ERR_OOM
;
1459 /* ---------------------------------------------------------------------- */
1461 while (sig
!= NULL
) {
1462 sha1_context sha1_headers
;
1463 sha2_context sha2_headers
;
1465 char headerhash
[32];
1467 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1468 sha1_starts(&sha1_headers
);
1470 sha2_starts(&sha2_headers
,0);
1473 if (ctx
->debug_stream
)
1474 fprintf(ctx
->debug_stream
,
1475 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1478 /* SIGNING ---------------------------------------------------------------- */
1479 /* When signing, walk through our header list and add them to the hash. As we
1480 go, construct a list of the header's names to use for the h= parameter. */
1481 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1482 pdkim_stringlist
*p
= sig
->headers
;
1485 /* Collect header names (Note: colon presence is guaranteed here) */
1486 char *q
= strchr(p
->value
,':');
1487 if (pdkim_strncat(headernames
, p
->value
,
1488 (q
-(p
->value
))+((p
->next
==NULL
)?0:1)) == NULL
)
1489 return PDKIM_ERR_OOM
;
1491 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1492 rh
= pdkim_relax_header(p
->value
,1); /* cook header for relaxed canon */
1494 rh
= strdup(p
->value
); /* just copy it for simple canon */
1496 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1498 /* Feed header to the hash algorithm */
1499 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1500 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1502 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1504 if (ctx
->debug_stream
)
1505 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1511 /* VERIFICATION ----------------------------------------------------------- */
1512 /* When verifying, walk through the header name list in the h= parameter and
1513 add the headers to the hash in that order. */
1515 char *b
= strdup(sig
->headernames
);
1518 pdkim_stringlist
*hdrs
= ctx
->headers
;
1520 if (b
== NULL
) return PDKIM_ERR_OOM
;
1523 while (hdrs
!= NULL
) {
1529 hdrs
= ctx
->headers
;
1531 if (q
!= NULL
) *q
= '\0';
1532 while (hdrs
!= NULL
) {
1533 if ( (hdrs
->tag
== 0) &&
1534 (strncasecmp(hdrs
->value
,p
,strlen(p
)) == 0) &&
1535 ((hdrs
->value
)[strlen(p
)] == ':') ) {
1537 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
)
1538 rh
= pdkim_relax_header(hdrs
->value
,1); /* cook header for relaxed canon */
1540 rh
= strdup(hdrs
->value
); /* just copy it for simple canon */
1541 if (rh
== NULL
) return PDKIM_ERR_OOM
;
1542 /* Feed header to the hash algorithm */
1543 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
)
1544 sha1_update(&(sha1_headers
),(unsigned char *)rh
,strlen(rh
));
1546 sha2_update(&(sha2_headers
),(unsigned char *)rh
,strlen(rh
));
1548 if (ctx
->debug_stream
)
1549 pdkim_quoteprint(ctx
->debug_stream
, rh
, strlen(rh
), 1);
1557 if (q
== NULL
) break;
1564 if (ctx
->debug_stream
)
1565 fprintf(ctx
->debug_stream
,
1566 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1569 /* SIGNING ---------------------------------------------------------------- */
1570 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1571 /* Copy headernames to signature struct */
1572 sig
->headernames
= strdup(headernames
->str
);
1573 pdkim_strfree(headernames
);
1575 /* Create signature header with b= omitted */
1576 sig_hdr
= pdkim_create_header(ctx
->sig
,0);
1578 /* VERIFICATION ----------------------------------------------------------- */
1580 sig_hdr
= strdup(sig
->rawsig_no_b_val
);
1582 /* ------------------------------------------------------------------------ */
1584 if (sig_hdr
== NULL
) return PDKIM_ERR_OOM
;
1586 /* Relax header if necessary */
1587 if (sig
->canon_headers
== PDKIM_CANON_RELAXED
) {
1588 char *relaxed_hdr
= pdkim_relax_header(sig_hdr
,0);
1590 if (relaxed_hdr
== NULL
) return PDKIM_ERR_OOM
;
1591 sig_hdr
= relaxed_hdr
;
1595 if (ctx
->debug_stream
) {
1596 fprintf(ctx
->debug_stream
,
1597 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1598 pdkim_quoteprint(ctx
->debug_stream
, sig_hdr
, strlen(sig_hdr
), 1);
1599 fprintf(ctx
->debug_stream
,
1600 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1604 /* Finalize header hash */
1605 if (sig
->algo
== PDKIM_ALGO_RSA_SHA1
) {
1606 sha1_update(&(sha1_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1607 sha1_finish(&(sha1_headers
),(unsigned char *)headerhash
);
1609 if (ctx
->debug_stream
) {
1610 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1611 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 20, 1);
1616 sha2_update(&(sha2_headers
),(unsigned char *)sig_hdr
,strlen(sig_hdr
));
1617 sha2_finish(&(sha2_headers
),(unsigned char *)headerhash
);
1619 if (ctx
->debug_stream
) {
1620 fprintf(ctx
->debug_stream
, "PDKIM [%s] hh computed: ", sig
->domain
);
1621 pdkim_hexprint(ctx
->debug_stream
, headerhash
, 32, 1);
1628 /* SIGNING ---------------------------------------------------------------- */
1629 if (ctx
->mode
== PDKIM_MODE_SIGN
) {
1632 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1634 /* Perform private key operation */
1635 if (rsa_parse_key(&rsa
, (unsigned char *)sig
->rsa_privkey
,
1636 strlen(sig
->rsa_privkey
), NULL
, 0) != 0) {
1637 return PDKIM_ERR_RSA_PRIVKEY
;
1640 sig
->sigdata_len
= mpi_size(&(rsa
.N
));
1641 sig
->sigdata
= malloc(sig
->sigdata_len
);
1642 if (sig
->sigdata
== NULL
) return PDKIM_ERR_OOM
;
1644 if (rsa_pkcs1_sign( &rsa
, RSA_PRIVATE
,
1645 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1646 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1648 (unsigned char *)headerhash
,
1649 (unsigned char *)sig
->sigdata
) != 0) {
1650 return PDKIM_ERR_RSA_SIGNING
;
1656 if (ctx
->debug_stream
) {
1657 fprintf(ctx
->debug_stream
, "PDKIM [%s] b computed: ",
1659 pdkim_hexprint(ctx
->debug_stream
, sig
->sigdata
, sig
->sigdata_len
, 1);
1663 sig
->signature_header
= pdkim_create_header(ctx
->sig
,1);
1664 if (sig
->signature_header
== NULL
) return PDKIM_ERR_OOM
;
1666 /* VERIFICATION ----------------------------------------------------------- */
1669 char *dns_txt_name
, *dns_txt_reply
;
1671 rsa_init(&rsa
,RSA_PKCS_V15
,0);
1673 dns_txt_name
= malloc(PDKIM_DNS_TXT_MAX_NAMELEN
);
1674 if (dns_txt_name
== NULL
) return PDKIM_ERR_OOM
;
1675 dns_txt_reply
= malloc(PDKIM_DNS_TXT_MAX_RECLEN
);
1676 if (dns_txt_reply
== NULL
) {
1678 return PDKIM_ERR_OOM
;
1680 memset(dns_txt_reply
,0,PDKIM_DNS_TXT_MAX_RECLEN
);
1681 memset(dns_txt_name
,0,PDKIM_DNS_TXT_MAX_NAMELEN
);
1683 if (snprintf(dns_txt_name
,PDKIM_DNS_TXT_MAX_NAMELEN
,
1684 "%s._domainkey.%s.",
1685 sig
->selector
,sig
->domain
) >= PDKIM_DNS_TXT_MAX_NAMELEN
) {
1686 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1687 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_BUFFER_SIZE
;
1691 if ((ctx
->dns_txt_callback(dns_txt_name
, dns_txt_reply
) != PDKIM_OK
) ||
1692 (dns_txt_reply
[0] == '\0')) {
1693 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1694 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE
;
1699 if (ctx
->debug_stream
) {
1700 fprintf(ctx
->debug_stream
,
1701 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1702 fprintf(ctx
->debug_stream
,"Raw record: ");
1703 pdkim_quoteprint(ctx
->debug_stream
, dns_txt_reply
, strlen(dns_txt_reply
), 1);
1707 sig
->pubkey
= pdkim_parse_pubkey_record(ctx
,dns_txt_reply
);
1708 if (sig
->pubkey
== NULL
) {
1709 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1710 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1712 if (ctx
->debug_stream
) {
1713 fprintf(ctx
->debug_stream
,"Error while parsing public key record\n");
1714 fprintf(ctx
->debug_stream
,
1715 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1722 if (ctx
->debug_stream
) {
1723 fprintf(ctx
->debug_stream
,
1724 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1728 if (rsa_parse_public_key(&rsa
,
1729 (unsigned char *)sig
->pubkey
->key
,
1730 sig
->pubkey
->key_len
) != 0) {
1731 sig
->verify_status
= PDKIM_VERIFY_INVALID
;
1732 sig
->verify_ext_status
= PDKIM_VERIFY_INVALID_PUBKEY_PARSING
;
1736 /* Check the signature */
1737 if (rsa_pkcs1_verify(&rsa
,
1739 ((sig
->algo
== PDKIM_ALGO_RSA_SHA1
)?
1740 SIG_RSA_SHA1
:SIG_RSA_SHA256
),
1742 (unsigned char *)headerhash
,
1743 (unsigned char *)sig
->sigdata
) != 0) {
1744 sig
->verify_status
= PDKIM_VERIFY_FAIL
;
1745 sig
->verify_ext_status
= PDKIM_VERIFY_FAIL_MESSAGE
;
1749 /* We have a winner! (if bodydhash was correct earlier) */
1750 if (sig
->verify_status
== PDKIM_VERIFY_NONE
) {
1751 sig
->verify_status
= PDKIM_VERIFY_PASS
;
1757 if (ctx
->debug_stream
) {
1758 fprintf(ctx
->debug_stream
, "PDKIM [%s] signature status: %s",
1759 sig
->domain
, pdkim_verify_status_str(sig
->verify_status
));
1760 if (sig
->verify_ext_status
> 0) {
1761 fprintf(ctx
->debug_stream
, " (%s)\n",
1762 pdkim_verify_ext_status_str(sig
->verify_ext_status
));
1765 fprintf(ctx
->debug_stream
, "\n");
1772 free(dns_txt_reply
);
1778 /* If requested, set return pointer to signature(s) */
1779 if (return_signatures
!= NULL
) {
1780 *return_signatures
= ctx
->sig
;
1787 /* -------------------------------------------------------------------------- */
1788 DLLEXPORT pdkim_ctx
*pdkim_init_verify(int input_mode
,
1789 int(*dns_txt_callback
)(char *, char *)
1791 pdkim_ctx
*ctx
= malloc(sizeof(pdkim_ctx
));
1792 if (ctx
== NULL
) return NULL
;
1793 memset(ctx
,0,sizeof(pdkim_ctx
));
1795 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1796 if (ctx
->linebuf
== NULL
) {
1801 ctx
->mode
= PDKIM_MODE_VERIFY
;
1802 ctx
->input_mode
= input_mode
;
1803 ctx
->dns_txt_callback
= dns_txt_callback
;
1809 /* -------------------------------------------------------------------------- */
1810 DLLEXPORT pdkim_ctx
*pdkim_init_sign(int input_mode
,
1813 char *rsa_privkey
) {
1815 pdkim_signature
*sig
;
1817 if (!domain
|| !selector
|| !rsa_privkey
) return NULL
;
1819 ctx
= malloc(sizeof(pdkim_ctx
));
1820 if (ctx
== NULL
) return NULL
;
1821 memset(ctx
,0,sizeof(pdkim_ctx
));
1823 ctx
->linebuf
= malloc(PDKIM_MAX_BODY_LINE_LEN
);
1824 if (ctx
->linebuf
== NULL
) {
1829 sig
= malloc(sizeof(pdkim_signature
));
1835 memset(sig
,0,sizeof(pdkim_signature
));
1836 sig
->bodylength
= -1;
1838 ctx
->mode
= PDKIM_MODE_SIGN
;
1839 ctx
->input_mode
= input_mode
;
1842 ctx
->sig
->domain
= strdup(domain
);
1843 ctx
->sig
->selector
= strdup(selector
);
1844 ctx
->sig
->rsa_privkey
= strdup(rsa_privkey
);
1846 if (!ctx
->sig
->domain
|| !ctx
->sig
->selector
|| !ctx
->sig
->rsa_privkey
) {
1847 pdkim_free_ctx(ctx
);
1851 ctx
->sig
->sha1_body
= malloc(sizeof(sha1_context
));
1852 if (ctx
->sig
->sha1_body
== NULL
) {
1853 pdkim_free_ctx(ctx
);
1856 sha1_starts(ctx
->sig
->sha1_body
);
1858 ctx
->sig
->sha2_body
= malloc(sizeof(sha2_context
));
1859 if (ctx
->sig
->sha2_body
== NULL
) {
1860 pdkim_free_ctx(ctx
);
1863 sha2_starts(ctx
->sig
->sha2_body
,0);
1869 /* -------------------------------------------------------------------------- */
1870 DLLEXPORT
void pdkim_set_debug_stream(pdkim_ctx
*ctx
,
1871 FILE *debug_stream
) {
1872 ctx
->debug_stream
= debug_stream
;
1876 /* -------------------------------------------------------------------------- */
1877 DLLEXPORT
int pdkim_set_optional(pdkim_ctx
*ctx
,
1884 unsigned long created
,
1885 unsigned long expires
) {
1887 if (identity
!= NULL
) {
1888 ctx
->sig
->identity
= strdup(identity
);
1889 if (ctx
->sig
->identity
== NULL
) return PDKIM_ERR_OOM
;
1892 if (sign_headers
!= NULL
) {
1893 ctx
->sig
->sign_headers
= strdup(sign_headers
);
1894 if (ctx
->sig
->sign_headers
== NULL
) return PDKIM_ERR_OOM
;
1897 ctx
->sig
->canon_headers
= canon_headers
;
1898 ctx
->sig
->canon_body
= canon_body
;
1899 ctx
->sig
->bodylength
= bodylength
;
1900 ctx
->sig
->algo
= algo
;
1901 ctx
->sig
->created
= created
;
1902 ctx
->sig
->expires
= expires
;