summaryrefslogtreecommitdiffstats
path: root/src/klammail/clamdmail.c
blob: 101e9b74ed4f4647e885463274ca8eb30d16da34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*
*
*  Clamdmail.c is based loosely on clamdscan.c by Tomasz Kojm.
*
*  This program takes a mail message as input from stdin, uses rfc822.c to extract
*  attachments to a temp directory, gets clamd to scan them, and
*  handles the message appropriately.
*
*  Copyright (C) 2003 Robert Hogan <[email protected]>
*
*  This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  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
*  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pwd.h>
#include <clamav.h>

#include "options.h"
#include "defaults.h"
#include "memory.h"
#include "../version.h"
#include "../../config.h"

#include "output.h"

#define BUFFSIZE 1024



/* this local macro takes care about freeing memory at exit */
/*
#define mexit(i)    if(opt) free_opt(opt);			    \
                    mprintf("*Memory freed. Exit code: %d\n", i);   \
                    exit(i);
*/
#define mexit(i)    exit(i)

struct s_info {
  int signs; /* number of signatures loaded */
  int dirs; /* number of scanned directories */
  int files; /* number of scanned files */
  int ifiles; /* number of infected files */
  int notremoved; /* number of not removed files (if --remove) */
  int notmoved; /* number of not moved files (if --move) */
  int errors; /*  ... of errors */
  long int blocks; /* number of read 16kb blocks */
};


void help(void);
void printtag(void);
void startclamd(struct optstruct *opt);

struct s_info claminfo;
short printinfected = 0;
/* short int mprintf_stdout; */

int clamdscan(struct optstruct *opt)
{
  int ds, dms;

  struct timeval t1, t2;
  struct timezone tz;
  const char *bndrystore;
  const char *tmpdir;
  char *tmpfil;
  char *pfx;
  char *tmper;
  char *dir;
  struct passwd *user = NULL;
  FILE *tmp;
  FILE *fs;
  int bytes;
  char buff[BUFFSIZE];
  struct cl_node *trie = NULL;
  int threads = 0;
  int fd, fdtmp, ret, no = 0;
  unsigned long int size = 0;
  long double mb;
  const char *virname;
  struct cl_engine *engine = NULL;
  struct stat sb;

  if(optc(opt, 'V')) {
    mprintf("clamdmail "KLAMAV_VERSION" \n");
    mexit(0);
  }

  if(optc(opt, 'h')) {
  free_opt(opt);
  help();
  }

  if(optc(opt, 'i')) printinfected = 1;
  else printinfected = 0;



  memset(&claminfo, 0, sizeof(struct s_info));

  gettimeofday(&t1, &tz);

  //if(user)


  char name[19];
  char *tmpnm;
  char *mdir;

  if((mdir = getenv("TMPDIR")) == NULL)
  #ifdef P_tmpdir
      mdir = P_tmpdir;
  #else
      mdir = "/tmp";
  #endif

  tmpnm = (char*) mcalloc(strlen(mdir) + 1 + 16 + 1 + 7, sizeof(char));
  if(tmpnm == NULL) {
      exit(2);
  }

  sprintf(tmpnm, "%s/", mdir);
  snprintf(name, sizeof(name), "klammailXXXXXX");
  strncat(tmpnm, name, 19);
  mkstemp(tmpnm);



  fd = open(tmpnm,O_RDWR|O_CREAT, S_IRWXU);

  while((bytes = read(0, buff, BUFFSIZE)) > 0) {

          if(write(fd, buff, bytes) != bytes) {
                  close(fd);
                  return CL_EMEM;
          }
  }

  if(fsync(fd) == -1) {
        close(fd);
	return CL_ETMPFILE;
  }

  close(fd);

  if((fd = open(tmpnm, O_RDONLY)) == -1) {
    printf("Can't open file %s\n", tmpnm);
    exit(2);
  }

  ret = 0;
  ret = client(tmpnm, opt, &virname);



  /* Clamd isn't running, scan the file ourselves */
  if((ret == 2)) {
      /* Clamd isn't running, start it so it is available next time. */
      startclamd(opt);

      if((engine = cl_engine_new()) == NULL) {
          printf("Database initialization error: %s\n", cl_strerror(ret));;
          cl_engine_free(engine);
          close(fd);
          exit(2);
      }

      if(optc(opt, 'd')) {
          if((ret = cl_load(getargc(opt, 'd'), engine, &no, CL_DB_STDOPT))) {
              printf("cl_load: %s\n", cl_strerror(ret));
              close(fd);
              return 50;
          }
      }else{
          if((ret = cl_load(cl_retdbdir(), engine, &no, CL_DB_STDOPT))) {
          printf("cl_loaddbdir: %s\n", cl_strerror(ret));
          close(fd);
          exit(2);
          }
      }

      /* build engine */
      if((ret = cl_engine_compile(engine))) {
          printf("Database initialization error: %s\n", cl_strerror(ret));;
          cl_engine_free(engine);
          close(fd);
          exit(2);
      }

      ret = cl_scandesc(fd, tmpnm, &virname, &size, engine,
             CL_SCAN_GENERAL_ALLMATCHES | CL_SCAN_GENERAL_HEURISTICS |
	     CL_SCAN_PARSE_ARCHIVE | CL_SCAN_PARSE_MAIL | CL_SCAN_PARSE_OLE2 |
	     CL_SCAN_PARSE_HTML | CL_SCAN_PARSE_PDF );
      printf("scandesc returned: %i\n", cl_strerror(ret));;
      if( ret == CL_VIRUS )
	      printf("virus found\n");
      else
	      printf("file clean\n");
  }

  /* scan descriptor (with archive and mail scanning enabled) */
  close(fd);
  fd = open(tmpnm,O_RDWR, S_IRWXU);

  spoolstdin(tmpnm, fd, ret, &virname, &bndrystore, opt);

  if((ret == 2))
      cl_engine_free(engine);

  unlink(tmpnm);

  mexit(0);
}

int spoolstdin(char *tmpnm, int fd, int ret, char **virname, const char **bndrystore, struct optstruct *opt)
{
  int bytes;
  int i, j;
  long int size = 0;
  char buff[BUFFSIZE];
  char string[1000];
  char To[1000];
  char ReplyTo[1000];
  char DelivTo[1000];
  char From[1000];
  char ToR[1000];
  char FromR[1000];
  char boundary[1000];
  char host[256];  /* could be HOST_NAME_MAX+1 on POSIX 1003.1-2001 */
  struct timeval tv;
  struct timezone tz;
  char *s;
  char *storage;
  FILE *tmp;
  int pcount = 0;
  time_t starttime;
  struct tm *tm;
  char *out = NULL;
  const char *format;
  size_t out_length = 0;
  time_t when;
  int childpid;


  strcpy (To, "To:");
  strcpy (From, "From:");
  strcpy (ReplyTo, "Reply-To:");
  strcpy (DelivTo, "Delivered");

  gethostname(host, sizeof(host));
  gettimeofday(&tv, &tz);
  time(&when);
  tm = localtime(&when);
  format = "%a, %_d %b %Y %H:%M:%S %z";
  do {
          out_length += 200;
          out = (char *) realloc (out, out_length);
          out[0] = '\1';
  } while (strftime (out, out_length, format, tm) == 0 && out[0] != '\0');

  if(ret == CL_VIRUS) {
      if(!(optc(opt, 'f'))){

          lseek(fd, 0, SEEK_SET);
          if (!(tmp = fdopen(fd,"r"))){
              mprintf("@Can't open file %s\n", tmpnm);
              return 54;
          }

          mprintf_stdout = 1;

          while (fgets(string, sizeof(string), tmp)) {
              if (strstr(string, To) && !(strstr(string, ReplyTo)) && !(strstr(string,DelivTo))){
                      strcpy(To, string);
                      strcpy(ToR, string);
              }
              if (strstr(string, From)){
                      strcpy(FromR, string);
              }
              if (strncmp(string, "\n", 1) == 0 && pcount != 0){
                      break;
              }
              ++pcount;
          }

          if (strcmp(To,"To:") == 0){
                  strcat(To, " ");
                  strcat(To, getargl(opt, "admin"));
                  strcat(To, "\n");
          }
          strcat(From, " ");
          strcat(From, "KlamAV");
          strcat(From, "\n");
          strcat(ReplyTo, " ");
          strcat(ReplyTo, "KlamAV");
          strcat(ReplyTo, "\n");
          mprintf("%s", From);
          mprintf("%s", ReplyTo);
          mprintf("%s", To);
          mprintf("Subject: Virus %s found in attached mail by KlamAV.\n", *virname);
          mprintf("Date: %s\n", out);
          if(!(optl(opt, "quar"))){
              mprintf("MIME-Version: 1.0\n");
              mprintf("Content-Type: multipart/mixed;\n");
              mprintf("  boundary=\"----------=_%d\"\n",tv.tv_sec);
              mprintf("X-Virus-Status: Yes\n");
              mprintf("X-Virus-Checker: Scanned by KlamAV %s on %s (virus-found %s);\n\t%s\n",
                      KLAMAV_VERSION, host, *virname, out);
              mprintf("\n");
              mprintf("\n");
              mprintf("------------=_%d\n",tv.tv_sec);
          }
          mprintf("Content-Type: text/plain;\n");
          mprintf("  charset=\"us-ascii\"\n");
          mprintf("Content-Transfer-Encoding: quoted-printable\n");
          if((optl(opt, "quar"))){
              mprintf("X-Virus-Status: Yes\n");
              mprintf("X-Virus-Checker: Scanned by KlamAV %s on %s (virus-found %s);\n\t%s\n",
                      KLAMAV_VERSION, host, *virname, out);
              mprintf("\n");
              mprintf("KlamAV anti-virus scanner has intercepted and quarantined a message addressed to you.\n");
          }
          else
          {
              mprintf("\n");
              mprintf("KlamAV anti-virus scanner has detected a virus in the attached message.\n");
          }
          mprintf("\n");
          mprintf("The following is a summary of the infected message:\n");
          mprintf("\n");
          mprintf("Virus name: %s\n", *virname);
          mprintf("%s", FromR);
          mprintf("%s", ToR);
          mprintf("\n");
          mprintf("Please be aware that a virus spread by email normally forges the \n");
          mprintf("address of the sender. There is a good chance that the infected message\n");
          mprintf("was not received from the sender listed above. \n");
          mprintf("\n");
          if(!(optl(opt, "quar"))){
              mprintf("------------=_%d\n",tv.tv_sec);
              mprintf("Content-Type: message/rfc822; x-virus-type=original\n");
              mprintf("Content-Description: Infected Message - Open At Your Own Risk\n");
              mprintf("Content-Disposition: inline\n");
              mprintf("Content-Transfer-Encoding: 8bit\n");
              mprintf("\n");
              fflush(stdout);

              lseek(fd, 0, SEEK_SET);
              while((bytes = read(fd, buff, BUFFSIZE)) > 0) {

                      if(write(1, buff, bytes) != bytes) {
                              close(fd);
                              return CL_EMEM;
                      }
              }
              mprintf("------------=_%d--\n",tv.tv_sec);
          }
          fflush(stdout);

          fclose(tmp);
      }else{
          int bcnt = 0;
          lseek(fd, 0, SEEK_SET);
          if (!(tmp = fdopen(fd,"r"))){
                  mprintf("@Can't open file %s\n", tmpnm);
                  return 54;
          }

          mprintf_stdout = 1;

          while (fgets(string, sizeof(string), tmp)) {
              if (*string == '\n') {
              mprintf("X-Virus-Status: Yes\n");
              mprintf("X-Virus-Checker: Scanned by KlamAV %s on %s (virus-found %s);\n\t%s\n",
                      KLAMAV_VERSION, host, *virname, out);
                      break;
              }
              fputs(string, stdout);
          }
          while (fgets(string, sizeof(string), tmp)) {
              fputs(string, stdout);
          }

          if(optl(opt, "tag")) {
              if (!(*bndrystore))
                      printtag();
          }
          fclose(tmp);
      }

      if ( ( childpid=fork() ) == -1 ) {
          perror("Failed to fork; quitting\n");
          exit(2);
      }

      if ( childpid == 0 ) {
          char *dialogmessage;
          dialogmessage = malloc(77+sizeof(virname)+sizeof(FromR)+sizeof(ToR)+4+84+54);
          sprintf(dialogmessage,"KlamAV has found an infected mail with the following details:\nVirus name: %s\n%s\n%s\nThe mail has been handled according to the filter rules set up in your mail client (probably put in your trash/deleted items directory).",*virname,FromR,ToR);

          if (setenv("PATH","/usr/local/sbin:/usr/sbin:/sbin:/usr/bin:/bin:/usr/local/bin:/opt/kde/bin",1) == 0)
                  execlp("kdialog", "kdialog", "--msgbox", dialogmessage, "--title", "Virus found by KlamAV:",  NULL);
          free(dialogmessage);
      }
  } else if(ret == CL_CLEAN) {
      int bcnt = 0;
      lseek(fd, 0, SEEK_SET);
      if (!(tmp = fdopen(fd,"r"))){
          mprintf("@Can't open file %s\n", tmpnm);
          return 54;
      }

      mprintf_stdout = 1;

      while (fgets(string, sizeof(string), tmp)) {
          if (*string == '\n') {
                  mprintf("X-Virus-Status: No\n");
                  mprintf("X-Virus-Checker: Scanned by KlamAV %s on %s (no viruses);\n\t%s\n\n",
                          KLAMAV_VERSION, host, out);
                  break;
          }
          fputs(string, stdout);
      }
      while (fgets(string, sizeof(string), tmp)) {
          fputs(string, stdout);
      }

      if(optl(opt, "tag"))
          if (!(*bndrystore))
                  printtag();

      fclose(tmp);
  } else {
      if(!printinfected)
          mprintf("stdin: %s\n", cl_strerror(ret));
  }
  return ret;
}

void printtag(void)
{

    mprintf_stdout = 1;
    mprintf("\n");
    mprintf("----------------------------------------------------------------------------\n");
    mprintf("			This message was scanned by\n");
    mprintf("		ClamAV Open Source Anti-Virus Technology\n");
    mprintf("				using KlamAV\n");
    mprintf("\n");
    mprintf("			http://www.clamav.net\n");
    mprintf("			http://klamav.sf.net\n");
    mprintf("----------------------------------------------------------------------------\n");
    mprintf("\n");
    fflush(stdout);

}

void help(void)
{

    mprintf_stdout = 1;

    mprintf("\n");
    mprintf("		   KlamAV Mail Processing Client "KLAMAV_VERSION"\n");
    mprintf("		   (c) 2004 Robert Hogan <[email protected]>\n");
    mprintf("		   	Uses a lot of code written by:\n");
    mprintf("		       Tomasz Kojm <[email protected]>\n");
    mprintf("		       Nigel Horne <[email protected]>\n");
    mprintf("	  \n");
    mprintf("    --help		-h	Show help\n");
    mprintf("    --version		-V	Print version number and exit\n");
    mprintf("    -f			Header Flag Only.\n");
    mprintf("    --tag		Tag messages as scanned.\n");
    mprintf("    -d			Location of virus definition database.\n");

    exit(0);
}

void startclamd(struct optstruct *opt)
{

    int pfds[2];
    int childpid;
    int fd;
    char tmpnm[19];
    char conffile[31];
    struct stat sb;
    FILE *tmp;
    char *fullpath;
    char cwd[200];
    char *scancmd;

    snprintf(tmpnm, sizeof(tmpnm), "klammailXXXXXX");
    mkstemp(tmpnm);

    fd = open(tmpnm,O_RDWR|O_CREAT, S_IRWXU);


    lseek(fd, 0, SEEK_SET);
    if (!(tmp = fdopen(fd,"w"))){
            mprintf("@Can't open file \n");
    }

    fprintf(tmp,"LocalSocket /tmp/KlamMailSock\n");
    fprintf(tmp,"MaxDirectoryRecursion 15\n");
    fprintf(tmp,"SelfCheck 900\n");
    //fprintf(tmp,"ScanArchive\n");
    if(optc(opt, 'd')) {
            stat(getargc(opt, 'd'), &sb);
            switch(sb.st_mode & S_IFMT) {
                    case S_IFREG:
                    fprintf(tmp,"DatabaseDirectory %s\n",getargc(opt, 'd'));
                    break;
                    case S_IFDIR:
                    fprintf(tmp,"DatabaseDirectory %s\n",getargc(opt, 'd'));
                    break;
                    default:
                    mprintf("@%s: Not supported database file type\n", getargc(opt, 'd'));
                    break;
                    }
    }else{
            fprintf(tmp,"DatabaseDirectory /usr/local/share/clamav\n");
    }
    //fprintf(tmp,"ScanMail\n");
    if ((strstr(cl_retver(), "0.8")) || (strstr(cl_retver(), "0.7")))
        fprintf(tmp,"FixStaleSocket\n");
    else
        fprintf(tmp,"FixStaleSocket yes\n");

    fflush(tmp);

    fclose(tmp);
    close(fd);

    fullpath = (char*) mcalloc(200 + strlen(tmpnm) + 10, sizeof(char));

    if(!getcwd(cwd, 200)) {
            mprintf("@Can't get absolute pathname of current working directory.\n");
            return;
    }
    sprintf(fullpath, "%s/%s", cwd, tmpnm);


    if ( pipe(pfds) == -1 ) {
      perror("Failed to create pipe; quitting\n");
      exit(1);
    }

    if ( ( childpid=fork() ) == -1 ) {
      perror("Failed to fork; quitting\n");
      exit(2);
    }

    /* instead of STDIN -> clamdmail -> STDOUT, do
    STDIN -> clamdmail -> spamc -> STDOUT
    (previously incorrect as STDIN -> spamc -> clamdmail -> STDOUT)
    */
    if ( childpid == 0 ) {
            if (setenv("PATH","/usr/local/sbin:/usr/sbin:/sbin:/usr/bin:/bin:/usr/local/bin:/opt/kde/bin",1) == 0)
                    execlp("clamd", "clamd", "-c", fullpath,  NULL);
    }

    sleep(1);
    unlink(fullpath);
}