2003-07-29 15:48:06 +00:00
/*
2025-02-14 10:24:30 -05:00
* Copyright ( C ) 2013 - 2025 Cisco Systems , Inc . and / or its affiliates . All rights reserved .
2019-01-25 10:15:50 -05:00
* Copyright ( C ) 2007 - 2013 Sourcefire , Inc .
2008-04-02 15:24:51 +00:00
*
* Authors : Nigel Horne
2019-03-26 15:09:52 -04:00
*
2018-03-05 16:34:35 -05:00
* Acknowledgements : Some ideas came from Stephen White < stephen @ earth . li > ,
* Michael Dankov < misha @ btrc . ru > , Gianluigi Tiesi < sherpya @ netfarm . it > ,
* Everton da Silva Marques , Thomas Lamy < Thomas . Lamy @ in - online . net > ,
* James Stevens < James @ kyzo . com >
2003-07-29 15:48:06 +00:00
*
* This program is free software ; you can redistribute it and / or modify
2008-04-02 15:24:51 +00:00
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation .
2003-07-29 15:48:06 +00:00
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
2006-04-09 19:59:28 +00:00
* Foundation , Inc . , 51 Franklin Street , Fifth Floor , Boston ,
* MA 02110 - 1301 , USA .
2003-07-29 15:48:06 +00:00
*/
2004-02-06 13:46:08 +00:00
# if HAVE_CONFIG_H
# include "clamav-config.h"
# endif
2003-07-29 15:48:06 +00:00
# ifdef CL_THREAD_SAFE
2018-12-03 12:40:13 -05:00
# ifndef _REENTRANT
# define _REENTRANT /* for Solaris 2.8 */
2003-07-29 15:48:06 +00:00
# endif
2003-12-06 04:05:18 +00:00
# endif
2003-07-29 15:48:06 +00:00
# include <stdio.h>
# include <stdlib.h>
# include <errno.h>
# include <assert.h>
# include <string.h>
2021-10-20 21:10:59 -07:00
# include <stdbool.h>
2018-12-03 12:40:13 -05:00
# ifdef HAVE_STRINGS_H
2003-07-29 15:48:06 +00:00
# include <strings.h>
2006-07-25 15:09:45 +00:00
# endif
2018-12-03 12:40:13 -05:00
# ifdef HAVE_STRING_H
2008-01-24 13:58:46 +00:00
# include <string.h>
# endif
2003-07-29 15:48:06 +00:00
# include <ctype.h>
# include <time.h>
# include <fcntl.h>
2018-12-03 12:40:13 -05:00
# ifdef HAVE_SYS_PARAM_H
2003-08-02 22:37:52 +00:00
# include <sys/param.h>
2006-07-25 15:09:45 +00:00
# endif
2004-10-05 15:48:47 +00:00
# include <dirent.h>
2004-10-21 09:41:07 +00:00
# include <limits.h>
2006-09-21 09:37:47 +00:00
# include <signal.h>
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
# ifdef HAVE_UNISTD_H
2006-10-13 13:43:40 +00:00
# include <unistd.h>
# endif
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
2004-06-16 08:07:39 +00:00
# include <pthread.h>
# endif
2019-03-26 15:09:52 -04:00
# if defined(_WIN32) || defined(_WIN64)
# define strtok_r strtok_s
# endif
2014-07-01 19:38:01 -04:00
# include "clamav.h"
2006-05-03 09:36:40 +00:00
# include "others.h"
# include "str.h"
# include "filetypes.h"
2003-07-29 15:48:06 +00:00
# include "mbox.h"
2007-03-27 18:43:30 +00:00
# include "dconf.h"
2009-09-10 03:19:43 +02:00
# include "fmap.h"
2016-05-10 18:53:59 -04:00
# include "json_api.h"
2016-05-19 17:24:53 -04:00
# include "msxml_parser.h"
2016-07-06 17:27:25 -04:00
# include <libxml/xmlversion.h>
2016-05-19 17:24:53 -04:00
# include <libxml/HTMLtree.h>
2016-07-06 17:27:25 -04:00
# include <libxml/HTMLparser.h>
2016-05-19 17:24:53 -04:00
# include <libxml/xmlreader.h>
2007-03-27 18:43:30 +00:00
# define DCONF_PHISHING mctx->ctx->dconf->phishing
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
# ifdef CL_DEBUG
2006-09-21 09:37:47 +00:00
2018-12-03 12:40:13 -05:00
# if defined(C_LINUX)
2006-09-21 09:37:47 +00:00
# include <features.h>
2006-11-10 22:42:08 +00:00
# endif
2006-09-21 09:37:47 +00:00
2021-11-19 22:07:22 +01:00
# if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 1 && !defined(__UCLIBC__) || defined(__UCLIBC_HAS_BACKTRACE__)
2004-06-22 04:08:02 +00:00
# define HAVE_BACKTRACE
# endif
2004-06-30 14:32:28 +00:00
# endif
2004-06-22 04:08:02 +00:00
# ifdef HAVE_BACKTRACE
# include <execinfo.h>
2019-03-26 15:09:52 -04:00
# ifdef USE_SYSLOG
2004-06-22 04:08:02 +00:00
# include <syslog.h>
2019-03-26 15:09:52 -04:00
# endif
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
static void sigsegv ( int sig ) ;
static void print_trace ( int use_syslog ) ;
2007-03-01 16:51:47 +00:00
2020-07-29 10:26:55 -07:00
/*#define SAVE_TMP */ /* Save the file being worked on in tmp */
2004-06-22 04:08:02 +00:00
# endif
2018-12-03 12:40:13 -05:00
# if defined(NO_STRTOK_R) || !defined(CL_THREAD_SAFE)
2003-07-29 15:48:06 +00:00
# undef strtok_r
# undef __strtok_r
2018-12-03 12:40:13 -05:00
# define strtok_r(a, b, c) strtok(a, b)
2003-07-29 15:48:06 +00:00
# endif
2018-12-03 12:40:13 -05:00
typedef enum {
FAIL ,
OK ,
OK_ATTACHMENTS_NOT_SAVED ,
VIRUS ,
MAXREC ,
MAXFILES
2006-12-27 23:15:36 +00:00
} mbox_status ;
2005-12-09 17:19:10 +00:00
# ifndef isblank
2018-12-03 12:40:13 -05:00
# define isblank(c) (((c) == ' ') || ((c) == '\t'))
2005-12-09 17:19:10 +00:00
# endif
2018-12-03 12:40:13 -05:00
# define SAVE_TO_DISC /* multipart/message are saved in a temporary file */
2004-08-17 08:31:58 +00:00
2006-09-13 21:40:03 +00:00
# include "htmlnorm.h"
# include "phishcheck.h"
2018-12-03 12:40:13 -05:00
# ifndef _WIN32
2009-09-24 16:21:51 +02:00
# include <sys/time.h>
2006-09-27 16:30:12 +00:00
# include <netdb.h>
# include <sys/socket.h>
# include <netinet/in.h>
2012-08-09 09:59:56 -04:00
# if !defined(C_BEOS) && !defined(C_INTERIX)
2006-09-27 16:30:12 +00:00
# include <net/if.h>
# include <arpa/inet.h>
# endif
2007-02-13 19:05:28 +00:00
# endif
2006-09-29 20:28:48 +00:00
2006-09-27 16:30:12 +00:00
# include <fcntl.h>
2004-10-05 15:48:47 +00:00
/*
2018-07-20 22:28:48 -04:00
* Use CL_SCAN_MAIL_PARTIAL_MESSAGE to handle messages covered by section 7.3 .2 of RFC1341 .
2020-07-29 10:26:55 -07:00
* This is experimental code so it is up to YOU to ( 1 ) ensure it ' s secure
2004-10-14 17:47:19 +00:00
* ( 2 ) periodically trim the directory of old files
*
* If you use the load balancing feature of clamav - milter to run clamd on
2004-11-12 09:46:01 +00:00
* more than one machine you must make sure that . . . / partial is on a shared
2004-10-14 17:47:19 +00:00
* network filesystem
2004-10-05 15:48:47 +00:00
*/
2005-02-16 22:20:49 +00:00
2018-12-03 12:37:58 -05:00
/*
* Slows things down a lot and only catches unencoded copies
* of EICAR within bounces , which don ' t matter
*/
2024-01-09 19:41:17 -05:00
// #define SCAN_UNENCODED_BOUNCES
2006-04-13 12:09:44 +00:00
2018-12-03 12:40:13 -05:00
typedef struct mbox_ctx {
const char * dir ;
const table_t * rfc821Table ;
const table_t * subtypeTable ;
cli_ctx * ctx ;
unsigned int files ; /* number of files extracted */
json_object * wrkobj ;
2006-06-28 21:07:36 +00:00
} mbox_ctx ;
2008-02-11 16:48:14 +00:00
/* if supported by the system, use the optimized
* version of getc , that doesn ' t do locking ,
* and is possibly implemented entirely as a macro */
# if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L
# define GETC(fp) getc_unlocked(fp)
# define LOCKFILE(fp) flockfile(fp)
# define UNLOCKFILE(fp) funlockfile(fp)
# else
# define GETC(fp) getc(fp)
# define LOCKFILE(fp)
# define UNLOCKFILE(fp)
# endif
2018-12-03 12:40:13 -05:00
static int cli_parse_mbox ( const char * dir , cli_ctx * ctx ) ;
2019-11-07 09:10:26 -08:00
static message * parseEmailFile ( fmap_t * map , size_t * at , const table_t * rfc821Table , const char * firstLine , const char * dir , cli_ctx * ctx , bool * heuristicFound ) ;
static message * parseEmailHeaders ( message * m , const table_t * rfc821Table , bool * heuristicFound ) ;
static int parseEmailHeader ( message * m , const char * line , const table_t * rfc821 , cli_ctx * ctx , bool * heuristicFound ) ;
2019-05-04 17:28:16 -04:00
static cl_error_t parseMHTMLComment ( const char * comment , cli_ctx * ctx , void * wrkjobj , void * cbdata ) ;
2018-12-03 12:40:13 -05:00
static mbox_status parseRootMHTML ( mbox_ctx * mctx , message * m , text * t ) ;
static mbox_status parseEmailBody ( message * messageIn , text * textIn , mbox_ctx * mctx , unsigned int recursion_level ) ;
static int boundaryStart ( const char * line , const char * boundary ) ;
static int boundaryEnd ( const char * line , const char * boundary ) ;
static int initialiseTables ( table_t * * rfc821Table , table_t * * subtypeTable ) ;
static int getTextPart ( message * const messages [ ] , size_t size ) ;
static size_t strip ( char * buf , int len ) ;
2019-11-07 09:10:26 -08:00
static int parseMimeHeader ( message * m , const char * cmd , const table_t * rfc821Table , const char * arg , cli_ctx * ctx , bool * heuristicFound ) ;
2018-12-03 12:40:13 -05:00
static int saveTextPart ( mbox_ctx * mctx , message * m , int destroy_text ) ;
static char * rfc2047 ( const char * in ) ;
static char * rfc822comments ( const char * in , char * out ) ;
2019-05-23 22:50:04 -04:00
static int rfc1341 ( mbox_ctx * mctx , message * m ) ;
2018-12-03 12:40:13 -05:00
static bool usefulHeader ( int commandNumber , const char * cmd ) ;
static char * getline_from_mbox ( char * buffer , size_t len , fmap_t * map , size_t * at ) ;
static bool isBounceStart ( mbox_ctx * mctx , const char * line ) ;
static bool exportBinhexMessage ( mbox_ctx * mctx , message * m ) ;
static int exportBounceMessage ( mbox_ctx * ctx , text * start ) ;
static const char * getMimeTypeStr ( mime_type mimetype ) ;
static const char * getEncTypeStr ( encoding_type enctype ) ;
static message * do_multipart ( message * mainMessage , message * * messages , int i , mbox_status * rc , mbox_ctx * mctx , message * messageIn , text * * tptr , unsigned int recursion_level ) ;
static int count_quotes ( const char * buf ) ;
static bool next_is_folded_header ( const text * t ) ;
static bool newline_in_header ( const char * line ) ;
2023-04-18 14:29:30 -04:00
static blob * getHrefs ( cli_ctx * , message * m , tag_arguments_t * hrefs ) ;
2018-12-03 12:40:13 -05:00
static void hrefs_done ( blob * b , tag_arguments_t * hrefs ) ;
static void checkURLs ( message * m , mbox_ctx * mctx , mbox_status * rc , int is_html ) ;
2004-08-10 08:17:19 +00:00
2019-05-23 22:50:04 -04:00
static bool haveTooManyMIMEPartsPerMessage ( size_t mimePartCnt , cli_ctx * ctx , mbox_status * rc ) ;
static bool hitLineFoldCnt ( const char * const line , size_t * lineFoldCnt , cli_ctx * ctx , bool * heuristicFound ) ;
static bool haveTooManyHeaderBytes ( size_t totalLen , cli_ctx * ctx , bool * heuristicFound ) ;
static bool haveTooManyEmailHeaders ( size_t totalHeaderCnt , cli_ctx * ctx , bool * heuristicFound ) ;
static bool haveTooManyMIMEArguments ( size_t argCnt , cli_ctx * ctx , bool * heuristicFound ) ;
2019-11-07 09:10:26 -08:00
2007-12-13 16:18:18 +00:00
/* Maximum line length according to RFC2821 */
2018-12-03 12:40:13 -05:00
# define RFC2821LENGTH 1000
2003-07-29 15:48:06 +00:00
/* Hashcodes for our hash tables */
2018-12-03 12:40:13 -05:00
# define CONTENT_TYPE 1
# define CONTENT_TRANSFER_ENCODING 2
# define CONTENT_DISPOSITION 3
2003-07-29 15:48:06 +00:00
/* Mime sub types */
2018-12-03 12:40:13 -05:00
# define PLAIN 1
# define ENRICHED 2
# define HTML 3
# define RICHTEXT 4
# define MIXED 5
# define ALTERNATIVE 6 /* RFC1521*/
# define DIGEST 7
# define SIGNED 8
# define PARALLEL 9
# define RELATED 10 /* RFC2387 */
# define REPORT 11 /* RFC1892 */
# define APPLEDOUBLE 12 /* Handling of this in only noddy for now */
# define FAX MIXED / * \
* RFC3458 \
* Drafts stated to treat is as mixed if it is \
* not known . This disappeared in the final \
* version ( except when talking about \
* voice - message ) , but it is good enough for us \
* since we do no validation of coversheet \
* presence etc . ( which also has disappeared \
* in the final version ) \
*/
# define ENCRYPTED 13 / * \
* e . g . RFC2015 \
* Content - Type : multipart / encrypted ; \
* boundary = " nextPart1383049.XCRrrar2yq " ; \
* protocol = " application/pgp-encrypted " \
*/
2020-07-29 10:26:55 -07:00
# define X_BFILE RELATED / * \
2024-01-09 19:41:17 -05:00
* BeOS , expert two parts : the file and its \
2020-07-29 10:26:55 -07:00
* attributes . The attributes part comes as \
* Content - Type : application / x - be_attribute \
* name = " foo " \
* I can ' t find where it is defined , any \
* pointers would be appreciated . For now \
* we treat it as multipart / related \
2018-12-03 12:40:13 -05:00
*/
# define KNOWBOT 14 /* Unknown and undocumented format? */
2019-11-07 09:10:26 -08:00
# define HEURISTIC_EMAIL_MAX_LINE_FOLDS_PER_HEADER (256 * 1024)
# define HEURISTIC_EMAIL_MAX_HEADER_BYTES (1024 * 256)
# define HEURISTIC_EMAIL_MAX_HEADERS 1024
# define HEURISTIC_EMAIL_MAX_MIME_PARTS_PER_MESSAGE 1024
# define HEURISTIC_EMAIL_MAX_ARGUMENTS_PER_HEADER 256
2018-12-03 12:40:13 -05:00
static const struct tableinit {
const char * key ;
int value ;
2003-07-29 15:48:06 +00:00
} rfc821headers [ ] = {
2018-12-03 12:40:13 -05:00
/* TODO: make these regular expressions */
{ " Content-Type " , CONTENT_TYPE } ,
{ " Content-Transfer-Encoding " , CONTENT_TRANSFER_ENCODING } ,
{ " Content-Disposition " , CONTENT_DISPOSITION } ,
{ NULL , 0 } } ,
mimeSubtypes [ ] = { /* see RFC2045 */
/* subtypes of Text */
{ " plain " , PLAIN } ,
{ " enriched " , ENRICHED } ,
{ " html " , HTML } ,
{ " richtext " , RICHTEXT } ,
/* subtypes of Multipart */
{ " mixed " , MIXED } ,
{ " alternative " , ALTERNATIVE } ,
{ " digest " , DIGEST } ,
{ " signed " , SIGNED } ,
{ " parallel " , PARALLEL } ,
{ " related " , RELATED } ,
{ " report " , REPORT } ,
{ " appledouble " , APPLEDOUBLE } ,
{ " fax-message " , FAX } ,
{ " encrypted " , ENCRYPTED } ,
{ " x-bfile " , X_BFILE } , /* BeOS */
{ " knowbot " , KNOWBOT } , /* ??? */
{ " knowbot-metadata " , KNOWBOT } , /* ??? */
{ " knowbot-code " , KNOWBOT } , /* ??? */
{ " knowbot-state " , KNOWBOT } , /* ??? */
{ NULL , 0 } } ,
mimeTypeStr [ ] = { { " NOMIME " , NOMIME } , { " APPLICATION " , APPLICATION } , { " AUDIO " , AUDIO } , { " IMAGE " , IMAGE } , { " MESSAGE " , MESSAGE } , { " MULTIPART " , MULTIPART } , { " TEXT " , TEXT } , { " VIDEO " , VIDEO } , { " MEXTENSION " , MEXTENSION } , { NULL , 0 } } , encTypeStr [ ] = { { " NOENCODING " , NOENCODING } , { " QUOTEDPRINTABLE " , QUOTEDPRINTABLE } , { " BASE64 " , BASE64 } , { " EIGHTBIT " , EIGHTBIT } , { " BINARY " , BINARY } , { " UUENCODE " , UUENCODE } , { " YENCODE " , YENCODE } , { " EEXTENSION " , EEXTENSION } , { " BINHEX " , BINHEX } , { NULL , 0 } } ;
# ifdef CL_THREAD_SAFE
static pthread_mutex_t tables_mutex = PTHREAD_MUTEX_INITIALIZER ;
2004-06-16 08:07:39 +00:00
# endif
2018-12-03 12:40:13 -05:00
static table_t * rfc821 = NULL ;
static table_t * subtype = NULL ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
int cli_mbox ( const char * dir , cli_ctx * ctx )
2004-12-16 15:29:08 +00:00
{
2018-12-03 12:40:13 -05:00
if ( dir = = NULL ) {
cli_dbgmsg ( " cli_mbox called with NULL dir \n " ) ;
return CL_ENULLARG ;
}
return cli_parse_mbox ( dir , ctx ) ;
2004-12-16 15:29:08 +00:00
}
2003-07-29 15:48:06 +00:00
/*
* TODO : when signal handling is added , need to remove temp files when a
2020-07-29 10:26:55 -07:00
* signal is received
2003-07-29 15:48:06 +00:00
* TODO : add option to scan in memory not via temp files , perhaps with a
2004-03-30 22:46:44 +00:00
* named pipe or memory mapped file , though this won ' t work on big e - mails
* containing many levels of encapsulated messages - it ' d just take too much
* RAM
2003-08-29 14:27:15 +00:00
* TODO : parse . msg format files
2003-10-12 12:39:49 +00:00
* TODO : fully handle AppleDouble format , see
2020-07-29 10:26:55 -07:00
* http : //www.lazerware.com/formats/Specs/AppleSingle_AppleDouble.pdf
2003-12-20 13:57:26 +00:00
* TODO : ensure parseEmailHeaders is always called before parseEmailBody
* TODO : create parseEmail which calls parseEmailHeaders then parseEmailBody
2018-02-21 15:00:59 -05:00
* TODO : Handle unexpected NUL bytes in header lines which stop strcmp ( ) s :
2020-07-29 10:26:55 -07:00
* e . g . \ 0 Content - Type : application / binary ;
2003-07-29 15:48:06 +00:00
*/
2004-12-16 15:29:08 +00:00
static int
2011-06-10 20:17:19 +03:00
cli_parse_mbox ( const char * dir , cli_ctx * ctx )
2003-07-29 15:48:06 +00:00
{
2018-12-03 12:40:13 -05:00
int retcode ;
message * body ;
char buffer [ RFC2821LENGTH + 1 ] ;
mbox_ctx mctx ;
size_t at = 0 ;
libclamav: Fix scan recursion tracking
Scan recursion is the process of identifying files embedded in other
files and then scanning them, recursively.
Internally this process is more complex than it may sound because a file
may have multiple layers of types before finding a new "file".
At present we treat the recursion count in the scanning context as an
index into both our fmap list AND our container list. These two lists
are conceptually a part of the same thing and should be unified.
But what's concerning is that the "recursion level" isn't actually
incremented or decremented at the same time that we add a layer to the
fmap or container lists but instead is more touchy-feely, increasing
when we find a new "file".
To account for this shadiness, the size of the fmap and container lists
has always been a little longer than our "max scan recursion" limit so
we don't accidentally overflow the fmap or container arrays (!).
I've implemented a single recursion-stack as an array, similar to before,
which includes a pointer to each fmap at each layer, along with the size
and type. Push and pop functions add and remove layers whenever a new
fmap is added. A boolean argument when pushing indicates if the new layer
represents a new buffer or new file (descriptor). A new buffer will reset
the "nested fmap level" (described below).
This commit also provides a solution for an issue where we detect
embedded files more than once during scan recursion.
For illustration, imagine a tarball named foo.tar.gz with this structure:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
But suppose baz.exe embeds a ZIP archive and a 7Z archive, like this:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| baz.exe | PE | 0 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| │  └── hello.txt | ASCII | 2 | 0 |
| └── sfx.7z | 7Z | 1 | 1 |
|   └── world.txt | ASCII | 2 | 0 |
(A) If we scan for embedded files at any layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| ├── foo.tar | TAR | 1 | 0 |
| │ ├── bar.zip | ZIP | 2 | 1 |
| │ │  └── hola.txt | ASCII | 3 | 0 |
| │ ├── baz.exe | PE | 2 | 1 |
| │ │ ├── sfx.zip | ZIP | 3 | 1 |
| │ │ │  └── hello.txt | ASCII | 4 | 0 |
| │ │ └── sfx.7z | 7Z | 3 | 1 |
| │ │   └── world.txt | ASCII | 4 | 0 |
| │ ├── sfx.zip | ZIP | 2 | 1 |
| │ │  └── hello.txt | ASCII | 3 | 0 |
| │ └── sfx.7z | 7Z | 2 | 1 |
| │  └── world.txt | ASCII | 3 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| └── sfx.7z | 7Z | 1 | 1 |
(A) is bad because it scans content more than once.
Note that for the GZ layer, it may detect the ZIP and 7Z if the
signature hits on the compressed data, which it might, though
extracting the ZIP and 7Z will likely fail.
The reason the above doesn't happen now is that we restrict embedded
type scans for a bunch of archive formats to include GZ and TAR.
(B) If we scan for embedded files at the foo.tar layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| ├── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 2 | 1 |
| │  └── hello.txt | ASCII | 3 | 0 |
| └── sfx.7z | 7Z | 2 | 1 |
|   └── world.txt | ASCII | 3 | 0 |
(B) is almost right. But we can achieve it easily enough only scanning for
embedded content in the current fmap when the "nested fmap level" is 0.
The upside is that it should safely detect all embedded content, even if
it may think the sfz.zip and sfx.7z are in foo.tar instead of in baz.exe.
The biggest risk I can think of affects ZIPs. SFXZIP detection
is identical to ZIP detection, which is why we don't allow SFXZIP to be
detected if insize of a ZIP. If we only allow embedded type scanning at
fmap-layer 0 in each buffer, this will fail to detect the embedded ZIP
if the bar.exe was not compressed in foo.zip and if non-compressed files
extracted from ZIPs aren't extracted as new buffers:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.zip | ZIP | 0 | 0 |
| └── bar.exe | PE | 1 | 1 |
| └── sfx.zip | ZIP | 2 | 2 |
Provided that we ensure all files extracted from zips are scanned in
new buffers, option (B) should be safe.
(C) If we scan for embedded files at the baz.exe layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 3 | 1 |
| │  └── hello.txt | ASCII | 4 | 0 |
| └── sfx.7z | 7Z | 3 | 1 |
|   └── world.txt | ASCII | 4 | 0 |
(C) is right. But it's harder to achieve. For this example we can get it by
restricting 7ZSFX and ZIPSFX detection only when scanning an executable.
But that may mean losing detection of archives embedded elsewhere.
And we'd have to identify allowable container types for each possible
embedded type, which would be very difficult.
So this commit aims to solve the issue the (B)-way.
Note that in all situations, we still have to scan with file typing
enabled to determine if we need to reassign the current file type, such
as re-identifying a Bzip2 archive as a DMG that happens to be Bzip2-
compressed. Detection of DMG and a handful of other types rely on
finding data partway through or near the ned of a file before
reassigning the entire file as the new type.
Other fixes and considerations in this commit:
- The utf16 HTML parser has weak error handling, particularly with respect
to creating a nested fmap for scanning the ascii decoded file.
This commit cleans up the error handling and wraps the nested scan with
the recursion-stack push()/pop() for correct recursion tracking.
Before this commit, each container layer had a flag to indicate if the
container layer is valid.
We need something similar so that the cli_recursion_stack_get_*()
functions ignore normalized layers. Details...
Imagine an LDB signature for HTML content that specifies a ZIP
container. If the signature actually alerts on the normalized HTML and
you don't ignore normalized layers for the container check, it will
appear as though the alert is in an HTML container rather than a ZIP
container.
This commit accomplishes this with a boolean you set in the scan context
before scanning a new layer. Then when the new fmap is created, it will
use that flag to set similar flag for the layer. The context flag is
reset those that anything after this doesn't have that flag.
The flag allows the new recursion_stack_get() function to ignore
normalized layers when iterating the stack to return a layer at a
requested index, negative or positive.
Scanning normalized extracted/normalized javascript and VBA should also
use the 'layer is normalized' flag.
- This commit also fixes Heuristic.Broken.Executable alert for ELF files
to make sure that:
A) these only alert if cli_append_virus() returns CL_VIRUS (aka it
respects the FP check).
B) all broken-executable alerts for ELF only happen if the
SCAN_HEURISTIC_BROKEN option is enabled.
- This commit also cleans up the error handling in cli_magic_scan_dir().
This was needed so we could correctly apply the layer-is-normalized-flag
to all VBA macros extracted to a directory when scanning the directory.
- Also fix an issue where exceeding scan maximums wouldn't cause embedded
file detection scans to abort. Granted we don't actually want to abort
if max filesize or max recursion depth are exceeded... only if max
scansize, max files, and max scantime are exceeded.
Add 'abort_scan' flag to scan context, to protect against depending on
correct error propagation for fatal conditions. Instead, setting this
flag in the scan context should guarantee that a fatal condition deep in
scan recursion isn't lost which result in more stuff being scanned
instead of aborting. This shouldn't be necessary, but some status codes
like CL_ETIMEOUT never used to be fatal and it's easier to do this than
to verify every parser only returns CL_ETIMEOUT and other "fatal
status codes" in fatal conditions.
- Remove duplicate is_tar() prototype from filestypes.c and include
is_tar.h instead.
- Presently we create the fmap hash when creating the fmap.
This wastes a bit of CPU if the hash is never needed.
Now that we're creating fmap's for all embedded files discovered with
file type recognition scans, this is a much more frequent occurence and
really slows things down.
This commit fixes the issue by only creating fmap hashes as needed.
This should not only resolve the perfomance impact of creating fmap's
for all embedded files, but also should improve performance in general.
- Add allmatch check to the zip parser after the central-header meta
match. That way we don't multiple alerts with the same match except in
allmatch mode. Clean up error handling in the zip parser a tiny bit.
- Fixes to ensure that the scan limits such as scansize, filesize,
recursion depth, # of embedded files, and scantime are always reported
if AlertExceedsMax (--alert-exceeds-max) is enabled.
- Fixed an issue where non-fatal alerts for exceeding scan maximums may
mask signature matches later on. I changed it so these alerts use the
"possibly unwanted" alert-type and thus only alert if no other alerts
were found or if all-match or heuristic-precedence are enabled.
- Added the "Heuristics.Limits.Exceeded.*" events to the JSON metadata
when the --gen-json feature is enabled. These will show up once under
"ParseErrors" the first time a limit is exceeded. In the present
implementation, only one limits-exceeded events will be added, so as to
prevent a malicious or malformed sample from filling the JSON buffer
with millions of events and using a tonne of RAM.
2021-09-11 14:15:21 -07:00
fmap_t * map = ctx - > fmap ;
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " in mbox() \n " ) ;
if ( ! fmap_gets ( map , buffer , & at , sizeof ( buffer ) - 1 ) ) {
/* empty message */
return CL_CLEAN ;
}
2021-10-20 21:10:59 -07:00
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
pthread_mutex_lock ( & tables_mutex ) ;
2004-06-16 08:07:39 +00:00
# endif
2018-12-03 12:40:13 -05:00
2021-10-20 21:10:59 -07:00
if ( initialiseTables ( & rfc821 , & subtype ) < 0 ) {
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
2021-10-20 21:10:59 -07:00
pthread_mutex_unlock ( & tables_mutex ) ;
2005-03-15 18:01:25 +00:00
# endif
2021-10-20 21:10:59 -07:00
return CL_EMEM ;
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
pthread_mutex_unlock ( & tables_mutex ) ;
2004-06-16 08:07:39 +00:00
# endif
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
retcode = CL_SUCCESS ;
body = NULL ;
2006-05-04 08:34:02 +00:00
2018-12-03 12:40:13 -05:00
mctx . dir = dir ;
mctx . rfc821Table = rfc821 ;
mctx . subtypeTable = subtype ;
mctx . ctx = ctx ;
mctx . files = 0 ;
2025-06-08 01:12:33 -04:00
mctx . wrkobj = ctx - > this_layer_metadata_json ;
2006-06-28 21:07:36 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Is it a UNIX style mbox with more than one
* mail message , or just a single mail message ?
*
* TODO : It would be better if we called cli_magic_scan_dir here rather than
* in cli_scanmail . Then we could improve the way mailboxes with more
* than one message is handled , e . g . giving a better indication of
* which message within the mailbox is infected
*/
2018-12-03 12:40:13 -05:00
/*if((strncmp(buffer, "From ", 5) == 0) && isalnum(buffer[5])) {*/
if ( strncmp ( buffer , " From " , 5 ) = = 0 ) {
/*
2020-07-29 10:26:55 -07:00
* Have been asked to check a UNIX style mbox file , which
* may contain more than one e - mail message to decode
*
* It would be far better for scanners . c to do this splitting
* and do this
* FOR EACH mail in the mailbox
* DO
* pass this mail to cli_mbox - -
* scan this file
* IF this file has a virus quit
* THEN
* return CL_VIRUS
* FI
* END
* This would remove a problem with this code that it can
* fill up the tmp directory before it starts scanning
*/
2018-12-03 12:40:13 -05:00
bool lastLineWasEmpty ;
int messagenumber ;
2019-11-07 09:10:26 -08:00
message * m = messageCreate ( ) ; /*Create an empty email */
2018-12-03 12:40:13 -05:00
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
if ( m = = NULL ) {
2018-12-03 12:40:13 -05:00
return CL_EMEM ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2018-12-03 12:40:13 -05:00
2021-10-20 21:10:59 -07:00
lastLineWasEmpty = false ;
2018-12-03 12:40:13 -05:00
messagenumber = 1 ;
messageSetCTX ( m , ctx ) ;
do {
cli_chomp ( buffer ) ;
2019-11-07 09:10:26 -08:00
/*if(lastLineWasEmpty && (strncmp(buffer, "From ", 5) == 0) && isalnum(buffer[5])) */
2018-12-03 12:40:13 -05:00
if ( lastLineWasEmpty & & ( strncmp ( buffer , " From " , 5 ) = = 0 ) ) {
cli_dbgmsg ( " Deal with message number %d \n " , messagenumber + + ) ;
/*
2020-07-29 10:26:55 -07:00
* End of a message in the mail box
*/
2021-10-20 21:10:59 -07:00
bool heuristicFound = false ;
2019-11-07 09:10:26 -08:00
body = parseEmailHeaders ( m , rfc821 , & heuristicFound ) ;
2018-12-03 12:40:13 -05:00
if ( body = = NULL ) {
messageReset ( m ) ;
2021-04-06 10:06:04 -07:00
messageSetCTX ( m , ctx ) ;
2019-11-07 09:10:26 -08:00
if ( heuristicFound ) {
retcode = CL_VIRUS ;
break ;
}
2018-12-03 12:40:13 -05:00
continue ;
}
messageSetCTX ( body , ctx ) ;
messageDestroy ( m ) ;
if ( messageGetBody ( body ) ) {
mbox_status rc = parseEmailBody ( body , NULL , & mctx , 0 ) ;
if ( rc = = FAIL ) {
m = body ;
2021-04-06 10:06:04 -07:00
messageReset ( m ) ;
messageSetCTX ( m , ctx ) ;
2018-12-03 12:40:13 -05:00
continue ;
} else if ( rc = = VIRUS ) {
cli_dbgmsg ( " Message number %d is infected \n " ,
messagenumber - 1 ) ;
retcode = CL_VIRUS ;
m = NULL ;
break ;
}
}
/*
2020-07-29 10:26:55 -07:00
* Starting a new message , throw away all the
* information about the old one . It would
* be best to be able to scan this message
* now , but cli_magic_scan_file needs arguments
* that haven ' t been passed here so it can ' t be
* called
*/
2018-12-03 12:40:13 -05:00
m = body ;
2021-04-06 10:06:04 -07:00
messageReset ( m ) ;
messageSetCTX ( m , ctx ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Finished processing message \n " ) ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
} else {
2018-12-03 12:40:13 -05:00
lastLineWasEmpty = ( bool ) ( buffer [ 0 ] = = ' \0 ' ) ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2005-03-07 11:26:18 +00:00
2018-12-03 12:40:13 -05:00
if ( isuuencodebegin ( buffer ) ) {
/*
2020-07-29 10:26:55 -07:00
* Fast track visa to uudecode .
* TODO : binhex , yenc
*/
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
if ( uudecodeFile ( m , buffer , dir , map , & at ) < 0 ) {
if ( messageAddStr ( m , buffer ) < 0 ) {
2018-12-03 12:40:13 -05:00
break ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
}
} else {
2018-12-03 12:40:13 -05:00
/* at this point, the \n has been removed */
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
if ( messageAddStr ( m , buffer ) < 0 ) {
2022-02-16 00:13:55 +01:00
break ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
}
2018-12-03 12:40:13 -05:00
} while ( fmap_gets ( map , buffer , & at , sizeof ( buffer ) - 1 ) ) ;
if ( retcode = = CL_SUCCESS ) {
cli_dbgmsg ( " Extract attachments from email %d \n " , messagenumber ) ;
2021-10-20 21:10:59 -07:00
bool heuristicFound = false ;
2019-11-07 09:10:26 -08:00
body = parseEmailHeaders ( m , rfc821 , & heuristicFound ) ;
if ( heuristicFound ) {
retcode = CL_VIRUS ;
}
2018-12-03 12:40:13 -05:00
}
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
if ( m ) {
2018-12-03 12:40:13 -05:00
messageDestroy ( m ) ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2018-12-03 12:40:13 -05:00
} else {
/*
2020-07-29 10:26:55 -07:00
* It ' s a single message , parse the headers then the body
*/
2018-12-03 12:40:13 -05:00
if ( strncmp ( buffer , " P I " , 4 ) = = 0 )
/*
2020-07-29 10:26:55 -07:00
* CommuniGate Pro format : ignore headers until
* blank line
*/
2018-12-03 12:40:13 -05:00
while ( fmap_gets ( map , buffer , & at , sizeof ( buffer ) - 1 ) & &
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
( strchr ( " \r \n " , buffer [ 0 ] ) = = NULL ) ) {
2018-12-03 12:40:13 -05:00
;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2018-12-03 12:40:13 -05:00
/* getline_from_mbox could be using unlocked_stdio(3),
2020-07-29 10:26:55 -07:00
* so lock file here */
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Ignore any blank lines at the top of the message
*/
2018-12-03 12:40:13 -05:00
while ( strchr ( " \r \n " , buffer [ 0 ] ) & &
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
( getline_from_mbox ( buffer , sizeof ( buffer ) - 1 , map , & at ) ! = NULL ) ) {
2018-12-03 12:40:13 -05:00
;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2004-08-12 10:37:53 +00:00
2018-12-03 12:40:13 -05:00
buffer [ sizeof ( buffer ) - 1 ] = ' \0 ' ;
2004-11-08 10:30:05 +00:00
2021-10-20 21:10:59 -07:00
bool heuristicFound = false ;
2019-11-07 09:10:26 -08:00
body = parseEmailFile ( map , & at , rfc821 , buffer , dir , ctx , & heuristicFound ) ;
if ( heuristicFound ) {
retcode = CL_VIRUS ;
}
2018-12-03 12:40:13 -05:00
}
2003-12-11 14:37:28 +00:00
2018-12-03 12:40:13 -05:00
if ( body ) {
/*
2020-07-29 10:26:55 -07:00
* Write out the last entry in the mailbox
*/
2018-12-03 12:40:13 -05:00
if ( ( retcode = = CL_SUCCESS ) & & messageGetBody ( body ) ) {
messageSetCTX ( body , ctx ) ;
switch ( parseEmailBody ( body , NULL , & mctx , 0 ) ) {
case OK :
case OK_ATTACHMENTS_NOT_SAVED :
break ;
case FAIL :
/*
2020-07-29 10:26:55 -07:00
* beware : cli_magic_scan_desc ( ) ,
* changes this into CL_CLEAN , so only
* use it to inform the higher levels
* that we couldn ' t decode it because
* it isn ' t an mbox , not to signal
* decoding errors on what * is * a valid
* mbox
*/
2018-12-03 12:40:13 -05:00
retcode = CL_EFORMAT ;
break ;
case MAXREC :
retcode = CL_EMAXREC ;
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted_if_heur_exceedsmax ( ctx , " Heuristics.Limits.Exceeded.MaxRecursion " ) ; // Doing this now because it's actually tracking email recursion,-
// not fmap recursion, but it still is aborting with stuff not scanned.
// Also, we didn't have access to the ctx when this happened earlier.
2018-12-03 12:40:13 -05:00
break ;
case MAXFILES :
retcode = CL_EMAXFILES ;
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted_if_heur_exceedsmax ( ctx , " Heuristics.Limits.Exceeded.MaxFiles " ) ; // Doing this now because it's actually tracking email parts,-
// not actual files, but it still is aborting with stuff not scanned.
// Also, we didn't have access to the ctx when this happened earlier.
2018-12-03 12:40:13 -05:00
break ;
case VIRUS :
retcode = CL_VIRUS ;
break ;
}
}
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
if ( body - > isTruncated & & retcode = = CL_SUCCESS ) {
2018-12-03 12:40:13 -05:00
retcode = CL_EMEM ;
Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.
In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`. You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.
In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true
AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
bleeblah = 1;
blah = function(arg1,
arg2,
arg3);
// ^--- these args 4-left from where they should be.
```
VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:
1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
bug if we wanted those GH Actions tests to pass.
Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.
This commit should resolve the clang-format github action test failures,
for now.
2022-03-10 20:55:13 -08:00
}
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Tidy up and quit
*/
2018-12-03 12:40:13 -05:00
messageDestroy ( body ) ;
}
cli_dbgmsg ( " cli_mbox returning %d \n " , retcode ) ;
return retcode ;
2003-07-29 15:48:06 +00:00
}
2019-11-07 09:10:26 -08:00
# define READ_STRUCT_BUFFER_LEN 1024
typedef struct _ReadStruct {
char buffer [ READ_STRUCT_BUFFER_LEN + 1 ] ;
size_t bufferLen ;
struct _ReadStruct * next ;
} ReadStruct ;
static ReadStruct *
appendReadStruct ( ReadStruct * rs , const char * const buffer )
{
if ( NULL = = rs ) {
2021-10-20 21:10:59 -07:00
cli_dbgmsg ( " appendReadStruct: Invalid argument \n " ) ;
2019-11-07 09:10:26 -08:00
goto done ;
}
size_t spaceLeft = ( READ_STRUCT_BUFFER_LEN - rs - > bufferLen ) ;
if ( strlen ( buffer ) > spaceLeft ) {
ReadStruct * next = NULL ;
2019-05-23 22:50:04 -04:00
int part = spaceLeft ;
2019-11-07 09:10:26 -08:00
strncpy ( & ( rs - > buffer [ rs - > bufferLen ] ) , buffer , part ) ;
rs - > bufferLen + = part ;
2024-01-09 17:44:33 -05:00
CLI_CALLOC_OR_GOTO_DONE ( next , 1 , sizeof ( ReadStruct ) ) ;
2019-11-07 09:10:26 -08:00
rs - > next = next ;
strcpy ( next - > buffer , & ( buffer [ part ] ) ) ;
next - > bufferLen = strlen ( & ( buffer [ part ] ) ) ;
rs = next ;
} else {
strcpy ( & ( rs - > buffer [ rs - > bufferLen ] ) , buffer ) ;
rs - > bufferLen + = strlen ( buffer ) ;
}
done :
return rs ;
}
static char *
getMallocedBufferFromList ( const ReadStruct * head )
{
const ReadStruct * rs = head ;
int bufferLen = 1 ;
char * working = NULL ;
char * ret = NULL ;
while ( rs ) {
bufferLen + = rs - > bufferLen ;
rs = rs - > next ;
}
2024-01-09 17:44:33 -05:00
CLI_MAX_MALLOC_OR_GOTO_DONE ( working , bufferLen ) ;
2019-11-07 09:10:26 -08:00
rs = head ;
bufferLen = 0 ;
while ( rs ) {
memcpy ( & ( working [ bufferLen ] ) , rs - > buffer , rs - > bufferLen ) ;
bufferLen + = rs - > bufferLen ;
working [ bufferLen ] = 0 ;
rs = rs - > next ;
}
ret = working ;
done :
if ( NULL = = ret ) {
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( working ) ;
2019-11-07 09:10:26 -08:00
}
return ret ;
}
static void
freeList ( ReadStruct * head )
{
while ( head ) {
ReadStruct * rs = head - > next ;
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( head ) ;
2019-11-07 09:10:26 -08:00
head = rs ;
}
}
# ifndef FREELIST_REALLOC
# define FREELIST_REALLOC(head, curr) \
do { \
if ( curr ! = head ) { \
freeList ( head - > next ) ; \
} \
head - > bufferLen = 0 ; \
head - > next = 0 ; \
curr = head ; \
} while ( 0 )
# endif /*FREELIST_REALLOC*/
2019-05-23 22:50:04 -04:00
/*Check if we have repeated blank lines with only a semicolon at the end. Semicolon is a delimiter for parameters,
* but if there is no data , it isn ' t a parameter . Allow the first one because it may be continuation of a previous line
2019-11-07 09:10:26 -08:00
* that actually had data in it . */
static bool
doContinueMultipleEmptyOptions ( const char * const line , bool * lastWasOnlySemi )
{
if ( line ) {
size_t i = 0 ;
int doCont = 1 ;
for ( ; i < strlen ( line ) ; i + + ) {
if ( isblank ( line [ i ] ) ) {
} else if ( ' ; ' = = line [ i ] ) {
} else {
doCont = 0 ;
break ;
}
}
if ( 1 = = doCont ) {
if ( * lastWasOnlySemi ) {
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
* lastWasOnlySemi = true ;
2019-11-07 09:10:26 -08:00
} else {
2021-10-20 21:10:59 -07:00
* lastWasOnlySemi = false ;
2019-11-07 09:10:26 -08:00
}
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
static bool
2019-05-23 22:50:04 -04:00
hitLineFoldCnt ( const char * const line , size_t * lineFoldCnt , cli_ctx * ctx , bool * heuristicFound )
2019-11-07 09:10:26 -08:00
{
if ( line ) {
if ( isblank ( line [ 0 ] ) ) {
( * lineFoldCnt ) + + ;
} else {
( * lineFoldCnt ) = 0 ;
}
if ( ( * lineFoldCnt ) > = HEURISTIC_EMAIL_MAX_LINE_FOLDS_PER_HEADER ) {
2021-10-05 14:26:09 -07:00
if ( SCAN_HEURISTIC_EXCEEDS_MAX ) {
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted ( ctx , " Heuristics.Limits.Exceeded.EmailLineFoldCnt " ) ;
2021-10-20 21:10:59 -07:00
* heuristicFound = true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
static bool
2019-05-23 22:50:04 -04:00
haveTooManyHeaderBytes ( size_t totalLen , cli_ctx * ctx , bool * heuristicFound )
2019-11-07 09:10:26 -08:00
{
if ( totalLen > HEURISTIC_EMAIL_MAX_HEADER_BYTES ) {
2021-10-05 14:26:09 -07:00
if ( SCAN_HEURISTIC_EXCEEDS_MAX ) {
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted ( ctx , " Heuristics.Limits.Exceeded.EmailHeaderBytes " ) ;
2021-10-20 21:10:59 -07:00
* heuristicFound = true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
static bool
2019-05-23 22:50:04 -04:00
haveTooManyEmailHeaders ( size_t totalHeaderCnt , cli_ctx * ctx , bool * heuristicFound )
2019-11-07 09:10:26 -08:00
{
if ( totalHeaderCnt > HEURISTIC_EMAIL_MAX_HEADERS ) {
2021-10-05 14:26:09 -07:00
if ( SCAN_HEURISTIC_EXCEEDS_MAX ) {
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted ( ctx , " Heuristics.Limits.Exceeded.EmailHeaders " ) ;
2021-10-20 21:10:59 -07:00
* heuristicFound = true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
static bool
2019-05-23 22:50:04 -04:00
haveTooManyMIMEPartsPerMessage ( size_t mimePartCnt , cli_ctx * ctx , mbox_status * rc )
2019-11-07 09:10:26 -08:00
{
if ( mimePartCnt > = HEURISTIC_EMAIL_MAX_MIME_PARTS_PER_MESSAGE ) {
2021-10-05 14:26:09 -07:00
if ( SCAN_HEURISTIC_EXCEEDS_MAX ) {
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted ( ctx , " Heuristics.Limits.Exceeded.EmailMIMEPartsPerMessage " ) ;
2019-11-19 15:55:47 -08:00
* rc = VIRUS ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
static bool
2019-05-23 22:50:04 -04:00
haveTooManyMIMEArguments ( size_t argCnt , cli_ctx * ctx , bool * heuristicFound )
2019-11-07 09:10:26 -08:00
{
if ( argCnt > = HEURISTIC_EMAIL_MAX_ARGUMENTS_PER_HEADER ) {
2021-10-05 14:26:09 -07:00
if ( SCAN_HEURISTIC_EXCEEDS_MAX ) {
2022-08-19 16:21:42 -07:00
cli_append_potentially_unwanted ( ctx , " Heuristics.Limits.Exceeded.EmailMIMEArguments " ) ;
2021-10-20 21:10:59 -07:00
* heuristicFound = true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return true ;
2019-11-07 09:10:26 -08:00
}
2021-10-20 21:10:59 -07:00
return false ;
2019-11-07 09:10:26 -08:00
}
2003-12-11 14:37:28 +00:00
/*
2004-12-18 16:34:31 +00:00
* Read in an email message from fin , parse it , and return the message
2003-12-11 14:37:28 +00:00
*
2004-12-18 16:34:31 +00:00
* FIXME : files full of new lines and nothing else are
* handled ungracefully . . .
*/
static message *
2019-11-07 09:10:26 -08:00
parseEmailFile ( fmap_t * map , size_t * at , const table_t * rfc821 , const char * firstLine , const char * dir , cli_ctx * ctx , bool * heuristicFound )
2004-12-18 16:34:31 +00:00
{
2021-10-20 21:10:59 -07:00
bool inHeader = true ;
bool bodyIsEmpty = true ;
bool lastWasBlank = false , lastBodyLineWasBlank = false ;
2018-12-03 12:40:13 -05:00
message * ret ;
2021-10-20 21:10:59 -07:00
bool anyHeadersFound = false ;
2018-12-03 12:40:13 -05:00
int commandNumber = - 1 ;
2019-11-07 09:10:26 -08:00
char * boundary = NULL ;
2018-12-03 12:40:13 -05:00
char buffer [ RFC2821LENGTH + 1 ] ;
2021-10-20 21:10:59 -07:00
bool lastWasOnlySemi = false ;
2019-11-07 09:10:26 -08:00
int err = 1 ;
size_t totalHeaderBytes = 0 ;
size_t totalHeaderCnt = 0 ;
size_t lineFoldCnt = 0 ;
2021-10-20 21:10:59 -07:00
* heuristicFound = false ;
2019-11-07 09:10:26 -08:00
ReadStruct * head = NULL ;
ReadStruct * curr = NULL ;
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailFile \n " ) ;
ret = messageCreate ( ) ;
if ( ret = = NULL )
return NULL ;
2024-01-09 17:44:33 -05:00
CLI_CALLOC_OR_GOTO_DONE ( head , 1 , sizeof ( ReadStruct ) ) ;
2020-08-02 18:12:37 -04:00
curr = head ;
2018-12-03 12:40:13 -05:00
strncpy ( buffer , firstLine , sizeof ( buffer ) - 1 ) ;
do {
const char * line ;
( void ) cli_chomp ( buffer ) ;
if ( buffer [ 0 ] = = ' \0 ' )
line = NULL ;
else
line = buffer ;
2019-11-07 09:10:26 -08:00
if ( doContinueMultipleEmptyOptions ( line , & lastWasOnlySemi ) ) {
continue ;
}
2019-11-19 15:55:47 -08:00
if ( hitLineFoldCnt ( line , & lineFoldCnt , ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Don ' t blank lines which are only spaces from headers ,
* otherwise they ' ll be treated as the end of header marker
*/
2018-12-03 12:40:13 -05:00
if ( lastWasBlank ) {
2021-10-20 21:10:59 -07:00
lastWasBlank = false ;
2018-12-03 12:40:13 -05:00
if ( boundaryStart ( buffer , boundary ) ) {
cli_dbgmsg ( " Found a header line with space that should be blank \n " ) ;
2021-10-20 21:10:59 -07:00
inHeader = false ;
2018-12-03 12:40:13 -05:00
}
}
if ( inHeader ) {
2019-11-07 09:10:26 -08:00
cli_dbgmsg ( " parseEmailFile: check '%s' \n " , buffer ) ;
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Ensure wide characters are handled where
* sizeof ( char ) > 1
*/
2018-12-03 12:40:13 -05:00
if ( line & & isspace ( line [ 0 ] & 0xFF ) ) {
char copy [ sizeof ( buffer ) ] ;
2005-03-22 11:28:42 +00:00
2018-12-03 12:40:13 -05:00
strcpy ( copy , buffer ) ;
strstrip ( copy ) ;
if ( copy [ 0 ] = = ' \0 ' ) {
/*
2020-07-29 10:26:55 -07:00
* The header line contains only white
* space . This is not the end of the
* headers according to RFC2822 , but
* some MUAs will handle it as though
* it were , and virus writers exploit
* this bug . We can ' t just break from
* the loop here since that would allow
* other exploits such as inserting a
* white space line before the
* content - type line . So we just have
* to make a best guess . Sigh .
*/
2019-11-07 09:10:26 -08:00
if ( head - > bufferLen ) {
char * header = getMallocedBufferFromList ( head ) ;
int needContinue = 0 ;
2024-01-09 17:44:33 -05:00
CLI_VERIFY_POINTER_OR_GOTO_DONE ( header ) ;
2019-11-07 09:10:26 -08:00
totalHeaderCnt + + ;
2019-11-19 15:55:47 -08:00
if ( haveTooManyEmailHeaders ( totalHeaderCnt , ctx , heuristicFound ) ) {
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
break ;
}
needContinue = ( parseEmailHeader ( ret , header , rfc821 , ctx , heuristicFound ) < 0 ) ;
if ( * heuristicFound ) {
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
break ;
}
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
FREELIST_REALLOC ( head , curr ) ;
2018-12-03 12:40:13 -05:00
2019-11-07 09:10:26 -08:00
if ( needContinue ) {
continue ;
}
2018-12-03 12:40:13 -05:00
}
2019-11-07 09:10:26 -08:00
2018-12-03 12:40:13 -05:00
if ( boundary | |
( ( boundary = ( char * ) messageFindArgument ( ret , " boundary " ) ) ! = NULL ) ) {
2021-10-20 21:10:59 -07:00
lastWasBlank = true ;
2018-12-03 12:40:13 -05:00
continue ;
}
}
}
2019-11-07 09:10:26 -08:00
if ( ( line = = NULL ) & & ( 0 = = head - > bufferLen ) ) { /* empty line */
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* A blank line signifies the end of
* the header and the start of the text
*/
2018-12-03 12:40:13 -05:00
if ( ! anyHeadersFound )
/* Ignore the junk at the top */
continue ;
2005-01-27 14:12:00 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " End of header information \n " ) ;
2021-10-20 21:10:59 -07:00
inHeader = false ;
bodyIsEmpty = true ;
2018-12-03 12:40:13 -05:00
} else {
char * ptr ;
const char * lookahead ;
2021-10-20 21:10:59 -07:00
bool lineAdded = true ;
2004-12-18 16:34:31 +00:00
2019-11-07 09:10:26 -08:00
if ( 0 = = head - > bufferLen ) {
2018-12-03 12:40:13 -05:00
char cmd [ RFC2821LENGTH + 1 ] , out [ RFC2821LENGTH + 1 ] ;
2004-12-18 16:34:31 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Continuation of line we ' re ignoring ?
*/
2018-12-03 12:40:13 -05:00
if ( isblank ( line [ 0 ] ) )
continue ;
2008-08-01 14:50:27 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Is this a header we ' re interested in ?
*/
2018-12-03 12:40:13 -05:00
if ( ( strchr ( line , ' : ' ) = = NULL ) | |
( cli_strtokbuf ( line , 0 , " : " , cmd ) = = NULL ) ) {
if ( strncmp ( line , " From " , 5 ) = = 0 )
2021-10-20 21:10:59 -07:00
anyHeadersFound = true ;
2018-12-03 12:40:13 -05:00
continue ;
}
ptr = rfc822comments ( cmd , out ) ;
commandNumber = tableFind ( rfc821 , ptr ? ptr : cmd ) ;
switch ( commandNumber ) {
case CONTENT_TRANSFER_ENCODING :
case CONTENT_DISPOSITION :
case CONTENT_TYPE :
2021-10-20 21:10:59 -07:00
anyHeadersFound = true ;
2018-12-03 12:40:13 -05:00
break ;
default :
if ( ! anyHeadersFound )
anyHeadersFound = usefulHeader ( commandNumber , cmd ) ;
continue ;
}
2019-11-07 09:10:26 -08:00
curr = appendReadStruct ( curr , line ) ;
if ( NULL = = curr ) {
if ( ret ) {
2021-10-20 21:10:59 -07:00
ret - > isTruncated = true ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
break ;
}
} else if ( line ! = NULL ) {
2019-11-07 09:10:26 -08:00
curr = appendReadStruct ( curr , line ) ;
} else {
2021-10-20 21:10:59 -07:00
lineAdded = false ;
2018-12-03 12:40:13 -05:00
}
2019-11-07 09:10:26 -08:00
if ( lineAdded ) {
totalHeaderBytes + = strlen ( line ) ;
2019-11-19 15:55:47 -08:00
if ( haveTooManyHeaderBytes ( totalHeaderBytes , ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
}
2018-12-03 12:40:13 -05:00
if ( ( lookahead = fmap_need_off_once ( map , * at , 1 ) ) ) {
/*
2020-07-29 10:26:55 -07:00
* Section B .2 of RFC822 says TAB or
* SPACE means a continuation of the
* previous entry .
*
* Add all the arguments on the line
*/
2018-12-03 12:40:13 -05:00
if ( isblank ( * lookahead ) )
continue ;
}
2004-12-18 16:34:31 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Handle broken headers , where the next
* line isn ' t indented by whitespace
*/
2019-11-07 09:10:26 -08:00
{
char * header = getMallocedBufferFromList ( head ) ; /*This is the issue */
int needContinue = 0 ;
2024-01-09 17:44:33 -05:00
CLI_VERIFY_POINTER_OR_GOTO_DONE ( header ) ;
2020-01-31 10:34:58 -08:00
2019-05-23 22:50:04 -04:00
needContinue = ( header [ strlen ( header ) - 1 ] = = ' ; ' ) ;
2019-11-07 09:10:26 -08:00
if ( 0 = = needContinue ) {
needContinue = ( line & & ( count_quotes ( header ) & 1 ) ) ;
}
2018-12-03 12:40:13 -05:00
2019-11-07 09:10:26 -08:00
if ( 0 = = needContinue ) {
totalHeaderCnt + + ;
2019-11-19 15:55:47 -08:00
if ( haveTooManyEmailHeaders ( totalHeaderCnt , ctx , heuristicFound ) ) {
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
break ;
}
needContinue = ( parseEmailHeader ( ret , header , rfc821 , ctx , heuristicFound ) < 0 ) ;
if ( * heuristicFound ) {
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
break ;
}
/*Check total headers here;*/
}
2018-12-03 12:40:13 -05:00
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( header ) ;
2019-11-07 09:10:26 -08:00
if ( needContinue ) {
continue ;
}
FREELIST_REALLOC ( head , curr ) ;
2018-12-03 12:40:13 -05:00
}
}
} else if ( line & & isuuencodebegin ( line ) ) {
/*
2020-07-29 10:26:55 -07:00
* Fast track visa to uudecode .
* TODO : binhex , yenc
*/
2021-10-20 21:10:59 -07:00
bodyIsEmpty = false ;
2018-12-03 12:40:13 -05:00
if ( uudecodeFile ( ret , line , dir , map , at ) < 0 )
if ( messageAddStr ( ret , line ) < 0 )
break ;
} else {
if ( line = = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* Although this would save time and RAM , some
* phish signatures have been built which need
* the blank lines
*/
2018-12-03 12:40:13 -05:00
if ( lastBodyLineWasBlank & &
( messageGetMimeType ( ret ) ! = TEXT ) ) {
cli_dbgmsg ( " Ignoring consecutive blank lines in the body \n " ) ;
continue ;
}
2021-10-20 21:10:59 -07:00
lastBodyLineWasBlank = true ;
2018-12-03 12:40:13 -05:00
} else {
if ( bodyIsEmpty ) {
/*
2020-07-29 10:26:55 -07:00
* Broken message : new line in the
* middle of the headers , so the first
* line of the body is in fact
* the last lines of the header
*/
2018-12-03 12:40:13 -05:00
if ( newline_in_header ( line ) )
continue ;
2021-10-20 21:10:59 -07:00
bodyIsEmpty = false ;
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
lastBodyLineWasBlank = false ;
2018-12-03 12:40:13 -05:00
}
if ( messageAddStr ( ret , line ) < 0 )
break ;
}
} while ( getline_from_mbox ( buffer , sizeof ( buffer ) - 1 , map , at ) ! = NULL ) ;
2019-11-07 09:10:26 -08:00
err = 0 ;
done :
if ( err ) {
cli_errmsg ( " parseEmailFile: ERROR parsing file \n " ) ;
2021-10-20 21:10:59 -07:00
ret - > isTruncated = true ;
2018-12-03 12:40:13 -05:00
}
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( boundary ) ;
2019-11-07 09:10:26 -08:00
freeList ( head ) ;
2018-12-03 12:40:13 -05:00
if ( ! anyHeadersFound ) {
/*
2020-07-29 10:26:55 -07:00
* False positive in believing we have an e - mail when we don ' t
*/
2018-12-03 12:40:13 -05:00
messageDestroy ( ret ) ;
cli_dbgmsg ( " parseEmailFile: no headers found, assuming it isn't an email \n " ) ;
return NULL ;
}
2004-12-18 16:34:31 +00:00
2019-11-07 09:10:26 -08:00
if ( * heuristicFound ) {
messageDestroy ( ret ) ;
cli_dbgmsg ( " parseEmailFile: found heuristic \n " ) ;
return NULL ;
}
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailFile: return \n " ) ;
2004-12-18 16:34:31 +00:00
2018-12-03 12:40:13 -05:00
return ret ;
2004-12-18 16:34:31 +00:00
}
/*
* The given message contains a raw e - mail .
2003-12-14 18:08:29 +00:00
*
2007-09-12 13:25:13 +00:00
* Returns the message ' s body with the correct arguments set , empties the
* given message ' s contents ( note that it isn ' t destroyed )
2004-12-18 16:34:31 +00:00
*
* TODO : remove the duplication with parseEmailFile
2003-12-11 14:37:28 +00:00
*/
2003-12-14 18:08:29 +00:00
static message *
2019-11-07 09:10:26 -08:00
parseEmailHeaders ( message * m , const table_t * rfc821 , bool * heuristicFound )
2003-12-11 14:37:28 +00:00
{
2021-10-20 21:10:59 -07:00
bool inHeader = true ;
bool bodyIsEmpty = true ;
2018-12-03 12:40:13 -05:00
text * t ;
message * ret ;
2021-10-20 21:10:59 -07:00
bool anyHeadersFound = false ;
2018-12-03 12:40:13 -05:00
int commandNumber = - 1 ;
char * fullline = NULL ;
size_t fulllinelength = 0 ;
2021-10-20 21:10:59 -07:00
bool lastWasOnlySemi = false ;
2019-11-07 09:10:26 -08:00
size_t lineFoldCnt = 0 ;
size_t totalHeaderCnt = 0 ;
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailHeaders \n " ) ;
2021-10-20 21:10:59 -07:00
* heuristicFound = false ;
2019-11-07 09:10:26 -08:00
2018-12-03 12:40:13 -05:00
if ( m = = NULL )
return NULL ;
ret = messageCreate ( ) ;
for ( t = messageGetBody ( m ) ; t ; t = t - > t_next ) {
const char * line ;
if ( t - > t_line )
line = lineGetData ( t - > t_line ) ;
else
line = NULL ;
2019-11-07 09:10:26 -08:00
if ( doContinueMultipleEmptyOptions ( line , & lastWasOnlySemi ) ) {
continue ;
}
2019-11-19 15:55:47 -08:00
if ( hitLineFoldCnt ( line , & lineFoldCnt , m - > ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
2018-12-03 12:40:13 -05:00
if ( inHeader ) {
cli_dbgmsg ( " parseEmailHeaders: check '%s' \n " ,
line ? line : " " ) ;
if ( line = = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* A blank line signifies the end of
* the header and the start of the text
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " End of header information \n " ) ;
if ( ! anyHeadersFound ) {
cli_dbgmsg ( " Nothing interesting in the header \n " ) ;
break ;
}
2021-10-20 21:10:59 -07:00
inHeader = false ;
bodyIsEmpty = true ;
2018-12-03 12:40:13 -05:00
} else {
char * ptr ;
2021-10-20 21:10:59 -07:00
bool lineAdded = true ;
2018-12-03 12:40:13 -05:00
if ( fullline = = NULL ) {
char cmd [ RFC2821LENGTH + 1 ] ;
/*
2020-07-29 10:26:55 -07:00
* Continuation of line we ' re ignoring ?
*/
2018-12-03 12:40:13 -05:00
if ( isblank ( line [ 0 ] ) )
continue ;
2004-11-12 22:22:21 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Is this a header we ' re interested in ?
*/
2018-12-03 12:40:13 -05:00
if ( ( strchr ( line , ' : ' ) = = NULL ) | |
( cli_strtokbuf ( line , 0 , " : " , cmd ) = = NULL ) ) {
if ( strncmp ( line , " From " , 5 ) = = 0 )
2021-10-20 21:10:59 -07:00
anyHeadersFound = true ;
2018-12-03 12:40:13 -05:00
continue ;
}
ptr = rfc822comments ( cmd , NULL ) ;
commandNumber = tableFind ( rfc821 , ptr ? ptr : cmd ) ;
if ( ptr )
free ( ptr ) ;
switch ( commandNumber ) {
case CONTENT_TRANSFER_ENCODING :
case CONTENT_DISPOSITION :
case CONTENT_TYPE :
2021-10-20 21:10:59 -07:00
anyHeadersFound = true ;
2018-12-03 12:40:13 -05:00
break ;
default :
if ( ! anyHeadersFound )
anyHeadersFound = usefulHeader ( commandNumber , cmd ) ;
continue ;
}
2024-01-09 17:44:33 -05:00
fullline = cli_safer_strdup ( line ) ;
2018-12-03 12:40:13 -05:00
fulllinelength = strlen ( line ) + 1 ;
} else if ( line ) {
fulllinelength + = strlen ( line ) + 1 ;
2022-05-09 14:28:34 -07:00
ptr = cli_max_realloc ( fullline , fulllinelength ) ;
2018-12-03 12:40:13 -05:00
if ( ptr = = NULL )
continue ;
fullline = ptr ;
cli_strlcat ( fullline , line , fulllinelength ) ;
2019-11-07 09:10:26 -08:00
} else {
2021-10-20 21:10:59 -07:00
lineAdded = false ;
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
2019-11-07 09:10:26 -08:00
/*continue doesn't seem right here, but that is what is done everywhere else when a malloc fails.*/
if ( NULL = = fullline ) {
continue ;
}
if ( lineAdded ) {
2019-11-19 15:55:47 -08:00
if ( haveTooManyHeaderBytes ( fulllinelength , m - > ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
}
2018-12-03 12:40:13 -05:00
if ( next_is_folded_header ( t ) )
/* Add arguments to this line */
continue ;
lineUnlink ( t - > t_line ) ;
t - > t_line = NULL ;
if ( count_quotes ( fullline ) & 1 )
continue ;
ptr = rfc822comments ( fullline , NULL ) ;
if ( ptr ) {
free ( fullline ) ;
fullline = ptr ;
}
2019-11-07 09:10:26 -08:00
totalHeaderCnt + + ;
2019-11-19 15:55:47 -08:00
if ( haveTooManyEmailHeaders ( totalHeaderCnt , m - > ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
if ( parseEmailHeader ( ret , fullline , rfc821 , m - > ctx , heuristicFound ) < 0 ) {
2018-12-03 12:40:13 -05:00
continue ;
2019-11-07 09:10:26 -08:00
}
if ( * heuristicFound ) {
break ;
}
2018-12-03 12:40:13 -05:00
free ( fullline ) ;
fullline = NULL ;
}
} else {
if ( bodyIsEmpty ) {
if ( line = = NULL )
/* throw away leading blank lines */
continue ;
/*
2020-07-29 10:26:55 -07:00
* Broken message : new line in the
* middle of the headers , so the first
* line of the body is in fact
* the last lines of the header
*/
2018-12-03 12:40:13 -05:00
if ( newline_in_header ( line ) )
continue ;
2021-10-20 21:10:59 -07:00
bodyIsEmpty = false ;
2018-12-03 12:40:13 -05:00
}
/*if(t->t_line && isuuencodebegin(t->t_line))
2020-07-29 10:26:55 -07:00
puts ( " FIXME: add fast visa here " ) ; */
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailHeaders: finished with headers, moving body \n " ) ;
messageMoveText ( ret , t , m ) ;
break ;
}
}
if ( fullline ) {
if ( * fullline ) switch ( commandNumber ) {
case CONTENT_TRANSFER_ENCODING :
case CONTENT_DISPOSITION :
case CONTENT_TYPE :
cli_dbgmsg ( " parseEmailHeaders: Fullline unparsed '%s' \n " , fullline ) ;
}
free ( fullline ) ;
}
if ( ! anyHeadersFound ) {
/*
2020-07-29 10:26:55 -07:00
* False positive in believing we have an e - mail when we don ' t
*/
2018-12-03 12:40:13 -05:00
messageDestroy ( ret ) ;
cli_dbgmsg ( " parseEmailHeaders: no headers found, assuming it isn't an email \n " ) ;
return NULL ;
}
2019-11-07 09:10:26 -08:00
if ( * heuristicFound ) {
messageDestroy ( ret ) ;
cli_dbgmsg ( " parseEmailHeaders: found a heuristic, delete message and stop parsing. \n " ) ;
return NULL ;
}
2004-08-11 14:48:13 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailHeaders: return \n " ) ;
2004-03-10 22:07:54 +00:00
2018-12-03 12:40:13 -05:00
return ret ;
2003-12-11 14:37:28 +00:00
}
2004-01-13 10:14:13 +00:00
/*
* Handle a header line of an email message
*/
static int
2019-11-07 09:10:26 -08:00
parseEmailHeader ( message * m , const char * line , const table_t * rfc821 , cli_ctx * ctx , bool * heuristicFound )
2004-01-13 10:14:13 +00:00
{
2019-11-07 09:10:26 -08:00
int ret = - 1 ;
2004-01-13 10:14:13 +00:00
# ifdef CL_THREAD_SAFE
2018-12-03 12:40:13 -05:00
char * strptr ;
2004-01-13 10:14:13 +00:00
# endif
2018-12-03 12:40:13 -05:00
const char * separator ;
char * cmd , * copy , tokenseparator [ 2 ] ;
2004-01-13 10:14:13 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailHeader '%s' \n " , line ) ;
2004-02-14 19:05:27 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* In RFC822 the separator between the key a value is a colon ,
* e . g . Content - Transfer - Encoding : base64
* However some MUA ' s are lapse about this and virus writers exploit
* this hole , so we need to check all known possibilities
*/
2018-12-03 12:40:13 -05:00
for ( separator = " := " ; * separator ; separator + + )
if ( strchr ( line , * separator ) ! = NULL )
break ;
2004-09-16 13:01:30 +00:00
2018-12-03 12:40:13 -05:00
if ( * separator = = ' \0 ' )
return - 1 ;
2004-03-30 22:46:44 +00:00
2018-12-03 12:40:13 -05:00
copy = rfc2047 ( line ) ;
2019-11-07 09:10:26 -08:00
if ( copy = = NULL ) {
2018-12-03 12:40:13 -05:00
/* an RFC checker would return -1 here */
2024-01-09 17:44:33 -05:00
copy = cli_safer_strdup ( line ) ;
2019-11-07 09:10:26 -08:00
if ( NULL = = copy ) {
goto done ;
}
}
2004-06-28 11:47:16 +00:00
2018-12-03 12:40:13 -05:00
tokenseparator [ 0 ] = * separator ;
tokenseparator [ 1 ] = ' \0 ' ;
2004-09-16 13:01:30 +00:00
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
cmd = strtok_r ( copy , tokenseparator , & strptr ) ;
2004-09-21 08:16:29 +00:00
# else
2018-12-03 12:40:13 -05:00
cmd = strtok ( copy , tokenseparator ) ;
2004-09-21 08:16:29 +00:00
# endif
2004-01-13 10:14:13 +00:00
2018-12-03 12:40:13 -05:00
if ( cmd & & ( strstrip ( cmd ) > 0 ) ) {
# ifdef CL_THREAD_SAFE
char * arg = strtok_r ( NULL , " " , & strptr ) ;
2004-09-21 08:16:29 +00:00
# else
2018-12-03 12:40:13 -05:00
char * arg = strtok ( NULL , " " ) ;
2004-09-21 08:16:29 +00:00
# endif
2004-01-13 10:14:13 +00:00
2019-11-07 09:10:26 -08:00
if ( arg ) {
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Found a header such as
* Content - Type : multipart / mixed ;
* set arg to be
* " multipart/mixed " and cmd to
* be " Content-Type "
*/
2019-11-07 09:10:26 -08:00
ret = parseMimeHeader ( m , cmd , rfc821 , arg , ctx , heuristicFound ) ;
}
2018-12-03 12:40:13 -05:00
}
2019-11-07 09:10:26 -08:00
done :
2024-01-09 17:44:33 -05:00
CLI_FREE_AND_SET_NULL ( copy ) ;
2019-11-07 09:10:26 -08:00
2018-12-03 12:40:13 -05:00
return ret ;
2004-01-13 10:14:13 +00:00
}
2016-05-19 17:24:53 -04:00
static const struct key_entry mhtml_keys [ ] = {
2018-12-03 12:40:13 -05:00
/* root html tags for microsoft office document */
{ " html " , " RootHTML " , MSXML_JSON_ROOT | MSXML_JSON_ATTRIB } ,
{ " head " , " Head " , MSXML_JSON_WRKPTR | MSXML_COMMENT_CB } ,
{ " meta " , " Meta " , MSXML_JSON_WRKPTR | MSXML_JSON_MULTI | MSXML_JSON_ATTRIB } ,
{ " link " , " Link " , MSXML_JSON_WRKPTR | MSXML_JSON_MULTI | MSXML_JSON_ATTRIB } ,
{ " script " , " Script " , MSXML_JSON_WRKPTR | MSXML_JSON_MULTI | MSXML_JSON_VALUE } } ;
2016-05-19 17:24:53 -04:00
static size_t num_mhtml_keys = sizeof ( mhtml_keys ) / sizeof ( struct key_entry ) ;
2016-05-26 16:06:39 -04:00
static const struct key_entry mhtml_comment_keys [ ] = {
2018-12-03 12:40:13 -05:00
/* embedded xml tags (comment) for microsoft office document */
{ " o:documentproperties " , " DocumentProperties " , MSXML_JSON_ROOT | MSXML_JSON_ATTRIB } ,
{ " o:author " , " Author " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:lastauthor " , " LastAuthor " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:revision " , " Revision " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:totaltime " , " TotalTime " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:created " , " Created " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:lastsaved " , " LastSaved " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:pages " , " Pages " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:words " , " Words " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:characters " , " Characters " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:company " , " Company " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:lines " , " Lines " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:paragraphs " , " Paragraphs " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:characterswithspaces " , " CharactersWithSpaces " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:version " , " Version " , MSXML_JSON_WRKPTR | MSXML_JSON_VALUE } ,
{ " o:officedocumentsettings " , " DocumentSettings " , MSXML_IGNORE_ELEM } ,
{ " w:worddocument " , " WordDocument " , MSXML_IGNORE_ELEM } ,
{ " w:latentstyles " , " LatentStyles " , MSXML_IGNORE_ELEM } } ;
2016-05-26 16:06:39 -04:00
static size_t num_mhtml_comment_keys = sizeof ( mhtml_comment_keys ) / sizeof ( struct key_entry ) ;
2016-05-19 17:24:53 -04:00
2016-05-26 16:06:39 -04:00
/*
* The related multipart root HTML file comment parsing wrapper .
*
* Attempts to leverage msxml parser , cannot operate without LIBXML2 .
* This function is only used for Preclassification JSON .
*/
2019-05-04 17:28:16 -04:00
static cl_error_t parseMHTMLComment ( const char * comment , cli_ctx * ctx , void * wrkjobj , void * cbdata )
2016-05-26 16:06:39 -04:00
{
2019-05-04 17:28:16 -04:00
cl_error_t ret = CL_SUCCESS ;
2018-12-03 12:40:13 -05:00
const char * xmlsrt , * xmlend ;
xmlTextReaderPtr reader ;
2016-05-26 16:06:39 -04:00
2018-12-03 12:40:13 -05:00
UNUSEDPARAM ( cbdata ) ;
UNUSEDPARAM ( wrkjobj ) ;
2016-05-26 16:06:39 -04:00
2018-12-03 12:40:13 -05:00
xmlend = comment ;
while ( ( xmlsrt = strstr ( xmlend , " <xml> " ) ) ) {
xmlend = strstr ( xmlsrt , " </xml> " ) ;
if ( xmlend = = NULL ) {
cli_dbgmsg ( " parseMHTMLComment: unbounded xml tag \n " ) ;
break ;
}
2016-05-26 16:06:39 -04:00
2018-12-03 12:40:13 -05:00
reader = xmlReaderForMemory ( xmlsrt , xmlend - xmlsrt + 6 , " comment.xml " , NULL , CLAMAV_MIN_XMLREADER_FLAGS ) ;
if ( ! reader ) {
cli_dbgmsg ( " parseMHTMLComment: cannot initialize xmlReader \n " ) ;
2016-05-26 16:06:39 -04:00
2025-06-08 01:12:33 -04:00
if ( ctx - > this_layer_metadata_json ! = NULL )
ret = cli_json_parse_error ( ctx - > this_layer_metadata_json , " MHTML_ERROR_XML_READER_MEM " ) ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
return ret ; // libxml2 failed!
}
/* comment callback is not set to prevent recursion */
/* TODO: should we separate the key dictionaries? */
/* TODO: should we use the json object pointer? */
ret = cli_msxml_parse_document ( ctx , reader , mhtml_comment_keys , num_mhtml_comment_keys , MSXML_FLAG_JSON , NULL ) ;
xmlTextReaderClose ( reader ) ;
xmlFreeTextReader ( reader ) ;
if ( ret ! = CL_SUCCESS )
return ret ;
}
2019-05-04 17:28:16 -04:00
return ret ;
2016-05-26 16:06:39 -04:00
}
2016-05-19 17:24:53 -04:00
/*
* The related multipart root HTML file parsing wrapper .
*
* Attempts to leverage msxml parser , cannot operate without LIBXML2 .
* This function is only used for Preclassification JSON .
*/
static mbox_status
parseRootMHTML ( mbox_ctx * mctx , message * m , text * t )
{
2018-12-03 12:40:13 -05:00
cli_ctx * ctx = mctx - > ctx ;
2016-07-06 17:27:25 -04:00
# ifdef LIBXML_HTML_ENABLED
2018-12-03 12:40:13 -05:00
struct msxml_ctx mxctx ;
blob * input = NULL ;
htmlDocPtr htmlDoc ;
xmlTextReaderPtr reader ;
int ret = CL_SUCCESS ;
mbox_status rc = OK ;
json_object * rhtml ;
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " in parseRootMHTML \n " ) ;
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
if ( ctx = = NULL )
return OK ;
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
if ( m = = NULL & & t = = NULL )
return OK ;
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
if ( m ! = NULL )
input = messageToBlob ( m , 0 ) ;
else /* t != NULL */
input = textToBlob ( t , NULL , 0 ) ;
2017-08-15 16:50:01 -04:00
2018-12-03 12:40:13 -05:00
if ( input = = NULL )
return OK ;
2016-05-19 17:24:53 -04:00
2020-03-30 18:14:53 -04:00
htmlDoc = htmlReadMemory ( ( char * ) input - > data , input - > len , " mhtml.html " , NULL , CLAMAV_MIN_XMLREADER_FLAGS | HTML_PARSE_NOWARNING ) ;
2018-12-03 12:40:13 -05:00
if ( htmlDoc = = NULL ) {
cli_dbgmsg ( " parseRootMHTML: cannot initialize read html document \n " ) ;
2024-03-25 13:01:46 -04:00
2025-06-08 01:12:33 -04:00
if ( ctx - > this_layer_metadata_json ! = NULL )
ret = cli_json_parse_error ( ctx - > this_layer_metadata_json , " MHTML_ERROR_HTML_READ " ) ;
2018-12-03 12:40:13 -05:00
if ( ret ! = CL_SUCCESS )
rc = FAIL ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
blobDestroy ( input ) ;
return rc ;
}
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
if ( mctx - > wrkobj ) {
rhtml = cli_jsonobj ( mctx - > wrkobj , " RootHTML " ) ;
if ( rhtml ! = NULL ) {
/* MHTML-specific properties */
cli_jsonstr ( rhtml , " Encoding " , ( const char * ) htmlGetMetaEncoding ( htmlDoc ) ) ;
cli_jsonint ( rhtml , " CompressMode " , xmlGetDocCompressMode ( htmlDoc ) ) ;
}
}
2016-05-19 17:24:53 -04:00
2018-12-03 12:40:13 -05:00
reader = xmlReaderWalker ( htmlDoc ) ;
if ( reader = = NULL ) {
cli_dbgmsg ( " parseRootMHTML: cannot initialize xmlTextReader \n " ) ;
2024-03-25 13:01:46 -04:00
2025-06-08 01:12:33 -04:00
if ( ctx - > this_layer_metadata_json ! = NULL )
ret = cli_json_parse_error ( ctx - > this_layer_metadata_json , " MHTML_ERROR_XML_READER_IO " ) ;
2018-12-03 12:40:13 -05:00
if ( ret ! = CL_SUCCESS )
rc = FAIL ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
blobDestroy ( input ) ;
return rc ;
}
memset ( & mxctx , 0 , sizeof ( mxctx ) ) ;
/* no scanning callback set */
mxctx . comment_cb = parseMHTMLComment ;
ret = cli_msxml_parse_document ( ctx , reader , mhtml_keys , num_mhtml_keys , MSXML_FLAG_JSON | MSXML_FLAG_WALK , & mxctx ) ;
switch ( ret ) {
case CL_SUCCESS :
case CL_ETIMEOUT :
case CL_BREAK :
rc = OK ;
break ;
case CL_EMAXREC :
rc = MAXREC ;
break ;
case CL_EMAXFILES :
rc = MAXFILES ;
break ;
case CL_VIRUS :
rc = VIRUS ;
break ;
default :
rc = FAIL ;
}
xmlTextReaderClose ( reader ) ;
xmlFreeTextReader ( reader ) ;
xmlFreeDoc ( htmlDoc ) ;
blobDestroy ( input ) ;
return rc ;
2016-07-06 17:27:25 -04:00
# else /* LIBXML_HTML_ENABLED */
2018-12-03 12:40:13 -05:00
UNUSEDPARAM ( m ) ;
UNUSEDPARAM ( t ) ;
cli_dbgmsg ( " in parseRootMHTML \n " ) ;
cli_dbgmsg ( " parseRootMHTML: parsing html documents disabled in libxml2! \n " ) ;
2016-07-06 17:27:25 -04:00
# endif /* LIBXML_HTML_ENABLED */
2016-05-19 17:24:53 -04:00
}
2003-07-29 15:48:06 +00:00
/*
* This is a recursive routine .
*
2003-12-11 14:37:28 +00:00
* This function parses the body of mainMessage and saves its attachments in dir
*
2003-12-14 18:08:29 +00:00
* mainMessage is the buffer to be parsed , it contains an e - mail ' s body , without
2004-08-04 19:00:43 +00:00
* any headers . First time of calling it ' ll be
* the whole message . Later it ' ll be parts of a multipart message
2003-07-29 15:48:06 +00:00
* textIn is the plain text message being built up so far
*/
2006-12-27 23:15:36 +00:00
static mbox_status
2006-10-29 13:54:06 +00:00
parseEmailBody ( message * messageIn , text * textIn , mbox_ctx * mctx , unsigned int recursion_level )
2003-07-29 15:48:06 +00:00
{
2018-12-03 12:40:13 -05:00
mbox_status rc ;
text * aText = textIn ;
message * mainMessage = messageIn ;
fileblob * fb ;
2021-10-20 21:10:59 -07:00
bool infected = false ;
2018-12-03 12:40:13 -05:00
const struct cl_engine * engine = mctx - > ctx - > engine ;
const int doPhishingScan = engine - > dboptions & CL_DB_PHISHING_URLS & & ( DCONF_PHISHING & PHISHING_CONF_ENGINE ) ;
2024-03-25 13:01:46 -04:00
json_object * saveobj = mctx - > wrkobj ;
bool heuristicFound = false ;
2006-09-20 10:24:17 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " in parseEmailBody, %u files saved so far \n " ,
mctx - > files ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/* FIXMELIMITS: this should be better integrated */
libclamav: Fix scan recursion tracking
Scan recursion is the process of identifying files embedded in other
files and then scanning them, recursively.
Internally this process is more complex than it may sound because a file
may have multiple layers of types before finding a new "file".
At present we treat the recursion count in the scanning context as an
index into both our fmap list AND our container list. These two lists
are conceptually a part of the same thing and should be unified.
But what's concerning is that the "recursion level" isn't actually
incremented or decremented at the same time that we add a layer to the
fmap or container lists but instead is more touchy-feely, increasing
when we find a new "file".
To account for this shadiness, the size of the fmap and container lists
has always been a little longer than our "max scan recursion" limit so
we don't accidentally overflow the fmap or container arrays (!).
I've implemented a single recursion-stack as an array, similar to before,
which includes a pointer to each fmap at each layer, along with the size
and type. Push and pop functions add and remove layers whenever a new
fmap is added. A boolean argument when pushing indicates if the new layer
represents a new buffer or new file (descriptor). A new buffer will reset
the "nested fmap level" (described below).
This commit also provides a solution for an issue where we detect
embedded files more than once during scan recursion.
For illustration, imagine a tarball named foo.tar.gz with this structure:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
But suppose baz.exe embeds a ZIP archive and a 7Z archive, like this:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| baz.exe | PE | 0 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| │  └── hello.txt | ASCII | 2 | 0 |
| └── sfx.7z | 7Z | 1 | 1 |
|   └── world.txt | ASCII | 2 | 0 |
(A) If we scan for embedded files at any layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| ├── foo.tar | TAR | 1 | 0 |
| │ ├── bar.zip | ZIP | 2 | 1 |
| │ │  └── hola.txt | ASCII | 3 | 0 |
| │ ├── baz.exe | PE | 2 | 1 |
| │ │ ├── sfx.zip | ZIP | 3 | 1 |
| │ │ │  └── hello.txt | ASCII | 4 | 0 |
| │ │ └── sfx.7z | 7Z | 3 | 1 |
| │ │   └── world.txt | ASCII | 4 | 0 |
| │ ├── sfx.zip | ZIP | 2 | 1 |
| │ │  └── hello.txt | ASCII | 3 | 0 |
| │ └── sfx.7z | 7Z | 2 | 1 |
| │  └── world.txt | ASCII | 3 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| └── sfx.7z | 7Z | 1 | 1 |
(A) is bad because it scans content more than once.
Note that for the GZ layer, it may detect the ZIP and 7Z if the
signature hits on the compressed data, which it might, though
extracting the ZIP and 7Z will likely fail.
The reason the above doesn't happen now is that we restrict embedded
type scans for a bunch of archive formats to include GZ and TAR.
(B) If we scan for embedded files at the foo.tar layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| ├── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 2 | 1 |
| │  └── hello.txt | ASCII | 3 | 0 |
| └── sfx.7z | 7Z | 2 | 1 |
|   └── world.txt | ASCII | 3 | 0 |
(B) is almost right. But we can achieve it easily enough only scanning for
embedded content in the current fmap when the "nested fmap level" is 0.
The upside is that it should safely detect all embedded content, even if
it may think the sfz.zip and sfx.7z are in foo.tar instead of in baz.exe.
The biggest risk I can think of affects ZIPs. SFXZIP detection
is identical to ZIP detection, which is why we don't allow SFXZIP to be
detected if insize of a ZIP. If we only allow embedded type scanning at
fmap-layer 0 in each buffer, this will fail to detect the embedded ZIP
if the bar.exe was not compressed in foo.zip and if non-compressed files
extracted from ZIPs aren't extracted as new buffers:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.zip | ZIP | 0 | 0 |
| └── bar.exe | PE | 1 | 1 |
| └── sfx.zip | ZIP | 2 | 2 |
Provided that we ensure all files extracted from zips are scanned in
new buffers, option (B) should be safe.
(C) If we scan for embedded files at the baz.exe layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 3 | 1 |
| │  └── hello.txt | ASCII | 4 | 0 |
| └── sfx.7z | 7Z | 3 | 1 |
|   └── world.txt | ASCII | 4 | 0 |
(C) is right. But it's harder to achieve. For this example we can get it by
restricting 7ZSFX and ZIPSFX detection only when scanning an executable.
But that may mean losing detection of archives embedded elsewhere.
And we'd have to identify allowable container types for each possible
embedded type, which would be very difficult.
So this commit aims to solve the issue the (B)-way.
Note that in all situations, we still have to scan with file typing
enabled to determine if we need to reassign the current file type, such
as re-identifying a Bzip2 archive as a DMG that happens to be Bzip2-
compressed. Detection of DMG and a handful of other types rely on
finding data partway through or near the ned of a file before
reassigning the entire file as the new type.
Other fixes and considerations in this commit:
- The utf16 HTML parser has weak error handling, particularly with respect
to creating a nested fmap for scanning the ascii decoded file.
This commit cleans up the error handling and wraps the nested scan with
the recursion-stack push()/pop() for correct recursion tracking.
Before this commit, each container layer had a flag to indicate if the
container layer is valid.
We need something similar so that the cli_recursion_stack_get_*()
functions ignore normalized layers. Details...
Imagine an LDB signature for HTML content that specifies a ZIP
container. If the signature actually alerts on the normalized HTML and
you don't ignore normalized layers for the container check, it will
appear as though the alert is in an HTML container rather than a ZIP
container.
This commit accomplishes this with a boolean you set in the scan context
before scanning a new layer. Then when the new fmap is created, it will
use that flag to set similar flag for the layer. The context flag is
reset those that anything after this doesn't have that flag.
The flag allows the new recursion_stack_get() function to ignore
normalized layers when iterating the stack to return a layer at a
requested index, negative or positive.
Scanning normalized extracted/normalized javascript and VBA should also
use the 'layer is normalized' flag.
- This commit also fixes Heuristic.Broken.Executable alert for ELF files
to make sure that:
A) these only alert if cli_append_virus() returns CL_VIRUS (aka it
respects the FP check).
B) all broken-executable alerts for ELF only happen if the
SCAN_HEURISTIC_BROKEN option is enabled.
- This commit also cleans up the error handling in cli_magic_scan_dir().
This was needed so we could correctly apply the layer-is-normalized-flag
to all VBA macros extracted to a directory when scanning the directory.
- Also fix an issue where exceeding scan maximums wouldn't cause embedded
file detection scans to abort. Granted we don't actually want to abort
if max filesize or max recursion depth are exceeded... only if max
scansize, max files, and max scantime are exceeded.
Add 'abort_scan' flag to scan context, to protect against depending on
correct error propagation for fatal conditions. Instead, setting this
flag in the scan context should guarantee that a fatal condition deep in
scan recursion isn't lost which result in more stuff being scanned
instead of aborting. This shouldn't be necessary, but some status codes
like CL_ETIMEOUT never used to be fatal and it's easier to do this than
to verify every parser only returns CL_ETIMEOUT and other "fatal
status codes" in fatal conditions.
- Remove duplicate is_tar() prototype from filestypes.c and include
is_tar.h instead.
- Presently we create the fmap hash when creating the fmap.
This wastes a bit of CPU if the hash is never needed.
Now that we're creating fmap's for all embedded files discovered with
file type recognition scans, this is a much more frequent occurence and
really slows things down.
This commit fixes the issue by only creating fmap hashes as needed.
This should not only resolve the perfomance impact of creating fmap's
for all embedded files, but also should improve performance in general.
- Add allmatch check to the zip parser after the central-header meta
match. That way we don't multiple alerts with the same match except in
allmatch mode. Clean up error handling in the zip parser a tiny bit.
- Fixes to ensure that the scan limits such as scansize, filesize,
recursion depth, # of embedded files, and scantime are always reported
if AlertExceedsMax (--alert-exceeds-max) is enabled.
- Fixed an issue where non-fatal alerts for exceeding scan maximums may
mask signature matches later on. I changed it so these alerts use the
"possibly unwanted" alert-type and thus only alert if no other alerts
were found or if all-match or heuristic-precedence are enabled.
- Added the "Heuristics.Limits.Exceeded.*" events to the JSON metadata
when the --gen-json feature is enabled. These will show up once under
"ParseErrors" the first time a limit is exceeded. In the present
implementation, only one limits-exceeded events will be added, so as to
prevent a malicious or malformed sample from filling the JSON buffer
with millions of events and using a tonne of RAM.
2021-09-11 14:15:21 -07:00
if ( engine - > max_recursion_level )
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* This is approximate
*/
libclamav: Fix scan recursion tracking
Scan recursion is the process of identifying files embedded in other
files and then scanning them, recursively.
Internally this process is more complex than it may sound because a file
may have multiple layers of types before finding a new "file".
At present we treat the recursion count in the scanning context as an
index into both our fmap list AND our container list. These two lists
are conceptually a part of the same thing and should be unified.
But what's concerning is that the "recursion level" isn't actually
incremented or decremented at the same time that we add a layer to the
fmap or container lists but instead is more touchy-feely, increasing
when we find a new "file".
To account for this shadiness, the size of the fmap and container lists
has always been a little longer than our "max scan recursion" limit so
we don't accidentally overflow the fmap or container arrays (!).
I've implemented a single recursion-stack as an array, similar to before,
which includes a pointer to each fmap at each layer, along with the size
and type. Push and pop functions add and remove layers whenever a new
fmap is added. A boolean argument when pushing indicates if the new layer
represents a new buffer or new file (descriptor). A new buffer will reset
the "nested fmap level" (described below).
This commit also provides a solution for an issue where we detect
embedded files more than once during scan recursion.
For illustration, imagine a tarball named foo.tar.gz with this structure:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
But suppose baz.exe embeds a ZIP archive and a 7Z archive, like this:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| baz.exe | PE | 0 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| │  └── hello.txt | ASCII | 2 | 0 |
| └── sfx.7z | 7Z | 1 | 1 |
|   └── world.txt | ASCII | 2 | 0 |
(A) If we scan for embedded files at any layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| ├── foo.tar | TAR | 1 | 0 |
| │ ├── bar.zip | ZIP | 2 | 1 |
| │ │  └── hola.txt | ASCII | 3 | 0 |
| │ ├── baz.exe | PE | 2 | 1 |
| │ │ ├── sfx.zip | ZIP | 3 | 1 |
| │ │ │  └── hello.txt | ASCII | 4 | 0 |
| │ │ └── sfx.7z | 7Z | 3 | 1 |
| │ │   └── world.txt | ASCII | 4 | 0 |
| │ ├── sfx.zip | ZIP | 2 | 1 |
| │ │  └── hello.txt | ASCII | 3 | 0 |
| │ └── sfx.7z | 7Z | 2 | 1 |
| │  └── world.txt | ASCII | 3 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| └── sfx.7z | 7Z | 1 | 1 |
(A) is bad because it scans content more than once.
Note that for the GZ layer, it may detect the ZIP and 7Z if the
signature hits on the compressed data, which it might, though
extracting the ZIP and 7Z will likely fail.
The reason the above doesn't happen now is that we restrict embedded
type scans for a bunch of archive formats to include GZ and TAR.
(B) If we scan for embedded files at the foo.tar layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| ├── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 2 | 1 |
| │  └── hello.txt | ASCII | 3 | 0 |
| └── sfx.7z | 7Z | 2 | 1 |
|   └── world.txt | ASCII | 3 | 0 |
(B) is almost right. But we can achieve it easily enough only scanning for
embedded content in the current fmap when the "nested fmap level" is 0.
The upside is that it should safely detect all embedded content, even if
it may think the sfz.zip and sfx.7z are in foo.tar instead of in baz.exe.
The biggest risk I can think of affects ZIPs. SFXZIP detection
is identical to ZIP detection, which is why we don't allow SFXZIP to be
detected if insize of a ZIP. If we only allow embedded type scanning at
fmap-layer 0 in each buffer, this will fail to detect the embedded ZIP
if the bar.exe was not compressed in foo.zip and if non-compressed files
extracted from ZIPs aren't extracted as new buffers:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.zip | ZIP | 0 | 0 |
| └── bar.exe | PE | 1 | 1 |
| └── sfx.zip | ZIP | 2 | 2 |
Provided that we ensure all files extracted from zips are scanned in
new buffers, option (B) should be safe.
(C) If we scan for embedded files at the baz.exe layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │  └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 3 | 1 |
| │  └── hello.txt | ASCII | 4 | 0 |
| └── sfx.7z | 7Z | 3 | 1 |
|   └── world.txt | ASCII | 4 | 0 |
(C) is right. But it's harder to achieve. For this example we can get it by
restricting 7ZSFX and ZIPSFX detection only when scanning an executable.
But that may mean losing detection of archives embedded elsewhere.
And we'd have to identify allowable container types for each possible
embedded type, which would be very difficult.
So this commit aims to solve the issue the (B)-way.
Note that in all situations, we still have to scan with file typing
enabled to determine if we need to reassign the current file type, such
as re-identifying a Bzip2 archive as a DMG that happens to be Bzip2-
compressed. Detection of DMG and a handful of other types rely on
finding data partway through or near the ned of a file before
reassigning the entire file as the new type.
Other fixes and considerations in this commit:
- The utf16 HTML parser has weak error handling, particularly with respect
to creating a nested fmap for scanning the ascii decoded file.
This commit cleans up the error handling and wraps the nested scan with
the recursion-stack push()/pop() for correct recursion tracking.
Before this commit, each container layer had a flag to indicate if the
container layer is valid.
We need something similar so that the cli_recursion_stack_get_*()
functions ignore normalized layers. Details...
Imagine an LDB signature for HTML content that specifies a ZIP
container. If the signature actually alerts on the normalized HTML and
you don't ignore normalized layers for the container check, it will
appear as though the alert is in an HTML container rather than a ZIP
container.
This commit accomplishes this with a boolean you set in the scan context
before scanning a new layer. Then when the new fmap is created, it will
use that flag to set similar flag for the layer. The context flag is
reset those that anything after this doesn't have that flag.
The flag allows the new recursion_stack_get() function to ignore
normalized layers when iterating the stack to return a layer at a
requested index, negative or positive.
Scanning normalized extracted/normalized javascript and VBA should also
use the 'layer is normalized' flag.
- This commit also fixes Heuristic.Broken.Executable alert for ELF files
to make sure that:
A) these only alert if cli_append_virus() returns CL_VIRUS (aka it
respects the FP check).
B) all broken-executable alerts for ELF only happen if the
SCAN_HEURISTIC_BROKEN option is enabled.
- This commit also cleans up the error handling in cli_magic_scan_dir().
This was needed so we could correctly apply the layer-is-normalized-flag
to all VBA macros extracted to a directory when scanning the directory.
- Also fix an issue where exceeding scan maximums wouldn't cause embedded
file detection scans to abort. Granted we don't actually want to abort
if max filesize or max recursion depth are exceeded... only if max
scansize, max files, and max scantime are exceeded.
Add 'abort_scan' flag to scan context, to protect against depending on
correct error propagation for fatal conditions. Instead, setting this
flag in the scan context should guarantee that a fatal condition deep in
scan recursion isn't lost which result in more stuff being scanned
instead of aborting. This shouldn't be necessary, but some status codes
like CL_ETIMEOUT never used to be fatal and it's easier to do this than
to verify every parser only returns CL_ETIMEOUT and other "fatal
status codes" in fatal conditions.
- Remove duplicate is_tar() prototype from filestypes.c and include
is_tar.h instead.
- Presently we create the fmap hash when creating the fmap.
This wastes a bit of CPU if the hash is never needed.
Now that we're creating fmap's for all embedded files discovered with
file type recognition scans, this is a much more frequent occurence and
really slows things down.
This commit fixes the issue by only creating fmap hashes as needed.
This should not only resolve the perfomance impact of creating fmap's
for all embedded files, but also should improve performance in general.
- Add allmatch check to the zip parser after the central-header meta
match. That way we don't multiple alerts with the same match except in
allmatch mode. Clean up error handling in the zip parser a tiny bit.
- Fixes to ensure that the scan limits such as scansize, filesize,
recursion depth, # of embedded files, and scantime are always reported
if AlertExceedsMax (--alert-exceeds-max) is enabled.
- Fixed an issue where non-fatal alerts for exceeding scan maximums may
mask signature matches later on. I changed it so these alerts use the
"possibly unwanted" alert-type and thus only alert if no other alerts
were found or if all-match or heuristic-precedence are enabled.
- Added the "Heuristics.Limits.Exceeded.*" events to the JSON metadata
when the --gen-json feature is enabled. These will show up once under
"ParseErrors" the first time a limit is exceeded. In the present
implementation, only one limits-exceeded events will be added, so as to
prevent a malicious or malformed sample from filling the JSON buffer
with millions of events and using a tonne of RAM.
2021-09-11 14:15:21 -07:00
if ( recursion_level > engine - > max_recursion_level ) {
// Note: engine->max_recursion_level is re-purposed here out of convenience.
// ole2 recursion does not leverage the ctx->recursion_stack stack.
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailBody: hit maximum recursion level (%u) \n " , recursion_level ) ;
return MAXREC ;
}
if ( engine - > maxfiles & & ( mctx - > files > = engine - > maxfiles ) ) {
/*
2020-07-29 10:26:55 -07:00
* FIXME : This is only approx - it may have already
* been exceeded
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailBody: number of files exceeded %u \n " , engine - > maxfiles ) ;
return MAXFILES ;
}
rc = OK ;
/* Anything left to be parsed? */
if ( mainMessage & & ( messageGetBody ( mainMessage ) ! = NULL ) ) {
mime_type mimeType ;
int subtype , inhead , htmltextPart , inMimeHead , i ;
const char * mimeSubtype ;
char * boundary ;
const text * t_line ;
/*bool isAlternative;*/
message * aMessage ;
int multiparts = 0 ;
message * * messages = NULL ; /* parts of a multipart message */
cli_dbgmsg ( " Parsing mail file \n " ) ;
mimeType = messageGetMimeType ( mainMessage ) ;
mimeSubtype = messageGetMimeSubtype ( mainMessage ) ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
if ( mctx - > wrkobj ! = NULL ) {
mctx - > wrkobj = cli_jsonobj ( mctx - > wrkobj , " Body " ) ;
cli_jsonstr ( mctx - > wrkobj , " MimeType " , getMimeTypeStr ( mimeType ) ) ;
cli_jsonstr ( mctx - > wrkobj , " MimeSubtype " , mimeSubtype ) ;
cli_jsonstr ( mctx - > wrkobj , " EncodingType " , getEncTypeStr ( messageGetEncoding ( mainMessage ) ) ) ;
cli_jsonstr ( mctx - > wrkobj , " Disposition " , messageGetDispositionType ( mainMessage ) ) ;
2021-10-20 21:10:59 -07:00
if ( messageHasFilename ( mainMessage ) ) {
char * filename = messageGetFilename ( mainMessage ) ;
cli_jsonstr ( mctx - > wrkobj , " Filename " , filename ) ;
free ( filename ) ;
} else {
cli_jsonstr ( mctx - > wrkobj , " Filename " , " (inline) " ) ;
}
2018-12-03 12:40:13 -05:00
}
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/* pre-process */
subtype = tableFind ( mctx - > subtypeTable , mimeSubtype ) ;
if ( ( mimeType = = TEXT ) & & ( subtype = = PLAIN ) ) {
/*
2020-07-29 10:26:55 -07:00
* This is effectively no encoding , notice that we
* don ' t check that charset is us - ascii
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " text/plain: Assume no attachments \n " ) ;
mimeType = NOMIME ;
messageSetMimeSubtype ( mainMessage , " " ) ;
} else if ( ( mimeType = = MESSAGE ) & &
( strcasecmp ( mimeSubtype , " rfc822-headers " ) = = 0 ) ) {
/*
2020-07-29 10:26:55 -07:00
* RFC1892 / RFC3462 : section 2 text / rfc822 - headers
* incorrectly sent as message / rfc822 - headers
*
* Parse as text / plain , i . e . no mime
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Changing message/rfc822-headers to text/rfc822-headers \n " ) ;
mimeType = NOMIME ;
messageSetMimeSubtype ( mainMessage , " " ) ;
} else
cli_dbgmsg ( " mimeType = %d \n " , ( int ) mimeType ) ;
switch ( mimeType ) {
case NOMIME :
cli_dbgmsg ( " Not a mime encoded message \n " ) ;
aText = textAddMessage ( aText , mainMessage ) ;
2019-11-07 09:10:26 -08:00
if ( ! doPhishingScan ) {
2018-12-03 12:40:13 -05:00
break ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Fall through : some phishing mails claim they are
* text / plain , when they are in fact html
*/
2019-11-07 09:10:26 -08:00
/* fall through */
2018-12-03 12:40:13 -05:00
case TEXT :
/* text/plain has been preprocessed as no encoding */
if ( doPhishingScan ) {
/*
2020-07-29 10:26:55 -07:00
* It would be better to save and scan the
* file and only checkURLs if it ' s found to be
* clean
*/
2018-12-03 12:40:13 -05:00
checkURLs ( mainMessage , mctx , & rc , ( subtype = = HTML ) ) ;
/*
2020-07-29 10:26:55 -07:00
* There might be html sent without subtype
* html too , so scan them for phishing
*/
2018-12-03 12:40:13 -05:00
if ( rc = = VIRUS )
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
}
break ;
case MULTIPART :
cli_dbgmsg ( " Content-type 'multipart' handler \n " ) ;
boundary = messageFindArgument ( mainMessage , " boundary " ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
if ( mctx - > wrkobj ! = NULL )
cli_jsonstr ( mctx - > wrkobj , " Boundary " , boundary ) ;
2016-05-10 18:53:59 -04:00
2018-12-03 12:40:13 -05:00
if ( boundary = = NULL ) {
cli_dbgmsg ( " Multipart/%s MIME message contains no boundary header \n " ,
mimeSubtype ) ;
/* Broken e-mail message */
mimeType = NOMIME ;
/*
2020-07-29 10:26:55 -07:00
* The break means that we will still
* check if the file contains a uuencoded file
*/
2018-12-03 12:40:13 -05:00
break ;
}
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
cli_chomp ( boundary ) ;
2014-02-25 11:57:42 -05:00
2018-12-03 12:40:13 -05:00
/* Perhaps it should assume mixed? */
if ( mimeSubtype [ 0 ] = = ' \0 ' ) {
cli_dbgmsg ( " Multipart has no subtype assuming alternative \n " ) ;
mimeSubtype = " alternative " ;
messageSetMimeSubtype ( mainMessage , " alternative " ) ;
}
2004-06-14 09:08:29 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Get to the start of the first message
*/
2018-12-03 12:40:13 -05:00
t_line = messageGetBody ( mainMessage ) ;
if ( t_line = = NULL ) {
cli_dbgmsg ( " Multipart MIME message has no body \n " ) ;
free ( ( char * ) boundary ) ;
mimeType = NOMIME ;
break ;
}
do
if ( t_line - > t_line ) {
if ( boundaryStart ( lineGetData ( t_line - > t_line ) , boundary ) )
break ;
/*
2020-07-29 10:26:55 -07:00
* Found a binhex file before
* the first multipart
* TODO : check yEnc
*/
2018-12-03 12:40:13 -05:00
if ( binhexBegin ( mainMessage ) = = t_line ) {
if ( exportBinhexMessage ( mctx , mainMessage ) ) {
/* virus found */
rc = VIRUS ;
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
break ;
}
} else if ( t_line - > t_next & &
( encodingLine ( mainMessage ) = = t_line - > t_next ) ) {
/*
2020-07-29 10:26:55 -07:00
* We look for the next line
* since later on we ' ll skip
* over the important line when
* we think it ' s a blank line
* at the top of the message -
* which it would have been in
* an RFC compliant world
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Found MIME attachment before the first MIME section \" %s \" \n " ,
lineGetData ( t_line - > t_next - > t_line ) ) ;
if ( messageGetEncoding ( mainMessage ) = = NOENCODING )
break ;
}
}
while ( ( t_line = t_line - > t_next ) ! = NULL ) ;
if ( t_line = = NULL ) {
cli_dbgmsg ( " Multipart MIME message contains no boundary lines (%s) \n " ,
boundary ) ;
free ( ( char * ) boundary ) ;
mimeType = NOMIME ;
/*
2020-07-29 14:14:43 -07:00
* The break means that we will still
* check if the file contains a yEnc / binhex file
*/
2018-12-03 12:40:13 -05:00
break ;
}
/*
2020-07-29 10:26:55 -07:00
* Build up a table of all of the parts of this
* multipart message . Remember , each part may itself
* be a multipart message .
*/
2018-12-03 12:40:13 -05:00
inhead = 1 ;
inMimeHead = 0 ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Re - read this variable in case mimeSubtype has changed
*/
2018-12-03 12:40:13 -05:00
subtype = tableFind ( mctx - > subtypeTable , mimeSubtype ) ;
2006-07-03 12:09:58 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Parse the mainMessage object and create an array
* of objects called messages , one for each of the
* multiparts that mainMessage contains .
*
* This looks like parseEmailHeaders ( ) - maybe there ' s
* some duplication of code to be cleaned up
*
* We may need to create an array rather than just
* save each part as it is found because not all
* elements will need scanning , and we don ' t yet know
* which of those elements it will be , except in
* the case of mixed , when all parts need to be scanned .
*/
2018-12-03 12:40:13 -05:00
for ( multiparts = 0 ; t_line & & ! infected ; multiparts + + ) {
int lines = 0 ;
message * * m ;
mbox_status old_rc ;
2022-05-09 14:28:34 -07:00
m = cli_max_realloc ( messages , ( ( multiparts + 1 ) * sizeof ( message * ) ) ) ;
2018-12-03 12:40:13 -05:00
if ( m = = NULL )
break ;
messages = m ;
aMessage = messages [ multiparts ] = messageCreate ( ) ;
if ( aMessage = = NULL ) {
multiparts - - ;
/* if allocation failed the first time,
2020-07-29 10:26:55 -07:00
* there ' s no point in retrying , just
* break out */
2018-12-03 12:40:13 -05:00
break ;
}
messageSetCTX ( aMessage , mctx - > ctx ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Now read in part %d \n " , multiparts ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Ignore blank lines . There shouldn ' t be ANY
* but some viruses insert them
*/
2018-12-03 12:40:13 -05:00
while ( ( t_line = t_line - > t_next ) ! = NULL )
if ( t_line - > t_line & &
/*(cli_chomp(t_line->t_text) > 0))*/
( strlen ( lineGetData ( t_line - > t_line ) ) > 0 ) )
break ;
if ( t_line = = NULL ) {
cli_dbgmsg ( " Empty part \n " ) ;
/*
2020-07-29 10:26:55 -07:00
* Remove this part unless there ' s
* a binhex portion somewhere in
* the complete message that we may
* throw away by mistake if the MIME
* encoding information is incorrect
*/
2018-12-03 12:40:13 -05:00
if ( mainMessage & &
( binhexBegin ( mainMessage ) = = NULL ) ) {
messageDestroy ( aMessage ) ;
- - multiparts ;
}
continue ;
}
do {
const char * line = lineGetData ( t_line - > t_line ) ;
2020-07-29 10:26:55 -07:00
/*
cli_dbgmsg ( " multipart %d: inMimeHead %d inhead %d boundary '%s' line '%s' next '%s' \n " ,
multiparts , inMimeHead , inhead , boundary , line ,
t_line - > t_next & & t_line - > t_next - > t_line ? lineGetData ( t_line - > t_next - > t_line ) : " (null) " ) ;
*/
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
if ( inMimeHead ) { /* continuation line */
if ( line = = NULL ) {
/*inhead =*/ inMimeHead = 0 ;
continue ;
}
/*
2020-07-29 10:26:55 -07:00
* Handle continuation lines
* because the previous line
* ended with a ; or this line
* starts with a white space
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Multipart %d: About to add mime Argument '%s' \n " ,
multiparts , line ) ;
/*
2020-07-29 10:26:55 -07:00
* Handle the case when it
* isn ' t really a continuation
* line :
* Content - Type : application / octet - stream ;
* Content - Transfer - Encoding : base64
*/
2019-11-07 09:10:26 -08:00
parseEmailHeader ( aMessage , line , mctx - > rfc821Table , mctx - > ctx , & heuristicFound ) ;
if ( heuristicFound ) {
rc = VIRUS ;
break ;
}
2018-12-03 12:40:13 -05:00
while ( isspace ( ( int ) * line ) )
line + + ;
if ( * line = = ' \0 ' ) {
inhead = inMimeHead = 0 ;
continue ;
}
2021-10-20 21:10:59 -07:00
inMimeHead = false ;
2018-12-03 12:40:13 -05:00
messageAddArgument ( aMessage , line ) ;
} else if ( inhead ) { /* handling normal headers */
/*int quotes;*/
char * fullline , * ptr ;
if ( line = = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* empty line , should the end of the headers ,
* but some base64 decoders , e . g . uudeview , are broken
* and will handle this type of entry , decoding the
* base64 content . . .
* Content - Type : application / octet - stream ; name = text . zip
* Content - Transfer - Encoding : base64
* Content - Disposition : attachment ; filename = " text.zip "
*
* Content - Disposition : attachment ;
* filename = text . zip
* Content - Type : application / octet - stream ;
* name = text . zip
* Content - Transfer - Encoding : base64
*
* UEsDBAoAAAAAAACgPjJ2RHw676gAAO + oAABEAAAAbWFpbF90ZXh0LWluZm8udHh0ICAgICAgICAg
*/
2018-12-03 12:40:13 -05:00
const text * next = t_line - > t_next ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
if ( next & & next - > t_line ) {
const char * data = lineGetData ( next - > t_line ) ;
2005-02-06 18:25:10 +00:00
2018-12-03 12:40:13 -05:00
if ( ( messageGetEncoding ( aMessage ) = = NOENCODING ) & &
( messageGetMimeType ( aMessage ) = = APPLICATION ) & &
data & & strstr ( data , " base64 " ) ) {
/*
2020-07-29 10:26:55 -07:00
* Handle this nightmare ( note the blank
* line in the header and the incorrect
* content - transfer - encoding header )
*
* Content - Type : application / octet - stream ; name = " zipped_files.EXEX-Spanska: Yes
*
* r - Encoding : base64
* Content - Disposition : attachment ; filename = " zipped_files.EXE "
*/
2018-12-03 12:40:13 -05:00
messageSetEncoding ( aMessage , " base64 " ) ;
cli_dbgmsg ( " Ignoring fake end of headers \n " ) ;
continue ;
}
if ( ( strncmp ( data , " Content " , 7 ) = = 0 ) | |
( strncmp ( data , " filename= " , 9 ) = = 0 ) ) {
cli_dbgmsg ( " Ignoring fake end of headers \n " ) ;
continue ;
}
}
cli_dbgmsg ( " Multipart %d: End of header information \n " ,
multiparts ) ;
inhead = 0 ;
continue ;
}
if ( isspace ( ( int ) * line ) ) {
/*
2020-07-29 10:26:55 -07:00
* The first line is
* continuation line .
* This is tricky
* to handle , but
* all we can do is our
* best
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Part %d starts with a continuation line \n " ,
multiparts ) ;
messageAddArgument ( aMessage , line ) ;
/*
2020-07-29 10:26:55 -07:00
* Give it a default
* MIME type since
* that may be the
* missing line
*
* Choose application to
* force a save
*/
2018-12-03 12:40:13 -05:00
if ( messageGetMimeType ( aMessage ) = = NOMIME )
messageSetMimeType ( aMessage , " application " ) ;
continue ;
}
2004-02-02 09:53:53 +00:00
2021-10-20 21:10:59 -07:00
inMimeHead = false ;
2004-08-21 12:01:07 +00:00
2021-10-20 21:10:59 -07:00
if ( strlen ( line ) > RFC2821LENGTH ) {
2024-01-19 09:08:36 -08:00
cli_dbgmsg ( " parseEmailBody: line length exceeds RFC2821 maximum length (1000) \n " ) ;
2021-10-20 21:10:59 -07:00
// We must skip this line because functions like rfc822comments() may accept output buffers
// that [RFC2821LENGTH + 1] in and don't have any length checks to prevent exceeding that max.
// E.g. See `boundaryStart()`.
// TODO: A larger audit would be needed to remove this limitation, though frankly I recommend
// fully re-writing the email parser (in Rust).
continue ;
}
2004-10-31 09:32:05 +00:00
2018-12-03 12:40:13 -05:00
fullline = rfc822comments ( line , NULL ) ;
if ( fullline = = NULL )
2024-01-09 17:44:33 -05:00
fullline = cli_safer_strdup ( line ) ;
2004-11-11 22:18:10 +00:00
2018-12-03 12:40:13 -05:00
/*quotes = count_quotes(fullline);*/
2004-10-31 09:32:05 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Fold next lines to the end of this
* if they start with a white space
* or if this line has an odd number of quotes :
* Content - Type : application / octet - stream ; name = " foo
* "
*/
2018-12-03 12:40:13 -05:00
while ( t_line & & next_is_folded_header ( t_line ) ) {
const char * data ;
size_t datasz ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
t_line = t_line - > t_next ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
data = lineGetData ( t_line - > t_line ) ;
2004-10-31 09:32:05 +00:00
2018-12-03 12:40:13 -05:00
if ( data [ 1 ] = = ' \0 ' ) {
/*
2020-07-29 10:26:55 -07:00
* Broken message : the
* blank line at the end
* of the headers isn ' t blank -
* it contains a space
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Multipart %d: headers not terminated by blank line \n " ,
multiparts ) ;
2021-10-20 21:10:59 -07:00
inhead = false ;
2018-12-03 12:40:13 -05:00
break ;
}
2005-11-23 11:21:45 +00:00
2018-12-03 12:40:13 -05:00
datasz = strlen ( fullline ) + strlen ( data ) + 1 ;
2022-05-09 14:28:34 -07:00
ptr = cli_max_realloc ( fullline , datasz ) ;
2004-01-09 14:46:59 +00:00
2018-12-03 12:40:13 -05:00
if ( ptr = = NULL )
break ;
2004-09-16 11:22:03 +00:00
2018-12-03 12:40:13 -05:00
fullline = ptr ;
cli_strlcat ( fullline , data , datasz ) ;
2004-11-11 22:18:10 +00:00
2018-12-03 12:40:13 -05:00
/*quotes = count_quotes(data);*/
}
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Multipart %d: About to parse folded header '%s' \n " ,
multiparts , fullline ) ;
2004-12-01 13:16:08 +00:00
2019-11-07 09:10:26 -08:00
parseEmailHeader ( aMessage , fullline , mctx - > rfc821Table , mctx - > ctx , & heuristicFound ) ;
2018-12-03 12:40:13 -05:00
free ( fullline ) ;
2019-11-07 09:10:26 -08:00
if ( heuristicFound ) {
rc = VIRUS ;
}
2018-12-03 12:40:13 -05:00
} else if ( boundaryEnd ( line , boundary ) ) {
/*
2020-07-29 10:26:55 -07:00
* Some viruses put information
* * after * the end of message ,
* which presumably some broken
* mail clients find , so we
* can ' t assume that this
* is the end of the message
*/
2018-12-03 12:40:13 -05:00
/* t_line = NULL;*/
break ;
} else if ( boundaryStart ( line , boundary ) ) {
inhead = 1 ;
break ;
} else {
if ( messageAddLine ( aMessage , t_line - > t_line ) < 0 )
break ;
lines + + ;
}
} while ( ( t_line = t_line - > t_next ) ! = NULL ) ;
cli_dbgmsg ( " Part %d has %d lines, rc = %d \n " ,
multiparts , lines , ( int ) rc ) ;
/*
2020-07-29 10:26:55 -07:00
* Only save in the array of messages if some
* decision will be taken on whether to scan .
* If all parts will be scanned then save to
* file straight away
*/
2018-12-03 12:40:13 -05:00
switch ( subtype ) {
case MIXED :
case ALTERNATIVE :
case REPORT :
case DIGEST :
case APPLEDOUBLE :
case KNOWBOT :
case - 1 :
old_rc = rc ;
mainMessage = do_multipart ( mainMessage ,
messages , multiparts ,
& rc , mctx , messageIn ,
& aText , recursion_level ) ;
if ( ( rc = = OK_ATTACHMENTS_NOT_SAVED ) & & ( old_rc = = OK ) )
rc = OK ;
if ( messages [ multiparts ] ) {
messageDestroy ( messages [ multiparts ] ) ;
messages [ multiparts ] = NULL ;
}
- - multiparts ;
if ( rc = = VIRUS )
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
break ;
case RELATED :
case ENCRYPTED :
case SIGNED :
case PARALLEL :
/* all the subtypes that we handle
2020-07-29 10:26:55 -07:00
* ( all from the switch ( tableFind . . . ) below )
* must be listed here */
2018-12-03 12:40:13 -05:00
break ;
default :
2019-03-26 15:09:52 -04:00
/* this is a subtype that we
2020-07-29 10:26:55 -07:00
* don ' t handle anyway ,
* don ' t store */
2018-12-03 12:40:13 -05:00
if ( messages [ multiparts ] ) {
messageDestroy ( messages [ multiparts ] ) ;
messages [ multiparts ] = NULL ;
}
- - multiparts ;
}
}
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
free ( ( char * ) boundary ) ;
2003-07-29 15:48:06 +00:00
2019-11-19 15:55:47 -08:00
if ( haveTooManyMIMEPartsPerMessage ( multiparts , mctx - > ctx , & rc ) ) {
2020-07-29 14:14:43 -07:00
if ( messages ) {
for ( i = 0 ; i < multiparts ; i + + ) {
if ( messages [ i ] )
messageDestroy ( messages [ i ] ) ;
}
free ( messages ) ;
messages = NULL ;
}
2019-11-07 09:10:26 -08:00
break ;
}
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Preprocess . Anything special to be done before
* we handle the multiparts ?
*/
2018-12-03 12:40:13 -05:00
switch ( subtype ) {
case KNOWBOT :
/* TODO */
cli_dbgmsg ( " multipart/knowbot parsed as multipart/mixed for now \n " ) ;
mimeSubtype = " mixed " ;
break ;
case - 1 :
/*
2020-07-29 10:26:55 -07:00
* According to section 7.2 .6 of
* RFC1521 , unrecognized multiparts
* should be treated as multipart / mixed .
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Unsupported multipart format `%s', parsed as mixed \n " , mimeSubtype ) ;
mimeSubtype = " mixed " ;
break ;
}
2004-10-04 12:21:11 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* We ' ve finished message we ' re parsing
*/
2018-12-03 12:40:13 -05:00
if ( mainMessage & & ( mainMessage ! = messageIn ) ) {
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
}
cli_dbgmsg ( " The message has %d parts \n " , multiparts ) ;
if ( infected | | ( ( multiparts = = 0 ) & & ( aText = = NULL ) ) ) {
if ( messages ) {
2020-07-29 14:14:43 -07:00
for ( i = 0 ; i < multiparts ; i + + ) {
2018-12-03 12:40:13 -05:00
if ( messages [ i ] )
messageDestroy ( messages [ i ] ) ;
2020-07-29 14:14:43 -07:00
}
2018-12-03 12:40:13 -05:00
free ( messages ) ;
2020-07-29 14:14:43 -07:00
messages = NULL ;
2018-12-03 12:40:13 -05:00
}
if ( aText & & ( textIn = = NULL ) )
textDestroy ( aText ) ;
2006-07-30 10:10:40 +00:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Nothing to do
*/
2018-12-03 12:40:13 -05:00
switch ( rc ) {
case VIRUS :
return VIRUS ;
case MAXREC :
return MAXREC ;
default :
return OK_ATTACHMENTS_NOT_SAVED ;
}
}
2004-03-31 17:01:18 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Find out the multipart type (%s) \n " , mimeSubtype ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* We now have all the parts of the multipart message
* in the messages array :
* message * messages [ multiparts ]
* Let ' s decide what to do with them all
*/
2018-12-03 12:40:13 -05:00
switch ( tableFind ( mctx - > subtypeTable , mimeSubtype ) ) {
case RELATED :
cli_dbgmsg ( " Multipart related handler \n " ) ;
/*
2020-07-29 10:26:55 -07:00
* Have a look to see if there ' s HTML code
* which will need scanning
*/
2021-10-20 21:10:59 -07:00
// It's okay if multiparts == 0
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
htmltextPart = getTextPart ( messages , multiparts ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
if ( htmltextPart > = 0 & & messages ) {
2019-11-07 09:10:26 -08:00
if ( messageGetBody ( messages [ htmltextPart ] ) ) {
2007-12-17 20:22:11 +00:00
2018-12-03 12:40:13 -05:00
aText = textAddMessage ( aText , messages [ htmltextPart ] ) ;
2019-11-07 09:10:26 -08:00
}
} else {
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* There isn ' t an HTML bit . If there ' s a
* multipart bit , it ' ll may be in there
* somewhere
*/
2019-11-07 09:10:26 -08:00
for ( i = 0 ; i < multiparts ; i + + ) {
2018-12-03 12:40:13 -05:00
if ( messageGetMimeType ( messages [ i ] ) = = MULTIPART ) {
htmltextPart = i ;
break ;
}
2019-11-07 09:10:26 -08:00
}
}
2018-12-03 12:40:13 -05:00
2019-11-07 09:10:26 -08:00
if ( htmltextPart = = - 1 ) {
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " No HTML code found to be scanned \n " ) ;
2019-11-07 09:10:26 -08:00
} else {
2018-12-03 12:40:13 -05:00
/* Send root HTML file for preclassification */
2025-06-08 01:12:33 -04:00
if ( mctx - > ctx - > this_layer_metadata_json )
2021-10-20 21:10:59 -07:00
( void ) parseRootMHTML ( mctx , messages [ htmltextPart ] , aText ) ;
2024-03-25 13:01:46 -04:00
2021-10-20 21:10:59 -07:00
rc = parseEmailBody ( messages [ htmltextPart ] , aText , mctx , recursion_level + 1 ) ;
if ( ( rc = = OK ) & & messages [ htmltextPart ] ) {
messageDestroy ( messages [ htmltextPart ] ) ;
2018-12-03 12:40:13 -05:00
messages [ htmltextPart ] = NULL ;
} else if ( rc = = VIRUS ) {
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
break ;
}
}
/*
2020-07-29 10:26:55 -07:00
* The message is confused about the difference
* between alternative and related . Badtrans . B
* suffers from this problem .
*
* Fall through in this case :
* Content - Type : multipart / related ;
* type = " multipart/alternative "
*/
2019-11-07 09:10:26 -08:00
/* fall through */
2018-12-03 12:40:13 -05:00
case DIGEST :
/*
2020-07-29 10:26:55 -07:00
* According to section 5.1 .5 RFC2046 , the
* default mime type of multipart / digest parts
* is message / rfc822
*
* We consider them as alternative , wrong in
* the strictest sense since they aren ' t
* alternatives - all parts a valid - but it ' s
* OK for our needs since it means each part
* will be scanned
*/
2018-12-03 12:40:13 -05:00
case ALTERNATIVE :
cli_dbgmsg ( " Multipart alternative handler \n " ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Fall through - some clients are broken and
* say alternative instead of mixed . The Klez
* virus is broken that way , and anyway we
* wish to scan all of the alternatives
*/
2019-11-07 09:10:26 -08:00
/* fall through */
2018-12-03 12:40:13 -05:00
case REPORT :
/*
2020-07-29 10:26:55 -07:00
* According to section 1 of RFC1892 , the
* syntax of multipart / report is the same
* as multipart / mixed . There are some required
* parameters , but there ' s no need for us to
* verify that they exist
*/
2018-12-03 12:40:13 -05:00
case ENCRYPTED :
/* MUAs without encryption plugins can display as multipart/mixed,
2020-07-29 10:26:55 -07:00
* just scan it */
2018-12-03 12:40:13 -05:00
case MIXED :
case APPLEDOUBLE : /* not really supported */
/*
2020-07-29 10:26:55 -07:00
* Look for attachments
*
* Not all formats are supported . If an
* unsupported format turns out to be
* common enough to implement , it is a simple
* matter to add it
*/
2018-12-03 12:40:13 -05:00
if ( aText ) {
if ( mainMessage & & ( mainMessage ! = messageIn ) )
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
}
cli_dbgmsg ( " Mixed message with %d parts \n " , multiparts ) ;
for ( i = 0 ; i < multiparts ; i + + ) {
mainMessage = do_multipart ( mainMessage ,
messages , i , & rc , mctx ,
messageIn , & aText , recursion_level + 1 ) ;
if ( rc = = VIRUS ) {
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
break ;
}
if ( rc = = MAXREC )
break ;
if ( rc = = OK_ATTACHMENTS_NOT_SAVED )
rc = OK ;
}
/* rc = parseEmailBody(NULL, NULL, mctx, recursion_level + 1); */
break ;
case SIGNED :
case PARALLEL :
/*
2020-07-29 10:26:55 -07:00
* If we ' re here it could be because we have a
* multipart / mixed message , consisting of a
* message followed by an attachment . That
* message itself is a multipart / alternative
* message and we need to dig out the plain
* text part of that alternative
*/
2018-12-03 12:40:13 -05:00
if ( messages ) {
htmltextPart = getTextPart ( messages , multiparts ) ;
if ( htmltextPart = = - 1 )
htmltextPart = 0 ;
rc = parseEmailBody ( messages [ htmltextPart ] , aText , mctx , recursion_level + 1 ) ;
}
break ;
default :
2024-01-19 09:08:36 -08:00
cli_dbgmsg ( " Unexpected mime sub type \n " ) ;
2021-06-04 16:56:10 -07:00
rc = CL_EFORMAT ;
break ;
2018-12-03 12:40:13 -05:00
}
if ( mainMessage & & ( mainMessage ! = messageIn ) )
messageDestroy ( mainMessage ) ;
if ( aText & & ( textIn = = NULL ) ) {
if ( ( ! infected ) & & ( fb = fileblobCreate ( ) ) ! = NULL ) {
cli_dbgmsg ( " Save non mime and/or text/plain part \n " ) ;
fileblobSetFilename ( fb , mctx - > dir , " textpart " ) ;
/*fileblobAddData(fb, "Received: by clamd (textpart)\n", 30);*/
fileblobSetCTX ( fb , mctx - > ctx ) ;
( void ) textToFileblob ( aText , fb , 1 ) ;
fileblobDestroy ( fb ) ;
mctx - > files + + ;
}
textDestroy ( aText ) ;
}
2020-07-29 14:14:43 -07:00
if ( messages ) {
for ( i = 0 ; i < multiparts ; i + + ) {
if ( messages [ i ] )
messageDestroy ( messages [ i ] ) ;
}
2018-12-03 12:40:13 -05:00
free ( messages ) ;
2020-07-29 14:14:43 -07:00
messages = NULL ;
}
2004-06-18 10:09:33 +00:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
return rc ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
case MESSAGE :
/*
2020-07-29 10:26:55 -07:00
* Check for forbidden encodings
*/
2018-12-03 12:40:13 -05:00
switch ( messageGetEncoding ( mainMessage ) ) {
case NOENCODING :
case EIGHTBIT :
case BINARY :
break ;
default :
cli_dbgmsg ( " MIME type 'message' cannot be decoded \n " ) ;
break ;
}
rc = FAIL ;
if ( ( strcasecmp ( mimeSubtype , " rfc822 " ) = = 0 ) | |
( strcasecmp ( mimeSubtype , " delivery-status " ) = = 0 ) ) {
2019-11-07 09:10:26 -08:00
message * m = parseEmailHeaders ( mainMessage , mctx - > rfc821Table , & heuristicFound ) ;
2018-12-03 12:40:13 -05:00
if ( m ) {
cli_dbgmsg ( " Decode rfc822 \n " ) ;
messageSetCTX ( m , mctx - > ctx ) ;
if ( mainMessage & & ( mainMessage ! = messageIn ) ) {
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
} else
messageReset ( mainMessage ) ;
if ( messageGetBody ( m ) )
rc = parseEmailBody ( m , NULL , mctx , recursion_level + 1 ) ;
messageDestroy ( m ) ;
2019-11-07 09:10:26 -08:00
} else if ( heuristicFound ) {
rc = VIRUS ;
2018-12-03 12:40:13 -05:00
}
break ;
} else if ( strcasecmp ( mimeSubtype , " disposition-notification " ) = = 0 ) {
/* RFC 2298 - handle like a normal email */
rc = OK ;
break ;
} else if ( strcasecmp ( mimeSubtype , " partial " ) = = 0 ) {
if ( mctx - > ctx - > options - > mail & CL_SCAN_MAIL_PARTIAL_MESSAGE ) {
/* RFC1341 message split over many emails */
2019-05-23 22:50:04 -04:00
if ( rfc1341 ( mctx , mainMessage ) > = 0 )
2018-12-03 12:40:13 -05:00
rc = OK ;
} else {
cli_warnmsg ( " Partial message received from MUA/MTA - message cannot be scanned \n " ) ;
}
} else if ( strcasecmp ( mimeSubtype , " external-body " ) = = 0 )
/* TODO */
cli_warnmsg ( " Attempt to send Content-type message/external-body trapped \n " ) ;
else
cli_warnmsg ( " Unsupported message format `%s' - if you believe this file contains a virus, submit it to www.clamav.net \n " , mimeSubtype ) ;
if ( mainMessage & & ( mainMessage ! = messageIn ) )
messageDestroy ( mainMessage ) ;
2020-07-29 14:14:43 -07:00
if ( messages ) {
for ( i = 0 ; i < multiparts ; i + + ) {
if ( messages [ i ] )
messageDestroy ( messages [ i ] ) ;
}
2018-12-03 12:40:13 -05:00
free ( messages ) ;
2020-07-29 14:14:43 -07:00
messages = NULL ;
}
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
return rc ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
default :
cli_dbgmsg ( " Message received with unknown mime encoding - assume application \n " ) ;
/*
2020-07-29 10:26:55 -07:00
* Some Yahoo emails attach as
* Content - Type : X - unknown / unknown ;
* instead of
* Content - Type : application / unknown ;
* so let ' s try our best to salvage something
*/
2019-11-07 09:10:26 -08:00
/* fall through */
2018-12-03 12:40:13 -05:00
case APPLICATION :
/*cptr = messageGetMimeSubtype(mainMessage);
2003-08-02 22:37:52 +00:00
2020-07-29 10:26:55 -07:00
if ( ( strcasecmp ( cptr , " octet-stream " ) = = 0 ) | |
( strcasecmp ( cptr , " x-msdownload " ) = = 0 ) ) { */
2018-12-03 12:40:13 -05:00
{
fb = messageToFileblob ( mainMessage , mctx - > dir , 1 ) ;
if ( fb ) {
cli_dbgmsg ( " Saving main message as attachment \n " ) ;
if ( fileblobScanAndDestroy ( fb ) = = CL_VIRUS )
rc = VIRUS ;
mctx - > files + + ;
if ( mainMessage ! = messageIn ) {
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
} else
messageReset ( mainMessage ) ;
}
} /*else
2020-07-29 10:26:55 -07:00
cli_warnmsg ( " Discarded application not sent as attachment \n " ) ; */
2018-12-03 12:40:13 -05:00
break ;
case AUDIO :
case VIDEO :
case IMAGE :
break ;
}
if ( messages ) {
/* "can't happen" */
cli_warnmsg ( " messages != NULL \n " ) ;
2020-07-29 14:14:43 -07:00
for ( i = 0 ; i < multiparts ; i + + ) {
if ( messages [ i ] )
messageDestroy ( messages [ i ] ) ;
}
2018-12-03 12:40:13 -05:00
free ( messages ) ;
2020-07-29 14:14:43 -07:00
messages = NULL ;
2018-12-03 12:40:13 -05:00
}
}
if ( aText & & ( textIn = = NULL ) ) {
/* Look for a bounce in the text (non mime encoded) portion */
const text * t ;
/* isBounceStart() is expensive, reduce the number of calls */
2023-11-26 15:01:19 -08:00
bool lookahead_definitely_is_bounce = false ;
2018-12-03 12:40:13 -05:00
for ( t = aText ; t & & ( rc ! = VIRUS ) ; t = t - > t_next ) {
const line_t * l = t - > t_line ;
const text * lookahead , * topofbounce ;
const char * s ;
bool inheader ;
if ( l = = NULL ) {
continue ;
}
2023-11-26 15:01:19 -08:00
if ( lookahead_definitely_is_bounce )
lookahead_definitely_is_bounce = false ;
2018-12-03 12:40:13 -05:00
else if ( ! isBounceStart ( mctx , lineGetData ( l ) ) )
continue ;
lookahead = t - > t_next ;
if ( lookahead ) {
if ( isBounceStart ( mctx , lineGetData ( lookahead - > t_line ) ) ) {
2023-11-26 15:01:19 -08:00
lookahead_definitely_is_bounce = true ;
2018-12-03 12:40:13 -05:00
/* don't save worthless header lines */
continue ;
}
} else /* don't save a single liner */
break ;
/*
2020-07-29 10:26:55 -07:00
* We ' ve found what looks like the start of a bounce
* message . Only bother saving if it really is a bounce
* message , this helps to speed up scanning of ping - pong
* messages that have lots of bounces within bounces in
* them
*/
2018-12-03 12:40:13 -05:00
for ( ; lookahead ; lookahead = lookahead - > t_next ) {
l = lookahead - > t_line ;
if ( l = = NULL )
break ;
s = lineGetData ( l ) ;
if ( strncasecmp ( s , " Content-Type: " , 13 ) = = 0 ) {
/*
2020-07-29 10:26:55 -07:00
* Don ' t bother with text / plain or
* text / html
*/
2019-08-22 16:51:01 -04:00
if ( CLI_STRCASESTR ( s , " text/plain " ) ! = NULL )
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Don ' t bother to save the
* unuseful part , read past
* the headers then we ' ll go
* on to look for the next
* bounce message
*/
2018-12-03 12:40:13 -05:00
continue ;
if ( ( ! doPhishingScan ) & &
2019-08-22 16:51:01 -04:00
( CLI_STRCASESTR ( s , " text/html " ) ! = NULL ) )
2018-12-03 12:40:13 -05:00
continue ;
break ;
}
}
if ( lookahead & & ( lookahead - > t_line = = NULL ) ) {
cli_dbgmsg ( " Non mime part bounce message is not mime encoded, so it will not be scanned \n " ) ;
t = lookahead ;
/* look for next bounce message */
continue ;
}
/*
2020-07-29 10:26:55 -07:00
* Prescan the bounce message to see if there ' s likely
* to be anything nasty .
* This algorithm is hand crafted and may be breakable
* so all submissions are welcome . It ' s best NOT to
* remove this however you may be tempted , because it
* significantly speeds up the scanning of multiple
* bounces ( i . e . bounces within many bounces )
*/
2018-12-03 12:40:13 -05:00
for ( ; lookahead ; lookahead = lookahead - > t_next ) {
l = lookahead - > t_line ;
if ( l ) {
s = lineGetData ( l ) ;
if ( ( strncasecmp ( s , " Content-Type: " , 13 ) = = 0 ) & &
( strstr ( s , " multipart/ " ) = = NULL ) & &
( strstr ( s , " message/rfc822 " ) = = NULL ) & &
( strstr ( s , " text/plain " ) = = NULL ) )
break ;
}
}
if ( lookahead = = NULL ) {
cli_dbgmsg ( " cli_mbox: I believe it's plain text which must be clean \n " ) ;
/* nothing here, move along please */
break ;
}
if ( ( fb = fileblobCreate ( ) ) = = NULL )
break ;
cli_dbgmsg ( " Save non mime part bounce message \n " ) ;
fileblobSetFilename ( fb , mctx - > dir , " bounce " ) ;
fileblobAddData ( fb , ( const unsigned char * ) " Received: by clamd (bounce) \n " , 28 ) ;
fileblobSetCTX ( fb , mctx - > ctx ) ;
2021-10-20 21:10:59 -07:00
inheader = true ;
2018-12-03 12:40:13 -05:00
topofbounce = NULL ;
do {
l = t - > t_line ;
if ( l = = NULL ) {
if ( inheader ) {
2021-10-20 21:10:59 -07:00
inheader = false ;
2018-12-03 12:40:13 -05:00
topofbounce = t ;
}
} else {
s = lineGetData ( l ) ;
fileblobAddData ( fb , ( const unsigned char * ) s , strlen ( s ) ) ;
}
fileblobAddData ( fb , ( const unsigned char * ) " \n " , 1 ) ;
lookahead = t - > t_next ;
if ( lookahead = = NULL )
break ;
t = lookahead ;
l = t - > t_line ;
if ( ( ! inheader ) & & l ) {
s = lineGetData ( l ) ;
if ( isBounceStart ( mctx , s ) ) {
cli_dbgmsg ( " Found the start of another bounce candidate (%s) \n " , s ) ;
2023-11-26 15:01:19 -08:00
lookahead_definitely_is_bounce = true ;
2018-12-03 12:40:13 -05:00
break ;
}
}
} while ( ! fileblobInfected ( fb ) ) ;
if ( fileblobScanAndDestroy ( fb ) = = CL_VIRUS )
rc = VIRUS ;
mctx - > files + + ;
if ( topofbounce )
t = topofbounce ;
}
textDestroy ( aText ) ;
aText = NULL ;
}
/*
2020-07-29 10:26:55 -07:00
* No attachments - scan the text portions , often files
* are hidden in HTML code
*/
2018-12-03 12:40:13 -05:00
if ( mainMessage & & ( rc ! = VIRUS ) ) {
text * t_line ;
2006-07-04 08:40:46 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Look for uu - encoded main file
*/
2018-12-03 12:40:13 -05:00
if ( mainMessage - > body_first ! = NULL & &
( encodingLine ( mainMessage ) ! = NULL ) & &
( ( t_line = bounceBegin ( mainMessage ) ) ! = NULL ) )
rc = ( exportBounceMessage ( mctx , t_line ) = = CL_VIRUS ) ? VIRUS : OK ;
else {
bool saveIt ;
if ( messageGetMimeType ( mainMessage ) = = MESSAGE )
/*
2020-07-29 10:26:55 -07:00
* Quick peek , if the encapsulated
* message has no
* content encoding statement don ' t
* bother saving to scan , it ' s safe
*/
2018-12-03 12:40:13 -05:00
saveIt = ( bool ) ( encodingLine ( mainMessage ) ! = NULL ) ;
else if ( mainMessage - > body_last ! = NULL & & ( t_line = encodingLine ( mainMessage ) ) ! = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* Some bounces include the message
* body without the headers .
* FIXME : Unfortunately this generates a
* lot of false positives that a bounce
* has been found when it hasn ' t .
*/
2018-12-03 12:40:13 -05:00
if ( ( fb = fileblobCreate ( ) ) ! = NULL ) {
cli_dbgmsg ( " Found a bounce message with no header at '%s' \n " ,
lineGetData ( t_line - > t_line ) ) ;
fileblobSetFilename ( fb , mctx - > dir , " bounce " ) ;
fileblobAddData ( fb ,
( const unsigned char * ) " Received: by clamd (bounce) \n " ,
28 ) ;
fileblobSetCTX ( fb , mctx - > ctx ) ;
if ( fileblobScanAndDestroy ( textToFileblob ( t_line , fb , 1 ) ) = = CL_VIRUS )
rc = VIRUS ;
mctx - > files + + ;
}
2021-10-20 21:10:59 -07:00
saveIt = false ;
2018-12-03 12:40:13 -05:00
} else
/*
2020-07-29 10:26:55 -07:00
* Save the entire text portion ,
2023-11-26 15:01:19 -08:00
* since it may be an HTML file with
2020-07-29 10:26:55 -07:00
* a JavaScript virus or a phish
*/
2021-10-20 21:10:59 -07:00
saveIt = true ;
2018-12-03 12:40:13 -05:00
if ( saveIt ) {
cli_dbgmsg ( " Saving text part to scan, rc = %d \n " ,
( int ) rc ) ;
if ( saveTextPart ( mctx , mainMessage , 1 ) = = CL_VIRUS )
rc = VIRUS ;
if ( mainMessage ! = messageIn ) {
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
} else
messageReset ( mainMessage ) ;
}
}
} /*else
2020-07-29 10:26:55 -07:00
rc = OK_ATTACHMENTS_NOT_SAVED ; */
2018-12-03 12:40:13 -05:00
/* nothing saved */
if ( mainMessage & & ( mainMessage ! = messageIn ) )
messageDestroy ( mainMessage ) ;
if ( ( rc ! = FAIL ) & & infected )
rc = VIRUS ;
2006-05-03 15:41:44 +00:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2016-05-10 18:53:59 -04:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseEmailBody() returning %d \n " , ( int ) rc ) ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
return rc ;
2003-07-29 15:48:06 +00:00
}
/*
* Is the current line the start of a new section ?
*
* New sections start with - - boundary
*/
static int
boundaryStart ( const char * line , const char * boundary )
{
2018-12-03 12:40:13 -05:00
const char * ptr ;
char * out ;
int rc ;
char buf [ RFC2821LENGTH + 1 ] ;
2014-02-25 11:57:42 -05:00
char * newline ;
2004-11-11 22:18:10 +00:00
2018-12-03 12:40:13 -05:00
if ( line = = NULL | | * line = = ' \0 ' )
return 0 ; /* empty line */
if ( boundary = = NULL )
return 0 ;
2004-07-06 09:32:45 +00:00
2014-02-25 11:57:42 -05:00
newline = strdup ( line ) ;
if ( ! ( newline ) )
2014-07-10 18:11:49 -04:00
newline = ( char * ) line ;
2014-02-25 11:57:42 -05:00
2016-06-16 11:02:21 -04:00
if ( newline ! = line & & strlen ( line ) ) {
2014-02-25 11:57:42 -05:00
char * p ;
/* Trim trailing spaces */
2017-10-25 14:37:14 -04:00
p = newline + strlen ( line ) - 1 ;
2014-05-12 13:57:22 -04:00
while ( p > = newline & & * p = = ' ' )
2014-02-25 11:57:42 -05:00
* ( p - - ) = ' \0 ' ;
}
if ( newline ! = line )
cli_chomp ( newline ) ;
2004-11-11 22:18:10 +00:00
2018-12-03 12:40:13 -05:00
/* cli_dbgmsg("boundaryStart: line = '%s' boundary = '%s'\n", line, boundary); */
2014-02-25 11:57:42 -05:00
2018-12-03 12:40:13 -05:00
if ( ( * newline ! = ' - ' ) & & ( * newline ! = ' ( ' ) ) {
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-25 11:57:42 -05:00
}
2005-02-18 18:05:31 +00:00
2018-12-03 12:40:13 -05:00
if ( strchr ( newline , ' - ' ) = = NULL ) {
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-25 11:57:42 -05:00
}
2005-02-18 18:05:31 +00:00
2018-12-03 12:40:13 -05:00
if ( strlen ( newline ) < = sizeof ( buf ) ) {
out = NULL ;
ptr = rfc822comments ( newline , buf ) ;
} else
ptr = out = rfc822comments ( newline , NULL ) ;
2005-02-16 22:20:49 +00:00
2018-12-03 12:40:13 -05:00
if ( ptr = = NULL )
ptr = newline ;
2004-11-11 22:18:10 +00:00
2018-12-03 12:40:13 -05:00
if ( ( * ptr + + ! = ' - ' ) | | ( * ptr = = ' \0 ' ) ) {
if ( out )
free ( out ) ;
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
}
2004-07-06 09:32:45 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Gibe . B3 is broken , it has :
* boundary = " ---- =_NextPart_000_01C31177.9DC7C000 "
2023-11-26 15:01:19 -08:00
* but its boundaries look like
2020-07-29 10:26:55 -07:00
* - - - - - - = _NextPart_000_01C31177 .9 DC7C000
* notice the one too few ' - ' .
* Presumably this is a deliberate exploitation of a bug in some mail
* clients .
*
* The trouble is that this creates a lot of false positives for
* boundary conditions , if we ' re too lax about matches . We do our level
* best to avoid these false positives . For example if we have
* boundary = " 1 " we want to ensure that we don ' t break out of every line
* that has - 1 in it instead of starting - - 1. This needs some more work .
*
* Look with and without RFC822 comments stripped , I ' ve seen some
* samples where ( ) are taken as comments in boundaries and some where
* they ' re not . Irrespective of whatever RFC2822 says , we need to find
* viruses in both types of mails .
*/
2018-12-03 12:40:13 -05:00
if ( ( strstr ( & ptr [ 1 ] , boundary ) ! = NULL ) | | ( strstr ( newline , boundary ) ! = NULL ) ) {
const char * k = ptr ;
2007-02-15 12:29:51 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* We need to ensure that we don ' t match - - 11 = - = - = 11 when
* looking for - - 1 = - = - = 1 in well behaved headers , that ' s a
* false positive problem mentioned above
*/
2018-12-03 12:40:13 -05:00
rc = 0 ;
do
if ( strcmp ( + + k , boundary ) = = 0 ) {
rc = 1 ;
break ;
}
while ( * k = = ' - ' ) ;
if ( rc = = 0 ) {
k = & line [ 1 ] ;
do
if ( strcmp ( + + k , boundary ) = = 0 ) {
rc = 1 ;
break ;
}
while ( * k = = ' - ' ) ;
}
} else if ( * ptr + + ! = ' - ' )
rc = 0 ;
else
rc = ( strcasecmp ( ptr , boundary ) = = 0 ) ;
if ( out )
free ( out ) ;
if ( rc = = 1 )
cli_dbgmsg ( " boundaryStart: found %s in %s \n " , boundary , line ) ;
2004-11-15 13:58:50 +00:00
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return rc ;
2003-07-29 15:48:06 +00:00
}
/*
* Is the current line the end ?
*
2023-11-26 15:01:19 -08:00
* The message ends with - - boundary - -
2003-07-29 15:48:06 +00:00
*/
static int
2007-02-15 12:29:51 +00:00
boundaryEnd ( const char * line , const char * boundary )
2003-07-29 15:48:06 +00:00
{
2018-12-03 12:40:13 -05:00
size_t len ;
2014-02-25 11:57:42 -05:00
char * newline , * p , * p2 ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
if ( line = = NULL | | * line = = ' \0 ' )
return 0 ;
2007-02-15 12:29:51 +00:00
2014-02-25 11:57:42 -05:00
p = newline = strdup ( line ) ;
2014-02-27 13:44:08 -05:00
if ( ! ( newline ) ) {
2018-12-03 12:40:13 -05:00
p = ( char * ) line ;
2014-07-10 18:11:49 -04:00
newline = ( char * ) line ;
2014-02-27 13:44:08 -05:00
}
2014-02-25 11:57:42 -05:00
2016-06-16 11:02:21 -04:00
if ( newline ! = line & & strlen ( line ) ) {
2014-02-25 11:57:42 -05:00
/* Trim trailing spaces */
2017-10-25 14:37:14 -04:00
p2 = newline + strlen ( line ) - 1 ;
2014-05-12 12:51:02 -04:00
while ( p2 > = newline & & * p2 = = ' ' )
2014-02-25 11:57:42 -05:00
* ( p2 - - ) = ' \0 ' ;
}
2018-12-03 12:40:13 -05:00
/* cli_dbgmsg("boundaryEnd: line = '%s' boundary = '%s'\n", newline, boundary); */
2007-02-15 12:29:51 +00:00
2018-12-03 12:40:13 -05:00
if ( * p + + ! = ' - ' ) {
2014-02-27 15:19:34 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-27 15:19:34 -05:00
}
2018-12-03 12:40:13 -05:00
if ( * p + + ! = ' - ' ) {
2014-02-27 15:19:34 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-27 15:19:34 -05:00
}
2018-12-03 12:40:13 -05:00
len = strlen ( boundary ) ;
if ( strncasecmp ( p , boundary , len ) ! = 0 ) {
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-25 11:57:42 -05:00
}
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Use < rather than = = because some broken mails have white
* space after the boundary
*/
2018-12-03 12:40:13 -05:00
if ( strlen ( p ) < ( len + 2 ) ) {
2014-02-27 13:44:08 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-27 13:44:08 -05:00
}
2014-02-27 15:19:34 -05:00
2018-12-03 12:40:13 -05:00
p = & p [ len ] ;
if ( * p + + ! = ' - ' ) {
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2014-02-25 11:57:42 -05:00
}
2014-02-27 15:19:34 -05:00
2018-12-03 12:40:13 -05:00
if ( * p = = ' - ' ) {
/* cli_dbgmsg("boundaryEnd: found %s in %s\n", boundary, p); */
2014-02-25 11:57:42 -05:00
if ( newline ! = line )
free ( newline ) ;
2014-02-27 13:44:08 -05:00
2018-12-03 12:40:13 -05:00
return 1 ;
}
2014-02-27 12:56:46 -05:00
if ( newline ! = line )
free ( newline ) ;
2018-12-03 12:40:13 -05:00
return 0 ;
2003-07-29 15:48:06 +00:00
}
/*
* Initialise the various lookup tables
2021-10-20 21:10:59 -07:00
*
* Only initializes the tables if not already initialized .
2003-07-29 15:48:06 +00:00
*/
static int
initialiseTables ( table_t * * rfc821Table , table_t * * subtypeTable )
{
2018-12-03 12:40:13 -05:00
const struct tableinit * tableinit ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Initialise the various look up tables
*/
2021-10-20 21:10:59 -07:00
if ( NULL = = * rfc821Table ) {
* rfc821Table = tableCreate ( ) ;
if ( * rfc821Table = = NULL ) {
return - 1 ;
}
2018-12-03 12:40:13 -05:00
2021-10-20 21:10:59 -07:00
for ( tableinit = rfc821headers ; tableinit - > key ; tableinit + + ) {
if ( tableInsert ( * rfc821Table , tableinit - > key , tableinit - > value ) < 0 ) {
tableDestroy ( * rfc821Table ) ;
* rfc821Table = NULL ;
return - 1 ;
}
}
}
if ( NULL = = * subtypeTable ) {
* subtypeTable = tableCreate ( ) ;
if ( * subtypeTable = = NULL ) {
2018-12-03 12:40:13 -05:00
tableDestroy ( * rfc821Table ) ;
* rfc821Table = NULL ;
return - 1 ;
}
2021-10-20 21:10:59 -07:00
for ( tableinit = mimeSubtypes ; tableinit - > key ; tableinit + + ) {
if ( tableInsert ( * subtypeTable , tableinit - > key , tableinit - > value ) < 0 ) {
tableDestroy ( * rfc821Table ) ;
tableDestroy ( * subtypeTable ) ;
* rfc821Table = NULL ;
* subtypeTable = NULL ;
return - 1 ;
}
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
}
2018-12-03 12:40:13 -05:00
return 0 ;
2003-07-29 15:48:06 +00:00
}
/*
2003-08-02 22:37:52 +00:00
* If there ' s a HTML text version use that , otherwise
2003-07-29 15:48:06 +00:00
* use the first text part , otherwise just use the
2003-08-02 22:37:52 +00:00
* first one around . HTML text is most likely to include
* a scripting worm
2003-07-29 15:48:06 +00:00
*
* If we can ' t find one , return - 1
*/
static int
getTextPart ( message * const messages [ ] , size_t size )
{
2018-12-03 12:40:13 -05:00
size_t i ;
int textpart = - 1 ;
2003-07-29 15:48:06 +00:00
2018-12-03 12:40:13 -05:00
for ( i = 0 ; i < size ; i + + )
if ( messages [ i ] & & ( messageGetMimeType ( messages [ i ] ) = = TEXT ) ) {
if ( strcasecmp ( messageGetMimeSubtype ( messages [ i ] ) , " html " ) = = 0 )
return ( int ) i ;
textpart = ( int ) i ;
}
2007-09-15 09:00:57 +00:00
2018-12-03 12:40:13 -05:00
return textpart ;
2003-07-29 15:48:06 +00:00
}
/*
* strip -
2020-07-29 10:26:55 -07:00
* Remove the trailing spaces from a buffer . Don ' t call this directly ,
2004-09-18 15:03:15 +00:00
* always call strstrip ( ) which is a wrapper to this routine to be used with
2023-11-26 15:01:19 -08:00
* NUL terminated strings . This code looks a bit strange because of its
2004-09-18 15:03:15 +00:00
* heritage from code that worked on strings that weren ' t necessarily NUL
* terminated .
* TODO : rewrite for clamAV
*
2023-11-26 15:01:19 -08:00
* Returns its new length ( a la strlen )
2003-07-29 15:48:06 +00:00
*
* len must be int not size_t because of the > = 0 test , it is sizeof ( buf )
2020-07-29 10:26:55 -07:00
* not strlen ( buf )
2003-07-29 15:48:06 +00:00
*/
static size_t
strip ( char * buf , int len )
{
2018-12-03 12:40:13 -05:00
register char * ptr ;
register size_t i ;
if ( ( buf = = NULL ) | | ( len < = 0 ) )
return 0 ;
i = strlen ( buf ) ;
if ( len > ( int ) ( i + 1 ) )
return i ;
ptr = & buf [ - - len ] ;
# if defined(UNIX) || defined(C_LINUX) || defined(C_DARWIN) /* watch - it may be in shared text area */
do
if ( * ptr )
* ptr = ' \0 ' ;
while ( ( - - len > = 0 ) & & ( ! isgraph ( * - - ptr ) ) & & ( * ptr ! = ' \n ' ) & & ( * ptr ! = ' \r ' ) ) ;
# else /* more characters can be displayed on DOS */
do
# ifndef REAL_MODE_DOS
if ( * ptr ) /* C8.0 puts into a text area */
2003-07-29 15:48:06 +00:00
# endif
2018-12-03 12:40:13 -05:00
* ptr = ' \0 ' ;
while ( ( - - len > = 0 ) & & ( ( * - - ptr = = ' \0 ' ) | | isspace ( ( int ) ( * ptr & 0xFF ) ) ) ) ;
2003-07-29 15:48:06 +00:00
# endif
2018-12-03 12:40:13 -05:00
return ( ( size_t ) ( len + 1 ) ) ;
2003-07-29 15:48:06 +00:00
}
/*
* strstrip :
2020-07-29 10:26:55 -07:00
* Strip a given string
2003-07-29 15:48:06 +00:00
*/
2004-04-29 09:01:16 +00:00
size_t
2003-07-29 15:48:06 +00:00
strstrip ( char * s )
{
2018-12-03 12:40:13 -05:00
if ( s = = ( char * ) NULL )
return ( 0 ) ;
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
return ( strip ( s , strlen ( s ) + 1 ) ) ;
2003-07-29 15:48:06 +00:00
}
2007-09-11 10:22:49 +00:00
/*
* Returns 0 for OK , - 1 for error
*/
2003-07-29 15:48:06 +00:00
static int
2019-11-07 09:10:26 -08:00
parseMimeHeader ( message * m , const char * cmd , const table_t * rfc821Table , const char * arg , cli_ctx * ctx , bool * heuristicFound )
2003-07-29 15:48:06 +00:00
{
2018-12-03 12:40:13 -05:00
char * copy , * p , * buf ;
const char * ptr ;
int commandNumber ;
2019-11-07 09:10:26 -08:00
size_t argCnt = 0 ;
2021-10-20 21:10:59 -07:00
* heuristicFound = false ;
2004-08-11 14:48:13 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " parseMimeHeader: cmd='%s', arg='%s' \n " , cmd , arg ) ;
2004-09-16 08:58:56 +00:00
2018-12-03 12:40:13 -05:00
copy = rfc822comments ( cmd , NULL ) ;
if ( copy ) {
commandNumber = tableFind ( rfc821Table , copy ) ;
free ( copy ) ;
2019-11-07 09:10:26 -08:00
} else {
2018-12-03 12:40:13 -05:00
commandNumber = tableFind ( rfc821Table , cmd ) ;
2019-11-07 09:10:26 -08:00
}
2004-09-16 08:58:56 +00:00
2018-12-03 12:40:13 -05:00
copy = rfc822comments ( arg , NULL ) ;
2003-07-29 15:48:06 +00:00
2019-11-07 09:10:26 -08:00
if ( copy ) {
2018-12-03 12:40:13 -05:00
ptr = copy ;
2019-11-07 09:10:26 -08:00
} else {
2018-12-03 12:40:13 -05:00
ptr = arg ;
2019-11-07 09:10:26 -08:00
}
2004-11-07 16:59:42 +00:00
2018-12-03 12:40:13 -05:00
buf = NULL ;
2007-09-11 10:22:49 +00:00
2018-12-03 12:40:13 -05:00
switch ( commandNumber ) {
case CONTENT_TYPE :
/*
2020-07-29 10:26:55 -07:00
* Fix for non RFC1521 compliant mailers
* that send content - type : Text instead
* of content - type : Text / Plain , or
* just simply " Content-Type: "
*/
2018-12-03 12:40:13 -05:00
if ( arg = = NULL )
/*
2020-07-29 10:26:55 -07:00
* According to section 4 of RFC1521 :
* " Note also that a subtype specification is
* MANDATORY . There are no default subtypes "
*
* We have to break this and make an assumption
* for the subtype because virus writers and
* email client writers don ' t get it right
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Empty content-type received, no subtype specified, assuming text/plain; charset=us-ascii \n " ) ;
else if ( strchr ( ptr , ' / ' ) = = NULL )
/*
2020-07-29 10:26:55 -07:00
* Empty field , such as
* Content - Type :
* which I believe is illegal according to
* RFC1521
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Invalid content-type '%s' received, no subtype specified, assuming text/plain; charset=us-ascii \n " , ptr ) ;
else {
int i ;
2004-09-17 10:57:56 +00:00
2022-05-09 14:28:34 -07:00
buf = cli_max_malloc ( strlen ( ptr ) + 1 ) ;
2018-12-03 12:40:13 -05:00
if ( buf = = NULL ) {
2016-02-22 13:26:15 -05:00
cli_errmsg ( " parseMimeHeader: Unable to allocate memory for buf %llu \n " , ( long long unsigned ) ( strlen ( ptr ) + 1 ) ) ;
2018-12-03 12:40:13 -05:00
if ( copy )
free ( copy ) ;
return - 1 ;
}
/*
2020-07-29 10:26:55 -07:00
* Some clients are broken and
* put white space after the ;
*/
2018-12-03 12:40:13 -05:00
if ( * arg = = ' / ' ) {
cli_dbgmsg ( " Content-type '/' received, assuming application/octet-stream \n " ) ;
messageSetMimeType ( m , " application " ) ;
messageSetMimeSubtype ( m , " octet-stream " ) ;
} else {
/*
2020-07-29 10:26:55 -07:00
* The content type could be in quotes :
* Content - Type : " multipart/mixed "
* FIXME : this is a hack in that ignores
* the quotes , it doesn ' t handle
* them properly
*/
2020-12-07 15:18:29 -08:00
while ( isspace ( ( const unsigned char ) * ptr ) )
2018-12-03 12:40:13 -05:00
ptr + + ;
if ( ptr [ 0 ] = = ' \" ' )
ptr + + ;
2004-09-16 14:26:20 +00:00
2018-12-03 12:40:13 -05:00
if ( ptr [ 0 ] ! = ' / ' ) {
char * s ;
2004-11-27 21:56:41 +00:00
# ifdef CL_THREAD_SAFE
2018-12-03 12:40:13 -05:00
char * strptr = NULL ;
2004-11-27 21:56:41 +00:00
# endif
2004-09-20 08:31:56 +00:00
2018-12-03 12:40:13 -05:00
s = cli_strtokbuf ( ptr , 0 , " ; " , buf ) ;
/*
2020-07-29 10:26:55 -07:00
* Handle
* Content - Type : foo / bar multipart / mixed
* and
* Content - Type : multipart / mixed foo / bar
*/
2018-12-03 12:40:13 -05:00
if ( s & & * s ) {
2024-01-09 17:44:33 -05:00
char * buf2 = cli_safer_strdup ( buf ) ;
2018-12-03 12:40:13 -05:00
if ( buf2 = = NULL ) {
if ( copy )
free ( copy ) ;
free ( buf ) ;
return - 1 ;
}
for ( ; ; ) {
# ifdef CL_THREAD_SAFE
int set = messageSetMimeType ( m , strtok_r ( s , " / " , & strptr ) ) ;
2004-09-21 08:16:29 +00:00
# else
2018-12-03 12:40:13 -05:00
int set = messageSetMimeType ( m , strtok ( s , " / " ) ) ;
2004-09-21 08:16:29 +00:00
# endif
2004-09-17 10:57:56 +00:00
2018-12-03 12:40:13 -05:00
# ifdef CL_THREAD_SAFE
s = strtok_r ( NULL , " ; " , & strptr ) ;
2004-09-21 08:16:29 +00:00
# else
2024-04-13 14:39:19 -04:00
s = strtok ( NULL , " ; " ) ;
2007-09-17 16:59:02 +00:00
# endif
2018-12-03 12:40:13 -05:00
if ( s = = NULL )
break ;
if ( set ) {
size_t len = strstrip ( s ) - 1 ;
if ( s [ len ] = = ' \" ' ) {
s [ len ] = ' \0 ' ;
len = strstrip ( s ) ;
}
if ( len ) {
if ( strchr ( s , ' ' ) )
messageSetMimeSubtype ( m ,
cli_strtokbuf ( s , 0 , " " , buf2 ) ) ;
else
messageSetMimeSubtype ( m , s ) ;
}
}
2020-12-07 15:18:29 -08:00
while ( * s & & ! isspace ( ( unsigned char ) * s ) )
2018-12-03 12:40:13 -05:00
s + + ;
if ( * s + + = = ' \0 ' )
break ;
if ( * s = = ' \0 ' )
break ;
}
free ( buf2 ) ;
}
}
}
/*
2023-11-26 15:01:19 -08:00
* Add in all rest of the arguments .
2020-07-29 10:26:55 -07:00
* e . g . if the header is this :
* Content - Type : ' , arg = ' multipart / mixed ; boundary = foo
* we find the boundary argument set it
*/
2018-12-03 12:40:13 -05:00
i = 1 ;
while ( cli_strtokbuf ( ptr , i + + , " ; " , buf ) ! = NULL ) {
cli_dbgmsg ( " mimeArgs = '%s' \n " , buf ) ;
2019-11-07 09:10:26 -08:00
argCnt + + ;
2019-05-23 22:50:04 -04:00
if ( haveTooManyMIMEArguments ( argCnt , ctx , heuristicFound ) ) {
2019-11-07 09:10:26 -08:00
break ;
}
2018-12-03 12:40:13 -05:00
messageAddArguments ( m , buf ) ;
}
}
break ;
case CONTENT_TRANSFER_ENCODING :
messageSetEncoding ( m , ptr ) ;
break ;
case CONTENT_DISPOSITION :
2022-05-09 14:28:34 -07:00
buf = cli_max_malloc ( strlen ( ptr ) + 1 ) ;
2018-12-03 12:40:13 -05:00
if ( buf = = NULL ) {
2016-02-22 13:26:15 -05:00
cli_errmsg ( " parseMimeHeader: Unable to allocate memory for buf %llu \n " , ( long long unsigned ) ( strlen ( ptr ) + 1 ) ) ;
2018-12-03 12:40:13 -05:00
if ( copy )
free ( copy ) ;
return - 1 ;
}
p = cli_strtokbuf ( ptr , 0 , " ; " , buf ) ;
if ( p & & * p ) {
messageSetDispositionType ( m , p ) ;
messageAddArgument ( m , cli_strtokbuf ( ptr , 1 , " ; " , buf ) ) ;
}
if ( ! messageHasFilename ( m ) )
/*
2020-07-29 10:26:55 -07:00
* Handle this type of header , without
* a filename ( e . g . some Worm . Torvil . D )
* Content - ID : < nRfkHdrKsAxRU >
* Content - Transfer - Encoding : base64
* Content - Disposition : attachment
*/
2018-12-03 12:40:13 -05:00
messageAddArgument ( m , " filename=unknown " ) ;
}
if ( copy )
free ( copy ) ;
if ( buf )
free ( buf ) ;
return 0 ;
2003-07-29 15:48:06 +00:00
}
2004-01-28 10:16:51 +00:00
/*
* Save the text portion of the message
*/
2007-09-04 09:43:40 +00:00
static int
2007-10-30 17:26:29 +00:00
saveTextPart ( mbox_ctx * mctx , message * m , int destroy_text )
2004-01-28 10:16:51 +00:00
{
2018-12-03 12:40:13 -05:00
fileblob * fb ;
2004-01-28 10:16:51 +00:00
2018-12-03 12:40:13 -05:00
messageAddArgument ( m , " filename=textportion " ) ;
if ( ( fb = messageToFileblob ( m , mctx - > dir , destroy_text ) ) ! = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* Save main part to scan that
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Saving main message \n " ) ;
2004-01-28 10:16:51 +00:00
2018-12-03 12:40:13 -05:00
mctx - > files + + ;
return fileblobScanAndDestroy ( fb ) ;
}
return CL_ETMPFILE ;
2004-01-28 10:16:51 +00:00
}
2004-09-17 09:11:06 +00:00
/*
2004-09-20 08:31:56 +00:00
* Handle RFC822 comments in headers .
2005-02-16 22:20:49 +00:00
* If out = = NULL , return a buffer without the comments , the caller must free
2020-07-29 10:26:55 -07:00
* the returned buffer
2005-02-16 22:20:49 +00:00
* Return NULL on error or if the input * has no comments .
2018-02-21 15:00:59 -05:00
* See section 3.4 .3 of RFC822
2004-09-17 09:11:06 +00:00
* TODO : handle comments that go on to more than one line
*/
static char *
2005-02-16 22:20:49 +00:00
rfc822comments ( const char * in , char * out )
2004-09-17 09:11:06 +00:00
{
2018-12-03 12:40:13 -05:00
const char * iptr ;
char * optr ;
int backslash , inquote , commentlevel ;
2004-09-17 09:11:06 +00:00
2021-10-20 21:10:59 -07:00
if ( in = = NULL | | out = = in ) {
cli_errmsg ( " rfc822comments: Invalid parameters.n " ) ;
2018-12-03 12:40:13 -05:00
return NULL ;
2021-10-20 21:10:59 -07:00
}
2004-09-17 09:11:06 +00:00
2021-10-20 21:10:59 -07:00
if ( strchr ( in , ' ( ' ) = = NULL ) {
2018-12-03 12:40:13 -05:00
return NULL ;
2021-10-20 21:10:59 -07:00
}
2004-09-17 09:11:06 +00:00
2021-10-20 21:10:59 -07:00
while ( isspace ( ( const unsigned char ) * in ) ) {
2018-12-03 12:40:13 -05:00
in + + ;
2021-10-20 21:10:59 -07:00
}
2007-12-17 20:22:11 +00:00
2018-12-03 12:40:13 -05:00
if ( out = = NULL ) {
2022-05-09 14:28:34 -07:00
out = cli_max_malloc ( strlen ( in ) + 1 ) ;
2018-12-03 12:40:13 -05:00
if ( out = = NULL ) {
2016-02-22 13:26:15 -05:00
cli_errmsg ( " rfc822comments: Unable to allocate memory for out %llu \n " , ( long long unsigned ) ( strlen ( in ) + 1 ) ) ;
2018-12-03 12:40:13 -05:00
return NULL ;
2013-03-01 13:51:15 -05:00
}
2018-12-03 12:40:13 -05:00
}
backslash = commentlevel = inquote = 0 ;
optr = out ;
cli_dbgmsg ( " rfc822comments: contains a comment \n " ) ;
for ( iptr = in ; * iptr ; iptr + + )
if ( backslash ) {
if ( commentlevel = = 0 )
* optr + + = * iptr ;
backslash = 0 ;
} else
switch ( * iptr ) {
case ' \\ ' :
backslash = 1 ;
break ;
case ' \" ' :
* optr + + = ' \" ' ;
inquote = ! inquote ;
break ;
case ' ( ' :
if ( inquote )
* optr + + = ' ( ' ;
else
commentlevel + + ;
break ;
case ' ) ' :
if ( inquote )
* optr + + = ' ) ' ;
else if ( commentlevel > 0 )
commentlevel - - ;
break ;
default :
if ( commentlevel = = 0 )
* optr + + = * iptr ;
}
if ( backslash ) /* last character was a single backslash */
* optr + + = ' \\ ' ;
* optr = ' \0 ' ;
/*strstrip(out);*/
cli_dbgmsg ( " rfc822comments '%s'=>'%s' \n " , in , out ) ;
return out ;
2004-09-17 09:11:06 +00:00
}
2004-09-16 18:03:25 +00:00
/*
* Handle RFC2047 encoding . Returns a malloc ' d buffer that the caller must
* free , or NULL on error
*/
static char *
rfc2047 ( const char * in )
{
2018-12-03 12:40:13 -05:00
char * out , * pout ;
size_t len ;
2004-09-16 18:03:25 +00:00
2018-12-03 12:40:13 -05:00
if ( ( strstr ( in , " =? " ) = = NULL ) | | ( strstr ( in , " ?= " ) = = NULL ) )
2024-01-09 17:44:33 -05:00
return cli_safer_strdup ( in ) ;
2004-09-16 18:03:25 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " rfc2047 '%s' \n " , in ) ;
2022-05-09 14:28:34 -07:00
out = cli_max_malloc ( strlen ( in ) + 1 ) ;
2004-09-16 18:03:25 +00:00
2018-12-03 12:40:13 -05:00
if ( out = = NULL ) {
2016-02-22 13:26:15 -05:00
cli_errmsg ( " rfc2047: Unable to allocate memory for out %llu \n " , ( long long unsigned ) ( strlen ( in ) + 1 ) ) ;
2018-12-03 12:40:13 -05:00
return NULL ;
2013-03-01 13:51:15 -05:00
}
2004-09-16 18:03:25 +00:00
2018-12-03 12:40:13 -05:00
pout = out ;
/* For each RFC2047 string */
while ( * in ) {
char encoding , * ptr , * enctext ;
message * m ;
blob * b ;
/* Find next RFC2047 string */
while ( * in ) {
if ( ( * in = = ' = ' ) & & ( in [ 1 ] = = ' ? ' ) ) {
in + = 2 ;
break ;
}
* pout + + = * in + + ;
}
/* Skip over charset, find encoding */
while ( ( * in ! = ' ? ' ) & & * in )
in + + ;
if ( * in = = ' \0 ' )
break ;
encoding = * + + in ;
encoding = ( char ) tolower ( encoding ) ;
if ( ( encoding ! = ' q ' ) & & ( encoding ! = ' b ' ) ) {
cli_warnmsg ( " Unsupported RFC2047 encoding type '%c' - if you believe this file contains a virus, submit it to www.clamav.net \n " , encoding ) ;
free ( out ) ;
out = NULL ;
break ;
}
/* Skip to encoded text */
if ( * + + in ! = ' ? ' )
break ;
if ( * + + in = = ' \0 ' )
break ;
2024-01-09 17:44:33 -05:00
enctext = cli_safer_strdup ( in ) ;
2018-12-03 12:40:13 -05:00
if ( enctext = = NULL ) {
free ( out ) ;
out = NULL ;
break ;
}
in = strstr ( in , " ?= " ) ;
if ( in = = NULL ) {
free ( enctext ) ;
break ;
}
in + = 2 ;
ptr = strstr ( enctext , " ?= " ) ;
2021-10-20 21:10:59 -07:00
if ( NULL = = ptr ) {
free ( enctext ) ;
break ;
}
2018-12-03 12:40:13 -05:00
* ptr = ' \0 ' ;
/*cli_dbgmsg("Need to decode '%s' with method '%c'\n", enctext, encoding);*/
m = messageCreate ( ) ;
2018-11-14 16:58:30 -05:00
if ( m = = NULL ) {
free ( enctext ) ;
2018-12-03 12:40:13 -05:00
break ;
2018-11-14 16:58:30 -05:00
}
2018-12-03 12:40:13 -05:00
messageAddStr ( m , enctext ) ;
2021-10-20 21:10:59 -07:00
2018-12-03 12:40:13 -05:00
free ( enctext ) ;
2021-10-20 21:10:59 -07:00
enctext = NULL ;
2018-12-03 12:40:13 -05:00
switch ( encoding ) {
case ' q ' :
messageSetEncoding ( m , " quoted-printable " ) ;
break ;
case ' b ' :
messageSetEncoding ( m , " base64 " ) ;
break ;
}
b = messageToBlob ( m , 1 ) ;
if ( b = = NULL ) {
messageDestroy ( m ) ;
break ;
}
len = blobGetDataSize ( b ) ;
cli_dbgmsg ( " Decoded as '%*.*s' \n " , ( int ) len , ( int ) len ,
( const char * ) blobGetData ( b ) ) ;
memcpy ( pout , blobGetData ( b ) , len ) ;
blobDestroy ( b ) ;
messageDestroy ( m ) ;
if ( len > 0 & & pout [ len - 1 ] = = ' \n ' )
pout + = len - 1 ;
else
pout + = len ;
}
if ( out = = NULL )
return NULL ;
* pout = ' \0 ' ;
cli_dbgmsg ( " rfc2047 returns '%s' \n " , out ) ;
return out ;
2004-09-16 18:03:25 +00:00
}
2004-10-05 15:48:47 +00:00
/*
* Handle partial messages
*/
static int
2019-05-23 22:50:04 -04:00
rfc1341 ( mbox_ctx * mctx , message * m )
2004-10-05 15:48:47 +00:00
{
2018-12-03 12:40:13 -05:00
char * arg , * id , * number , * total , * oldfilename ;
2019-05-23 22:50:04 -04:00
const char * tmpdir = NULL ;
2018-12-03 12:40:13 -05:00
int n ;
Improve tmp sub-directory names
At present many parsers create tmp subdirectories to store extracted
files. For parsers like the vba parser, this is required as the
directory is later scanned. For other parsers, these subdirectories are
probably not helpful now that we provide recursive sub-dirs when
--leave-temps is enabled. It's not quite as simple as removing the extra
subdirectories, however. Certain parsers, like autoit, don't create very
unique filenames and would result in file name collisions when
--leave-temps is not enabled.
The best thing to do would be to make sure each parser uses unique
filenames and doesn't rely on cli_magic_scan_dir() to scan extracted
content before removing the extra subdirectory. In the meantime, this
commit gives the extra subdirectories meaningful names to improve
readability.
This commit also:
- Provides the 'bmp' prefix for extracted PE icons.
- Removes empty tmp subdirs when extracting rtf files, to eliminate
clutter.
- The PDF parser sometimes creates tmp files when decompressing streams
before it knows if there is actually any content to decompress. This
resulted in a large number of empty files. While it would be best to
avoid creating empty files in the first place, that's not quite as
as it sounds. This commit does the next best thing and deletes the
tmp files if nothing was actually extracted, even if --leave-temps is
enabled.
- Removes the "scantemp" prefix for unnamed fmaps scanned with
cli_magic_scan(). The 5-character hashes given to tmp files with
prefixes resulted in occasional file name collisions when extracting
certain file types with thousands of embedded files.
- The VBA and TAR parsers mistakenly used NAME_MAX instead of PATH_MAX,
resulting in truncated file paths and failed extraction when
--leave-temps is enabled and a lot of recursion is in play. This commit
switches them from NAME_MAX to PATH_MAX.
2020-03-27 16:06:22 -04:00
char pdir [ PATH_MAX + 1 ] ;
2018-12-03 12:40:13 -05:00
unsigned char md5_val [ 16 ] ;
char * md5_hex ;
2019-05-23 22:50:04 -04:00
if ( ( NULL = = mctx ) | | ( NULL = = m ) ) {
cli_dbgmsg ( " rfc1341: Invalid NULL arguments \n " ) ;
return - 1 ;
}
2018-12-03 12:40:13 -05:00
id = ( char * ) messageFindArgument ( m , " id " ) ;
2019-05-23 22:50:04 -04:00
if ( id = = NULL ) {
2018-12-03 12:40:13 -05:00
return - 1 ;
2019-05-23 22:50:04 -04:00
}
2018-12-03 12:40:13 -05:00
2019-05-23 22:50:04 -04:00
if ( NULL ! = mctx - > ctx ) {
tmpdir = cl_engine_get_str ( ( const struct cl_engine * ) mctx - > ctx - > engine , CL_ENGINE_TMPDIR , NULL ) ;
}
if ( NULL = = tmpdir ) {
tmpdir = cli_gettmpdir ( ) ;
}
2018-12-03 12:40:13 -05:00
snprintf ( pdir , sizeof ( pdir ) - 1 , " %s " PATHSEP " clamav-partial " , tmpdir ) ;
2020-03-30 20:42:44 -04:00
if ( ( mkdir ( pdir , S_IRUSR | S_IWUSR ) < 0 ) & & ( errno ! = EEXIST ) ) {
2018-12-03 12:40:13 -05:00
cli_errmsg ( " Can't create the directory '%s' \n " , pdir ) ;
free ( id ) ;
return - 1 ;
} else if ( errno = = EEXIST ) {
STATBUF statb ;
if ( CLAMSTAT ( pdir , & statb ) < 0 ) {
char err [ 128 ] ;
cli_errmsg ( " Partial directory %s: %s \n " , pdir ,
cli_strerror ( errno , err , sizeof ( err ) ) ) ;
free ( id ) ;
return - 1 ;
}
if ( statb . st_mode & 077 )
cli_warnmsg ( " Insecure partial directory %s (mode 0%o) \n " ,
pdir ,
# ifdef ACCESSPERMS
( int ) ( statb . st_mode & ACCESSPERMS )
2007-09-04 16:34:00 +00:00
# else
2018-12-03 12:40:13 -05:00
( int ) ( statb . st_mode & 0777 )
2007-09-04 16:34:00 +00:00
# endif
2018-12-03 12:40:13 -05:00
) ;
}
number = ( char * ) messageFindArgument ( m , " number " ) ;
if ( number = = NULL ) {
free ( id ) ;
return - 1 ;
}
oldfilename = messageGetFilename ( m ) ;
2022-05-09 14:28:34 -07:00
arg = cli_max_malloc ( 10 + strlen ( id ) + strlen ( number ) ) ;
2018-12-03 12:40:13 -05:00
if ( arg ) {
sprintf ( arg , " filename=%s%s " , id , number ) ;
messageAddArgument ( m , arg ) ;
free ( arg ) ;
}
if ( oldfilename ) {
cli_dbgmsg ( " Must reset to %s \n " , oldfilename ) ;
free ( oldfilename ) ;
}
n = atoi ( number ) ;
2014-02-08 01:42:41 -05:00
cl_hash_data ( " md5 " , id , strlen ( id ) , md5_val , NULL ) ;
2018-12-03 12:40:13 -05:00
md5_hex = cli_str2hex ( ( const char * ) md5_val , 16 ) ;
if ( ! md5_hex ) {
free ( id ) ;
free ( number ) ;
return CL_EMEM ;
}
if ( messageSavePartial ( m , pdir , md5_hex , n ) < 0 ) {
free ( md5_hex ) ;
free ( id ) ;
free ( number ) ;
return - 1 ;
}
total = ( char * ) messageFindArgument ( m , " total " ) ;
cli_dbgmsg ( " rfc1341: %s, %s of %s \n " , id , number , ( total ) ? total : " ? " ) ;
if ( total ) {
int t = atoi ( total ) ;
DIR * dd = NULL ;
free ( total ) ;
/*
2020-07-29 10:26:55 -07:00
* If it ' s the last one - reassemble it
* FIXME : this assumes that we receive the parts in order
*/
2018-12-03 12:40:13 -05:00
if ( ( n = = t ) & & ( ( dd = opendir ( pdir ) ) ! = NULL ) ) {
FILE * fout ;
Improve tmp sub-directory names
At present many parsers create tmp subdirectories to store extracted
files. For parsers like the vba parser, this is required as the
directory is later scanned. For other parsers, these subdirectories are
probably not helpful now that we provide recursive sub-dirs when
--leave-temps is enabled. It's not quite as simple as removing the extra
subdirectories, however. Certain parsers, like autoit, don't create very
unique filenames and would result in file name collisions when
--leave-temps is not enabled.
The best thing to do would be to make sure each parser uses unique
filenames and doesn't rely on cli_magic_scan_dir() to scan extracted
content before removing the extra subdirectory. In the meantime, this
commit gives the extra subdirectories meaningful names to improve
readability.
This commit also:
- Provides the 'bmp' prefix for extracted PE icons.
- Removes empty tmp subdirs when extracting rtf files, to eliminate
clutter.
- The PDF parser sometimes creates tmp files when decompressing streams
before it knows if there is actually any content to decompress. This
resulted in a large number of empty files. While it would be best to
avoid creating empty files in the first place, that's not quite as
as it sounds. This commit does the next best thing and deletes the
tmp files if nothing was actually extracted, even if --leave-temps is
enabled.
- Removes the "scantemp" prefix for unnamed fmaps scanned with
cli_magic_scan(). The 5-character hashes given to tmp files with
prefixes resulted in occasional file name collisions when extracting
certain file types with thousands of embedded files.
- The VBA and TAR parsers mistakenly used NAME_MAX instead of PATH_MAX,
resulting in truncated file paths and failed extraction when
--leave-temps is enabled and a lot of recursion is in play. This commit
switches them from NAME_MAX to PATH_MAX.
2020-03-27 16:06:22 -04:00
char outname [ PATH_MAX + 1 ] ;
2018-12-03 12:40:13 -05:00
time_t now ;
sanitiseName ( id ) ;
2019-05-23 22:50:04 -04:00
snprintf ( outname , sizeof ( outname ) - 1 , " %s " PATHSEP " %s " , mctx - > dir , id ) ;
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " outname: %s \n " , outname ) ;
fout = fopen ( outname , " wb " ) ;
if ( fout = = NULL ) {
cli_errmsg ( " Can't open '%s' for writing " , outname ) ;
free ( id ) ;
free ( number ) ;
free ( md5_hex ) ;
closedir ( dd ) ;
return - 1 ;
}
time ( & now ) ;
for ( n = 1 ; n < = t ; n + + ) {
char filename [ NAME_MAX + 1 ] ;
struct dirent * dent ;
2004-10-05 15:48:47 +00:00
2018-12-03 12:40:13 -05:00
snprintf ( filename , sizeof ( filename ) , " _%s-%u " , md5_hex , n ) ;
2004-10-21 10:18:40 +00:00
2018-12-03 12:40:13 -05:00
while ( ( dent = readdir ( dd ) ) ) {
FILE * fin ;
2021-04-06 10:06:04 -07:00
char buffer [ BUFSIZ ] , fullname [ PATH_MAX + 1 + 256 + 1 ] ;
2018-12-03 12:40:13 -05:00
int nblanks ;
STATBUF statb ;
const char * dentry_idpart ;
2012-07-09 10:59:49 -04:00
int test_fd ;
2009-09-24 16:08:52 +02:00
2018-12-03 12:40:13 -05:00
if ( dent - > d_ino = = 0 )
continue ;
2004-10-05 15:48:47 +00:00
2018-12-03 12:40:13 -05:00
if ( ! strcmp ( " . " , dent - > d_name ) | |
! strcmp ( " .. " , dent - > d_name ) )
continue ;
snprintf ( fullname , sizeof ( fullname ) - 1 ,
" %s " PATHSEP " %s " , pdir , dent - > d_name ) ;
dentry_idpart = strchr ( dent - > d_name , ' _ ' ) ;
2006-01-22 20:24:33 +00:00
2018-12-03 12:40:13 -05:00
if ( ! dentry_idpart | |
strcmp ( filename , dentry_idpart ) ! = 0 ) {
if ( ! m - > ctx - > engine - > keeptmp )
continue ;
2012-07-09 10:59:49 -04:00
2020-12-07 15:18:29 -08:00
if ( ( test_fd = open ( fullname , O_RDONLY | O_BINARY ) ) < 0 )
2012-07-09 10:59:49 -04:00
continue ;
2018-12-03 12:40:13 -05:00
if ( FSTAT ( test_fd , & statb ) < 0 ) {
2012-07-09 10:59:49 -04:00
close ( test_fd ) ;
2018-12-03 12:40:13 -05:00
continue ;
2012-07-09 10:59:49 -04:00
}
2018-12-03 12:40:13 -05:00
if ( now - statb . st_mtime > ( time_t ) ( 7 * 24 * 3600 ) ) {
if ( cli_unlink ( fullname ) ) {
cli_unlink ( outname ) ;
fclose ( fout ) ;
free ( md5_hex ) ;
free ( id ) ;
free ( number ) ;
closedir ( dd ) ;
2012-07-09 10:59:49 -04:00
close ( test_fd ) ;
2018-12-03 12:40:13 -05:00
return - 1 ;
}
}
2012-07-09 10:59:49 -04:00
close ( test_fd ) ;
2018-12-03 12:40:13 -05:00
continue ;
}
fin = fopen ( fullname , " rb " ) ;
if ( fin = = NULL ) {
cli_errmsg ( " Can't open '%s' for reading " , fullname ) ;
fclose ( fout ) ;
cli_unlink ( outname ) ;
free ( md5_hex ) ;
free ( id ) ;
free ( number ) ;
closedir ( dd ) ;
return - 1 ;
}
nblanks = 0 ;
while ( fgets ( buffer , sizeof ( buffer ) - 1 , fin ) ! = NULL )
/*
2020-07-29 10:26:55 -07:00
* Ensure that trailing newlines
* aren ' t copied
*/
2018-12-03 12:40:13 -05:00
if ( buffer [ 0 ] = = ' \n ' )
nblanks + + ;
else {
if ( nblanks )
do {
if ( putc ( ' \n ' , fout ) = = EOF ) break ;
} while ( - - nblanks > 0 ) ;
if ( nblanks | | fputs ( buffer , fout ) = = EOF ) {
fclose ( fin ) ;
fclose ( fout ) ;
cli_unlink ( outname ) ;
free ( md5_hex ) ;
free ( id ) ;
free ( number ) ;
closedir ( dd ) ;
return - 1 ;
}
}
fclose ( fin ) ;
/* don't unlink if leave temps */
if ( ! m - > ctx - > engine - > keeptmp ) {
if ( cli_unlink ( fullname ) ) {
fclose ( fout ) ;
cli_unlink ( outname ) ;
free ( md5_hex ) ;
free ( id ) ;
free ( number ) ;
closedir ( dd ) ;
return - 1 ;
}
}
break ;
}
rewinddir ( dd ) ;
}
closedir ( dd ) ;
fclose ( fout ) ;
}
}
free ( number ) ;
free ( id ) ;
free ( md5_hex ) ;
return 0 ;
2004-10-05 15:48:47 +00:00
}
2006-09-13 21:40:03 +00:00
static void
hrefs_done ( blob * b , tag_arguments_t * hrefs )
{
2018-12-03 12:40:13 -05:00
if ( b )
blobDestroy ( b ) ;
html_tag_arg_free ( hrefs ) ;
2006-09-13 21:40:03 +00:00
}
2009-04-02 20:36:22 +00:00
/* extract URLs from static text */
static void extract_text_urls ( const unsigned char * mem , size_t len , tag_arguments_t * hrefs )
{
char url [ 1024 ] ;
size_t off ;
2018-12-03 12:40:13 -05:00
for ( off = 0 ; off + 10 < len ; off + + ) {
/* check whether this is the start of a URL */
int32_t proto = cli_readint32 ( mem + off ) ;
/* convert to lowercase */
proto | = 0x20202020 ;
/* 'http:', 'https:', or 'ftp:' in little-endian */
if ( ( proto = = 0x70747468 & &
( mem [ off + 4 ] = = ' : ' | | ( mem [ off + 5 ] = = ' s ' & & mem [ off + 6 ] = = ' : ' ) ) ) | |
proto = = 0x3a707466 ) {
size_t url_len ;
for ( url_len = 4 ; off + url_len < len & & url_len < ( sizeof ( url ) - 1 ) ; url_len + + ) {
unsigned char c = mem [ off + url_len ] ;
/* smart compilers will compile this if into
2020-07-29 10:26:55 -07:00
* a single bt + jb instruction */
2018-12-03 12:40:13 -05:00
if ( c = = ' ' | | c = = ' \n ' | | c = = ' \t ' )
break ;
}
memcpy ( url , mem + off , url_len ) ;
url [ url_len ] = ' \0 ' ;
html_tag_arg_add ( hrefs , " href " , url ) ;
off + = url_len ;
}
2009-04-02 20:36:22 +00:00
}
}
2006-09-13 21:40:03 +00:00
/*
* This used to be part of checkURLs , split out , because phishingScan needs it
* too , and phishingScan might be used in situations where checkURLs is
* disabled ( see ifdef )
*/
static blob *
2022-12-16 13:36:17 -08:00
getHrefs ( cli_ctx * ctx , message * m , tag_arguments_t * hrefs )
2006-09-13 21:40:03 +00:00
{
2018-12-03 12:40:13 -05:00
unsigned char * mem ;
blob * b = messageToBlob ( m , 0 ) ;
size_t len ;
if ( b = = NULL )
return NULL ;
len = blobGetDataSize ( b ) ;
if ( len = = 0 ) {
blobDestroy ( b ) ;
return NULL ;
}
/* TODO: make this size customisable */
if ( len > 100 * 1024 ) {
2025-08-07 13:31:09 -04:00
cli_dbgmsg ( " HTML pointed to by URLs not scanned in large message \n " ) ;
2018-12-03 12:40:13 -05:00
blobDestroy ( b ) ;
return NULL ;
}
hrefs - > count = 0 ;
hrefs - > tag = hrefs - > value = NULL ;
hrefs - > contents = NULL ;
cli_dbgmsg ( " getHrefs: calling html_normalise_mem \n " ) ;
mem = blobGetData ( b ) ;
2022-12-16 13:36:17 -08:00
if ( ! html_normalise_mem ( ctx , mem , ( off_t ) len , NULL , hrefs , m - > ctx - > dconf ) ) {
2018-12-03 12:40:13 -05:00
blobDestroy ( b ) ;
return NULL ;
}
cli_dbgmsg ( " getHrefs: html_normalise_mem returned \n " ) ;
if ( ! hrefs - > count & & hrefs - > scanContents ) {
extract_text_urls ( mem , len , hrefs ) ;
}
/* TODO: Do we need to call remove_html_comments? */
return b ;
2006-09-13 21:40:03 +00:00
}
2007-03-11 01:56:08 +00:00
/*
2007-09-04 09:43:40 +00:00
* validate URLs for phishes
2007-03-11 01:56:08 +00:00
* followurls : see if URLs point to malware
*/
2006-09-13 21:40:03 +00:00
static void
2006-12-27 23:15:36 +00:00
checkURLs ( message * mainMessage , mbox_ctx * mctx , mbox_status * rc , int is_html )
2006-09-13 21:40:03 +00:00
{
2018-12-03 12:40:13 -05:00
blob * b ;
tag_arguments_t hrefs ;
2006-09-13 21:40:03 +00:00
2014-07-10 18:11:49 -04:00
UNUSEDPARAM ( is_html ) ;
2018-12-03 12:40:13 -05:00
if ( * rc = = VIRUS )
return ;
2007-09-04 09:43:40 +00:00
2018-12-03 12:40:13 -05:00
hrefs . scanContents = mctx - > ctx - > engine - > dboptions & CL_DB_PHISHING_URLS & & ( DCONF_PHISHING & PHISHING_CONF_ENGINE ) ;
2006-09-13 21:40:03 +00:00
2018-12-03 12:40:13 -05:00
if ( ! hrefs . scanContents )
/*
2020-07-29 10:26:55 -07:00
* Don ' t waste time extracting hrefs ( parsing html ) , nobody
* will need it
*/
2018-12-03 12:40:13 -05:00
return ;
2006-09-13 21:40:03 +00:00
2018-12-03 12:40:13 -05:00
hrefs . count = 0 ;
hrefs . tag = hrefs . value = NULL ;
hrefs . contents = NULL ;
2006-10-06 15:25:15 +00:00
2022-12-16 13:36:17 -08:00
b = getHrefs ( mctx - > ctx , mainMessage , & hrefs ) ;
2018-12-03 12:40:13 -05:00
if ( b ) {
if ( hrefs . scanContents ) {
if ( phishingScan ( mctx - > ctx , & hrefs ) = = CL_VIRUS ) {
/*
2020-07-29 10:26:55 -07:00
* FIXME : message objects ' contents are
* encapsulated so we should not access
* the members directly
*/
2021-10-20 21:10:59 -07:00
mainMessage - > isInfected = true ;
2018-12-03 12:40:13 -05:00
* rc = VIRUS ;
cli_dbgmsg ( " PH:Phishing found \n " ) ;
}
}
}
hrefs_done ( b , & hrefs ) ;
2006-09-13 21:40:03 +00:00
}
2004-06-28 11:47:16 +00:00
# ifdef HAVE_BACKTRACE
2004-08-11 14:48:13 +00:00
static void
2004-06-22 04:08:02 +00:00
sigsegv ( int sig )
{
2018-12-03 12:40:13 -05:00
signal ( SIGSEGV , SIG_DFL ) ;
print_trace ( 1 ) ;
exit ( SIGSEGV ) ;
2004-06-22 04:08:02 +00:00
}
2004-08-11 14:48:13 +00:00
static void
2004-06-22 04:08:02 +00:00
print_trace ( int use_syslog )
{
2018-12-03 12:40:13 -05:00
void * array [ 10 ] ;
size_t size ;
char * * strings ;
size_t i ;
pid_t pid = getpid ( ) ;
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
cli_errmsg ( " Segmentation fault, attempting to print backtrace \n " ) ;
2007-10-01 10:35:02 +00:00
2018-12-03 12:40:13 -05:00
size = backtrace ( array , 10 ) ;
strings = backtrace_symbols ( array , size ) ;
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
cli_errmsg ( " Backtrace of pid %d: \n " , pid ) ;
if ( use_syslog )
syslog ( LOG_ERR , " Backtrace of pid %d: " , pid ) ;
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
for ( i = 0 ; i < size ; i + + ) {
cli_errmsg ( " %s \n " , strings [ i ] ) ;
if ( use_syslog )
syslog ( LOG_ERR , " bt[%llu]: %s " , ( unsigned long long ) i , strings [ i ] ) ;
}
2004-06-22 04:08:02 +00:00
2018-12-03 12:40:13 -05:00
# ifdef SAVE_TMP
cli_errmsg ( " The errant mail file has been saved \n " ) ;
2007-10-01 10:35:02 +00:00
# endif
2018-12-03 12:40:13 -05:00
/* #else TODO: dump the current email */
2004-09-06 11:05:44 +00:00
2018-12-03 12:40:13 -05:00
free ( strings ) ;
2004-06-22 04:08:02 +00:00
}
# endif
2004-12-16 15:29:08 +00:00
2006-08-25 10:10:13 +00:00
/* See also clamav-milter */
2004-12-18 16:34:31 +00:00
static bool
usefulHeader ( int commandNumber , const char * cmd )
{
2018-12-03 12:40:13 -05:00
switch ( commandNumber ) {
case CONTENT_TRANSFER_ENCODING :
case CONTENT_DISPOSITION :
case CONTENT_TYPE :
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
default :
if ( strcasecmp ( cmd , " From " ) = = 0 )
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
if ( strcasecmp ( cmd , " Received " ) = = 0 )
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
if ( strcasecmp ( cmd , " De " ) = = 0 )
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
return false ;
2004-12-18 16:34:31 +00:00
}
2005-04-19 09:23:12 +00:00
/*
* Like fgets but cope with end of line by " \n " , " \r \n " , " \n \r " , " \r "
*/
static char *
2009-10-08 20:28:58 +02:00
getline_from_mbox ( char * buffer , size_t buffer_len , fmap_t * map , size_t * at )
2005-04-19 09:23:12 +00:00
{
2012-01-05 14:16:09 +02:00
const char * src , * cursrc ;
char * curbuf ;
2009-09-10 03:19:43 +02:00
size_t i ;
2009-10-08 20:28:58 +02:00
size_t input_len = MIN ( map - > len - * at , buffer_len + 1 ) ;
src = cursrc = fmap_need_off_once ( map , * at , input_len ) ;
2005-04-19 09:23:12 +00:00
2020-07-29 10:26:55 -07:00
/* we check for eof from the result of GETC()
if ( feof ( fin ) )
return NULL ; */
2018-12-03 12:40:13 -05:00
if ( ! src ) {
cli_dbgmsg ( " getline_from_mbox: fmap need failed \n " ) ;
return NULL ;
2009-09-10 03:19:43 +02:00
}
2018-12-03 12:40:13 -05:00
if ( ( buffer_len = = 0 ) | | ( buffer = = NULL ) ) {
2021-07-17 16:15:33 -07:00
cli_errmsg ( " Invalid call to getline_from_mbox(). Refer to https://docs.clamav.net/manual/Installing.html \n " ) ;
2018-12-03 12:40:13 -05:00
return NULL ;
2009-09-10 03:19:43 +02:00
}
2005-04-19 09:23:12 +00:00
2009-09-10 03:19:43 +02:00
curbuf = buffer ;
2018-12-03 12:40:13 -05:00
for ( i = 0 ; i < buffer_len - 1 ; i + + ) {
char c ;
if ( ! input_len - - ) {
if ( curbuf = = buffer ) {
/* EOF on first char */
return NULL ;
}
break ;
}
switch ( ( c = * cursrc + + ) ) {
case ' \0 ' :
continue ;
case ' \n ' :
* curbuf + + = ' \n ' ;
if ( input_len & & * cursrc = = ' \r ' ) {
i + + ;
cursrc + + ;
}
break ;
case ' \r ' :
* curbuf + + = ' \r ' ;
if ( input_len & & * cursrc = = ' \n ' ) {
i + + ;
cursrc + + ;
}
break ;
default :
* curbuf + + = c ;
continue ;
}
break ;
2009-09-10 03:19:43 +02:00
}
* at + = cursrc - src ;
* curbuf = ' \0 ' ;
2018-12-03 12:40:13 -05:00
2009-09-10 03:19:43 +02:00
return buffer ;
2005-04-19 09:23:12 +00:00
}
2006-05-02 15:21:59 +00:00
2006-05-03 15:41:44 +00:00
/*
* Is this line a candidate for the start of a bounce message ?
*/
2006-05-02 15:21:59 +00:00
static bool
2007-12-14 22:39:37 +00:00
isBounceStart ( mbox_ctx * mctx , const char * line )
2006-05-02 15:21:59 +00:00
{
2018-12-03 12:40:13 -05:00
size_t len ;
2007-09-13 17:25:37 +00:00
2018-12-03 12:40:13 -05:00
if ( line = = NULL )
2021-10-20 21:10:59 -07:00
return false ;
2018-12-03 12:40:13 -05:00
if ( * line = = ' \0 ' )
2021-10-20 21:10:59 -07:00
return false ;
2018-12-03 12:40:13 -05:00
/*if((strncmp(line, "From ", 5) == 0) && !isalnum(line[5]))
2021-10-20 21:10:59 -07:00
return false ;
2020-07-29 10:26:55 -07:00
if ( ( strncmp ( line , " >From " , 6 ) = = 0 ) & & ! isalnum ( line [ 6 ] ) )
2021-10-20 21:10:59 -07:00
return false ; */
2006-05-02 15:21:59 +00:00
2018-12-03 12:40:13 -05:00
len = strlen ( line ) ;
if ( ( len < 6 ) | | ( len > = 72 ) )
2021-10-20 21:10:59 -07:00
return false ;
2007-09-13 17:25:37 +00:00
2018-12-03 12:40:13 -05:00
if ( ( memcmp ( line , " From " , 5 ) = = 0 ) | |
( memcmp ( line , " >From " , 6 ) = = 0 ) ) {
int numSpaces = 0 , numDigits = 0 ;
line + = 4 ;
do
if ( * line = = ' ' )
numSpaces + + ;
else if ( isdigit ( ( * line ) & 0xFF ) )
numDigits + + ;
while ( * + + line ! = ' \0 ' ) ;
if ( numSpaces < 6 )
2021-10-20 21:10:59 -07:00
return false ;
2018-12-03 12:40:13 -05:00
if ( numDigits < 11 )
2021-10-20 21:10:59 -07:00
return false ;
return true ;
2018-12-03 12:40:13 -05:00
}
2020-03-21 14:15:28 -04:00
return ( bool ) ( cli_compare_ftm_file ( ( const unsigned char * ) line , len , mctx - > ctx - > engine ) = = CL_TYPE_MAIL ) ;
2006-05-02 15:21:59 +00:00
}
2006-06-28 16:06:07 +00:00
/*
* Extract a binhexEncoded message , return if it ' s found to be infected as we
2020-07-29 10:26:55 -07:00
* extract it
2006-06-28 16:06:07 +00:00
*/
static bool
2007-10-30 17:26:29 +00:00
exportBinhexMessage ( mbox_ctx * mctx , message * m )
2006-06-28 16:06:07 +00:00
{
2021-10-20 21:10:59 -07:00
bool infected = false ;
2018-12-03 12:40:13 -05:00
fileblob * fb ;
2006-06-28 16:06:07 +00:00
2018-12-03 12:40:13 -05:00
if ( messageGetEncoding ( m ) = = NOENCODING )
messageSetEncoding ( m , " x-binhex " ) ;
2006-06-28 16:06:07 +00:00
2018-12-03 12:40:13 -05:00
fb = messageToFileblob ( m , mctx - > dir , 0 ) ;
2006-06-28 16:06:07 +00:00
2018-12-03 12:40:13 -05:00
if ( fb ) {
cli_dbgmsg ( " Binhex file decoded to %s \n " ,
fileblobGetFilename ( fb ) ) ;
2007-08-29 18:21:39 +00:00
2018-12-03 12:40:13 -05:00
if ( fileblobScanAndDestroy ( fb ) = = CL_VIRUS )
2021-10-20 21:10:59 -07:00
infected = true ;
2018-12-03 12:40:13 -05:00
mctx - > files + + ;
} else
cli_errmsg ( " Couldn't decode binhex file to %s \n " , mctx - > dir ) ;
2006-06-28 16:06:07 +00:00
2018-12-03 12:40:13 -05:00
return infected ;
2006-06-28 16:06:07 +00:00
}
2006-06-28 21:07:36 +00:00
2006-07-04 08:40:46 +00:00
/*
2007-09-04 09:43:40 +00:00
* Locate any bounce message and extract it . Return cl_status
2006-07-04 08:40:46 +00:00
*/
static int
2007-10-30 17:26:29 +00:00
exportBounceMessage ( mbox_ctx * mctx , text * start )
2006-07-04 08:40:46 +00:00
{
2018-12-03 12:40:13 -05:00
int rc = CL_CLEAN ;
text * t ;
fileblob * fb ;
2006-07-04 08:40:46 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Attempt to save the original ( unbounced )
* message - clamscan will find that in the
* directory and call us again ( with any luck )
* having found an e - mail message to handle .
*
* This finds a lot of false positives , the
* search that a content type is in the
* bounce ( i . e . it ' s after the bounce header )
* helps a bit .
*
* messageAddLine
* optimization could help here , but needs
* careful thought , do it with line numbers
* would be best , since the current method in
* messageAddLine of checking encoding first
* must remain otherwise non bounce messages
* won ' t be scanned
*/
2018-12-03 12:40:13 -05:00
for ( t = start ; t ; t = t - > t_next ) {
const char * txt = lineGetData ( t - > t_line ) ;
char cmd [ RFC2821LENGTH + 1 ] ;
if ( txt = = NULL )
continue ;
if ( cli_strtokbuf ( txt , 0 , " : " , cmd ) = = NULL )
continue ;
switch ( tableFind ( mctx - > rfc821Table , cmd ) ) {
case CONTENT_TRANSFER_ENCODING :
if ( ( strstr ( txt , " 7bit " ) = = NULL ) & &
( strstr ( txt , " 8bit " ) = = NULL ) )
break ;
continue ;
case CONTENT_DISPOSITION :
break ;
case CONTENT_TYPE :
if ( strstr ( txt , " text/plain " ) ! = NULL )
t = NULL ;
break ;
default :
if ( strcasecmp ( cmd , " From " ) = = 0 )
start = t ;
else if ( strcasecmp ( cmd , " Received " ) = = 0 )
start = t ;
continue ;
}
break ;
}
if ( t & & ( ( fb = fileblobCreate ( ) ) ! = NULL ) ) {
cli_dbgmsg ( " Found a bounce message \n " ) ;
fileblobSetFilename ( fb , mctx - > dir , " bounce " ) ;
fileblobSetCTX ( fb , mctx - > ctx ) ;
if ( textToFileblob ( start , fb , 1 ) = = NULL ) {
cli_dbgmsg ( " Nothing new to save in the bounce message \n " ) ;
fileblobDestroy ( fb ) ;
} else
rc = fileblobScanAndDestroy ( fb ) ;
mctx - > files + + ;
} else
cli_dbgmsg ( " Not found a bounce message \n " ) ;
return rc ;
2006-07-04 08:40:46 +00:00
}
2016-05-10 18:53:59 -04:00
/*
* Get string representation of mimetype
*/
2018-12-03 12:40:13 -05:00
static const char * getMimeTypeStr ( mime_type mimetype )
2016-05-10 18:53:59 -04:00
{
2018-12-03 12:40:13 -05:00
const struct tableinit * entry = mimeTypeStr ;
while ( entry - > key ) {
2019-11-07 09:10:26 -08:00
if ( mimetype = = ( ( mime_type ) entry - > value ) ) {
2018-12-03 12:40:13 -05:00
return entry - > key ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
entry + + ;
}
return " UNKNOWN " ;
2016-05-10 18:53:59 -04:00
}
/*
* Get string representation of encoding type
*/
2018-12-03 12:40:13 -05:00
static const char * getEncTypeStr ( encoding_type enctype )
2016-05-10 18:53:59 -04:00
{
2018-12-03 12:40:13 -05:00
const struct tableinit * entry = encTypeStr ;
while ( entry - > key ) {
2019-11-07 09:10:26 -08:00
if ( enctype = = ( ( encoding_type ) entry - > value ) ) {
2018-12-03 12:40:13 -05:00
return entry - > key ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
entry + + ;
}
return " UNKNOWN " ;
2016-05-10 18:53:59 -04:00
}
2006-06-28 21:07:36 +00:00
/*
* Handle the ith element of a number of multiparts , e . g . multipart / alternative
*/
static message *
2006-12-27 23:15:36 +00:00
do_multipart ( message * mainMessage , message * * messages , int i , mbox_status * rc , mbox_ctx * mctx , message * messageIn , text * * tptr , unsigned int recursion_level )
2006-06-28 21:07:36 +00:00
{
2021-10-20 21:10:59 -07:00
bool addToText = false ;
2018-12-03 12:40:13 -05:00
const char * dtype ;
# ifndef SAVE_TO_DISC
message * body ;
2006-06-28 21:07:36 +00:00
# endif
2018-12-03 12:40:13 -05:00
message * aMessage = messages [ i ] ;
const int doPhishingScan = mctx - > ctx - > engine - > dboptions & CL_DB_PHISHING_URLS & & ( DCONF_PHISHING & PHISHING_CONF_ENGINE ) ;
2024-03-25 13:01:46 -04:00
json_object * thisobj = NULL ;
json_object * saveobj = mctx - > wrkobj ;
2018-12-03 12:40:13 -05:00
if ( mctx - > wrkobj ! = NULL ) {
json_object * multiobj = cli_jsonarray ( mctx - > wrkobj , " Multipart " ) ;
if ( multiobj = = NULL ) {
cli_errmsg ( " Cannot get multipart preclass array \n " ) ;
2024-08-18 17:37:46 -04:00
} else if ( NULL = = ( thisobj = cli_jsonobj ( NULL , NULL ) ) ) {
cli_dbgmsg ( " Cannot allocate new json object for message part. \n " ) ;
} else {
json_object_array_add ( multiobj , thisobj ) ;
2018-12-03 12:40:13 -05:00
}
}
2016-05-10 18:53:59 -04:00
2018-12-03 12:40:13 -05:00
if ( aMessage = = NULL ) {
if ( thisobj ! = NULL )
cli_jsonstr ( thisobj , " MimeType " , " NULL " ) ;
return mainMessage ;
}
2006-06-28 21:07:36 +00:00
2018-12-03 12:40:13 -05:00
if ( * rc ! = OK )
return mainMessage ;
2007-02-15 12:29:51 +00:00
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Mixed message part %d is of type %d \n " ,
i , messageGetMimeType ( aMessage ) ) ;
2006-06-28 21:07:36 +00:00
2018-12-03 12:40:13 -05:00
if ( thisobj ! = NULL ) {
cli_jsonstr ( thisobj , " MimeType " , getMimeTypeStr ( messageGetMimeType ( aMessage ) ) ) ;
cli_jsonstr ( thisobj , " MimeSubtype " , messageGetMimeSubtype ( aMessage ) ) ;
cli_jsonstr ( thisobj , " EncodingType " , getEncTypeStr ( messageGetEncoding ( aMessage ) ) ) ;
cli_jsonstr ( thisobj , " Disposition " , messageGetDispositionType ( aMessage ) ) ;
2021-10-20 21:10:59 -07:00
if ( messageHasFilename ( aMessage ) ) {
char * filename = messageGetFilename ( aMessage ) ;
cli_jsonstr ( thisobj , " Filename " , filename ) ;
free ( filename ) ;
} else {
cli_jsonstr ( thisobj , " Filename " , " (inline) " ) ;
}
2018-12-03 12:40:13 -05:00
}
2016-05-10 18:53:59 -04:00
2018-12-03 12:40:13 -05:00
switch ( messageGetMimeType ( aMessage ) ) {
case APPLICATION :
case AUDIO :
case IMAGE :
case VIDEO :
break ;
case NOMIME :
cli_dbgmsg ( " No mime headers found in multipart part %d \n " , i ) ;
if ( mainMessage ) {
if ( binhexBegin ( aMessage ) ) {
cli_dbgmsg ( " Found binhex message in multipart/mixed mainMessage \n " ) ;
if ( exportBinhexMessage ( mctx , mainMessage ) )
* rc = VIRUS ;
}
if ( mainMessage ! = messageIn )
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
} else if ( aMessage ) {
if ( binhexBegin ( aMessage ) ) {
cli_dbgmsg ( " Found binhex message in multipart/mixed non mime part \n " ) ;
if ( exportBinhexMessage ( mctx , aMessage ) )
* rc = VIRUS ;
messageReset ( messages [ i ] ) ;
}
}
2021-10-20 21:10:59 -07:00
addToText = true ;
2018-12-03 12:40:13 -05:00
if ( messageGetBody ( aMessage ) = = NULL )
/*
2020-07-29 10:26:55 -07:00
* No plain text version
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " No plain text alternative \n " ) ;
break ;
case TEXT :
dtype = messageGetDispositionType ( aMessage ) ;
cli_dbgmsg ( " Mixed message text part disposition \" %s \" \n " ,
dtype ) ;
if ( strcasecmp ( dtype , " attachment " ) = = 0 )
break ;
if ( ( * dtype = = ' \0 ' ) | | ( strcasecmp ( dtype , " inline " ) = = 0 ) ) {
const char * cptr ;
if ( mainMessage & & ( mainMessage ! = messageIn ) )
messageDestroy ( mainMessage ) ;
mainMessage = NULL ;
cptr = messageGetMimeSubtype ( aMessage ) ;
cli_dbgmsg ( " Mime subtype \" %s \" \n " , cptr ) ;
if ( ( tableFind ( mctx - > subtypeTable , cptr ) = = PLAIN ) & &
( messageGetEncoding ( aMessage ) = = NOENCODING ) ) {
/*
2020-07-29 10:26:55 -07:00
* Strictly speaking , a text / plain part
* is not an attachment . We pretend it
* is so that we can decode and scan it
*/
2018-12-03 12:40:13 -05:00
if ( ! messageHasFilename ( aMessage ) ) {
cli_dbgmsg ( " Adding part to main message \n " ) ;
2021-10-20 21:10:59 -07:00
addToText = true ;
2018-12-03 12:40:13 -05:00
} else
cli_dbgmsg ( " Treating inline as attachment \n " ) ;
} else {
const int is_html = ( tableFind ( mctx - > subtypeTable , cptr ) = = HTML ) ;
if ( doPhishingScan )
checkURLs ( aMessage , mctx , rc , is_html ) ;
messageAddArgument ( aMessage ,
" filename=mixedtextportion " ) ;
}
break ;
}
cli_dbgmsg ( " Text type %s is not supported \n " , dtype ) ;
return mainMessage ;
case MESSAGE :
/* Content-Type: message/rfc822 */
cli_dbgmsg ( " Found message inside multipart (encoding type %d) \n " ,
messageGetEncoding ( aMessage ) ) ;
# ifndef SCAN_UNENCODED_BOUNCES
switch ( messageGetEncoding ( aMessage ) ) {
case NOENCODING :
case EIGHTBIT :
case BINARY :
if ( encodingLine ( aMessage ) = = NULL ) {
/*
2020-07-29 10:26:55 -07:00
* This means that the message
* has no attachments
*
* The test for
* messageGetEncoding is needed
* since encodingLine won ' t have
* been set if the message
* itself has been encoded
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Unencoded multipart/message will not be scanned \n " ) ;
messageDestroy ( messages [ i ] ) ;
messages [ i ] = NULL ;
return mainMessage ;
}
/* FALLTHROUGH */
default :
cli_dbgmsg ( " Encoded multipart/message will be scanned \n " ) ;
}
2006-06-28 21:07:36 +00:00
# endif
2021-10-20 21:10:59 -07:00
2018-12-03 12:40:13 -05:00
# ifdef SAVE_TO_DISC
/*
2020-07-29 10:26:55 -07:00
* Save this embedded message
* to a temporary file
*/
2018-12-03 12:40:13 -05:00
if ( saveTextPart ( mctx , aMessage , 1 ) = = CL_VIRUS )
* rc = VIRUS ;
messageDestroy ( messages [ i ] ) ;
messages [ i ] = NULL ;
2006-06-28 21:07:36 +00:00
# else
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Scan in memory , faster but is open to DoS attacks
* when many nested levels are involved .
*/
2018-12-03 12:40:13 -05:00
body = parseEmailHeaders ( aMessage , mctx - > rfc821Table ) ;
2006-11-30 09:36:18 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* We ' ve finished with the
* original copy of the message ,
* so throw that away and
* deal with the encapsulated
* message as a message .
* This can save a lot of memory
*/
2018-12-03 12:40:13 -05:00
messageDestroy ( messages [ i ] ) ;
2024-04-13 14:39:19 -04:00
messages [ i ] = NULL ;
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = thisobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
if ( body ) {
messageSetCTX ( body , mctx - > ctx ) ;
* rc = parseEmailBody ( body , NULL , mctx , recursion_level + 1 ) ;
if ( ( * rc = = OK ) & & messageContainsVirus ( body ) )
* rc = VIRUS ;
messageDestroy ( body ) ;
}
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2006-06-28 21:07:36 +00:00
# endif
2018-12-03 12:40:13 -05:00
return mainMessage ;
case MULTIPART :
/*
2020-07-29 10:26:55 -07:00
* It ' s a multi part within a multi part
* Run the message parser on this bit , it won ' t
* be an attachment
*/
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " Found multipart inside multipart \n " ) ;
mctx - > wrkobj = thisobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
if ( aMessage ) {
/*
2020-07-29 10:26:55 -07:00
* The headers were parsed when reading in the
* whole multipart section
*/
2018-12-03 12:40:13 -05:00
* rc = parseEmailBody ( aMessage , * tptr , mctx , recursion_level + 1 ) ;
cli_dbgmsg ( " Finished recursion, rc = %d \n " , ( int ) * rc ) ;
messageDestroy ( messages [ i ] ) ;
messages [ i ] = NULL ;
} else {
* rc = parseEmailBody ( NULL , NULL , mctx , recursion_level + 1 ) ;
2019-11-07 09:10:26 -08:00
if ( mainMessage & & ( mainMessage ! = messageIn ) ) {
2018-12-03 12:40:13 -05:00
messageDestroy ( mainMessage ) ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
mainMessage = NULL ;
}
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
mctx - > wrkobj = saveobj ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
return mainMessage ;
default :
cli_dbgmsg ( " Only text and application attachments are fully supported, type = %d \n " ,
messageGetMimeType ( aMessage ) ) ;
/* fall through - we may be able to salvage something */
}
if ( * rc ! = VIRUS ) {
fileblob * fb = messageToFileblob ( aMessage , mctx - > dir , 1 ) ;
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
json_object * arrobj ;
2020-03-30 18:14:53 -04:00
# if (JSON_C_MAJOR_VERSION == 0) && (JSON_C_MINOR_VERSION < 13)
int arrlen = 0 ;
# else
2019-05-03 18:25:17 -04:00
size_t arrlen = 0 ;
2020-03-30 18:14:53 -04:00
# endif
2016-05-10 18:53:59 -04:00
2018-12-03 12:40:13 -05:00
if ( thisobj ! = NULL ) {
/* attempt to determine container size - prevents incorrect type reporting */
2025-06-08 01:12:33 -04:00
if ( json_object_object_get_ex ( mctx - > ctx - > this_layer_metadata_json , " ContainedObjects " , & arrobj ) ) {
2018-12-03 12:40:13 -05:00
arrlen = json_object_array_length ( arrobj ) ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
}
2006-06-28 21:07:36 +00:00
2018-12-03 12:40:13 -05:00
if ( fb ) {
/* aMessage doesn't always have a ctx set */
fileblobSetCTX ( fb , mctx - > ctx ) ;
2019-11-07 09:10:26 -08:00
if ( fileblobScanAndDestroy ( fb ) = = CL_VIRUS ) {
2018-12-03 12:40:13 -05:00
* rc = VIRUS ;
2019-11-07 09:10:26 -08:00
}
if ( ! addToText ) {
2018-12-03 12:40:13 -05:00
mctx - > files + + ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
}
2024-03-25 13:01:46 -04:00
2018-12-03 12:40:13 -05:00
if ( thisobj ! = NULL ) {
json_object * entry = NULL ;
const char * dtype = NULL ;
/* attempt to acquire container type */
2025-06-08 01:12:33 -04:00
if ( json_object_object_get_ex ( mctx - > ctx - > this_layer_metadata_json , " ContainedObjects " , & arrobj ) ) {
2020-03-30 18:14:53 -04:00
if ( json_object_array_length ( arrobj ) > arrlen ) {
2018-12-03 12:40:13 -05:00
entry = json_object_array_get_idx ( arrobj , arrlen ) ;
2019-11-07 09:10:26 -08:00
}
}
2018-12-03 12:40:13 -05:00
if ( entry ) {
json_object_object_get_ex ( entry , " FileType " , & entry ) ;
2019-11-07 09:10:26 -08:00
if ( entry ) {
2018-12-03 12:40:13 -05:00
dtype = json_object_get_string ( entry ) ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
}
2020-03-30 20:42:44 -04:00
cli_jsonint ( thisobj , " ContainedObjectsIndex " , ( int32_t ) arrlen ) ;
2018-12-03 12:40:13 -05:00
cli_jsonstr ( thisobj , " ClamAVFileType " , dtype ? dtype : " UNKNOWN " ) ;
}
2024-03-25 13:01:46 -04:00
2019-11-07 09:10:26 -08:00
if ( messageContainsVirus ( aMessage ) ) {
2018-12-03 12:40:13 -05:00
* rc = VIRUS ;
2019-11-07 09:10:26 -08:00
}
2018-12-03 12:40:13 -05:00
}
messageDestroy ( aMessage ) ;
messages [ i ] = NULL ;
2006-06-28 21:07:36 +00:00
2018-12-03 12:40:13 -05:00
return mainMessage ;
2006-06-28 21:07:36 +00:00
}
2006-07-12 21:21:25 +00:00
/*
* Returns the number of quote characters in the given string
*/
static int
count_quotes ( const char * buf )
{
2018-12-03 12:40:13 -05:00
int quotes = 0 ;
2006-07-12 21:21:25 +00:00
2018-12-03 12:40:13 -05:00
while ( * buf )
if ( * buf + + = = ' \" ' )
quotes + + ;
2006-07-12 21:21:25 +00:00
2018-12-03 12:40:13 -05:00
return quotes ;
2006-07-12 21:21:25 +00:00
}
2006-07-24 12:14:46 +00:00
/*
* Will the next line be a folded header ? See RFC2822 section 2.2 .3
*/
static bool
next_is_folded_header ( const text * t )
{
2018-12-03 12:40:13 -05:00
const text * next = t - > t_next ;
const char * data , * ptr ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
if ( next = = NULL )
2021-10-20 21:10:59 -07:00
return false ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
if ( next - > t_line = = NULL )
2021-10-20 21:10:59 -07:00
return false ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
data = lineGetData ( next - > t_line ) ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Section B .2 of RFC822 says TAB or SPACE means a continuation of the
* previous entry .
*/
2018-12-03 12:40:13 -05:00
if ( isblank ( data [ 0 ] ) )
2021-10-20 21:10:59 -07:00
return true ;
2006-07-24 12:14:46 +00:00
2018-12-03 12:40:13 -05:00
if ( strchr ( data , ' = ' ) = = NULL )
/*
2020-07-29 10:26:55 -07:00
* Avoid false positives with
* Content - Type : text / html ;
* Content - Transfer - Encoding : quoted - printable
*/
2021-10-20 21:10:59 -07:00
return false ;
2006-07-25 15:09:45 +00:00
2018-12-03 12:40:13 -05:00
/*
2020-07-29 10:26:55 -07:00
* Some are broken and don ' t fold headers lines
* correctly as per section 2.2 .3 of RFC2822 .
* Generally they miss the white space at
* the start of the fold line :
* Content - Type : multipart / related ;
* type = " multipart/alternative " ;
* boundary = " ----=_NextPart_000_006A_01C6AC47.348CB550 "
* should read :
* Content - Type : multipart / related ;
* type = " multipart/alternative " ;
* boundary = " ----=_NextPart_000_006A_01C6AC47.348CB550 "
* Since we ' re a virus checker not an RFC
* verifier we need to handle these
*/
2018-12-03 12:40:13 -05:00
data = lineGetData ( t - > t_line ) ;
ptr = strchr ( data , ' \0 ' ) ;
while ( - - ptr > data )
switch ( * ptr ) {
case ' ; ' :
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
case ' \n ' :
case ' ' :
case ' \r ' :
case ' \t ' :
continue ; /* white space at end of line */
default :
2021-10-20 21:10:59 -07:00
return false ;
2018-12-03 12:40:13 -05:00
}
2021-10-20 21:10:59 -07:00
return false ;
2006-07-24 12:14:46 +00:00
}
2007-01-07 21:31:43 +00:00
/*
* This routine is called on the first line of the body of
* an email to handle broken messages that have newlines
* in the middle of its headers
*/
static bool
newline_in_header ( const char * line )
{
2018-12-03 12:40:13 -05:00
cli_dbgmsg ( " newline_in_header, check \" %s \" \n " , line ) ;
2007-01-07 21:31:43 +00:00
2018-12-03 12:40:13 -05:00
if ( strncmp ( line , " Message-Id: " , 12 ) = = 0 )
2021-10-20 21:10:59 -07:00
return true ;
2018-12-03 12:40:13 -05:00
if ( strncmp ( line , " Date: " , 6 ) = = 0 )
2021-10-20 21:10:59 -07:00
return true ;
2007-01-07 21:31:43 +00:00
2019-11-07 09:10:26 -08:00
cli_dbgmsg ( " newline_in_header, returning \" %s \" \n " , line ) ;
2021-10-20 21:10:59 -07:00
return false ;
2007-01-07 21:31:43 +00:00
}