1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
6 * Copyright (c) The Exim Maintainers 2015 - 2022
7 * Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 - 2015
12 #ifdef WITH_CONTENT_SCAN /* entire file */
16 FILE *mime_stream = NULL;
17 uschar *mime_current_boundary = NULL;
19 static mime_header mime_header_list[] = {
20 /* name namelen value */
21 { US"content-type:", 13, &mime_content_type },
22 { US"content-disposition:", 20, &mime_content_disposition },
23 { US"content-transfer-encoding:", 26, &mime_content_transfer_encoding },
24 { US"content-id:", 11, &mime_content_id },
25 { US"content-description:", 20, &mime_content_description }
28 static int mime_header_list_size = nelem(mime_header_list);
30 static mime_parameter mime_parameter_list[] = {
31 /* name namelen value */
32 { US"name=", 5, &mime_filename },
33 { US"filename=", 9, &mime_filename },
34 { US"charset=", 8, &mime_charset },
35 { US"boundary=", 9, &mime_boundary }
39 /*************************************************
40 * set MIME anomaly level + text *
41 *************************************************/
43 /* Small wrapper to set the two expandables which
44 give info on detected "problems" in MIME
45 encodings. Indexes are defined in mime.h. */
48 mime_set_anomaly(int idx)
53 } anom[] = { {1, CUS"Broken Quoted-Printable encoding detected"},
54 {2, CUS"Broken BASE64 encoding detected"} };
56 mime_anomaly_level = anom[idx].level;
57 mime_anomaly_text = anom[idx].text;
61 /*************************************************
62 * decode quoted-printable chars *
63 *************************************************/
65 /* gets called when we hit a =
66 returns: new pointer position
69 -1 - soft line break, no char
74 mime_decode_qp_char(uschar *qp_p, int *c)
76 uschar *initial_pos = qp_p;
78 /* advance one char */
81 /* Check for two hex digits and decode them */
82 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
84 /* Do hex conversion */
85 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
87 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
91 /* tab or whitespace may follow just ignore it if it precedes \n */
92 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
95 if (*qp_p == '\n') /* hit soft line break */
101 /* illegal char here */
107 /* just dump MIME part without any decoding */
109 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
111 ssize_t len, size = 0;
112 uschar buffer[MIME_MAX_LINE_LENGTH];
114 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
117 && Ustrncmp(buffer, "--", 2) == 0
118 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
122 len = Ustrlen(buffer);
123 if (fwrite(buffer, 1, (size_t)len, out) < len)
132 /* decode quoted-printable MIME part */
134 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
136 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
138 ssize_t len, size = 0;
140 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
143 && Ustrncmp(ibuf, "--", 2) == 0
144 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
146 break; /* todo: check for missing boundary */
155 int decode_qp_result;
157 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
159 if (decode_qp_result == -2)
161 /* Error from decoder. ipos is unchanged. */
162 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
166 else if (decode_qp_result == -1)
168 else if (decode_qp_result >= 0)
169 *opos++ = decode_qp_result;
174 /* something to write? */
178 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
187 * Return open filehandle for combo of path and file.
188 * Side-effect: set mime_decoded_filename, to copy in allocated mem
191 mime_get_decode_file(uschar *pname, uschar *fname)
194 mime_decoded_filename = string_sprintf("%s/%s", pname, fname);
196 mime_decoded_filename = string_copy(fname);
202 /* must find first free sequential filename */
206 mime_decoded_filename = string_sprintf("%s/%s-%05u", pname, message_id, file_nr++);
210 result = stat(CS mime_decoded_filename, &mystat);
211 } while(result != -1);
214 return modefopen(mime_decoded_filename, "wb+", SPOOL_MODE);
219 mime_decode(const uschar **listptr)
222 const uschar *list = *listptr;
224 uschar * decode_path;
225 FILE *decode_file = NULL;
227 ssize_t size_counter = 0;
228 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
230 if (!mime_stream || (f_pos = ftell(mime_stream)) < 0)
233 /* build default decode path (will exist since MBOX must be spooled up) */
234 decode_path = string_sprintf("%s/scan/%s", spool_directory, message_id);
236 /* try to find 1st option */
237 if ((option = string_nextinlist(&list, &sep, NULL, 0)))
239 /* parse 1st option */
240 if ((Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0))
241 /* explicitly no decoding */
244 if (Ustrcmp(option,"default") == 0)
245 /* explicit default path + file names */
248 if (option[0] == '/')
252 memset(&statbuf,0,sizeof(statbuf));
254 /* assume either path or path+file name */
255 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
256 /* is directory, use it as decode_path */
257 decode_file = mime_get_decode_file(option, NULL);
259 /* does not exist or is a file, use as full file name */
260 decode_file = mime_get_decode_file(NULL, option);
263 /* assume file name only, use default path */
264 decode_file = mime_get_decode_file(decode_path, option);
268 /* no option? patch default path */
270 decode_file = mime_get_decode_file(decode_path, NULL);
276 /* decode according to mime type */
278 !mime_content_transfer_encoding
279 ? mime_decode_asis /* no encoding, dump as-is */
280 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
282 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
284 : mime_decode_asis; /* unknown encoding type, just dump as-is */
286 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
288 clearerr(mime_stream);
289 if (fseek(mime_stream, f_pos, SEEK_SET))
292 if (fclose(decode_file) != 0 || size_counter < 0)
295 /* round up to the next KiB */
296 mime_content_size = (size_counter + 1023) / 1024;
303 mime_get_header(FILE *f, uschar *header)
307 int header_value_mode = 0;
308 int header_open_brackets = 0;
313 if ((c = fgetc(f)) == EOF) break;
315 /* always skip CRs */
316 if (c == '\r') continue;
322 /* look if next char is '\t' or ' ' */
323 if ((c = fgetc(f)) == EOF) break;
324 if ( (c == '\t') || (c == ' ') ) continue;
327 /* end of the header, terminate with ';' */
332 /* skip control characters */
333 if (c < 32) continue;
335 if (header_value_mode)
337 /* --------- value mode ----------- */
338 /* skip leading whitespace */
339 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
342 /* we have hit a non-whitespace char, start copying value data */
343 header_value_mode = 2;
345 if (c == '"') /* flip "quoted" mode */
346 header_value_mode = header_value_mode==2 ? 3 : 2;
348 /* leave value mode on unquoted ';' */
349 if (header_value_mode == 2 && c == ';')
350 header_value_mode = 0;
351 /* -------------------------------- */
355 /* -------- non-value mode -------- */
356 /* skip whitespace + tabs */
357 if ( (c == ' ') || (c == '\t') )
361 /* quote next char. can be used
362 to escape brackets. */
363 if ((c = fgetc(f)) == EOF) break;
367 header_open_brackets++;
370 else if ((c == ')') && header_open_brackets)
372 header_open_brackets--;
375 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
376 header_value_mode = 1;
378 /* skip chars while we are in a comment */
379 if (header_open_brackets > 0)
381 /* -------------------------------- */
384 /* copy the char to the buffer */
385 header[num_copied++] = (uschar)c;
387 /* break if header buffer is full */
388 if (num_copied > MIME_MAX_HEADER_SIZE-1)
392 if ((num_copied > 0) && (header[num_copied-1] != ';'))
393 header[num_copied-1] = ';';
396 header[num_copied] = '\0';
398 /* return 0 for EOF or empty line */
399 return c == EOF || num_copied == 1 ? 0 : 1;
403 /* reset all per-part mime variables */
405 mime_vars_reset(void)
407 mime_anomaly_level = 0;
408 mime_anomaly_text = NULL;
409 mime_boundary = NULL;
411 mime_decoded_filename = NULL;
412 mime_filename = NULL;
413 mime_content_description = NULL;
414 mime_content_disposition = NULL;
415 mime_content_id = NULL;
416 mime_content_transfer_encoding = NULL;
417 mime_content_type = NULL;
418 mime_is_multipart = 0;
419 mime_content_size = 0;
423 /* Grab a parameter value, dealing with quoting.
426 str Input string. Updated on return to point to terminating ; or NUL
429 Allocated string with parameter value
432 mime_param_val(uschar ** sp)
435 gstring * val = NULL;
437 /* debug_printf_indent(" considering paramval '%s'\n", s); */
439 while (*s && *s != ';') /* ; terminates */
442 s++; /* skip opening " */
443 while (*s && *s != '"') /* " protects ; */
444 val = string_catn(val, s++, 1);
445 if (*s) s++; /* skip closing " */
448 val = string_catn(val, s++, 1);
450 return string_from_gstring(val);
454 mime_next_semicolon(uschar * s)
456 while (*s && *s != ';') /* ; terminates */
459 s++; /* skip opening " */
460 while (*s && *s != '"') /* " protects ; */
462 if (*s) s++; /* skip closing " */
471 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
473 gstring * val = string_catn(NULL, US"=?", 2);
477 val = string_cat(val, charset);
478 val = string_catn(val, US"?Q?", 3);
481 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
483 val = string_catn(val, US"=", 1);
484 val = string_catn(val, ++fname, 2);
488 val = string_catn(val, fname++, 1);
490 val = string_catn(val, US"?=", 2);
492 return string_from_gstring(val);
497 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
498 uschar **user_msgptr, uschar **log_msgptr)
501 uschar * header = NULL;
502 struct mime_boundary_context nested_context;
504 /* reserve a line buffer to work in. Assume tainted data. */
505 header = store_get(MIME_MAX_HEADER_SIZE+1, GET_TAINTED);
507 /* Not actually used at the moment, but will be vital to fixing
508 * some RFC 2046 nonconformance later... */
509 nested_context.parent = context;
511 /* loop through parts */
514 /* reset all per-part mime variables */
517 /* If boundary is null, we assume that *f is positioned on the start of
518 headers (for example, at the very beginning of a message. If a boundary is
519 given, we must first advance to it to reach the start of the next header
522 /* NOTE -- there's an error here -- RFC2046 specifically says to
523 * check for outer boundaries. This code doesn't do that, and
524 * I haven't fixed this.
526 * (I have moved partway towards adding support, however, by adding
527 * a "parent" field to my new boundary-context structure.)
529 if (context) for (;;)
531 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
533 /* Hit EOF or read error. Ugh. */
534 DEBUG(D_acl) debug_printf_indent("MIME: Hit EOF ...\n");
538 /* boundary line must start with 2 dashes */
539 if ( Ustrncmp(header, "--", 2) == 0
540 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
542 { /* found boundary */
543 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
545 /* END boundary found */
546 DEBUG(D_acl) debug_printf_indent("MIME: End boundary found %s\n",
551 DEBUG(D_acl) debug_printf_indent("MIME: Next part with boundary %s\n",
557 /* parse headers, set up expansion variables */
558 while (mime_get_header(f, header))
560 /* look for interesting headers */
561 for (struct mime_header * mh = mime_header_list;
562 mh < mime_header_list + mime_header_list_size;
563 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
565 uschar * p = header + mh->namelen;
568 /* grab the value (normalize to lower case)
569 and copy to its corresponding expansion variable */
571 for (q = p; *q != ';' && *q; q++) ;
572 *mh->value = string_copynlc(p, q-p);
573 DEBUG(D_acl) debug_printf_indent("MIME: found %s header, value is '%s'\n",
574 mh->name, *mh->value);
576 if (*(p = q)) p++; /* jump past the ; */
579 uschar * mime_fname = NULL;
580 uschar * mime_fname_rfc2231 = NULL;
581 uschar * mime_filename_charset = NULL;
582 BOOL decoding_failed = FALSE;
584 /* grab all param=value tags on the remaining line,
585 check if they are interesting */
589 DEBUG(D_acl) debug_printf_indent("MIME: considering paramlist '%s'\n", p);
592 && strncmpic(CUS"content-disposition:", header, 20) == 0
593 && strncmpic(CUS"filename*", p, 9) == 0
595 { /* RFC 2231 filename */
598 /* find value of the filename */
600 while(*p != '=' && *p) p++;
601 if (*p) p++; /* p is filename or NUL */
602 q = mime_param_val(&p); /* p now trailing ; or NUL */
606 uschar * temp_string, * err_msg;
609 /* build up an un-decoded filename over successive
610 filename*= parameters (for use when 2047 decode fails) */
612 mime_fname_rfc2231 = string_sprintf("%#s%s",
613 mime_fname_rfc2231, q);
615 if (!decoding_failed)
618 if (!mime_filename_charset)
622 /* look for a ' in the "filename" */
623 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
625 if ((size = s-q) > 0)
626 mime_filename_charset = string_copyn(q, size);
629 while(*p == '\'') p++; /* p is after 2nd ' */
634 DEBUG(D_acl) debug_printf_indent("MIME: charset %s fname '%s'\n",
635 mime_filename_charset ? mime_filename_charset : US"<NULL>", p);
637 temp_string = rfc2231_to_2047(p, mime_filename_charset, &slen);
638 DEBUG(D_acl) debug_printf_indent("MIME: 2047-name %s\n", temp_string);
640 temp_string = rfc2047_decode(temp_string, FALSE, NULL, ' ',
642 DEBUG(D_acl) debug_printf_indent("MIME: plain-name %s\n", temp_string);
644 if (!temp_string || (size = Ustrlen(temp_string)) == slen)
645 decoding_failed = TRUE;
647 /* build up a decoded filename over successive
648 filename*= parameters */
650 mime_filename = mime_fname = mime_fname
651 ? string_sprintf("%s%s", mime_fname, temp_string)
658 /* look for interesting parameters */
659 for (mime_parameter * mp = mime_parameter_list;
660 mp < mime_parameter_list + nelem(mime_parameter_list);
662 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
665 uschar * dummy_errstr;
667 /* grab the value and copy to its expansion variable */
669 q = mime_param_val(&p); /* p now trailing ; or NUL */
672 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
675 DEBUG(D_acl) debug_printf_indent(
676 "MIME: found %s parameter in %s header, value '%s'\n",
677 mp->name, mh->name, *mp->value);
679 break; /* done matching param names */
683 /* There is something, but not one of our interesting parameters.
684 Advance past the next semicolon */
685 p = mime_next_semicolon(p);
687 } /* param scan on line */
689 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
691 if (decoding_failed) mime_filename = mime_fname_rfc2231;
693 DEBUG(D_acl) debug_printf_indent(
694 "MIME: found %s parameter in %s header, value is '%s'\n",
695 "filename", mh->name, mime_filename);
700 /* set additional flag variables (easier access) */
701 if ( mime_content_type
702 && Ustrncmp(mime_content_type,"multipart",9) == 0
704 mime_is_multipart = 1;
706 /* Make a copy of the boundary pointer.
707 Required since mime_boundary is global
708 and can be overwritten further down in recursion */
709 nested_context.boundary = mime_boundary;
711 /* raise global counter */
714 /* copy current file handle to global variable */
716 mime_current_boundary = context ? context->boundary : 0;
718 /* Note the context */
719 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
721 /* call ACL handling function */
722 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
725 mime_current_boundary = NULL;
729 /* If we have a multipart entity and a boundary, go recursive */
730 if ( mime_content_type && nested_context.boundary
731 && Ustrncmp(mime_content_type,"multipart",9) == 0)
734 debug_printf_indent("MIME: Entering multipart recursion, boundary '%s'\n",
735 nested_context.boundary);
737 nested_context.context =
738 context && context->context == MBC_ATTACHMENT
740 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
741 || Ustrcmp(mime_content_type,"multipart/related") == 0
742 ? MBC_COVERLETTER_ALL
743 : MBC_COVERLETTER_ONESHOT;
745 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
748 else if ( mime_content_type
749 && Ustrncmp(mime_content_type,"message/rfc822",14) == 0)
751 const uschar * rfc822name = NULL;
756 /* must find first free sequential filename */
757 for (gstring * g = string_get(64); result != -1; g->ptr = 0)
760 g = string_fmt_append(g,
761 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
765 result = stat(CS (filename = string_from_gstring(g)), &mystat);
768 rfc822name = filename;
770 /* decode RFC822 attachment */
771 mime_decoded_filename = NULL;
773 mime_current_boundary = context ? context->boundary : NULL;
774 mime_decode(&rfc822name);
776 mime_current_boundary = NULL;
777 if (!mime_decoded_filename) /* decoding failed */
779 log_write(0, LOG_MAIN,
780 "MIME acl condition warning - could not decode RFC822 MIME part to file.");
784 mime_decoded_filename = NULL;
788 /* If the boundary of this instance is NULL, we are finished here */
791 if (context->context == MBC_COVERLETTER_ONESHOT)
792 context->context = MBC_ATTACHMENT;
800 #endif /*WITH_CONTENT_SCAN*/