1 /* $Cambridge: exim/src/src/pdkim/pdkim.c,v 1.1.2.6 2009/03/17 12:57:37 tom Exp $ */
13 /* -------------------------------------------------------------------------- */
14 /* A bunch of list constants */
15 char *pdkim_querymethods[] = {
19 char *pdkim_algos[] = {
24 char *pdkim_canons[] = {
29 char *pdkim_hashes[] = {
34 char *pdkim_keytypes[] = {
39 typedef struct pdkim_combined_canon_entry {
43 } pdkim_combined_canon_entry;
44 pdkim_combined_canon_entry pdkim_combined_canons[] = {
45 { "simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
46 { "simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
47 { "relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
48 { "relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
49 { "simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
50 { "relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
55 /* -------------------------------------------------------------------------- */
56 /* Various debugging functions */
58 void pdkim_quoteprint(FILE *stream, char *data, int len, int lf) {
60 unsigned char *p = (unsigned char *)data;
65 case ' ' : fprintf(stream,"{SP}"); break;
66 case '\t': fprintf(stream,"{TB}"); break;
67 case '\r': fprintf(stream,"{CR}"); break;
68 case '\n': fprintf(stream,"{LF}"); break;
69 case '{' : fprintf(stream,"{BO}"); break;
70 case '}' : fprintf(stream,"{BC}"); break;
72 if ( (c < 32) || (c > 127) )
73 fprintf(stream,"{%02x}",c);
82 void pdkim_hexprint(FILE *stream, char *data, int len, int lf) {
84 unsigned char *p = (unsigned char *)data;
88 fprintf(stream,"%02x ",c);
96 /* -------------------------------------------------------------------------- */
97 /* Simple string list implementation for convinience */
98 pdkim_stringlist *pdkim_append_stringlist(pdkim_stringlist *base, char *str) {
99 pdkim_stringlist *new_entry = malloc(sizeof(pdkim_stringlist));
100 if (new_entry == NULL) return NULL;
101 memset(new_entry,0,sizeof(pdkim_stringlist));
102 new_entry->value = malloc(strlen(str)+1);
103 if (new_entry->value == NULL) return NULL;
104 strcpy(new_entry->value,str);
106 pdkim_stringlist *last = base;
107 while (last->next != NULL) { last = last->next; };
108 last->next = new_entry;
111 else return new_entry;
115 /* -------------------------------------------------------------------------- */
116 /* A small "growing string" implementation to escape malloc/realloc hell */
117 pdkim_str *pdkim_strnew (char *cstr) {
118 unsigned int len = cstr?strlen(cstr):0;
119 pdkim_str *p = malloc(sizeof(pdkim_str));
120 if (p == NULL) return NULL;
121 memset(p,0,sizeof(pdkim_str));
122 p->str = malloc(len+1);
123 if (p->str == NULL) {
127 p->allocated=(len+1);
129 if (cstr) strcpy(p->str,cstr);
132 char *pdkim_strcat(pdkim_str *str, char *cstr) {
133 return pdkim_strncat(str, cstr, strlen(cstr));
135 char *pdkim_strncat(pdkim_str *str, char *data, int len) {
136 if ((str->allocated - str->len) < (len+1)) {
137 /* Extend the buffer */
138 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
139 char *n = realloc(str->str,
140 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
141 if (n == NULL) return NULL;
143 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
145 strncpy(&(str->str[str->len]),data,len);
147 str->str[str->len] = '\0';
150 char *pdkim_numcat(pdkim_str *str, unsigned long num) {
152 snprintf(minibuf,20,"%lu",num);
153 return pdkim_strcat(str,minibuf);
155 char *pdkim_strtrim(pdkim_str *str) {
158 while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
159 while (*p != '\0') {*q = *p; q++; p++;};
161 while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) ) {
165 str->len = strlen(str->str);
168 char *pdkim_strclear(pdkim_str *str) {
173 void pdkim_strfree(pdkim_str *str) {
174 if (str == NULL) return;
175 if (str->str != NULL) free(str->str);
180 /* -------------------------------------------------------------------------- */
181 /* Matches the name of the passed raw "header" against
182 the passed colon-separated "list", starting at entry
183 "start". Returns the position of the header name in
185 int header_name_match(char *header,
194 char *hcolon = strchr(header,':');
195 if (hcolon == NULL) return rc; /* This isn't a header */
196 hname = malloc((hcolon-header)+1);
197 if (hname == NULL) return PDKIM_ERR_OOM;
198 memset(hname,0,(hcolon-header)+1);
199 strncpy(hname,header,(hcolon-header));
200 lcopy = malloc(strlen(list)+1);
203 return PDKIM_ERR_OOM;
211 if (strcasecmp(p,hname) == 0) {
221 if (strcasecmp(p,hname) == 0)
231 /* -------------------------------------------------------------------------- */
232 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
234 char *pdkim_relax_header (char *header, int crlf) {
235 int past_field_name = 0;
239 char *relaxed = malloc(strlen(header));
240 if (relaxed == NULL) return NULL;
245 if ( (c == '\r') || (c == '\n') ) {
249 if ( (c == '\t') || (c == ' ') ) {
250 c = ' '; /* Turns WSP into SP */
258 if ( (!past_field_name) && (c == ':') ) {
259 if (seen_wsp) q--; /* This removes WSP before the colon */
260 seen_wsp = 1; /* This removes WSP after the colon */
265 /* Lowercase header name */
266 if (!past_field_name) c = tolower(c);
272 if (crlf) strcat(relaxed,"\r\n");
277 /* -------------------------------------------------------------------------- */
278 #define PDKIM_QP_ERROR_DECODE -1
279 char *pdkim_decode_qp_char(char *qp_p, int *c) {
280 char *initial_pos = qp_p;
282 /* Advance one char */
285 /* Check for two hex digits and decode them */
286 if (isxdigit(*qp_p) && isxdigit(qp_p[1])) {
287 /* Do hex conversion */
288 if (isdigit(*qp_p)) {*c = *qp_p - '0';}
289 else {*c = toupper(*qp_p) - 'A' + 10;};
291 if (isdigit(qp_p[1])) {*c |= qp_p[1] - '0';}
292 else {*c |= toupper(qp_p[1]) - 'A' + 10;};
296 /* Illegal char here */
297 *c = PDKIM_QP_ERROR_DECODE;
302 /* -------------------------------------------------------------------------- */
303 char *pdkim_decode_qp(char *str) {
307 char *n = malloc(strlen(p)+1);
308 if (n == NULL) return NULL;
313 p = pdkim_decode_qp_char(p,&nchar);
330 /* -------------------------------------------------------------------------- */
331 char *pdkim_decode_base64(char *str, int *num_decoded) {
335 base64_decode(NULL, &dlen, (unsigned char *)str, strlen(str));
336 res = malloc(dlen+1);
337 if (res == NULL) return NULL;
338 if (base64_decode((unsigned char *)res,&dlen,(unsigned char *)str,strlen(str)) != 0) {
342 if (num_decoded != NULL) *num_decoded = dlen;
346 /* -------------------------------------------------------------------------- */
347 char *pdkim_encode_base64(char *str, int num) {
351 base64_encode(NULL, &dlen, (unsigned char *)str, num);
352 res = malloc(dlen+1);
353 if (res == NULL) return NULL;
354 if (base64_encode((unsigned char *)res,&dlen,(unsigned char *)str,num) != 0) {
362 /* -------------------------------------------------------------------------- */
363 #define PDKIM_HDR_LIMBO 0
364 #define PDKIM_HDR_TAG 1
365 #define PDKIM_HDR_VALUE 2
366 pdkim_signature *pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr) {
367 pdkim_signature *sig ;
369 pdkim_str *cur_tag = NULL;
370 pdkim_str *cur_val = NULL;
373 int where = PDKIM_HDR_LIMBO;
376 sig = malloc(sizeof(pdkim_signature));
377 if (sig == NULL) return NULL;
378 memset(sig,0,sizeof(pdkim_signature));
380 sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1);
381 if (sig->rawsig_no_b_val == NULL) {
387 q = sig->rawsig_no_b_val;
392 if ( (*p == '\r') || (*p == '\n') )
395 /* Fast-forward through header name */
397 if (*p == ':') past_hname = 1;
401 if (where == PDKIM_HDR_LIMBO) {
402 /* In limbo, just wait for a tag-char to appear */
403 if (!((*p >= 'a') && (*p <= 'z')))
406 where = PDKIM_HDR_TAG;
409 if (where == PDKIM_HDR_TAG) {
411 cur_tag = pdkim_strnew(NULL);
413 if ((*p >= 'a') && (*p <= 'z'))
414 pdkim_strncat(cur_tag,p,1);
417 if (strcmp(cur_tag->str,"b") == 0) {
421 where = PDKIM_HDR_VALUE;
426 if (where == PDKIM_HDR_VALUE) {
428 cur_val = pdkim_strnew(NULL);
430 if ( (*p == '\r') || (*p == '\n') )
434 if (cur_tag->len > 0) {
435 pdkim_strtrim(cur_val);
437 if (ctx->debug_stream)
438 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
440 switch (cur_tag->str[0]) {
442 switch (cur_tag->str[1]) {
444 sig->bodyhash = pdkim_decode_base64(cur_val->str,&(sig->bodyhash_len));
447 sig->sigdata = pdkim_decode_base64(cur_val->str,&(sig->sigdata_len));
452 if (strcmp(cur_val->str,PDKIM_SIGNATURE_VERSION) == 0) {
453 /* We only support version 1, and that is currently the
454 only version there is. */
460 while (pdkim_algos[i] != NULL) {
461 if (strcmp(cur_val->str,pdkim_algos[i]) == 0 ) {
470 while (pdkim_combined_canons[i].str != NULL) {
471 if (strcmp(cur_val->str,pdkim_combined_canons[i].str) == 0 ) {
472 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
473 sig->canon_body = pdkim_combined_canons[i].canon_body;
481 while (pdkim_querymethods[i] != NULL) {
482 if (strcmp(cur_val->str,pdkim_querymethods[i]) == 0 ) {
483 sig->querymethod = i;
490 sig->selector = strdup(cur_val->str);
493 sig->domain = strdup(cur_val->str);
496 sig->identity = pdkim_decode_qp(cur_val->str);
499 sig->created = strtoul(cur_val->str,NULL,10);
502 sig->expires = strtoul(cur_val->str,NULL,10);
505 sig->bodylength = strtoul(cur_val->str,NULL,10);
508 sig->headernames = strdup(cur_val->str);
511 sig->copiedheaders = pdkim_decode_qp(cur_val->str);
515 if (ctx->debug_stream)
516 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
521 pdkim_strclear(cur_tag);
522 pdkim_strclear(cur_val);
524 where = PDKIM_HDR_LIMBO;
527 else pdkim_strncat(cur_val,p,1);
539 /* Make sure the most important bits are there. */
540 if (!(sig->domain && (*(sig->domain) != '\0') &&
541 sig->selector && (*(sig->selector) != '\0') &&
542 sig->headernames && (*(sig->headernames) != '\0') &&
552 if (ctx->debug_stream) {
553 fprintf(ctx->debug_stream,
554 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
555 pdkim_quoteprint(ctx->debug_stream,
556 sig->rawsig_no_b_val,
557 strlen(sig->rawsig_no_b_val), 1);
558 fprintf(ctx->debug_stream,
559 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
563 sha1_starts(&(sig->sha1_body));
564 sha2_starts(&(sig->sha2_body),0);
570 /* -------------------------------------------------------------------------- */
571 pdkim_pubkey *pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record) {
574 pdkim_str *cur_tag = NULL;
575 pdkim_str *cur_val = NULL;
576 int where = PDKIM_HDR_LIMBO;
578 pub = malloc(sizeof(pdkim_pubkey));
579 if (pub == NULL) return NULL;
580 memset(pub,0,sizeof(pdkim_pubkey));
587 if ( (*p == '\r') || (*p == '\n') )
590 if (where == PDKIM_HDR_LIMBO) {
591 /* In limbo, just wait for a tag-char to appear */
592 if (!((*p >= 'a') && (*p <= 'z')))
595 where = PDKIM_HDR_TAG;
598 if (where == PDKIM_HDR_TAG) {
600 cur_tag = pdkim_strnew(NULL);
602 if ((*p >= 'a') && (*p <= 'z'))
603 pdkim_strncat(cur_tag,p,1);
606 where = PDKIM_HDR_VALUE;
611 if (where == PDKIM_HDR_VALUE) {
613 cur_val = pdkim_strnew(NULL);
615 if ( (*p == '\r') || (*p == '\n') )
619 if (cur_tag->len > 0) {
620 pdkim_strtrim(cur_val);
622 if (ctx->debug_stream)
623 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
625 switch (cur_tag->str[0]) {
627 /* This tag isn't evaluated because:
628 - We only support version DKIM1.
629 - Which is the default for this value (set below)
630 - Other versions are currently not specified. */
633 pub->hashes = strdup(cur_val->str);
636 pub->granularity = strdup(cur_val->str);
639 pub->notes = pdkim_decode_qp(cur_val->str);
642 pub->key = pdkim_decode_base64(cur_val->str,&(pub->key_len));
645 pub->hashes = strdup(cur_val->str);
648 pub->srvtype = strdup(cur_val->str);
651 if (strchr(cur_val->str,'t') != NULL) pub->testing = 1;
652 if (strchr(cur_val->str,'s') != NULL) pub->no_subdomaining = 1;
656 if (ctx->debug_stream)
657 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
662 pdkim_strclear(cur_tag);
663 pdkim_strclear(cur_val);
664 where = PDKIM_HDR_LIMBO;
667 else pdkim_strncat(cur_val,p,1);
674 /* Set fallback defaults */
675 if (pub->version == NULL) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
676 if (pub->granularity == NULL) pub->granularity = strdup("*");
677 if (pub->keytype == NULL) pub->keytype = strdup("rsa");
678 if (pub->srvtype == NULL) pub->srvtype = strdup("*");
681 if (pub->key == NULL) {
682 pdkim_free_pubkey(pub);
690 /* -------------------------------------------------------------------------- */
691 int pdkim_update_bodyhash(pdkim_ctx *ctx, char *data, int len) {
692 pdkim_signature *sig = ctx->sig;
693 /* Cache relaxed version of data */
694 char *relaxed_data = NULL;
697 /* Traverse all signatures, updating their hashes. */
698 while (sig != NULL) {
699 /* Defaults to simple canon (no further treatment necessary) */
700 char *canon_data = data;
703 if (sig->canon_body == PDKIM_CANON_RELAXED) {
704 /* Relax the line if not done already */
705 if (relaxed_data == NULL) {
709 relaxed_data = malloc(len+1);
710 if (relaxed_data == NULL) return PDKIM_ERR_OOM;
713 if ( (c == '\t') || (c == ' ') ) {
714 c = ' '; /* Turns WSP into SP */
722 relaxed_data[q++] = c;
725 relaxed_data[q] = '\0';
728 canon_data = relaxed_data;
729 canon_len = relaxed_len;
732 /* Make sure we don't exceed the to-be-signed body length */
733 if (sig->bodylength &&
734 ((sig->signed_body_bytes+(unsigned long)canon_len) > sig->bodylength))
735 canon_len = (sig->bodylength - sig->signed_body_bytes);
738 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
739 sha1_update(&(sig->sha1_body),(unsigned char *)canon_data,canon_len);
741 sha2_update(&(sig->sha2_body),(unsigned char *)canon_data,canon_len);
742 sig->signed_body_bytes += canon_len;
744 if (ctx->debug_stream!=NULL)
745 pdkim_quoteprint(ctx->debug_stream,canon_data,canon_len,0);
752 if (relaxed_data != NULL) free(relaxed_data);
757 /* -------------------------------------------------------------------------- */
758 int pdkim_finish_bodyhash(pdkim_ctx *ctx) {
759 pdkim_signature *sig = ctx->sig;
761 /* Traverse all signatures */
762 while (sig != NULL) {
765 unsigned char bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
766 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
767 sha1_finish(&(sig->sha1_body),bh);
769 sha2_finish(&(sig->sha2_body),bh);
772 if (ctx->debug_stream) {
773 fprintf(ctx->debug_stream, "PDKIM [%s] Body bytes hashed: %lu\n",
774 sig->domain, sig->signed_body_bytes);
775 fprintf(ctx->debug_stream, "PDKIM [%s] bh computed: ", sig->domain);
776 pdkim_hexprint(ctx->debug_stream, (char *)bh,
777 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
781 /* SIGNING -------------------------------------------------------------- */
782 if (ctx->mode == PDKIM_MODE_SIGN) {
783 sig->bodyhash_len = (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32;
784 sig->bodyhash = malloc(sig->bodyhash_len);
785 if (sig->bodyhash == NULL) return PDKIM_ERR_OOM;
786 memcpy(sig->bodyhash,bh,sig->bodyhash_len);
788 /* If bodylength limit is set, and we have received less bytes
789 than the requested amount, effectively remove the limit tag. */
790 if (sig->signed_body_bytes < sig->bodylength) sig->bodylength = 0;
792 /* VERIFICATION --------------------------------------------------------- */
794 /* Compare bodyhash */
795 if (memcmp(bh,sig->bodyhash,
796 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0) {
798 if (ctx->debug_stream)
799 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash verified OK\n",
805 if (ctx->debug_stream) {
806 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash did NOT verify\n",
808 fprintf(ctx->debug_stream, "PDKIM [%s] bh signature: ", sig->domain);
809 pdkim_hexprint(ctx->debug_stream, sig->bodyhash,
810 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
813 sig->verify_status = PDKIM_VERIFY_FAIL;
814 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
826 /* -------------------------------------------------------------------------- */
827 /* Callback from pdkim_feed below for processing complete body lines */
828 int pdkim_bodyline_complete(pdkim_ctx *ctx) {
829 char *p = ctx->linebuf;
830 int n = ctx->linebuf_offset;
832 /* Ignore extra data if we've seen the end-of-data marker */
833 if (ctx->seen_eod) goto BAIL;
835 /* We've always got one extra byte to stuff a zero ... */
836 ctx->linebuf[(ctx->linebuf_offset)] = '\0';
838 if (ctx->input_mode == PDKIM_INPUT_SMTP) {
839 /* Terminate on EOD marker */
840 if (memcmp(p,".\r\n",3) == 0) {
845 if (memcmp(p,"..",2) == 0) {
851 /* Empty lines need to be buffered until we find a non-empty line */
852 if (memcmp(p,"\r\n",2) == 0) {
853 ctx->num_buffered_crlf++;
857 /* At this point, we have a non-empty line, so release the buffered ones. */
858 while (ctx->num_buffered_crlf) {
859 pdkim_update_bodyhash(ctx,"\r\n",2);
860 ctx->num_buffered_crlf--;
863 pdkim_update_bodyhash(ctx,p,n);
866 ctx->linebuf_offset = 0;
871 /* -------------------------------------------------------------------------- */
872 /* Callback from pdkim_feed below for processing complete headers */
873 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
874 int pdkim_header_complete(pdkim_ctx *ctx) {
875 pdkim_signature *sig = ctx->sig;
877 /* Special case: The last header can have an extra \r appended */
878 if ( (ctx->cur_header->len > 1) &&
879 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') ) {
880 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
881 ctx->cur_header->len--;
885 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
887 /* Traverse all signatures */
888 while (sig != NULL) {
890 /* SIGNING -------------------------------------------------------------- */
891 if (ctx->mode == PDKIM_MODE_SIGN) {
892 if (header_name_match(ctx->cur_header->str,
895 PDKIM_DEFAULT_SIGN_HEADERS, 0) < 0) goto NEXT_SIG;
897 /* VERIFICATION --------------------------------------------------------- */
899 int rc = header_name_match(ctx->cur_header->str,
901 sig->headernames_pos);
902 /* Header is not included or out-of-sequence */
903 if (rc < 0) goto NEXT_SIG;
904 sig->headernames_pos = rc;
907 /* Add header to the signed headers list */
908 pdkim_stringlist *list = pdkim_append_stringlist(sig->headers,
909 ctx->cur_header->str);
910 if (list == NULL) return PDKIM_ERR_OOM;
917 /* DKIM-Signature: headers are added to the verification list */
918 if ( (ctx->mode == PDKIM_MODE_VERIFY) &&
919 (strncasecmp(ctx->cur_header->str,
920 DKIM_SIGNATURE_HEADERNAME,
921 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0) ) {
922 /* Create and chain new signature block */
924 if (ctx->debug_stream)
925 fprintf(ctx->debug_stream,
926 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
928 pdkim_signature *new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str);
929 if (new_sig != NULL) {
930 pdkim_signature *last_sig = ctx->sig;
931 if (last_sig == NULL) {
935 while (last_sig->next != NULL) { last_sig = last_sig->next; };
936 last_sig->next = new_sig;
941 if (ctx->debug_stream) {
942 fprintf(ctx->debug_stream,"Error while parsing signature header\n");
943 fprintf(ctx->debug_stream,
944 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
951 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
957 /* -------------------------------------------------------------------------- */
958 #define HEADER_BUFFER_FRAG_SIZE 256
959 int pdkim_feed (pdkim_ctx *ctx,
963 for (p=0;p<len;p++) {
965 if (ctx->past_headers) {
966 /* Processing body byte */
967 ctx->linebuf[(ctx->linebuf_offset)++] = c;
969 int rc = pdkim_bodyline_complete(ctx); /* End of line */
970 if (rc != PDKIM_OK) return rc;
972 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
973 return PDKIM_ERR_LONG_LINE;
976 /* Processing header byte */
980 int rc = pdkim_header_complete(ctx); /* Seen last header line */
981 if (rc != PDKIM_OK) return rc;
982 ctx->past_headers = 1;
985 if (ctx->debug_stream)
986 fprintf(ctx->debug_stream,
987 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
991 else ctx->seen_lf = 1;
993 else if (ctx->seen_lf) {
994 if (! ((c == '\t') || (c == ' '))) {
995 int rc = pdkim_header_complete(ctx); /* End of header */
996 if (rc != PDKIM_OK) return rc;
1001 if (ctx->cur_header == NULL) {
1002 ctx->cur_header = pdkim_strnew(NULL);
1003 if (ctx->cur_header == NULL) return PDKIM_ERR_OOM;
1005 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1006 if (pdkim_strncat(ctx->cur_header,&data[p],1) == NULL)
1007 return PDKIM_ERR_OOM;
1014 /* -------------------------------------------------------------------------- */
1015 char *pdkim_create_header(pdkim_signature *sig, int final) {
1017 char *base64_bh = NULL;
1018 char *base64_b = NULL;
1019 pdkim_str *hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1020 if (hdr == NULL) return NULL;
1022 base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len);
1023 if (base64_bh == NULL) goto BAIL;
1025 /* Required and static bits */
1027 pdkim_strcat(hdr,"; a=") &&
1028 pdkim_strcat(hdr,pdkim_algos[sig->algo]) &&
1029 pdkim_strcat(hdr,"; q=") &&
1030 pdkim_strcat(hdr,pdkim_querymethods[sig->querymethod]) &&
1031 pdkim_strcat(hdr,"; c=") &&
1032 pdkim_strcat(hdr,pdkim_canons[sig->canon_headers]) &&
1033 pdkim_strcat(hdr,"/") &&
1034 pdkim_strcat(hdr,pdkim_canons[sig->canon_body]) &&
1035 pdkim_strcat(hdr,"; d=") &&
1036 pdkim_strcat(hdr,sig->domain) &&
1037 pdkim_strcat(hdr,"; s=") &&
1038 pdkim_strcat(hdr,sig->selector) &&
1039 pdkim_strcat(hdr,";\r\n\th=") &&
1040 pdkim_strcat(hdr,sig->headernames) &&
1041 pdkim_strcat(hdr,"; bh=") &&
1042 pdkim_strcat(hdr,base64_bh) &&
1043 pdkim_strcat(hdr,";\r\n\t")
1046 if (sig->identity != NULL) {
1047 if (!( pdkim_strcat(hdr,"i=") &&
1048 pdkim_strcat(hdr,sig->identity) &&
1049 pdkim_strcat(hdr,";") ) ) {
1053 if (sig->created > 0) {
1054 if (!( pdkim_strcat(hdr,"t=") &&
1055 pdkim_numcat(hdr,sig->created) &&
1056 pdkim_strcat(hdr,";") ) ) {
1060 if (sig->expires > 0) {
1061 if (!( pdkim_strcat(hdr,"x=") &&
1062 pdkim_numcat(hdr,sig->expires) &&
1063 pdkim_strcat(hdr,";") ) ) {
1067 if (sig->bodylength > 0) {
1068 if (!( pdkim_strcat(hdr,"l=") &&
1069 pdkim_numcat(hdr,sig->bodylength) &&
1070 pdkim_strcat(hdr,";") ) ) {
1074 /* Extra linebreak */
1075 if (hdr->str[(hdr->len)-1] == ';') {
1076 if (!pdkim_strcat(hdr," \r\n\t")) goto BAIL;
1078 /* Preliminary or final version? */
1080 base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len);
1081 if (base64_b == NULL) goto BAIL;
1083 pdkim_strcat(hdr,"b=") &&
1084 pdkim_strcat(hdr,base64_b) &&
1085 pdkim_strcat(hdr,";")
1089 if (pdkim_strcat(hdr,"b=;")) goto DONE;
1096 rc = strdup(hdr->str);
1100 if (base64_bh != NULL) free(base64_bh);
1101 if (base64_b != NULL) free(base64_b);
1106 /* -------------------------------------------------------------------------- */
1107 int pdkim_feed_finish(pdkim_ctx *ctx, char **signature) {
1108 pdkim_signature *sig = ctx->sig;
1109 pdkim_str *headernames = NULL; /* Collected signed header names */
1111 /* Check if we must still flush a (partial) header. If that is the
1112 case, the message has no body, and we must compute a body hash
1113 out of '<CR><LF>' */
1114 if (ctx->cur_header->len) {
1115 int rc = pdkim_header_complete(ctx);
1116 if (rc != PDKIM_OK) return rc;
1117 pdkim_update_bodyhash(ctx,"\r\n",2);
1120 /* For non-smtp input, check if there's an unfinished line in the
1121 body line buffer. If that is the case, we must add a CRLF to the
1122 hash to properly terminate the message. */
1123 if ((ctx->input_mode == PDKIM_INPUT_NORMAL) && ctx->linebuf_offset) {
1124 pdkim_update_bodyhash(ctx, ctx->linebuf, ctx->linebuf_offset);
1125 pdkim_update_bodyhash(ctx,"\r\n",2);
1128 if (ctx->debug_stream)
1129 fprintf(ctx->debug_stream,
1130 "\nPDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1134 /* Build (and/or evaluate) body hash */
1135 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK) return PDKIM_ERR_OOM;
1137 /* SIGNING -------------------------------------------------------------- */
1138 if (ctx->mode == PDKIM_MODE_SIGN) {
1139 headernames = pdkim_strnew(NULL);
1140 if (headernames == NULL) return PDKIM_ERR_OOM;
1142 /* ---------------------------------------------------------------------- */
1144 while (sig != NULL) {
1145 sha1_context sha1_headers;
1146 sha2_context sha2_headers;
1147 pdkim_stringlist *p = sig->headers;
1149 char headerhash[32];
1151 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1152 sha1_starts(&sha1_headers);
1154 sha2_starts(&sha2_headers,0);
1157 if (ctx->debug_stream)
1158 fprintf(ctx->debug_stream,
1159 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1165 /* SIGNING -------------------------------------------------------------- */
1166 if (ctx->mode == PDKIM_MODE_SIGN) {
1167 /* Collect header names (Note: colon presence is guaranteed here) */
1168 char *q = strchr(p->value,':');
1169 if (pdkim_strncat(headernames, p->value,
1170 (q-(p->value))+((p->next==NULL)?0:1)) == NULL)
1171 return PDKIM_ERR_OOM;
1173 /* ---------------------------------------------------------------------- */
1175 if (sig->canon_body == PDKIM_CANON_RELAXED)
1176 rh = pdkim_relax_header(p->value,1); /* cook header for relaxed canon */
1178 rh = strdup(p->value); /* just copy it for simple canon */
1180 if (rh == NULL) return PDKIM_ERR_OOM;
1182 /* Feed header to the hash algorithm */
1183 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1184 sha1_update(&(sha1_headers),(unsigned char *)rh,strlen(rh));
1186 sha2_update(&(sha2_headers),(unsigned char *)rh,strlen(rh));
1188 if (ctx->debug_stream)
1189 pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1196 if (ctx->debug_stream)
1197 fprintf(ctx->debug_stream,
1198 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1202 /* SIGNING ---------------------------------------------------------------- */
1203 if (ctx->mode == PDKIM_MODE_SIGN) {
1204 /* Copy headernames to signature struct */
1205 sig->headernames = strdup(headernames->str);
1206 pdkim_strfree(headernames);
1208 /* Create signature header with b= omitted */
1209 sig_hdr = pdkim_create_header(ctx->sig,0);
1211 /* VERIFICATION ----------------------------------------------------------- */
1213 sig_hdr = strdup(sig->rawsig_no_b_val);
1215 /* ------------------------------------------------------------------------ */
1217 if (sig_hdr == NULL) return PDKIM_ERR_OOM;
1219 /* Relax header if necessary */
1220 if (sig->canon_headers == PDKIM_CANON_RELAXED) {
1221 char *relaxed_hdr = pdkim_relax_header(sig_hdr,0);
1223 if (relaxed_hdr == NULL) return PDKIM_ERR_OOM;
1224 sig_hdr = relaxed_hdr;
1228 if (ctx->debug_stream) {
1229 fprintf(ctx->debug_stream,
1230 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1231 pdkim_quoteprint(ctx->debug_stream, sig_hdr, strlen(sig_hdr), 1);
1232 fprintf(ctx->debug_stream,
1233 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1237 /* Finalize header hash */
1238 if (sig->algo == PDKIM_ALGO_RSA_SHA1) {
1239 sha1_update(&(sha1_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1240 sha1_finish(&(sha1_headers),(unsigned char *)headerhash);
1243 sha2_update(&(sha2_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1244 sha2_finish(&(sha2_headers),(unsigned char *)headerhash);
1249 /* SIGNING ---------------------------------------------------------------- */
1250 if (ctx->mode == PDKIM_MODE_SIGN) {
1253 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1255 /* Perform private key operation */
1256 if (rsa_parse_key(&rsa, (unsigned char *)sig->rsa_privkey,
1257 strlen(sig->rsa_privkey), NULL, 0) != 0) {
1258 return PDKIM_ERR_RSA_PRIVKEY;
1261 sig->sigdata_len = mpi_size(&(rsa.N));
1262 sig->sigdata = malloc(sig->sigdata_len);
1263 if (sig->sigdata == NULL) return PDKIM_ERR_OOM;
1265 if (rsa_pkcs1_sign( &rsa, RSA_PRIVATE,
1266 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1267 RSA_SHA1:RSA_SHA256),
1269 (unsigned char *)headerhash,
1270 (unsigned char *)sig->sigdata ) != 0) {
1271 return PDKIM_ERR_RSA_SIGNING;
1277 if (ctx->debug_stream) {
1278 fprintf(ctx->debug_stream, "PDKIM [%s] b computed: ",
1280 pdkim_hexprint(ctx->debug_stream, sig->sigdata, sig->sigdata_len, 1);
1284 /* Recreate signature header with b= included, return it to the caller */
1285 if (signature != NULL) {
1286 *signature = pdkim_create_header(ctx->sig,1);
1287 if (*signature == NULL) return PDKIM_ERR_OOM;
1290 /* VERIFICATION ----------------------------------------------------------- */
1293 char *dns_txt_name, *dns_txt_reply;
1295 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1297 dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN);
1298 if (dns_txt_name == NULL) return PDKIM_ERR_OOM;
1299 dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN);
1300 if (dns_txt_reply == NULL) {
1302 return PDKIM_ERR_OOM;
1304 memset(dns_txt_reply,0,PDKIM_DNS_TXT_MAX_RECLEN);
1305 memset(dns_txt_name ,0,PDKIM_DNS_TXT_MAX_NAMELEN);
1307 if (snprintf(dns_txt_name,PDKIM_DNS_TXT_MAX_NAMELEN,
1308 "%s._domainkey.%s.",
1309 sig->selector,sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN) {
1310 sig->verify_status = PDKIM_VERIFY_INVALID;
1311 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1315 if ((ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK) ||
1316 (dns_txt_reply[0] == '\0')) {
1317 sig->verify_status = PDKIM_VERIFY_INVALID;
1318 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1323 if (ctx->debug_stream) {
1324 fprintf(ctx->debug_stream,
1325 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1326 fprintf(ctx->debug_stream,"Raw record: ");
1327 pdkim_quoteprint(ctx->debug_stream, dns_txt_reply, strlen(dns_txt_reply), 1);
1331 sig->pubkey = pdkim_parse_pubkey_record(ctx,dns_txt_reply);
1332 if (sig->pubkey == NULL) {
1333 sig->verify_status = PDKIM_VERIFY_INVALID;
1334 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1336 if (ctx->debug_stream) {
1337 fprintf(ctx->debug_stream,"Error while parsing public key record\n");
1338 fprintf(ctx->debug_stream,
1339 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1346 if (ctx->debug_stream) {
1347 fprintf(ctx->debug_stream,
1348 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1352 if (rsa_parse_public_key(&rsa,
1353 (unsigned char *)sig->pubkey->key,
1354 sig->pubkey->key_len) != 0) {
1355 sig->verify_status = PDKIM_VERIFY_INVALID;
1356 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1360 /* Check the signature */
1361 if (rsa_pkcs1_verify(&rsa,
1363 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1364 RSA_SHA1:RSA_SHA256),
1366 (unsigned char *)headerhash,
1367 (unsigned char *)sig->sigdata) != 0) {
1368 sig->verify_status = PDKIM_VERIFY_FAIL;
1369 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1371 if (ctx->debug_stream) {
1372 fprintf(ctx->debug_stream, "PDKIM [%s] signature did NOT verify OK\n",
1379 /* We have a winner! */
1380 sig->verify_status = PDKIM_VERIFY_PASS;
1383 if (ctx->debug_stream) {
1384 fprintf(ctx->debug_stream, "PDKIM [%s] signature verified OK\n",
1392 free(dns_txt_reply);
1402 /* -------------------------------------------------------------------------- */
1403 pdkim_ctx *pdkim_init_verify(int input_mode,
1404 int(*dns_txt_callback)(char *, char *)
1406 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
1407 if (ctx == NULL) return NULL;
1408 memset(ctx,0,sizeof(pdkim_ctx));
1409 ctx->mode = PDKIM_MODE_VERIFY;
1410 ctx->input_mode = input_mode;
1411 ctx->dns_txt_callback = dns_txt_callback;
1417 /* -------------------------------------------------------------------------- */
1418 pdkim_ctx *pdkim_init_sign(int input_mode,
1421 char *rsa_privkey) {
1424 if (!domain || !selector || !rsa_privkey) return NULL;
1426 ctx = malloc(sizeof(pdkim_ctx));
1427 if (ctx == NULL) return NULL;
1428 memset(ctx,0,sizeof(pdkim_ctx));
1429 pdkim_signature *sig = malloc(sizeof(pdkim_signature));
1434 memset(sig,0,sizeof(pdkim_signature));
1436 ctx->mode = PDKIM_MODE_SIGN;
1437 ctx->input_mode = input_mode;
1440 ctx->sig->domain = malloc(strlen(domain)+1);
1441 ctx->sig->selector = malloc(strlen(selector)+1);
1442 ctx->sig->rsa_privkey = malloc(strlen(rsa_privkey)+1);
1444 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey) {
1445 pdkim_free_ctx(ctx);
1449 strcpy(ctx->sig->domain, domain);
1450 strcpy(ctx->sig->selector, selector);
1451 strcpy(ctx->sig->rsa_privkey, rsa_privkey);
1453 sha1_starts(&(ctx->sig->sha1_body));
1454 sha2_starts(&(ctx->sig->sha2_body),0);
1460 /* -------------------------------------------------------------------------- */
1461 void pdkim_set_debug_stream(pdkim_ctx *ctx,
1462 FILE *debug_stream) {
1463 ctx->debug_stream = debug_stream;
1467 /* -------------------------------------------------------------------------- */
1468 int pdkim_set_optional(pdkim_ctx *ctx,
1473 unsigned long bodylength,
1475 unsigned long created,
1476 unsigned long expires) {
1478 if (identity != NULL) {
1479 ctx->sig->identity = malloc(strlen(identity)+1);
1480 if (!ctx->sig->identity) {
1481 return PDKIM_ERR_OOM;
1483 strcpy(ctx->sig->identity, identity);
1486 if (sign_headers != NULL) {
1487 ctx->sig->sign_headers = malloc(strlen(sign_headers)+1);
1488 if (!ctx->sig->sign_headers) {
1489 return PDKIM_ERR_OOM;
1491 strcpy(ctx->sig->sign_headers, sign_headers);
1494 ctx->sig->canon_headers = canon_headers;
1495 ctx->sig->canon_body = canon_body;
1496 ctx->sig->bodylength = bodylength;
1497 ctx->sig->algo = algo;
1498 ctx->sig->created = created;
1499 ctx->sig->expires = expires;
1505 /* -------------------------------------------------------------------------- */
1506 void pdkim_free_pubkey(pdkim_pubkey *pub) {
1508 if (pub->version != NULL) free(pub->version);
1509 if (pub->granularity != NULL) free(pub->granularity);
1510 if (pub->hashes != NULL) free(pub->hashes);
1511 if (pub->keytype != NULL) free(pub->keytype);
1512 if (pub->srvtype != NULL) free(pub->srvtype);
1513 if (pub->notes != NULL) free(pub->notes);
1514 if (pub->key != NULL) free(pub->key);
1520 /* -------------------------------------------------------------------------- */
1521 void pdkim_free_sig(pdkim_signature *sig) {
1523 pdkim_signature *next = (pdkim_signature *)sig->next;
1525 pdkim_stringlist *e = sig->headers;
1527 pdkim_stringlist *c = e;
1528 if (e->value != NULL) free(e->value);
1533 if (sig->sigdata != NULL) free(sig->sigdata);
1534 if (sig->bodyhash != NULL) free(sig->bodyhash);
1535 if (sig->selector != NULL) free(sig->selector);
1536 if (sig->domain != NULL) free(sig->domain);
1537 if (sig->identity != NULL) free(sig->identity);
1538 if (sig->headernames != NULL) free(sig->headernames);
1539 if (sig->copiedheaders != NULL) free(sig->copiedheaders);
1540 if (sig->rsa_privkey != NULL) free(sig->rsa_privkey);
1541 if (sig->sign_headers != NULL) free(sig->sign_headers);
1543 if (sig->pubkey != NULL) pdkim_free_pubkey(sig->pubkey);
1546 if (next != NULL) pdkim_free_sig(next);
1551 /* -------------------------------------------------------------------------- */
1552 void pdkim_free_ctx(pdkim_ctx *ctx) {
1554 pdkim_free_sig(ctx->sig);
1555 pdkim_strfree(ctx->cur_header);