1 /* $Cambridge: exim/src/src/pdkim/pdkim.c,v 1.1.2.7 2009/03/17 14:56:55 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 = malloc(strlen(str)+1);
140 if (new_entry->value == NULL) return NULL;
141 strcpy(new_entry->value,str);
143 pdkim_stringlist *last = base;
144 while (last->next != NULL) { last = last->next; };
145 last->next = new_entry;
148 else return new_entry;
152 /* -------------------------------------------------------------------------- */
153 /* A small "growing string" implementation to escape malloc/realloc hell */
154 pdkim_str *pdkim_strnew (char *cstr) {
155 unsigned int len = cstr?strlen(cstr):0;
156 pdkim_str *p = malloc(sizeof(pdkim_str));
157 if (p == NULL) return NULL;
158 memset(p,0,sizeof(pdkim_str));
159 p->str = malloc(len+1);
160 if (p->str == NULL) {
164 p->allocated=(len+1);
166 if (cstr) strcpy(p->str,cstr);
169 char *pdkim_strncat(pdkim_str *str, char *data, int len) {
170 if ((str->allocated - str->len) < (len+1)) {
171 /* Extend the buffer */
172 int num_frags = ((len+1)/PDKIM_STR_ALLOC_FRAG)+1;
173 char *n = realloc(str->str,
174 (str->allocated+(num_frags*PDKIM_STR_ALLOC_FRAG)));
175 if (n == NULL) return NULL;
177 str->allocated += (num_frags*PDKIM_STR_ALLOC_FRAG);
179 strncpy(&(str->str[str->len]),data,len);
181 str->str[str->len] = '\0';
184 char *pdkim_strcat(pdkim_str *str, char *cstr) {
185 return pdkim_strncat(str, cstr, strlen(cstr));
187 char *pdkim_numcat(pdkim_str *str, unsigned long num) {
189 snprintf(minibuf,20,"%lu",num);
190 return pdkim_strcat(str,minibuf);
192 char *pdkim_strtrim(pdkim_str *str) {
195 while ( (*p != '\0') && ((*p == '\t') || (*p == ' ')) ) p++;
196 while (*p != '\0') {*q = *p; q++; p++;};
198 while ( (q != str->str) && ( (*q == '\0') || (*q == '\t') || (*q == ' ') ) ) {
202 str->len = strlen(str->str);
205 char *pdkim_strclear(pdkim_str *str) {
210 void pdkim_strfree(pdkim_str *str) {
211 if (str == NULL) return;
212 if (str->str != NULL) free(str->str);
218 /* -------------------------------------------------------------------------- */
219 void pdkim_free_pubkey(pdkim_pubkey *pub) {
221 if (pub->version != NULL) free(pub->version);
222 if (pub->granularity != NULL) free(pub->granularity);
223 if (pub->hashes != NULL) free(pub->hashes);
224 if (pub->keytype != NULL) free(pub->keytype);
225 if (pub->srvtype != NULL) free(pub->srvtype);
226 if (pub->notes != NULL) free(pub->notes);
227 if (pub->key != NULL) free(pub->key);
233 /* -------------------------------------------------------------------------- */
234 void pdkim_free_sig(pdkim_signature *sig) {
236 pdkim_signature *next = (pdkim_signature *)sig->next;
238 pdkim_stringlist *e = sig->headers;
240 pdkim_stringlist *c = e;
241 if (e->value != NULL) free(e->value);
246 if (sig->sigdata != NULL) free(sig->sigdata);
247 if (sig->bodyhash != NULL) free(sig->bodyhash);
248 if (sig->selector != NULL) free(sig->selector);
249 if (sig->domain != NULL) free(sig->domain);
250 if (sig->identity != NULL) free(sig->identity);
251 if (sig->headernames != NULL) free(sig->headernames);
252 if (sig->copiedheaders != NULL) free(sig->copiedheaders);
253 if (sig->rsa_privkey != NULL) free(sig->rsa_privkey);
254 if (sig->sign_headers != NULL) free(sig->sign_headers);
256 if (sig->pubkey != NULL) pdkim_free_pubkey(sig->pubkey);
259 if (next != NULL) pdkim_free_sig(next);
264 /* -------------------------------------------------------------------------- */
265 void pdkim_free_ctx(pdkim_ctx *ctx) {
267 pdkim_free_sig(ctx->sig);
268 pdkim_strfree(ctx->cur_header);
274 /* -------------------------------------------------------------------------- */
275 /* Matches the name of the passed raw "header" against
276 the passed colon-separated "list", starting at entry
277 "start". Returns the position of the header name in
279 int header_name_match(char *header,
288 char *hcolon = strchr(header,':');
289 if (hcolon == NULL) return rc; /* This isn't a header */
290 hname = malloc((hcolon-header)+1);
291 if (hname == NULL) return PDKIM_ERR_OOM;
292 memset(hname,0,(hcolon-header)+1);
293 strncpy(hname,header,(hcolon-header));
294 lcopy = malloc(strlen(list)+1);
297 return PDKIM_ERR_OOM;
305 if (strcasecmp(p,hname) == 0) {
315 if (strcasecmp(p,hname) == 0)
325 /* -------------------------------------------------------------------------- */
326 /* Performs "relaxed" canonicalization of a header. The returned pointer needs
328 char *pdkim_relax_header (char *header, int crlf) {
329 int past_field_name = 0;
333 char *relaxed = malloc(strlen(header));
334 if (relaxed == NULL) return NULL;
339 if ( (c == '\r') || (c == '\n') ) {
343 if ( (c == '\t') || (c == ' ') ) {
344 c = ' '; /* Turns WSP into SP */
352 if ( (!past_field_name) && (c == ':') ) {
353 if (seen_wsp) q--; /* This removes WSP before the colon */
354 seen_wsp = 1; /* This removes WSP after the colon */
359 /* Lowercase header name */
360 if (!past_field_name) c = tolower(c);
366 if (crlf) strcat(relaxed,"\r\n");
371 /* -------------------------------------------------------------------------- */
372 #define PDKIM_QP_ERROR_DECODE -1
373 char *pdkim_decode_qp_char(char *qp_p, int *c) {
374 char *initial_pos = qp_p;
376 /* Advance one char */
379 /* Check for two hex digits and decode them */
380 if (isxdigit(*qp_p) && isxdigit(qp_p[1])) {
381 /* Do hex conversion */
382 if (isdigit(*qp_p)) {*c = *qp_p - '0';}
383 else {*c = toupper(*qp_p) - 'A' + 10;};
385 if (isdigit(qp_p[1])) {*c |= qp_p[1] - '0';}
386 else {*c |= toupper(qp_p[1]) - 'A' + 10;};
390 /* Illegal char here */
391 *c = PDKIM_QP_ERROR_DECODE;
396 /* -------------------------------------------------------------------------- */
397 char *pdkim_decode_qp(char *str) {
401 char *n = malloc(strlen(p)+1);
402 if (n == NULL) return NULL;
407 p = pdkim_decode_qp_char(p,&nchar);
424 /* -------------------------------------------------------------------------- */
425 char *pdkim_decode_base64(char *str, int *num_decoded) {
429 base64_decode(NULL, &dlen, (unsigned char *)str, strlen(str));
430 res = malloc(dlen+1);
431 if (res == NULL) return NULL;
432 if (base64_decode((unsigned char *)res,&dlen,(unsigned char *)str,strlen(str)) != 0) {
436 if (num_decoded != NULL) *num_decoded = dlen;
440 /* -------------------------------------------------------------------------- */
441 char *pdkim_encode_base64(char *str, int num) {
445 base64_encode(NULL, &dlen, (unsigned char *)str, num);
446 res = malloc(dlen+1);
447 if (res == NULL) return NULL;
448 if (base64_encode((unsigned char *)res,&dlen,(unsigned char *)str,num) != 0) {
456 /* -------------------------------------------------------------------------- */
457 #define PDKIM_HDR_LIMBO 0
458 #define PDKIM_HDR_TAG 1
459 #define PDKIM_HDR_VALUE 2
460 pdkim_signature *pdkim_parse_sig_header(pdkim_ctx *ctx, char *raw_hdr) {
461 pdkim_signature *sig ;
463 pdkim_str *cur_tag = NULL;
464 pdkim_str *cur_val = NULL;
467 int where = PDKIM_HDR_LIMBO;
470 sig = malloc(sizeof(pdkim_signature));
471 if (sig == NULL) return NULL;
472 memset(sig,0,sizeof(pdkim_signature));
474 sig->rawsig_no_b_val = malloc(strlen(raw_hdr)+1);
475 if (sig->rawsig_no_b_val == NULL) {
481 q = sig->rawsig_no_b_val;
486 if ( (*p == '\r') || (*p == '\n') )
489 /* Fast-forward through header name */
491 if (*p == ':') past_hname = 1;
495 if (where == PDKIM_HDR_LIMBO) {
496 /* In limbo, just wait for a tag-char to appear */
497 if (!((*p >= 'a') && (*p <= 'z')))
500 where = PDKIM_HDR_TAG;
503 if (where == PDKIM_HDR_TAG) {
505 cur_tag = pdkim_strnew(NULL);
507 if ((*p >= 'a') && (*p <= 'z'))
508 pdkim_strncat(cur_tag,p,1);
511 if (strcmp(cur_tag->str,"b") == 0) {
515 where = PDKIM_HDR_VALUE;
520 if (where == PDKIM_HDR_VALUE) {
522 cur_val = pdkim_strnew(NULL);
524 if ( (*p == '\r') || (*p == '\n') )
528 if (cur_tag->len > 0) {
529 pdkim_strtrim(cur_val);
531 if (ctx->debug_stream)
532 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
534 switch (cur_tag->str[0]) {
536 switch (cur_tag->str[1]) {
538 sig->bodyhash = pdkim_decode_base64(cur_val->str,&(sig->bodyhash_len));
541 sig->sigdata = pdkim_decode_base64(cur_val->str,&(sig->sigdata_len));
546 if (strcmp(cur_val->str,PDKIM_SIGNATURE_VERSION) == 0) {
547 /* We only support version 1, and that is currently the
548 only version there is. */
554 while (pdkim_algos[i] != NULL) {
555 if (strcmp(cur_val->str,pdkim_algos[i]) == 0 ) {
564 while (pdkim_combined_canons[i].str != NULL) {
565 if (strcmp(cur_val->str,pdkim_combined_canons[i].str) == 0 ) {
566 sig->canon_headers = pdkim_combined_canons[i].canon_headers;
567 sig->canon_body = pdkim_combined_canons[i].canon_body;
575 while (pdkim_querymethods[i] != NULL) {
576 if (strcmp(cur_val->str,pdkim_querymethods[i]) == 0 ) {
577 sig->querymethod = i;
584 sig->selector = strdup(cur_val->str);
587 sig->domain = strdup(cur_val->str);
590 sig->identity = pdkim_decode_qp(cur_val->str);
593 sig->created = strtoul(cur_val->str,NULL,10);
596 sig->expires = strtoul(cur_val->str,NULL,10);
599 sig->bodylength = strtoul(cur_val->str,NULL,10);
602 sig->headernames = strdup(cur_val->str);
605 sig->copiedheaders = pdkim_decode_qp(cur_val->str);
609 if (ctx->debug_stream)
610 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
615 pdkim_strclear(cur_tag);
616 pdkim_strclear(cur_val);
618 where = PDKIM_HDR_LIMBO;
621 else pdkim_strncat(cur_val,p,1);
633 /* Make sure the most important bits are there. */
634 if (!(sig->domain && (*(sig->domain) != '\0') &&
635 sig->selector && (*(sig->selector) != '\0') &&
636 sig->headernames && (*(sig->headernames) != '\0') &&
646 if (ctx->debug_stream) {
647 fprintf(ctx->debug_stream,
648 "PDKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
649 pdkim_quoteprint(ctx->debug_stream,
650 sig->rawsig_no_b_val,
651 strlen(sig->rawsig_no_b_val), 1);
652 fprintf(ctx->debug_stream,
653 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
657 sig->sha1_body = malloc(sizeof(sha1_context));
658 if (sig->sha1_body == NULL) {
662 sig->sha2_body = malloc(sizeof(sha2_context));
663 if (sig->sha2_body == NULL) {
668 sha1_starts(sig->sha1_body);
669 sha2_starts(sig->sha2_body,0);
675 /* -------------------------------------------------------------------------- */
676 pdkim_pubkey *pdkim_parse_pubkey_record(pdkim_ctx *ctx, char *raw_record) {
679 pdkim_str *cur_tag = NULL;
680 pdkim_str *cur_val = NULL;
681 int where = PDKIM_HDR_LIMBO;
683 pub = malloc(sizeof(pdkim_pubkey));
684 if (pub == NULL) return NULL;
685 memset(pub,0,sizeof(pdkim_pubkey));
692 if ( (*p == '\r') || (*p == '\n') )
695 if (where == PDKIM_HDR_LIMBO) {
696 /* In limbo, just wait for a tag-char to appear */
697 if (!((*p >= 'a') && (*p <= 'z')))
700 where = PDKIM_HDR_TAG;
703 if (where == PDKIM_HDR_TAG) {
705 cur_tag = pdkim_strnew(NULL);
707 if ((*p >= 'a') && (*p <= 'z'))
708 pdkim_strncat(cur_tag,p,1);
711 where = PDKIM_HDR_VALUE;
716 if (where == PDKIM_HDR_VALUE) {
718 cur_val = pdkim_strnew(NULL);
720 if ( (*p == '\r') || (*p == '\n') )
724 if (cur_tag->len > 0) {
725 pdkim_strtrim(cur_val);
727 if (ctx->debug_stream)
728 fprintf(ctx->debug_stream, "%s=%s\n", cur_tag->str, cur_val->str);
730 switch (cur_tag->str[0]) {
732 /* This tag isn't evaluated because:
733 - We only support version DKIM1.
734 - Which is the default for this value (set below)
735 - Other versions are currently not specified. */
738 pub->hashes = strdup(cur_val->str);
741 pub->granularity = strdup(cur_val->str);
744 pub->notes = pdkim_decode_qp(cur_val->str);
747 pub->key = pdkim_decode_base64(cur_val->str,&(pub->key_len));
750 pub->hashes = strdup(cur_val->str);
753 pub->srvtype = strdup(cur_val->str);
756 if (strchr(cur_val->str,'t') != NULL) pub->testing = 1;
757 if (strchr(cur_val->str,'s') != NULL) pub->no_subdomaining = 1;
761 if (ctx->debug_stream)
762 fprintf(ctx->debug_stream, "Unknown tag encountered\n");
767 pdkim_strclear(cur_tag);
768 pdkim_strclear(cur_val);
769 where = PDKIM_HDR_LIMBO;
772 else pdkim_strncat(cur_val,p,1);
779 /* Set fallback defaults */
780 if (pub->version == NULL) pub->version = strdup(PDKIM_PUB_RECORD_VERSION);
781 if (pub->granularity == NULL) pub->granularity = strdup("*");
782 if (pub->keytype == NULL) pub->keytype = strdup("rsa");
783 if (pub->srvtype == NULL) pub->srvtype = strdup("*");
786 if (pub->key == NULL) {
787 pdkim_free_pubkey(pub);
795 /* -------------------------------------------------------------------------- */
796 int pdkim_update_bodyhash(pdkim_ctx *ctx, char *data, int len) {
797 pdkim_signature *sig = ctx->sig;
798 /* Cache relaxed version of data */
799 char *relaxed_data = NULL;
802 /* Traverse all signatures, updating their hashes. */
803 while (sig != NULL) {
804 /* Defaults to simple canon (no further treatment necessary) */
805 char *canon_data = data;
808 if (sig->canon_body == PDKIM_CANON_RELAXED) {
809 /* Relax the line if not done already */
810 if (relaxed_data == NULL) {
814 relaxed_data = malloc(len+1);
815 if (relaxed_data == NULL) return PDKIM_ERR_OOM;
818 if ( (c == '\t') || (c == ' ') ) {
819 c = ' '; /* Turns WSP into SP */
827 relaxed_data[q++] = c;
830 relaxed_data[q] = '\0';
833 canon_data = relaxed_data;
834 canon_len = relaxed_len;
837 /* Make sure we don't exceed the to-be-signed body length */
838 if (sig->bodylength &&
839 ((sig->signed_body_bytes+(unsigned long)canon_len) > sig->bodylength))
840 canon_len = (sig->bodylength - sig->signed_body_bytes);
843 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
844 sha1_update(sig->sha1_body,(unsigned char *)canon_data,canon_len);
846 sha2_update(sig->sha2_body,(unsigned char *)canon_data,canon_len);
847 sig->signed_body_bytes += canon_len;
849 if (ctx->debug_stream!=NULL)
850 pdkim_quoteprint(ctx->debug_stream,canon_data,canon_len,0);
857 if (relaxed_data != NULL) free(relaxed_data);
862 /* -------------------------------------------------------------------------- */
863 int pdkim_finish_bodyhash(pdkim_ctx *ctx) {
864 pdkim_signature *sig = ctx->sig;
866 /* Traverse all signatures */
867 while (sig != NULL) {
870 unsigned char bh[32]; /* SHA-256 = 32 Bytes, SHA-1 = 20 Bytes */
871 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
872 sha1_finish(sig->sha1_body,bh);
874 sha2_finish(sig->sha2_body,bh);
877 if (ctx->debug_stream) {
878 fprintf(ctx->debug_stream, "PDKIM [%s] Body bytes hashed: %lu\n",
879 sig->domain, sig->signed_body_bytes);
880 fprintf(ctx->debug_stream, "PDKIM [%s] bh computed: ", sig->domain);
881 pdkim_hexprint(ctx->debug_stream, (char *)bh,
882 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
886 /* SIGNING -------------------------------------------------------------- */
887 if (ctx->mode == PDKIM_MODE_SIGN) {
888 sig->bodyhash_len = (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32;
889 sig->bodyhash = malloc(sig->bodyhash_len);
890 if (sig->bodyhash == NULL) return PDKIM_ERR_OOM;
891 memcpy(sig->bodyhash,bh,sig->bodyhash_len);
893 /* If bodylength limit is set, and we have received less bytes
894 than the requested amount, effectively remove the limit tag. */
895 if (sig->signed_body_bytes < sig->bodylength) sig->bodylength = 0;
897 /* VERIFICATION --------------------------------------------------------- */
899 /* Compare bodyhash */
900 if (memcmp(bh,sig->bodyhash,
901 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32) == 0) {
903 if (ctx->debug_stream)
904 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash verified OK\n",
910 if (ctx->debug_stream) {
911 fprintf(ctx->debug_stream, "PDKIM [%s] Body hash did NOT verify\n",
913 fprintf(ctx->debug_stream, "PDKIM [%s] bh signature: ", sig->domain);
914 pdkim_hexprint(ctx->debug_stream, sig->bodyhash,
915 (sig->algo == PDKIM_ALGO_RSA_SHA1)?20:32,1);
918 sig->verify_status = PDKIM_VERIFY_FAIL;
919 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
931 /* -------------------------------------------------------------------------- */
932 /* Callback from pdkim_feed below for processing complete body lines */
933 int pdkim_bodyline_complete(pdkim_ctx *ctx) {
934 char *p = ctx->linebuf;
935 int n = ctx->linebuf_offset;
937 /* Ignore extra data if we've seen the end-of-data marker */
938 if (ctx->seen_eod) goto BAIL;
940 /* We've always got one extra byte to stuff a zero ... */
941 ctx->linebuf[(ctx->linebuf_offset)] = '\0';
943 if (ctx->input_mode == PDKIM_INPUT_SMTP) {
944 /* Terminate on EOD marker */
945 if (memcmp(p,".\r\n",3) == 0) {
950 if (memcmp(p,"..",2) == 0) {
956 /* Empty lines need to be buffered until we find a non-empty line */
957 if (memcmp(p,"\r\n",2) == 0) {
958 ctx->num_buffered_crlf++;
962 /* At this point, we have a non-empty line, so release the buffered ones. */
963 while (ctx->num_buffered_crlf) {
964 pdkim_update_bodyhash(ctx,"\r\n",2);
965 ctx->num_buffered_crlf--;
968 pdkim_update_bodyhash(ctx,p,n);
971 ctx->linebuf_offset = 0;
976 /* -------------------------------------------------------------------------- */
977 /* Callback from pdkim_feed below for processing complete headers */
978 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
979 int pdkim_header_complete(pdkim_ctx *ctx) {
980 pdkim_signature *sig = ctx->sig;
982 /* Special case: The last header can have an extra \r appended */
983 if ( (ctx->cur_header->len > 1) &&
984 (ctx->cur_header->str[(ctx->cur_header->len)-1] == '\r') ) {
985 ctx->cur_header->str[(ctx->cur_header->len)-1] = '\0';
986 ctx->cur_header->len--;
990 if (ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
992 /* Traverse all signatures */
993 while (sig != NULL) {
995 /* SIGNING -------------------------------------------------------------- */
996 if (ctx->mode == PDKIM_MODE_SIGN) {
997 if (header_name_match(ctx->cur_header->str,
1000 PDKIM_DEFAULT_SIGN_HEADERS, 0) < 0) goto NEXT_SIG;
1002 /* VERIFICATION --------------------------------------------------------- */
1004 int rc = header_name_match(ctx->cur_header->str,
1006 sig->headernames_pos);
1007 /* Header is not included or out-of-sequence */
1008 if (rc < 0) goto NEXT_SIG;
1009 sig->headernames_pos = rc;
1012 /* Add header to the signed headers list */
1013 pdkim_stringlist *list = pdkim_append_stringlist(sig->headers,
1014 ctx->cur_header->str);
1015 if (list == NULL) return PDKIM_ERR_OOM;
1016 sig->headers = list;
1022 /* DKIM-Signature: headers are added to the verification list */
1023 if ( (ctx->mode == PDKIM_MODE_VERIFY) &&
1024 (strncasecmp(ctx->cur_header->str,
1025 DKIM_SIGNATURE_HEADERNAME,
1026 strlen(DKIM_SIGNATURE_HEADERNAME)) == 0) ) {
1027 /* Create and chain new signature block */
1029 if (ctx->debug_stream)
1030 fprintf(ctx->debug_stream,
1031 "PDKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1033 pdkim_signature *new_sig = pdkim_parse_sig_header(ctx, ctx->cur_header->str);
1034 if (new_sig != NULL) {
1035 pdkim_signature *last_sig = ctx->sig;
1036 if (last_sig == NULL) {
1040 while (last_sig->next != NULL) { last_sig = last_sig->next; };
1041 last_sig->next = new_sig;
1046 if (ctx->debug_stream) {
1047 fprintf(ctx->debug_stream,"Error while parsing signature header\n");
1048 fprintf(ctx->debug_stream,
1049 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1056 pdkim_strclear(ctx->cur_header); /* Re-use existing pdkim_str */
1062 /* -------------------------------------------------------------------------- */
1063 #define HEADER_BUFFER_FRAG_SIZE 256
1064 int pdkim_feed (pdkim_ctx *ctx,
1068 for (p=0;p<len;p++) {
1070 if (ctx->past_headers) {
1071 /* Processing body byte */
1072 ctx->linebuf[(ctx->linebuf_offset)++] = c;
1074 int rc = pdkim_bodyline_complete(ctx); /* End of line */
1075 if (rc != PDKIM_OK) return rc;
1077 if (ctx->linebuf_offset == (PDKIM_MAX_BODY_LINE_LEN-1))
1078 return PDKIM_ERR_LONG_LINE;
1081 /* Processing header byte */
1085 int rc = pdkim_header_complete(ctx); /* Seen last header line */
1086 if (rc != PDKIM_OK) return rc;
1087 ctx->past_headers = 1;
1090 if (ctx->debug_stream)
1091 fprintf(ctx->debug_stream,
1092 "PDKIM >> Hashed body data, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1096 else ctx->seen_lf = 1;
1098 else if (ctx->seen_lf) {
1099 if (! ((c == '\t') || (c == ' '))) {
1100 int rc = pdkim_header_complete(ctx); /* End of header */
1101 if (rc != PDKIM_OK) return rc;
1106 if (ctx->cur_header == NULL) {
1107 ctx->cur_header = pdkim_strnew(NULL);
1108 if (ctx->cur_header == NULL) return PDKIM_ERR_OOM;
1110 if (ctx->cur_header->len < PDKIM_MAX_HEADER_LEN)
1111 if (pdkim_strncat(ctx->cur_header,&data[p],1) == NULL)
1112 return PDKIM_ERR_OOM;
1119 /* -------------------------------------------------------------------------- */
1120 char *pdkim_create_header(pdkim_signature *sig, int final) {
1122 char *base64_bh = NULL;
1123 char *base64_b = NULL;
1124 pdkim_str *hdr = pdkim_strnew("DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1125 if (hdr == NULL) return NULL;
1127 base64_bh = pdkim_encode_base64(sig->bodyhash, sig->bodyhash_len);
1128 if (base64_bh == NULL) goto BAIL;
1130 /* Required and static bits */
1132 pdkim_strcat(hdr,"; a=") &&
1133 pdkim_strcat(hdr,pdkim_algos[sig->algo]) &&
1134 pdkim_strcat(hdr,"; q=") &&
1135 pdkim_strcat(hdr,pdkim_querymethods[sig->querymethod]) &&
1136 pdkim_strcat(hdr,"; c=") &&
1137 pdkim_strcat(hdr,pdkim_canons[sig->canon_headers]) &&
1138 pdkim_strcat(hdr,"/") &&
1139 pdkim_strcat(hdr,pdkim_canons[sig->canon_body]) &&
1140 pdkim_strcat(hdr,"; d=") &&
1141 pdkim_strcat(hdr,sig->domain) &&
1142 pdkim_strcat(hdr,"; s=") &&
1143 pdkim_strcat(hdr,sig->selector) &&
1144 pdkim_strcat(hdr,";\r\n\th=") &&
1145 pdkim_strcat(hdr,sig->headernames) &&
1146 pdkim_strcat(hdr,"; bh=") &&
1147 pdkim_strcat(hdr,base64_bh) &&
1148 pdkim_strcat(hdr,";\r\n\t")
1151 if (sig->identity != NULL) {
1152 if (!( pdkim_strcat(hdr,"i=") &&
1153 pdkim_strcat(hdr,sig->identity) &&
1154 pdkim_strcat(hdr,";") ) ) {
1158 if (sig->created > 0) {
1159 if (!( pdkim_strcat(hdr,"t=") &&
1160 pdkim_numcat(hdr,sig->created) &&
1161 pdkim_strcat(hdr,";") ) ) {
1165 if (sig->expires > 0) {
1166 if (!( pdkim_strcat(hdr,"x=") &&
1167 pdkim_numcat(hdr,sig->expires) &&
1168 pdkim_strcat(hdr,";") ) ) {
1172 if (sig->bodylength > 0) {
1173 if (!( pdkim_strcat(hdr,"l=") &&
1174 pdkim_numcat(hdr,sig->bodylength) &&
1175 pdkim_strcat(hdr,";") ) ) {
1179 /* Extra linebreak */
1180 if (hdr->str[(hdr->len)-1] == ';') {
1181 if (!pdkim_strcat(hdr," \r\n\t")) goto BAIL;
1183 /* Preliminary or final version? */
1185 base64_b = pdkim_encode_base64(sig->sigdata, sig->sigdata_len);
1186 if (base64_b == NULL) goto BAIL;
1188 pdkim_strcat(hdr,"b=") &&
1189 pdkim_strcat(hdr,base64_b) &&
1190 pdkim_strcat(hdr,";")
1194 if (pdkim_strcat(hdr,"b=;")) goto DONE;
1201 rc = strdup(hdr->str);
1205 if (base64_bh != NULL) free(base64_bh);
1206 if (base64_b != NULL) free(base64_b);
1211 /* -------------------------------------------------------------------------- */
1212 int pdkim_feed_finish(pdkim_ctx *ctx, char **signature) {
1213 pdkim_signature *sig = ctx->sig;
1214 pdkim_str *headernames = NULL; /* Collected signed header names */
1216 /* Check if we must still flush a (partial) header. If that is the
1217 case, the message has no body, and we must compute a body hash
1218 out of '<CR><LF>' */
1219 if (ctx->cur_header->len) {
1220 int rc = pdkim_header_complete(ctx);
1221 if (rc != PDKIM_OK) return rc;
1222 pdkim_update_bodyhash(ctx,"\r\n",2);
1225 /* For non-smtp input, check if there's an unfinished line in the
1226 body line buffer. If that is the case, we must add a CRLF to the
1227 hash to properly terminate the message. */
1228 if ((ctx->input_mode == PDKIM_INPUT_NORMAL) && ctx->linebuf_offset) {
1229 pdkim_update_bodyhash(ctx, ctx->linebuf, ctx->linebuf_offset);
1230 pdkim_update_bodyhash(ctx,"\r\n",2);
1233 if (ctx->debug_stream)
1234 fprintf(ctx->debug_stream,
1235 "\nPDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1239 /* Build (and/or evaluate) body hash */
1240 if (pdkim_finish_bodyhash(ctx) != PDKIM_OK) return PDKIM_ERR_OOM;
1242 /* SIGNING -------------------------------------------------------------- */
1243 if (ctx->mode == PDKIM_MODE_SIGN) {
1244 headernames = pdkim_strnew(NULL);
1245 if (headernames == NULL) return PDKIM_ERR_OOM;
1247 /* ---------------------------------------------------------------------- */
1249 while (sig != NULL) {
1250 sha1_context sha1_headers;
1251 sha2_context sha2_headers;
1252 pdkim_stringlist *p = sig->headers;
1254 char headerhash[32];
1256 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1257 sha1_starts(&sha1_headers);
1259 sha2_starts(&sha2_headers,0);
1262 if (ctx->debug_stream)
1263 fprintf(ctx->debug_stream,
1264 "PDKIM >> Hashed header data, canonicalized, in sequence >>>>>>>>>>>>>>\n");
1270 /* SIGNING -------------------------------------------------------------- */
1271 if (ctx->mode == PDKIM_MODE_SIGN) {
1272 /* Collect header names (Note: colon presence is guaranteed here) */
1273 char *q = strchr(p->value,':');
1274 if (pdkim_strncat(headernames, p->value,
1275 (q-(p->value))+((p->next==NULL)?0:1)) == NULL)
1276 return PDKIM_ERR_OOM;
1278 /* ---------------------------------------------------------------------- */
1280 if (sig->canon_body == PDKIM_CANON_RELAXED)
1281 rh = pdkim_relax_header(p->value,1); /* cook header for relaxed canon */
1283 rh = strdup(p->value); /* just copy it for simple canon */
1285 if (rh == NULL) return PDKIM_ERR_OOM;
1287 /* Feed header to the hash algorithm */
1288 if (sig->algo == PDKIM_ALGO_RSA_SHA1)
1289 sha1_update(&(sha1_headers),(unsigned char *)rh,strlen(rh));
1291 sha2_update(&(sha2_headers),(unsigned char *)rh,strlen(rh));
1293 if (ctx->debug_stream)
1294 pdkim_quoteprint(ctx->debug_stream, rh, strlen(rh), 1);
1301 if (ctx->debug_stream)
1302 fprintf(ctx->debug_stream,
1303 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1307 /* SIGNING ---------------------------------------------------------------- */
1308 if (ctx->mode == PDKIM_MODE_SIGN) {
1309 /* Copy headernames to signature struct */
1310 sig->headernames = strdup(headernames->str);
1311 pdkim_strfree(headernames);
1313 /* Create signature header with b= omitted */
1314 sig_hdr = pdkim_create_header(ctx->sig,0);
1316 /* VERIFICATION ----------------------------------------------------------- */
1318 sig_hdr = strdup(sig->rawsig_no_b_val);
1320 /* ------------------------------------------------------------------------ */
1322 if (sig_hdr == NULL) return PDKIM_ERR_OOM;
1324 /* Relax header if necessary */
1325 if (sig->canon_headers == PDKIM_CANON_RELAXED) {
1326 char *relaxed_hdr = pdkim_relax_header(sig_hdr,0);
1328 if (relaxed_hdr == NULL) return PDKIM_ERR_OOM;
1329 sig_hdr = relaxed_hdr;
1333 if (ctx->debug_stream) {
1334 fprintf(ctx->debug_stream,
1335 "PDKIM >> Signed DKIM-Signature header, canonicalized >>>>>>>>>>>>>>>>>\n");
1336 pdkim_quoteprint(ctx->debug_stream, sig_hdr, strlen(sig_hdr), 1);
1337 fprintf(ctx->debug_stream,
1338 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1342 /* Finalize header hash */
1343 if (sig->algo == PDKIM_ALGO_RSA_SHA1) {
1344 sha1_update(&(sha1_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1345 sha1_finish(&(sha1_headers),(unsigned char *)headerhash);
1348 sha2_update(&(sha2_headers),(unsigned char *)sig_hdr,strlen(sig_hdr));
1349 sha2_finish(&(sha2_headers),(unsigned char *)headerhash);
1354 /* SIGNING ---------------------------------------------------------------- */
1355 if (ctx->mode == PDKIM_MODE_SIGN) {
1358 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1360 /* Perform private key operation */
1361 if (rsa_parse_key(&rsa, (unsigned char *)sig->rsa_privkey,
1362 strlen(sig->rsa_privkey), NULL, 0) != 0) {
1363 return PDKIM_ERR_RSA_PRIVKEY;
1366 sig->sigdata_len = mpi_size(&(rsa.N));
1367 sig->sigdata = malloc(sig->sigdata_len);
1368 if (sig->sigdata == NULL) return PDKIM_ERR_OOM;
1370 if (rsa_pkcs1_sign( &rsa, RSA_PRIVATE,
1371 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1372 RSA_SHA1:RSA_SHA256),
1374 (unsigned char *)headerhash,
1375 (unsigned char *)sig->sigdata ) != 0) {
1376 return PDKIM_ERR_RSA_SIGNING;
1382 if (ctx->debug_stream) {
1383 fprintf(ctx->debug_stream, "PDKIM [%s] b computed: ",
1385 pdkim_hexprint(ctx->debug_stream, sig->sigdata, sig->sigdata_len, 1);
1389 /* Recreate signature header with b= included, return it to the caller */
1390 if (signature != NULL) {
1391 *signature = pdkim_create_header(ctx->sig,1);
1392 if (*signature == NULL) return PDKIM_ERR_OOM;
1395 /* VERIFICATION ----------------------------------------------------------- */
1398 char *dns_txt_name, *dns_txt_reply;
1400 rsa_init(&rsa,RSA_PKCS_V15,0,NULL,NULL);
1402 dns_txt_name = malloc(PDKIM_DNS_TXT_MAX_NAMELEN);
1403 if (dns_txt_name == NULL) return PDKIM_ERR_OOM;
1404 dns_txt_reply = malloc(PDKIM_DNS_TXT_MAX_RECLEN);
1405 if (dns_txt_reply == NULL) {
1407 return PDKIM_ERR_OOM;
1409 memset(dns_txt_reply,0,PDKIM_DNS_TXT_MAX_RECLEN);
1410 memset(dns_txt_name ,0,PDKIM_DNS_TXT_MAX_NAMELEN);
1412 if (snprintf(dns_txt_name,PDKIM_DNS_TXT_MAX_NAMELEN,
1413 "%s._domainkey.%s.",
1414 sig->selector,sig->domain) >= PDKIM_DNS_TXT_MAX_NAMELEN) {
1415 sig->verify_status = PDKIM_VERIFY_INVALID;
1416 sig->verify_ext_status = PDKIM_VERIFY_INVALID_BUFFER_SIZE;
1420 if ((ctx->dns_txt_callback(dns_txt_name, dns_txt_reply) != PDKIM_OK) ||
1421 (dns_txt_reply[0] == '\0')) {
1422 sig->verify_status = PDKIM_VERIFY_INVALID;
1423 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1428 if (ctx->debug_stream) {
1429 fprintf(ctx->debug_stream,
1430 "PDKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1431 fprintf(ctx->debug_stream,"Raw record: ");
1432 pdkim_quoteprint(ctx->debug_stream, dns_txt_reply, strlen(dns_txt_reply), 1);
1436 sig->pubkey = pdkim_parse_pubkey_record(ctx,dns_txt_reply);
1437 if (sig->pubkey == NULL) {
1438 sig->verify_status = PDKIM_VERIFY_INVALID;
1439 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1441 if (ctx->debug_stream) {
1442 fprintf(ctx->debug_stream,"Error while parsing public key record\n");
1443 fprintf(ctx->debug_stream,
1444 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1451 if (ctx->debug_stream) {
1452 fprintf(ctx->debug_stream,
1453 "PDKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1457 if (rsa_parse_public_key(&rsa,
1458 (unsigned char *)sig->pubkey->key,
1459 sig->pubkey->key_len) != 0) {
1460 sig->verify_status = PDKIM_VERIFY_INVALID;
1461 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_PARSING;
1465 /* Check the signature */
1466 if (rsa_pkcs1_verify(&rsa,
1468 ((sig->algo == PDKIM_ALGO_RSA_SHA1)?
1469 RSA_SHA1:RSA_SHA256),
1471 (unsigned char *)headerhash,
1472 (unsigned char *)sig->sigdata) != 0) {
1473 sig->verify_status = PDKIM_VERIFY_FAIL;
1474 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1476 if (ctx->debug_stream) {
1477 fprintf(ctx->debug_stream, "PDKIM [%s] signature did NOT verify OK\n",
1484 /* We have a winner! */
1485 sig->verify_status = PDKIM_VERIFY_PASS;
1488 if (ctx->debug_stream) {
1489 fprintf(ctx->debug_stream, "PDKIM [%s] signature verified OK\n",
1497 free(dns_txt_reply);
1507 /* -------------------------------------------------------------------------- */
1508 pdkim_ctx *pdkim_init_verify(int input_mode,
1509 int(*dns_txt_callback)(char *, char *)
1511 pdkim_ctx *ctx = malloc(sizeof(pdkim_ctx));
1512 if (ctx == NULL) return NULL;
1513 memset(ctx,0,sizeof(pdkim_ctx));
1515 ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN);
1516 if (ctx->linebuf == NULL) {
1521 ctx->mode = PDKIM_MODE_VERIFY;
1522 ctx->input_mode = input_mode;
1523 ctx->dns_txt_callback = dns_txt_callback;
1529 /* -------------------------------------------------------------------------- */
1530 pdkim_ctx *pdkim_init_sign(int input_mode,
1533 char *rsa_privkey) {
1536 if (!domain || !selector || !rsa_privkey) return NULL;
1538 ctx = malloc(sizeof(pdkim_ctx));
1539 if (ctx == NULL) return NULL;
1540 memset(ctx,0,sizeof(pdkim_ctx));
1542 ctx->linebuf = malloc(PDKIM_MAX_BODY_LINE_LEN);
1543 if (ctx->linebuf == NULL) {
1548 pdkim_signature *sig = malloc(sizeof(pdkim_signature));
1554 memset(sig,0,sizeof(pdkim_signature));
1556 ctx->mode = PDKIM_MODE_SIGN;
1557 ctx->input_mode = input_mode;
1560 ctx->sig->domain = malloc(strlen(domain)+1);
1561 ctx->sig->selector = malloc(strlen(selector)+1);
1562 ctx->sig->rsa_privkey = malloc(strlen(rsa_privkey)+1);
1564 if (!ctx->sig->domain || !ctx->sig->selector || !ctx->sig->rsa_privkey) {
1565 pdkim_free_ctx(ctx);
1569 strcpy(ctx->sig->domain, domain);
1570 strcpy(ctx->sig->selector, selector);
1571 strcpy(ctx->sig->rsa_privkey, rsa_privkey);
1573 sha1_starts(ctx->sig->sha1_body);
1574 sha2_starts(ctx->sig->sha2_body,0);
1580 /* -------------------------------------------------------------------------- */
1581 void pdkim_set_debug_stream(pdkim_ctx *ctx,
1582 FILE *debug_stream) {
1583 ctx->debug_stream = debug_stream;
1587 /* -------------------------------------------------------------------------- */
1588 int pdkim_set_optional(pdkim_ctx *ctx,
1593 unsigned long bodylength,
1595 unsigned long created,
1596 unsigned long expires) {
1598 if (identity != NULL) {
1599 ctx->sig->identity = malloc(strlen(identity)+1);
1600 if (!ctx->sig->identity) {
1601 return PDKIM_ERR_OOM;
1603 strcpy(ctx->sig->identity, identity);
1606 if (sign_headers != NULL) {
1607 ctx->sig->sign_headers = malloc(strlen(sign_headers)+1);
1608 if (!ctx->sig->sign_headers) {
1609 return PDKIM_ERR_OOM;
1611 strcpy(ctx->sig->sign_headers, sign_headers);
1614 ctx->sig->canon_headers = canon_headers;
1615 ctx->sig->canon_body = canon_body;
1616 ctx->sig->bodylength = bodylength;
1617 ctx->sig->algo = algo;
1618 ctx->sig->created = created;
1619 ctx->sig->expires = expires;