1 /* $Cambridge: exim/src/src/pdkim/pdkim.c,v 1.1.2.8 2009/03/17 16:20:13 tom Exp $ */
18 #define PDKIM_SIGNATURE_VERSION "1"
19 #define PDKIM_PUB_RECORD_VERSION "DKIM1"
21 #define PDKIM_MAX_HEADER_LEN 65536
22 #define PDKIM_MAX_HEADERS 512
23 #define PDKIM_MAX_BODY_LINE_LEN 1024
24 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
25 #define PDKIM_DNS_TXT_MAX_RECLEN 4096
26 #define PDKIM_DEFAULT_SIGN_HEADERS "From:Sender:Reply-To:Subject:Date:"\
27 "Message-ID:To:Cc:MIME-Version:Content-Type:"\
28 "Content-Transfer-Encoding:Content-ID:"\
29 "Content-Description:Resent-Date:Resent-From:"\
30 "Resent-Sender:Resent-To:Resent-Cc:"\
31 "Resent-Message-ID:In-Reply-To:References:"\
32 "List-Id:List-Help:List-Unsubscribe:"\
33 "List-Subscribe:List-Post:List-Owner:List-Archive"
36 struct pdkim_stringlist {
41 #define PDKIM_STR_ALLOC_FRAG 256
45 unsigned int allocated;
50 /* -------------------------------------------------------------------------- */
51 /* A bunch of list constants */
52 char *pdkim_querymethods[] = {
56 char *pdkim_algos[] = {
61 char *pdkim_canons[] = {
66 char *pdkim_hashes[] = {
71 char *pdkim_keytypes[] = {
76 typedef struct pdkim_combined_canon_entry {
80 } pdkim_combined_canon_entry;
81 pdkim_combined_canon_entry pdkim_combined_canons[] = {
82 { "simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
83 { "simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
84 { "relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
85 { "relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
86 { "simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
87 { "relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
92 /* -------------------------------------------------------------------------- */
93 /* Print debugging functions */
95 void pdkim_quoteprint(FILE *stream, char *data, int len, int lf) {
97 unsigned char *p = (unsigned char *)data;
102 case ' ' : fprintf(stream,"{SP}"); break;
103 case '\t': fprintf(stream,"{TB}"); break;
104 case '\r': fprintf(stream,"{CR}"); break;
105 case '\n': fprintf(stream,"{LF}"); break;
106 case '{' : fprintf(stream,"{BO}"); break;
107 case '}' : fprintf(stream,"{BC}"); break;
109 if ( (c < 32) || (c > 127) )
110 fprintf(stream,"{%02x}",c);
119 void pdkim_hexprint(FILE *stream, char *data, int len, int lf) {
121 unsigned char *p = (unsigned char *)data;
123 for (i=0;i<len;i++) {
125 fprintf(stream,"%02x ",c);
133 /* -------------------------------------------------------------------------- */
134 /* Simple string list implementation for convinience */
135 pdkim_stringlist *pdkim_append_stringlist(pdkim_stringlist *base, char *str) {
136 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
137 if (new_entry == NULL) return NULL;
138 memset(new_entry,0,sizeof(pdkim_stringlist));
139 new_entry->value = strdup(str);
140 if (new_entry->value == NULL) return NULL;
142 pdkim_stringlist *last = base;
143 while (last->next != NULL) { last = last->next; };
144 last->next = new_entry;
147 else return new_entry;
151 /* -------------------------------------------------------------------------- */
152 /* A small "growing string" implementation to escape malloc/realloc hell */
153 pdkim_str *pdkim_strnew (char *cstr) {
154 unsigned int len = cstr?strlen(cstr):0;
155 pdkim_str *p = malloc(sizeof(pdkim_str));
156 if (p == NULL) return NULL;
157 memset(p,0,sizeof(pdkim_str));
158 p->str = malloc(len+1);
159 if (p->str == NULL) {
163 p->allocated=(len+1);
165 if (cstr) strcpy(p->str,cstr);
168 char *pdkim_strncat(pdkim_str *str, char *data, int len) {
169 if ((str->allocated - str->len) < (len+1)) {
170 /* Extend the buffer */
171 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
172 char *n = realloc(str->str,
173 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
174 if (n == NULL) return NULL;
176 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
178 strncpy(&(str->str[str->len]),data,len);
180 str->str[str->len] = '\0';
183 char *pdkim_strcat(pdkim_str *str, char *cstr) {
184 return pdkim_strncat(str, cstr, strlen(cstr));
186 char *pdkim_numcat(pdkim_str *str, unsigned long num) {
188 snprintf(minibuf,20,"%lu",num);
189 return pdkim_strcat(str,minibuf);
191 char *pdkim_strtrim(pdkim_str *str) {
194 while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
195 while (*p != '\0') {*q = *p; q++; p++;};
197 while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) ) {
201 str->len = strlen(str->str);
204 char *pdkim_strclear(pdkim_str *str) {
209 void pdkim_strfree(pdkim_str *str) {
210 if (str == NULL) return;
211 if (str->str != NULL) free(str->str);
217 /* -------------------------------------------------------------------------- */
218 void pdkim_free_pubkey(pdkim_pubkey *pub) {
220 if (pub->version != NULL) free(pub->version);
221 if (pub->granularity != NULL) free(pub->granularity);
222 if (pub->hashes != NULL) free(pub->hashes);
223 if (pub->keytype != NULL) free(pub->keytype);
224 if (pub->srvtype != NULL) free(pub->srvtype);
225 if (pub->notes != NULL) free(pub->notes);
226 if (pub->key != NULL) free(pub->key);
232 /* -------------------------------------------------------------------------- */
233 void pdkim_free_sig(pdkim_signature *sig) {
235 pdkim_signature *next = (pdkim_signature *)sig->next;
237 pdkim_stringlist *e = sig->headers;
239 pdkim_stringlist *c = e;
240 if (e->value != NULL) free(e->value);
245 if (sig->sigdata != NULL) free(sig->sigdata);
246 if (sig->bodyhash != NULL) free(sig->bodyhash);
247 if (sig->selector != NULL) free(sig->selector);
248 if (sig->domain != NULL) free(sig->domain);
249 if (sig->identity != NULL) free(sig->identity);
250 if (sig->headernames != NULL) free(sig->headernames);
251 if (sig->copiedheaders != NULL) free(sig->copiedheaders);
252 if (sig->rsa_privkey != NULL) free(sig->rsa_privkey);
253 if (sig->sign_headers != NULL) free(sig->sign_headers);
254 if (sig->signature_header != NULL) free(sig->signature_header);
255 if (sig->sha1_body != NULL) free(sig->sha1_body);
256 if (sig->sha2_body != NULL) free(sig->sha2_body);
258 if (sig->pubkey != NULL) pdkim_free_pubkey(sig->pubkey);
261 if (next != NULL) pdkim_free_sig(next);
266 /* -------------------------------------------------------------------------- */
267 void pdkim_free_ctx(pdkim_ctx *ctx) {
269 pdkim_free_sig(ctx->sig);
270 pdkim_strfree(ctx->cur_header);
276 /* -------------------------------------------------------------------------- */
277 /* Matches the name of the passed raw "header" against
278 the passed colon-separated "list", starting at entry
279 "start". Returns the position of the header name in
281 int header_name_match(char *header,
290 char *hcolon = strchr(header,':');
291 if (hcolon == NULL) return rc; /* This isn't a header */
292 hname = malloc((hcolon-header)+1);
293 if (hname == NULL) return PDKIM_ERR_OOM;
294 memset(hname,0,(hcolon-header)+1);
295 strncpy(hname,header,(hcolon-header));
296 lcopy = strdup(list);
299 return PDKIM_ERR_OOM;
306 if (strcasecmp(p,hname) == 0) {
316 if (strcasecmp(p,hname) == 0)
326 /* -------------------------------------------------------------------------- */
327 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
329 char *pdkim_relax_header (char *header, int crlf) {
330 int past_field_name = 0;
334 char *relaxed = malloc(strlen(header));
335 if (relaxed == NULL) return NULL;
340 if ( (c == '\r') || (c == '\n') ) {
344 if ( (c == '\t') || (c == ' ') ) {
345 c = ' '; /* Turns WSP into SP */
353 if ( (!past_field_name) && (c == ':') ) {
354 if (seen_wsp) q--; /* This removes WSP before the colon */
355 seen_wsp = 1; /* This removes WSP after the colon */
360 /* Lowercase header name */
361 if (!past_field_name) c = tolower(c);
367 if (crlf) strcat(relaxed,"\r\n");
372 /* -------------------------------------------------------------------------- */
373 #define PDKIM_QP_ERROR_DECODE -1
374 char *pdkim_decode_qp_char(char *qp_p, int *c) {
375 char *initial_pos = qp_p;
377 /* Advance one char */
380 /* Check for two hex digits and decode them */
381 if (isxdigit(*qp_p) && isxdigit(qp_p[1])) {
382 /* Do hex conversion */
383 if (isdigit(*qp_p)) {*c = *qp_p - '0';}
384 else {*c = toupper(*qp_p) - 'A' + 10;};
386 if (isdigit(qp_p[1])) {*c |= qp_p[1] - '0';}
387 else {*c |= toupper(qp_p[1]) - 'A' + 10;};
391 /* Illegal char here */
392 *c = PDKIM_QP_ERROR_DECODE;
397 /* -------------------------------------------------------------------------- */
398 char *pdkim_decode_qp(char *str) {
402 char *n = malloc(strlen(p)+1);
403 if (n == NULL) return NULL;
408 p = pdkim_decode_qp_char(p,&nchar);
425 /* -------------------------------------------------------------------------- */
426 char *pdkim_decode_base64(char *str, int *num_decoded) {
430 base64_decode(NULL, &dlen, (unsigned char *)str, strlen(str));
431 res = malloc(dlen+1);
432 if (res == NULL) return NULL;
433 if (base64_decode((unsigned char *)res,&dlen,(unsigned char *)str,strlen(str)) != 0) {
437 if (num_decoded != NULL) *num_decoded = dlen;
441 /* -------------------------------------------------------------------------- */
442 char *pdkim_encode_base64(char *str, int num) {
446 base64_encode(NULL, &dlen, (unsigned char *)str, num);
447 res = malloc(dlen+1);
448 if (res == NULL) return NULL;
449 if (base64_encode((unsigned char *)res,&dlen,(unsigned char *)str,num) != 0) {
457 /* -------------------------------------------------------------------------- */
458 #define PDKIM_HDR_LIMBO 0
459 #define PDKIM_HDR_TAG 1
460 #define PDKIM_HDR_VALUE 2
461 pdkim_signature *pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr) {
462 pdkim_signature *sig ;
464 pdkim_str *cur_tag = NULL;
465 pdkim_str *cur_val = NULL;
468 int where = PDKIM_HDR_LIMBO;
471 sig = malloc(sizeof(pdkim_signature));
472 if (sig == NULL) return NULL;
473 memset(sig,0,sizeof(pdkim_signature));
475 sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1);
476 if (sig->rawsig_no_b_val == NULL) {
482 q = sig->rawsig_no_b_val;
487 if ( (*p == '\r') || (*p == '\n') )
490 /* Fast-forward through header name */
492 if (*p == ':') past_hname = 1;
496 if (where == PDKIM_HDR_LIMBO) {
497 /* In limbo, just wait for a tag-char to appear */
498 if (!((*p >= 'a') && (*p <= 'z')))
501 where = PDKIM_HDR_TAG;
504 if (where == PDKIM_HDR_TAG) {
506 cur_tag = pdkim_strnew(NULL);
508 if ((*p >= 'a') && (*p <= 'z'))
509 pdkim_strncat(cur_tag,p,1);
512 if (strcmp(cur_tag->str,"b") == 0) {
516 where = PDKIM_HDR_VALUE;
521 if (where == PDKIM_HDR_VALUE) {
523 cur_val = pdkim_strnew(NULL);
525 if ( (*p == '\r') || (*p == '\n') )
529 if (cur_tag->len > 0) {
530 pdkim_strtrim(cur_val);
532 if (ctx->debug_stream)
533 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
535 switch (cur_tag->str[0]) {
537 switch (cur_tag->str[1]) {
539 sig->bodyhash = pdkim_decode_base64(cur_val->str,&(sig->bodyhash_len));
542 sig->sigdata = pdkim_decode_base64(cur_val->str,&(sig->sigdata_len));
547 if (strcmp(cur_val->str,PDKIM_SIGNATURE_VERSION) == 0) {
548 /* We only support version 1, and that is currently the
549 only version there is. */
555 while (pdkim_algos[i] != NULL) {
556 if (strcmp(cur_val->str,pdkim_algos[i]) == 0 ) {
565 while (pdkim_combined_canons[i].str != NULL) {
566 if (strcmp(cur_val->str,pdkim_combined_canons[i].str) == 0 ) {
567 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
568 sig->canon_body = pdkim_combined_canons[i].canon_body;
576 while (pdkim_querymethods[i] != NULL) {
577 if (strcmp(cur_val->str,pdkim_querymethods[i]) == 0 ) {
578 sig->querymethod = i;
585 sig->selector = strdup(cur_val->str);
588 sig->domain = strdup(cur_val->str);
591 sig->identity = pdkim_decode_qp(cur_val->str);
594 sig->created = strtoul(cur_val->str,NULL,10);
597 sig->expires = strtoul(cur_val->str,NULL,10);
600 sig->bodylength = strtoul(cur_val->str,NULL,10);
603 sig->headernames = strdup(cur_val->str);
606 sig->copiedheaders = pdkim_decode_qp(cur_val->str);
610 if (ctx->debug_stream)
611 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
616 pdkim_strclear(cur_tag);
617 pdkim_strclear(cur_val);
619 where = PDKIM_HDR_LIMBO;
622 else pdkim_strncat(cur_val,p,1);
634 /* Make sure the most important bits are there. */
635 if (!(sig->domain && (*(sig->domain) != '\0') &&
636 sig->selector && (*(sig->selector) != '\0') &&
637 sig->headernames && (*(sig->headernames) != '\0') &&
647 if (ctx->debug_stream) {
648 fprintf(ctx->debug_stream,
649 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
650 pdkim_quoteprint(ctx->debug_stream,
651 sig->rawsig_no_b_val,
652 strlen(sig->rawsig_no_b_val), 1);
653 fprintf(ctx->debug_stream,
654 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
658 sig->sha1_body = malloc(sizeof(sha1_context));
659 if (sig->sha1_body == NULL) {
663 sig->sha2_body = malloc(sizeof(sha2_context));
664 if (sig->sha2_body == NULL) {
669 sha1_starts(sig->sha1_body);
670 sha2_starts(sig->sha2_body,0);
676 /* -------------------------------------------------------------------------- */
677 pdkim_pubkey *pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record) {
680 pdkim_str *cur_tag = NULL;
681 pdkim_str *cur_val = NULL;
682 int where = PDKIM_HDR_LIMBO;
684 pub = malloc(sizeof(pdkim_pubkey));
685 if (pub == NULL) return NULL;
686 memset(pub,0,sizeof(pdkim_pubkey));
693 if ( (*p == '\r') || (*p == '\n') )
696 if (where == PDKIM_HDR_LIMBO) {
697 /* In limbo, just wait for a tag-char to appear */
698 if (!((*p >= 'a') && (*p <= 'z')))
701 where = PDKIM_HDR_TAG;
704 if (where == PDKIM_HDR_TAG) {
706 cur_tag = pdkim_strnew(NULL);
708 if ((*p >= 'a') && (*p <= 'z'))
709 pdkim_strncat(cur_tag,p,1);
712 where = PDKIM_HDR_VALUE;
717 if (where == PDKIM_HDR_VALUE) {
719 cur_val = pdkim_strnew(NULL);
721 if ( (*p == '\r') || (*p == '\n') )
725 if (cur_tag->len > 0) {
726 pdkim_strtrim(cur_val);
728 if (ctx->debug_stream)
729 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
731 switch (cur_tag->str[0]) {
733 /* This tag isn't evaluated because:
734 - We only support version DKIM1.
735 - Which is the default for this value (set below)
736 - Other versions are currently not specified. */
739 pub->hashes = strdup(cur_val->str);
742 pub->granularity = strdup(cur_val->str);
745 pub->notes = pdkim_decode_qp(cur_val->str);
748 pub->key = pdkim_decode_base64(cur_val->str,&(pub->key_len));
751 pub->hashes = strdup(cur_val->str);
754 pub->srvtype = strdup(cur_val->str);
757 if (strchr(cur_val->str,'t') != NULL) pub->testing = 1;
758 if (strchr(cur_val->str,'s') != NULL) pub->no_subdomaining = 1;
762 if (ctx->debug_stream)
763 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
768 pdkim_strclear(cur_tag);
769 pdkim_strclear(cur_val);
770 where = PDKIM_HDR_LIMBO;
773 else pdkim_strncat(cur_val,p,1);
780 /* Set fallback defaults */
781 if (pub->version == NULL) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
782 if (pub->granularity == NULL) pub->granularity = strdup("*");
783 if (pub->keytype == NULL) pub->keytype = strdup("rsa");
784 if (pub->srvtype == NULL) pub->srvtype = strdup("*");
787 if (pub->key == NULL) {
788 pdkim_free_pubkey(pub);
796 /* -------------------------------------------------------------------------- */
797 int pdkim_update_bodyhash(pdkim_ctx *ctx, char *data, int len) {
798 pdkim_signature *sig = ctx->sig;
799 /* Cache relaxed version of data */
800 char *relaxed_data = NULL;
803 /* Traverse all signatures, updating their hashes. */
804 while (sig != NULL) {
805 /* Defaults to simple canon (no further treatment necessary) */
806 char *canon_data = data;
809 if (sig->canon_body == PDKIM_CANON_RELAXED) {
810 /* Relax the line if not done already */
811 if (relaxed_data == NULL) {
815 relaxed_data = malloc(len+1);
816 if (relaxed_data == NULL) return PDKIM_ERR_OOM;
819 if ( (c == '\t') || (c == ' ') ) {
820 c = ' '; /* Turns WSP into SP */
828 relaxed_data[q++] = c;
831 relaxed_data[q] = '\0';
834 canon_data = relaxed_data;
835 canon_len = relaxed_len;
838 /* Make sure we don't exceed the to-be-signed body length */
839 if (sig->bodylength &&
840 ((sig->signed_body_bytes+(unsigned long)canon_len) > sig->bodylength))
841 canon_len = (sig->bodylength - sig->signed_body_bytes);
844 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
845 sha1_update(sig->sha1_body,(unsigned char *)canon_data,canon_len);
847 sha2_update(sig->sha2_body,(unsigned char *)canon_data,canon_len);
848 sig->signed_body_bytes += canon_len;
850 if (ctx->debug_stream!=NULL)
851 pdkim_quoteprint(ctx->debug_stream,canon_data,canon_len,0);
858 if (relaxed_data != NULL) free(relaxed_data);
863 /* -------------------------------------------------------------------------- */
864 int pdkim_finish_bodyhash(pdkim_ctx *ctx) {
865 pdkim_signature *sig = ctx->sig;
867 /* Traverse all signatures */
868 while (sig != NULL) {
871 unsigned char bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
872 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
873 sha1_finish(sig->sha1_body,bh);
875 sha2_finish(sig->sha2_body,bh);
878 if (ctx->debug_stream) {
879 fprintf(ctx->debug_stream, "PDKIM [%s] Body bytes hashed: %lu\n",
880 sig->domain, sig->signed_body_bytes);
881 fprintf(ctx->debug_stream, "PDKIM [%s] bh computed: ", sig->domain);
882 pdkim_hexprint(ctx->debug_stream, (char *)bh,
883 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
887 /* SIGNING -------------------------------------------------------------- */
888 if (ctx->mode == PDKIM_MODE_SIGN) {
889 sig->bodyhash_len = (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32;
890 sig->bodyhash = malloc(sig->bodyhash_len);
891 if (sig->bodyhash == NULL) return PDKIM_ERR_OOM;
892 memcpy(sig->bodyhash,bh,sig->bodyhash_len);
894 /* If bodylength limit is set, and we have received less bytes
895 than the requested amount, effectively remove the limit tag. */
896 if (sig->signed_body_bytes < sig->bodylength) sig->bodylength = 0;
898 /* VERIFICATION --------------------------------------------------------- */
900 /* Compare bodyhash */
901 if (memcmp(bh,sig->bodyhash,
902 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0) {
904 if (ctx->debug_stream)
905 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash verified OK\n",
911 if (ctx->debug_stream) {
912 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash did NOT verify\n",
914 fprintf(ctx->debug_stream, "PDKIM [%s] bh signature: ", sig->domain);
915 pdkim_hexprint(ctx->debug_stream, sig->bodyhash,
916 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
919 sig->verify_status = PDKIM_VERIFY_FAIL;
920 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
932 /* -------------------------------------------------------------------------- */
933 /* Callback from pdkim_feed below for processing complete body lines */
934 int pdkim_bodyline_complete(pdkim_ctx *ctx) {
935 char *p = ctx->linebuf;
936 int n = ctx->linebuf_offset;
938 /* Ignore extra data if we've seen the end-of-data marker */
939 if (ctx->seen_eod) goto BAIL;
941 /* We've always got one extra byte to stuff a zero ... */
942 ctx->linebuf[(ctx->linebuf_offset)] = '\0';
944 if (ctx->input_mode == PDKIM_INPUT_SMTP) {
945 /* Terminate on EOD marker */
946 if (memcmp(p,".\r\n",3) == 0) {
951 if (memcmp(p,"..",2) == 0) {
957 /* Empty lines need to be buffered until we find a non-empty line */
958 if (memcmp(p,"\r\n",2) == 0) {
959 ctx->num_buffered_crlf++;
963 /* At this point, we have a non-empty line, so release the buffered ones. */
964 while (ctx->num_buffered_crlf) {
965 pdkim_update_bodyhash(ctx,"\r\n",2);
966 ctx->num_buffered_crlf--;
969 pdkim_update_bodyhash(ctx,p,n);
972 ctx->linebuf_offset = 0;
977 /* -------------------------------------------------------------------------- */
978 /* Callback from pdkim_feed below for processing complete headers */
979 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
980 int pdkim_header_complete(pdkim_ctx *ctx) {
981 pdkim_signature *sig = ctx->sig;
983 /* Special case: The last header can have an extra \r appended */
984 if ( (ctx->cur_header->len > 1) &&
985 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') ) {
986 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
987 ctx->cur_header->len--;
991 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
993 /* Traverse all signatures */
994 while (sig != NULL) {
996 /* SIGNING -------------------------------------------------------------- */
997 if (ctx->mode == PDKIM_MODE_SIGN) {
998 if (header_name_match(ctx->cur_header->str,
1001 PDKIM_DEFAULT_SIGN_HEADERS, 0) < 0) goto NEXT_SIG;
1003 /* VERIFICATION --------------------------------------------------------- */
1005 int rc = header_name_match(ctx->cur_header->str,
1007 sig->headernames_pos);
1008 /* Header is not included or out-of-sequence */
1009 if (rc < 0) goto NEXT_SIG;
1010 sig->headernames_pos = rc;
1013 /* Add header to the signed headers list */
1014 pdkim_stringlist *list = pdkim_append_stringlist(sig->headers,
1015 ctx->cur_header->str);
1016 if (list == NULL) return PDKIM_ERR_OOM;
1017 sig->headers = list;
1023 /* DKIM-Signature: headers are added to the verification list */
1024 if ( (ctx->mode == PDKIM_MODE_VERIFY) &&
1025 (strncasecmp(ctx->cur_header->str,
1026 DKIM_SIGNATURE_HEADERNAME,
1027 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0) ) {
1028 /* Create and chain new signature block */
1030 if (ctx->debug_stream)
1031 fprintf(ctx->debug_stream,
1032 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1034 pdkim_signature *new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str);
1035 if (new_sig != NULL) {
1036 pdkim_signature *last_sig = ctx->sig;
1037 if (last_sig == NULL) {
1041 while (last_sig->next != NULL) { last_sig = last_sig->next; };
1042 last_sig->next = new_sig;
1047 if (ctx->debug_stream) {
1048 fprintf(ctx->debug_stream,"Error while parsing signature header\n");
1049 fprintf(ctx->debug_stream,
1050 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1057 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1063 /* -------------------------------------------------------------------------- */
1064 #define HEADER_BUFFER_FRAG_SIZE 256
1065 int pdkim_feed (pdkim_ctx *ctx,
1069 for (p=0;p<len;p++) {
1071 if (ctx->past_headers) {
1072 /* Processing body byte */
1073 ctx->linebuf[(ctx->linebuf_offset)++] = c;
1075 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1076 if (rc != PDKIM_OK) return rc;
1078 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1079 return PDKIM_ERR_LONG_LINE;
1082 /* Processing header byte */
1086 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1087 if (rc != PDKIM_OK) return rc;
1088 ctx->past_headers = 1;
1091 if (ctx->debug_stream)
1092 fprintf(ctx->debug_stream,
1093 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1097 else ctx->seen_lf = 1;
1099 else if (ctx->seen_lf) {
1100 if (! ((c == '\t') || (c == ' '))) {
1101 int rc = pdkim_header_complete(ctx); /* End of header */
1102 if (rc != PDKIM_OK) return rc;
1107 if (ctx->cur_header == NULL) {
1108 ctx->cur_header = pdkim_strnew(NULL);
1109 if (ctx->cur_header == NULL) return PDKIM_ERR_OOM;
1111 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1112 if (pdkim_strncat(ctx->cur_header,&data[p],1) == NULL)
1113 return PDKIM_ERR_OOM;
1120 /* -------------------------------------------------------------------------- */
1121 char *pdkim_create_header(pdkim_signature *sig, int final) {
1123 char *base64_bh = NULL;
1124 char *base64_b = NULL;
1125 pdkim_str *hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1126 if (hdr == NULL) return NULL;
1128 base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len);
1129 if (base64_bh == NULL) goto BAIL;
1131 /* Required and static bits */
1133 pdkim_strcat(hdr,"; a=") &&
1134 pdkim_strcat(hdr,pdkim_algos[sig->algo]) &&
1135 pdkim_strcat(hdr,"; q=") &&
1136 pdkim_strcat(hdr,pdkim_querymethods[sig->querymethod]) &&
1137 pdkim_strcat(hdr,"; c=") &&
1138 pdkim_strcat(hdr,pdkim_canons[sig->canon_headers]) &&
1139 pdkim_strcat(hdr,"/") &&
1140 pdkim_strcat(hdr,pdkim_canons[sig->canon_body]) &&
1141 pdkim_strcat(hdr,"; d=") &&
1142 pdkim_strcat(hdr,sig->domain) &&
1143 pdkim_strcat(hdr,"; s=") &&
1144 pdkim_strcat(hdr,sig->selector) &&
1145 pdkim_strcat(hdr,";\r\n\th=") &&
1146 pdkim_strcat(hdr,sig->headernames) &&
1147 pdkim_strcat(hdr,"; bh=") &&
1148 pdkim_strcat(hdr,base64_bh) &&
1149 pdkim_strcat(hdr,";\r\n\t")
1152 if (sig->identity != NULL) {
1153 if (!( pdkim_strcat(hdr,"i=") &&
1154 pdkim_strcat(hdr,sig->identity) &&
1155 pdkim_strcat(hdr,";") ) ) {
1159 if (sig->created > 0) {
1160 if (!( pdkim_strcat(hdr,"t=") &&
1161 pdkim_numcat(hdr,sig->created) &&
1162 pdkim_strcat(hdr,";") ) ) {
1166 if (sig->expires > 0) {
1167 if (!( pdkim_strcat(hdr,"x=") &&
1168 pdkim_numcat(hdr,sig->expires) &&
1169 pdkim_strcat(hdr,";") ) ) {
1173 if (sig->bodylength > 0) {
1174 if (!( pdkim_strcat(hdr,"l=") &&
1175 pdkim_numcat(hdr,sig->bodylength) &&
1176 pdkim_strcat(hdr,";") ) ) {
1180 /* Extra linebreak */
1181 if (hdr->str[(hdr->len)-1] == ';') {
1182 if (!pdkim_strcat(hdr," \r\n\t")) goto BAIL;
1184 /* Preliminary or final version? */
1186 base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len);
1187 if (base64_b == NULL) goto BAIL;
1189 pdkim_strcat(hdr,"b=") &&
1190 pdkim_strcat(hdr,base64_b) &&
1191 pdkim_strcat(hdr,";")
1195 if (pdkim_strcat(hdr,"b=;")) goto DONE;
1202 rc = strdup(hdr->str);
1206 if (base64_bh != NULL) free(base64_bh);
1207 if (base64_b != NULL) free(base64_b);
1212 /* -------------------------------------------------------------------------- */
1213 int pdkim_feed_finish(pdkim_ctx *ctx, pdkim_signature **return_signatures) {
1214 pdkim_signature *sig = ctx->sig;
1215 pdkim_str *headernames = NULL; /* Collected signed header names */
1217 /* Check if we must still flush a (partial) header. If that is the
1218 case, the message has no body, and we must compute a body hash
1219 out of '<CR><LF>' */
1220 if (ctx->cur_header->len) {
1221 int rc = pdkim_header_complete(ctx);
1222 if (rc != PDKIM_OK) return rc;
1223 pdkim_update_bodyhash(ctx,"\r\n",2);
1226 /* For non-smtp input, check if there's an unfinished line in the
1227 body line buffer. If that is the case, we must add a CRLF to the
1228 hash to properly terminate the message. */
1229 if ((ctx->input_mode == PDKIM_INPUT_NORMAL) && ctx->linebuf_offset) {
1230 pdkim_update_bodyhash(ctx, ctx->linebuf, ctx->linebuf_offset);
1231 pdkim_update_bodyhash(ctx,"\r\n",2);
1234 if (ctx->debug_stream)
1235 fprintf(ctx->debug_stream,
1236 "\nPDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1240 /* Build (and/or evaluate) body hash */
1241 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK) return PDKIM_ERR_OOM;
1243 /* SIGNING -------------------------------------------------------------- */
1244 if (ctx->mode == PDKIM_MODE_SIGN) {
1245 headernames = pdkim_strnew(NULL);
1246 if (headernames == NULL) return PDKIM_ERR_OOM;
1248 /* ---------------------------------------------------------------------- */
1250 while (sig != NULL) {
1251 sha1_context sha1_headers;
1252 sha2_context sha2_headers;
1253 pdkim_stringlist *p = sig->headers;
1255 char headerhash[32];
1257 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1258 sha1_starts(&sha1_headers);
1260 sha2_starts(&sha2_headers,0);
1263 if (ctx->debug_stream)
1264 fprintf(ctx->debug_stream,
1265 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1271 /* SIGNING -------------------------------------------------------------- */
1272 if (ctx->mode == PDKIM_MODE_SIGN) {
1273 /* Collect header names (Note: colon presence is guaranteed here) */
1274 char *q = strchr(p->value,':');
1275 if (pdkim_strncat(headernames, p->value,
1276 (q-(p->value))+((p->next==NULL)?0:1)) == NULL)
1277 return PDKIM_ERR_OOM;
1279 /* ---------------------------------------------------------------------- */
1281 if (sig->canon_body == PDKIM_CANON_RELAXED)
1282 rh = pdkim_relax_header(p->value,1); /* cook header for relaxed canon */
1284 rh = strdup(p->value); /* just copy it for simple canon */
1286 if (rh == NULL) return PDKIM_ERR_OOM;
1288 /* Feed header to the hash algorithm */
1289 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1290 sha1_update(&(sha1_headers),(unsigned char *)rh,strlen(rh));
1292 sha2_update(&(sha2_headers),(unsigned char *)rh,strlen(rh));
1294 if (ctx->debug_stream)
1295 pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1302 if (ctx->debug_stream)
1303 fprintf(ctx->debug_stream,
1304 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1308 /* SIGNING ---------------------------------------------------------------- */
1309 if (ctx->mode == PDKIM_MODE_SIGN) {
1310 /* Copy headernames to signature struct */
1311 sig->headernames = strdup(headernames->str);
1312 pdkim_strfree(headernames);
1314 /* Create signature header with b= omitted */
1315 sig_hdr = pdkim_create_header(ctx->sig,0);
1317 /* VERIFICATION ----------------------------------------------------------- */
1319 sig_hdr = strdup(sig->rawsig_no_b_val);
1321 /* ------------------------------------------------------------------------ */
1323 if (sig_hdr == NULL) return PDKIM_ERR_OOM;
1325 /* Relax header if necessary */
1326 if (sig->canon_headers == PDKIM_CANON_RELAXED) {
1327 char *relaxed_hdr = pdkim_relax_header(sig_hdr,0);
1329 if (relaxed_hdr == NULL) return PDKIM_ERR_OOM;
1330 sig_hdr = relaxed_hdr;
1334 if (ctx->debug_stream) {
1335 fprintf(ctx->debug_stream,
1336 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1337 pdkim_quoteprint(ctx->debug_stream, sig_hdr, strlen(sig_hdr), 1);
1338 fprintf(ctx->debug_stream,
1339 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1343 /* Finalize header hash */
1344 if (sig->algo == PDKIM_ALGO_RSA_SHA1) {
1345 sha1_update(&(sha1_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1346 sha1_finish(&(sha1_headers),(unsigned char *)headerhash);
1349 sha2_update(&(sha2_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1350 sha2_finish(&(sha2_headers),(unsigned char *)headerhash);
1355 /* SIGNING ---------------------------------------------------------------- */
1356 if (ctx->mode == PDKIM_MODE_SIGN) {
1359 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1361 /* Perform private key operation */
1362 if (rsa_parse_key(&rsa, (unsigned char *)sig->rsa_privkey,
1363 strlen(sig->rsa_privkey), NULL, 0) != 0) {
1364 return PDKIM_ERR_RSA_PRIVKEY;
1367 sig->sigdata_len = mpi_size(&(rsa.N));
1368 sig->sigdata = malloc(sig->sigdata_len);
1369 if (sig->sigdata == NULL) return PDKIM_ERR_OOM;
1371 if (rsa_pkcs1_sign( &rsa, RSA_PRIVATE,
1372 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1373 RSA_SHA1:RSA_SHA256),
1375 (unsigned char *)headerhash,
1376 (unsigned char *)sig->sigdata ) != 0) {
1377 return PDKIM_ERR_RSA_SIGNING;
1383 if (ctx->debug_stream) {
1384 fprintf(ctx->debug_stream, "PDKIM [%s] b computed: ",
1386 pdkim_hexprint(ctx->debug_stream, sig->sigdata, sig->sigdata_len, 1);
1390 sig->signature_header = pdkim_create_header(ctx->sig,1);
1391 if (sig->signature_header == NULL) return PDKIM_ERR_OOM;
1393 /* VERIFICATION ----------------------------------------------------------- */
1396 char *dns_txt_name, *dns_txt_reply;
1398 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1400 dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN);
1401 if (dns_txt_name == NULL) return PDKIM_ERR_OOM;
1402 dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN);
1403 if (dns_txt_reply == NULL) {
1405 return PDKIM_ERR_OOM;
1407 memset(dns_txt_reply,0,PDKIM_DNS_TXT_MAX_RECLEN);
1408 memset(dns_txt_name ,0,PDKIM_DNS_TXT_MAX_NAMELEN);
1410 if (snprintf(dns_txt_name,PDKIM_DNS_TXT_MAX_NAMELEN,
1411 "%s._domainkey.%s.",
1412 sig->selector,sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN) {
1413 sig->verify_status = PDKIM_VERIFY_INVALID;
1414 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1418 if ((ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK) ||
1419 (dns_txt_reply[0] == '\0')) {
1420 sig->verify_status = PDKIM_VERIFY_INVALID;
1421 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1426 if (ctx->debug_stream) {
1427 fprintf(ctx->debug_stream,
1428 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1429 fprintf(ctx->debug_stream,"Raw record: ");
1430 pdkim_quoteprint(ctx->debug_stream, dns_txt_reply, strlen(dns_txt_reply), 1);
1434 sig->pubkey = pdkim_parse_pubkey_record(ctx,dns_txt_reply);
1435 if (sig->pubkey == NULL) {
1436 sig->verify_status = PDKIM_VERIFY_INVALID;
1437 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1439 if (ctx->debug_stream) {
1440 fprintf(ctx->debug_stream,"Error while parsing public key record\n");
1441 fprintf(ctx->debug_stream,
1442 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1449 if (ctx->debug_stream) {
1450 fprintf(ctx->debug_stream,
1451 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1455 if (rsa_parse_public_key(&rsa,
1456 (unsigned char *)sig->pubkey->key,
1457 sig->pubkey->key_len) != 0) {
1458 sig->verify_status = PDKIM_VERIFY_INVALID;
1459 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1463 /* Check the signature */
1464 if (rsa_pkcs1_verify(&rsa,
1466 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1467 RSA_SHA1:RSA_SHA256),
1469 (unsigned char *)headerhash,
1470 (unsigned char *)sig->sigdata) != 0) {
1471 sig->verify_status = PDKIM_VERIFY_FAIL;
1472 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1474 if (ctx->debug_stream) {
1475 fprintf(ctx->debug_stream, "PDKIM [%s] signature did NOT verify OK\n",
1482 /* We have a winner! */
1483 sig->verify_status = PDKIM_VERIFY_PASS;
1486 if (ctx->debug_stream) {
1487 fprintf(ctx->debug_stream, "PDKIM [%s] signature verified OK\n",
1495 free(dns_txt_reply);
1501 /* If requested, set return pointer to signature(s) */
1502 if (return_signatures != NULL) {
1503 *return_signatures = ctx->sig;
1510 /* -------------------------------------------------------------------------- */
1511 pdkim_ctx *pdkim_init_verify(int input_mode,
1512 int(*dns_txt_callback)(char *, char *)
1514 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
1515 if (ctx == NULL) return NULL;
1516 memset(ctx,0,sizeof(pdkim_ctx));
1518 ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN);
1519 if (ctx->linebuf == NULL) {
1524 ctx->mode = PDKIM_MODE_VERIFY;
1525 ctx->input_mode = input_mode;
1526 ctx->dns_txt_callback = dns_txt_callback;
1532 /* -------------------------------------------------------------------------- */
1533 pdkim_ctx *pdkim_init_sign(int input_mode,
1536 char *rsa_privkey) {
1539 if (!domain || !selector || !rsa_privkey) return NULL;
1541 ctx = malloc(sizeof(pdkim_ctx));
1542 if (ctx == NULL) return NULL;
1543 memset(ctx,0,sizeof(pdkim_ctx));
1545 ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN);
1546 if (ctx->linebuf == NULL) {
1551 pdkim_signature *sig = malloc(sizeof(pdkim_signature));
1557 memset(sig,0,sizeof(pdkim_signature));
1559 ctx->mode = PDKIM_MODE_SIGN;
1560 ctx->input_mode = input_mode;
1563 ctx->sig->domain = strdup(domain);
1564 ctx->sig->selector = strdup(selector);
1565 ctx->sig->rsa_privkey = strdup(rsa_privkey);
1567 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey) {
1568 pdkim_free_ctx(ctx);
1572 ctx->sig->sha1_body = malloc(sizeof(sha1_context));
1573 if (ctx->sig->sha1_body == NULL) {
1574 pdkim_free_ctx(ctx);
1577 sha1_starts(ctx->sig->sha1_body);
1579 ctx->sig->sha2_body = malloc(sizeof(sha2_context));
1580 if (ctx->sig->sha2_body == NULL) {
1581 pdkim_free_ctx(ctx);
1584 sha2_starts(ctx->sig->sha2_body,0);
1590 /* -------------------------------------------------------------------------- */
1591 void pdkim_set_debug_stream(pdkim_ctx *ctx,
1592 FILE *debug_stream) {
1593 ctx->debug_stream = debug_stream;
1597 /* -------------------------------------------------------------------------- */
1598 int pdkim_set_optional(pdkim_ctx *ctx,
1603 unsigned long bodylength,
1605 unsigned long created,
1606 unsigned long expires) {
1608 if (identity != NULL) {
1609 ctx->sig->identity = strdup(identity);
1610 if (ctx->sig->identity == NULL) return PDKIM_ERR_OOM;
1613 if (sign_headers != NULL) {
1614 ctx->sig->sign_headers = strdup(sign_headers);
1615 if (ctx->sig->sign_headers == NULL) return PDKIM_ERR_OOM;
1618 ctx->sig->canon_headers = canon_headers;
1619 ctx->sig->canon_body = canon_body;
1620 ctx->sig->bodylength = bodylength;
1621 ctx->sig->algo = algo;
1622 ctx->sig->created = created;
1623 ctx->sig->expires = expires;