1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
6 * Copyright (c) The Exim Maintainers 2015 - 2023
7 * Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 - 2015
9 * SPDX-License-Identifier: GPL-2.0-or-later
13 #ifdef WITH_CONTENT_SCAN /* entire file */
17 FILE *mime_stream = NULL;
18 uschar *mime_current_boundary = NULL;
20 static mime_header mime_header_list[] = {
21 /* name namelen value */
22 { US"content-type:", 13, &mime_content_type },
23 { US"content-disposition:", 20, &mime_content_disposition },
24 { US"content-transfer-encoding:", 26, &mime_content_transfer_encoding },
25 { US"content-id:", 11, &mime_content_id },
26 { US"content-description:", 20, &mime_content_description }
29 static int mime_header_list_size = nelem(mime_header_list);
31 static mime_parameter mime_parameter_list[] = {
32 /* name namelen value */
33 { US"name", 4, &mime_filename },
34 { US"filename", 8, &mime_filename },
35 { US"charset", 7, &mime_charset },
36 { US"boundary", 8, &mime_boundary }
40 /*************************************************
41 * set MIME anomaly level + text *
42 *************************************************/
44 /* Small wrapper to set the two expandables which
45 give info on detected "problems" in MIME
46 encodings. Indexes are defined in mime.h. */
49 mime_set_anomaly(int idx)
54 } anom[] = { {1, CUS"Broken Quoted-Printable encoding detected"},
55 {2, CUS"Broken BASE64 encoding detected"} };
57 mime_anomaly_level = anom[idx].level;
58 mime_anomaly_text = anom[idx].text;
62 /*************************************************
63 * decode quoted-printable chars *
64 *************************************************/
66 /* gets called when we hit a =
67 returns: new pointer position
70 -1 - soft line break, no char
75 mime_decode_qp_char(uschar *qp_p, int *c)
77 uschar *initial_pos = qp_p;
79 /* advance one char */
82 /* Check for two hex digits and decode them */
83 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
85 /* Do hex conversion */
86 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
88 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
92 /* tab or whitespace may follow just ignore it if it precedes \n */
93 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
96 if (*qp_p == '\n') /* hit soft line break */
102 /* illegal char here */
108 /* just dump MIME part without any decoding */
110 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
112 ssize_t len, size = 0;
113 uschar buffer[MIME_MAX_LINE_LENGTH];
115 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
118 && Ustrncmp(buffer, "--", 2) == 0
119 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
123 len = Ustrlen(buffer);
124 if (fwrite(buffer, 1, (size_t)len, out) < len)
133 /* decode quoted-printable MIME part */
135 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
137 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
139 ssize_t len, size = 0;
141 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
144 && Ustrncmp(ibuf, "--", 2) == 0
145 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
147 break; /* todo: check for missing boundary */
156 int decode_qp_result;
158 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
160 if (decode_qp_result == -2)
162 /* Error from decoder. ipos is unchanged. */
163 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
167 else if (decode_qp_result == -1)
169 else if (decode_qp_result >= 0)
170 *opos++ = decode_qp_result;
175 /* something to write? */
179 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
188 * Return open filehandle for combo of path and file.
189 * Side-effect: set mime_decoded_filename, to copy in allocated mem
192 mime_get_decode_file(uschar *pname, uschar *fname)
195 mime_decoded_filename = string_sprintf("%s/%s", pname, fname);
197 mime_decoded_filename = string_copy(fname);
203 /* must find first free sequential filename */
207 mime_decoded_filename = string_sprintf("%s/%s-%05u", pname, message_id, file_nr++);
211 result = stat(CS mime_decoded_filename, &mystat);
212 } while(result != -1);
215 return modefopen(mime_decoded_filename, "wb+", SPOOL_MODE);
220 mime_decode(const uschar **listptr)
223 const uschar *list = *listptr;
225 uschar * decode_path;
226 FILE *decode_file = NULL;
228 ssize_t size_counter = 0;
229 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
231 if (!mime_stream || (f_pos = ftell(mime_stream)) < 0)
234 /* build default decode path (will exist since MBOX must be spooled up) */
235 decode_path = string_sprintf("%s/scan/%s", spool_directory, message_id);
237 /* try to find 1st option */
238 if ((option = string_nextinlist(&list, &sep, NULL, 0)))
240 /* parse 1st option */
241 if ((Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0))
242 /* explicitly no decoding */
245 if (Ustrcmp(option,"default") == 0)
246 /* explicit default path + file names */
249 if (option[0] == '/')
253 memset(&statbuf,0,sizeof(statbuf));
255 /* assume either path or path+file name */
256 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
257 /* is directory, use it as decode_path */
258 decode_file = mime_get_decode_file(option, NULL);
260 /* does not exist or is a file, use as full file name */
261 decode_file = mime_get_decode_file(NULL, option);
264 /* assume file name only, use default path */
265 decode_file = mime_get_decode_file(decode_path, option);
269 /* no option? patch default path */
271 decode_file = mime_get_decode_file(decode_path, NULL);
277 /* decode according to mime type */
279 !mime_content_transfer_encoding
280 ? mime_decode_asis /* no encoding, dump as-is */
281 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
283 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
285 : mime_decode_asis; /* unknown encoding type, just dump as-is */
287 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
289 clearerr(mime_stream);
290 if (fseek(mime_stream, f_pos, SEEK_SET))
293 if (fclose(decode_file) != 0 || size_counter < 0)
296 /* round up to the next KiB */
297 mime_content_size = (size_counter + 1023) / 1024;
304 mime_get_header(FILE *f, uschar *header)
308 int header_value_mode = 0;
309 int header_open_brackets = 0;
314 if ((c = fgetc(f)) == EOF) break;
316 /* always skip CRs */
317 if (c == '\r') continue;
323 /* look if next char is '\t' or ' ' */
324 if ((c = fgetc(f)) == EOF) break;
325 if ( (c == '\t') || (c == ' ') ) continue;
328 /* end of the header, terminate with ';' */
333 /* skip control characters */
334 if (c < 32) continue;
336 if (header_value_mode)
338 /* --------- value mode ----------- */
339 /* skip leading whitespace */
340 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
343 /* we have hit a non-whitespace char, start copying value data */
344 header_value_mode = 2;
346 if (c == '"') /* flip "quoted" mode */
347 header_value_mode = header_value_mode==2 ? 3 : 2;
349 /* leave value mode on unquoted ';' */
350 if (header_value_mode == 2 && c == ';')
351 header_value_mode = 0;
352 /* -------------------------------- */
356 /* -------- non-value mode -------- */
357 /* skip whitespace + tabs */
358 if ( (c == ' ') || (c == '\t') )
362 /* quote next char. can be used
363 to escape brackets. */
364 if ((c = fgetc(f)) == EOF) break;
368 header_open_brackets++;
371 else if ((c == ')') && header_open_brackets)
373 header_open_brackets--;
376 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
377 header_value_mode = 1;
379 /* skip chars while we are in a comment */
380 if (header_open_brackets > 0)
382 /* -------------------------------- */
385 /* copy the char to the buffer */
386 header[num_copied++] = (uschar)c;
388 /* break if header buffer is full */
389 if (num_copied > MIME_MAX_HEADER_SIZE-1)
393 if ((num_copied > 0) && (header[num_copied-1] != ';'))
394 header[num_copied-1] = ';';
397 header[num_copied] = '\0';
399 /* return 0 for EOF or empty line */
400 return c == EOF || num_copied == 1 ? 0 : 1;
404 /* reset all per-part mime variables */
406 mime_vars_reset(void)
408 mime_anomaly_level = 0;
409 mime_anomaly_text = NULL;
410 mime_boundary = NULL;
412 mime_decoded_filename = NULL;
413 mime_filename = NULL;
414 mime_content_description = NULL;
415 mime_content_disposition = NULL;
416 mime_content_id = NULL;
417 mime_content_transfer_encoding = NULL;
418 mime_content_type = NULL;
419 mime_is_multipart = 0;
420 mime_content_size = 0;
424 /* Grab a parameter value, dealing with quoting.
427 str Input string. Updated on return to point to terminating ; or NUL
430 Allocated string with parameter value
433 mime_param_val(uschar ** sp)
436 gstring * val = NULL;
438 /* debug_printf_indent(" considering paramval '%s'\n", s); */
440 while (*s && *s != ';') /* ; terminates */
443 s++; /* skip opening " */
444 while (*s && *s != '"') /* " protects ; */
445 val = string_catn(val, s++, 1);
446 if (*s) s++; /* skip closing " */
449 val = string_catn(val, s++, 1);
451 return string_from_gstring(val);
455 mime_next_semicolon(uschar * s)
457 while (*s && *s != ';') /* ; terminates */
460 s++; /* skip opening " */
461 while (*s && *s != '"') /* " protects ; */
463 if (*s) s++; /* skip closing " */
472 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
474 gstring * val = string_catn(NULL, US"=?", 2);
478 val = string_cat(val, charset);
479 val = string_catn(val, US"?Q?", 3);
482 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
484 val = string_catn(val, US"=", 1);
485 val = string_catn(val, ++fname, 2);
489 val = string_catn(val, fname++, 1);
491 val = string_catn(val, US"?=", 2);
492 *len = gstring_length(val);
493 return string_from_gstring(val);
498 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
499 uschar **user_msgptr, uschar **log_msgptr)
502 uschar * header = NULL;
503 struct mime_boundary_context nested_context;
505 /* reserve a line buffer to work in. Assume tainted data. */
506 header = store_get(MIME_MAX_HEADER_SIZE+1, GET_TAINTED);
508 /* Not actually used at the moment, but will be vital to fixing
509 * some RFC 2046 nonconformance later... */
510 nested_context.parent = context;
512 /* loop through parts */
515 /* reset all per-part mime variables */
518 /* If boundary is null, we assume that *f is positioned on the start of
519 headers (for example, at the very beginning of a message. If a boundary is
520 given, we must first advance to it to reach the start of the next header
523 /* NOTE -- there's an error here -- RFC2046 specifically says to
524 * check for outer boundaries. This code doesn't do that, and
525 * I haven't fixed this.
527 * (I have moved partway towards adding support, however, by adding
528 * a "parent" field to my new boundary-context structure.)
530 if (context) for (;;)
532 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
534 /* Hit EOF or read error. Ugh. */
535 DEBUG(D_acl) debug_printf_indent("MIME: Hit EOF ...\n");
539 /* boundary line must start with 2 dashes */
540 if ( Ustrncmp(header, "--", 2) == 0
541 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
543 { /* found boundary */
544 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
546 /* END boundary found */
547 DEBUG(D_acl) debug_printf_indent("MIME: End boundary found %s\n",
552 DEBUG(D_acl) debug_printf_indent("MIME: Next part with boundary %s\n",
558 /* parse headers, set up expansion variables */
559 while (mime_get_header(f, header))
561 /* look for interesting headers */
562 for (struct mime_header * mh = mime_header_list;
563 mh < mime_header_list + mime_header_list_size;
564 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
566 uschar * p = header + mh->namelen;
569 /* grab the value (normalize to lower case)
570 and copy to its corresponding expansion variable */
572 for (q = p; *q != ';' && *q; q++) ;
573 *mh->value = string_copynlc(p, q-p);
574 DEBUG(D_acl) debug_printf_indent("MIME: found %s header, value is '%s'\n",
575 mh->name, *mh->value);
577 if (*(p = q)) p++; /* jump past the ; */
580 gstring * mime_fname = NULL;
581 gstring * mime_fname_rfc2231 = NULL;
582 uschar * mime_filename_charset = NULL;
583 BOOL decoding_failed = FALSE;
585 /* grab all param=value tags on the remaining line,
586 check if they are interesting */
591 debug_printf_indent("MIME: considering paramlist '%s'\n", p);
593 /* look for interesting parameters */
594 for (mime_parameter * mp = mime_parameter_list;
595 mp < mime_parameter_list + nelem(mime_parameter_list);
597 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
600 if (*p == '*') /* RFC 2231 */
602 while (isdigit(*++p)) ; /* ignore cont-cnt values */
603 if (*p == '*') p++; /* step over sep chset mark */
607 p++; /* step over = */
608 q = mime_param_val(&p); /* p now trailing ; or NUL */
610 if (q && *q) /* q is the dequoted value */
612 uschar * err_msg, * fname = q;
615 /* build up an un-decoded filename over successive
616 filename*= parameters (for use when 2047 decode fails) */
618 mime_fname_rfc2231 = string_cat(mime_fname_rfc2231, q);
620 if (!decoding_failed)
622 if (!mime_filename_charset)
623 { /* try for RFC 2231 chset/lang */
626 /* look for a ' in the raw paramval */
627 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
629 if (*s) /* there was a ' */
632 if ((size = s-q) > 0)
633 mime_filename_charset = string_copyn(q, size);
635 if (*(fname = s)) fname++;
636 while(*fname == '\'') fname++; /*fname is after 2nd '*/
641 debug_printf_indent("MIME: charset %s fname '%s'\n",
642 mime_filename_charset ? mime_filename_charset : US"<NULL>",
645 fname = rfc2231_to_2047(fname, mime_filename_charset,
648 debug_printf_indent("MIME: 2047-name %s\n", fname);
650 fname = rfc2047_decode(fname, FALSE, NULL, ' ',
652 DEBUG(D_acl) debug_printf_indent(
653 "MIME: plain-name %s\n", fname);
655 if (!fname || Ustrlen(fname) == slen)
656 decoding_failed = TRUE;
657 else if (mp->value == &mime_filename)
659 /* build up a decoded filename over successive
660 filename*= parameters */
662 mime_fname = string_cat(mime_fname, fname);
663 mime_filename = string_from_gstring(mime_fname);
665 } /*!decoding_failed*/
668 if (*p) p++; /* p is past ; */
669 goto param_done; /* done matching param names */
670 } /*2231 param coding extension*/
673 { /* non-2231 param */
674 uschar * q, * dummy_errstr;
676 /* grab the value and copy to its expansion variable */
678 if (*p) p++; /* step over = */
679 q = mime_param_val(&p); /* p now trailing ; or NUL */
682 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
685 DEBUG(D_acl) debug_printf_indent(
686 "MIME: found %s parameter in %s header, value '%s'\n",
687 mp->name, mh->name, *mp->value);
689 if (*p) p++; /* p is past ; */
690 goto param_done; /* done matching param names */
692 } /* interesting parameters */
694 /* There is something, but not one of our interesting parameters.
695 Advance past the next semicolon */
697 p = mime_next_semicolon(p);
700 } /* param scan on line */
702 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
705 mime_filename = string_from_gstring(mime_fname_rfc2231);
707 DEBUG(D_acl) debug_printf_indent(
708 "MIME: found %s parameter in %s header, value is '%s'\n",
709 "filename", mh->name, mime_filename);
713 } /* interesting headers */
715 /* set additional flag variables (easier access) */
716 if ( mime_content_type
717 && Ustrncmp(mime_content_type,"multipart",9) == 0
719 mime_is_multipart = 1;
721 /* Make a copy of the boundary pointer.
722 Required since mime_boundary is global
723 and can be overwritten further down in recursion */
724 nested_context.boundary = mime_boundary;
726 /* raise global counter */
729 /* copy current file handle to global variable */
731 mime_current_boundary = context ? context->boundary : 0;
733 /* Note the context */
734 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
736 /* call ACL handling function */
737 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
740 mime_current_boundary = NULL;
744 /* If we have a multipart entity and a boundary, go recursive */
745 if ( mime_content_type && nested_context.boundary
746 && Ustrncmp(mime_content_type,"multipart",9) == 0)
749 debug_printf_indent("MIME: Entering multipart recursion, boundary '%s'\n",
750 nested_context.boundary);
752 nested_context.context =
753 context && context->context == MBC_ATTACHMENT
755 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
756 || Ustrcmp(mime_content_type,"multipart/related") == 0
757 ? MBC_COVERLETTER_ALL
758 : MBC_COVERLETTER_ONESHOT;
760 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
763 else if ( mime_content_type
764 && Ustrncmp(mime_content_type,"message/rfc822",14) == 0)
766 const uschar * rfc822name = NULL;
771 /* must find first free sequential filename */
772 for (gstring * g = string_get(64); result != -1; gstring_reset(g))
775 g = string_fmt_append(g,
776 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
780 result = stat(CS (filename = string_from_gstring(g)), &mystat);
783 rfc822name = filename;
785 /* decode RFC822 attachment */
786 mime_decoded_filename = NULL;
788 mime_current_boundary = context ? context->boundary : NULL;
789 mime_decode(&rfc822name);
791 mime_current_boundary = NULL;
792 if (!mime_decoded_filename) /* decoding failed */
794 log_write(0, LOG_MAIN,
795 "MIME acl condition warning - could not decode RFC822 MIME part to file.");
799 mime_decoded_filename = NULL;
803 /* If the boundary of this instance is NULL, we are finished here */
806 if (context->context == MBC_COVERLETTER_ONESHOT)
807 context->context = MBC_ATTACHMENT;
815 #endif /*WITH_CONTENT_SCAN*/