Source

ossec-hids / src / syscheckd / run_realtime.c

Full commit
  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
/* @(#) $Id$ */

/* Copyright (C) 2009 Trend Micro Inc.
 * All right reserved.
 *
 * This program is a free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation
 */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>


#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#include <io.h>

#define sleep(x) Sleep(x * 1000)
#define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0)
#define os_strdup(x,y) (y = strdup(x))?(void)1:ErrorExit(MEM_ERROR, ARGV0)
#endif


#include "hash_op.h"
#include "debug_op.h"
#include "syscheck.h"
#include "error_messages/error_messages.h"


#ifdef USEINOTIFY
#include <sys/inotify.h>
#define OS_SIZE_6144    6144
#define OS_MAXSTR       OS_SIZE_6144    /* Size for logs, sockets, etc */
#else
#include "shared.h"
#endif



/** Global functions for all realtime options. **/
int c_read_file(char *file_name, char *oldsum, char *newsum);


/* Checking sum of the realtime file being monitored. */
int realtime_checksumfile(char *file_name)
{
    char *buf;

    buf = OSHash_Get(syscheck.fp, file_name);
    if(buf != NULL)
    {
        char c_sum[256 +2];

        c_sum[0] = '\0';
        c_sum[255] = '\0';


         /* If it returns < 0, we will already have alerted. */
         if(c_read_file(file_name, buf, c_sum) < 0)
         {
             return(0);
         }


         if(strcmp(c_sum, buf+6) != 0)
         {
             char *fullalert = NULL;
             char alert_msg[OS_MAXSTR +1];
             alert_msg[OS_MAXSTR] = '\0';
             if(buf[5] == 's' || buf[5] == 'n')
             {
                 fullalert = seechanges_addfile(file_name);
                 if(fullalert)
                 {
                    snprintf(alert_msg, OS_MAXSTR, "%s %s\n%s", c_sum, file_name, fullalert);
                    free(fullalert);
                    fullalert = NULL;
                 }
                 else
                 {
                     snprintf(alert_msg, 912, "%s %s", c_sum, file_name);
                 }
             }
             else
             {
                 snprintf(alert_msg, 912, "%s %s", c_sum, file_name);
             }
             send_syscheck_msg(alert_msg);

             return(1);
         }

         return(0);

    }

    return(0);
}




#ifdef USEINOTIFY
#include <sys/inotify.h>


#define REALTIME_MONITOR_FLAGS  IN_MODIFY|IN_ATTRIB|IN_MOVED_FROM|IN_MOVED_TO|IN_CREATE|IN_DELETE|IN_DELETE_SELF
#define REALTIME_EVENT_SIZE     (sizeof (struct inotify_event))
#define REALTIME_EVENT_BUFFER   (2048 * (REALTIME_EVENT_SIZE + 16))



/* Starts real time monitoring using inotify. */
int realtime_start()
{
    verbose("%s: INFO: Initializing real time file monitoring (not started).", ARGV0);

    syscheck.realtime = calloc(1, sizeof(rtfim));
    if(syscheck.realtime == NULL)
    {
        ErrorExit(MEM_ERROR, ARGV0);
    }
    syscheck.realtime->dirtb = (void *)OSHash_Create();
    syscheck.realtime->fd = -1;

    #ifdef USEINOTIFY
    syscheck.realtime->fd = inotify_init();
    if(syscheck.realtime->fd < 0)
    {
        merror("%s: ERROR: Unable to initialize inotify.", ARGV0);
        return(-1);
    }
    #endif    

    return(1);
}



/* Adds a directory to real time checking. */
int realtime_adddir(char *dir)
{
    if(!syscheck.realtime)
    {
        realtime_start();
    }


    /* Checking if it is ready to use. */
    if(syscheck.realtime->fd < 0)
    {
        return(-1);
    }
    else
    {
        int wd = 0;

        wd = inotify_add_watch(syscheck.realtime->fd,
                               dir,
                               REALTIME_MONITOR_FLAGS); 
        if(wd < 0)
        {
            merror("%s: ERROR: Unable to add directory to real time " 
                   "monitoring: '%s'. %d %d", ARGV0, dir, wd, errno);
        }
        else
        {
            char wdchar[32 +1];
            wdchar[32] = '\0';
            snprintf(wdchar, 32, "%d", wd);

            /* Entry not present. */
            if(!OSHash_Get(syscheck.realtime->dirtb, wdchar))
            {
                char *ndir;

                ndir = strdup(dir);
                if(ndir == NULL)
                {
                    ErrorExit("%s: ERROR: Out of memory. Exiting.", ARGV0);
                }

                OSHash_Add(syscheck.realtime->dirtb, strdup(wdchar), ndir);
                debug1("%s: DEBUG: Directory added for real time monitoring: "
                       "'%s'.", ARGV0, ndir);
            }
        }
    }

    return(1);
}


/* Process events in the real time queue. */
int realtime_process()
{
    int len, i = 0;
    char buf[REALTIME_EVENT_BUFFER +1];
    struct inotify_event *event;

    buf[REALTIME_EVENT_BUFFER] = '\0';


    len = read(syscheck.realtime->fd, buf, REALTIME_EVENT_BUFFER);
    if (len < 0) 
    {
        merror("%s: ERROR: Unable to read from real time buffer.", ARGV0);
    } 
    else if (len > 0)
    {
        while (i < len) 
        {
            event = (struct inotify_event *) &buf[i];

            if(event->len)
            {
                char wdchar[32 +1];
                char final_name[MAX_LINE +1];

                wdchar[32] = '\0';
                final_name[MAX_LINE] = '\0';

                snprintf(wdchar, 32, "%d", event->wd);

                snprintf(final_name, MAX_LINE, "%s/%s", 
                         (char *)OSHash_Get(syscheck.realtime->dirtb, wdchar),
                         event->name);
                realtime_checksumfile(final_name);
            }

            i += REALTIME_EVENT_SIZE + event->len;
        }
    }

    return(0);
}



#elif WIN32
typedef struct _win32rtfim
{
    HANDLE h;
    OVERLAPPED overlap;

    char *dir;
    TCHAR buffer[12288];
}win32rtfim;

int realtime_win32read(win32rtfim *rtlocald);

void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap)
{
    int lcount;
    size_t offset = 0;

    char *ptfile;
    char wdchar[32 +1];
    char final_path[MAX_LINE +1];

    win32rtfim *rtlocald;

    PFILE_NOTIFY_INFORMATION pinfo;
    TCHAR finalfile[MAX_PATH];

    if(dwBytes == 0)
    {
        merror("%s: ERROR: real time call back called, but 0 bytes.", ARGV0);
        return;
    }

    if(dwerror != ERROR_SUCCESS)
    {
        merror("%s: ERROR: real time call back called, but error is set.", 
               ARGV0);
        return;
    }


    /* Getting hash to parse the data. */
    wdchar[32] = '\0';
    snprintf(wdchar, 32, "%d", (int)overlap->Offset);
    rtlocald = OSHash_Get(syscheck.realtime->dirtb, wdchar);
    if(rtlocald == NULL)
    {
        merror("%s: ERROR: real time call back called, but hash is empty.", 
               ARGV0);
        return;
    }

        

    do
    {
        pinfo = (PFILE_NOTIFY_INFORMATION) &rtlocald->buffer[offset];
        offset += pinfo->NextEntryOffset;

        lcount = WideCharToMultiByte(CP_ACP, 0, pinfo->FileName,
                                     pinfo->FileNameLength / sizeof(WCHAR),
                                     finalfile, MAX_PATH - 1, NULL, NULL);
        finalfile[lcount] = TEXT('\0');


        /* Change forward slashes to backslashes on finalfile. */
        ptfile = strchr(finalfile, '\\');
        while(ptfile)
        {
            *ptfile = '/';
            ptfile++;

            ptfile = strchr(ptfile, '\\');
        }

        final_path[MAX_LINE] = '\0';
        snprintf(final_path, MAX_LINE, "%s/%s", rtlocald->dir, finalfile);


        /* Checking the change. */
        realtime_checksumfile(final_path);


        /*
        if(pinfo->Action == FILE_ACTION_ADDED)
        else if(pinfo->Action == FILE_ACTION_REMOVED)
        else if(pinfo->Action == FILE_ACTION_MODIFIED)
        else if(pinfo->Action == FILE_ACTION_RENAMED_OLD_NAME)
        else if(pinfo->Action == FILE_ACTION_RENAMED_NEW_NAME)
        else
        */

    }while(pinfo->NextEntryOffset != 0);


    realtime_win32read(rtlocald);


    return;
}



int realtime_start()
{
    verbose("%s: INFO: Initializing real time file monitoring (not started).", ARGV0);

    os_calloc(1, sizeof(rtfim), syscheck.realtime);
    syscheck.realtime->dirtb = (void *)OSHash_Create();
    syscheck.realtime->fd = -1;
    syscheck.realtime->evt = CreateEvent(NULL, TRUE, FALSE, NULL);
    return(0);
}

int realtime_win32read(win32rtfim *rtlocald)
{
    int rc;

    rc = ReadDirectoryChangesW(rtlocald->h,
                               rtlocald->buffer,
                               sizeof(rtlocald->buffer) / sizeof(TCHAR),
                               TRUE,
                               FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE,
                               0,
                               &rtlocald->overlap, 
                               RTCallBack);
    if(rc == 0)
    {
        merror("%s: ERROR: Unable to set directory for monitoring: %s", 
               ARGV0, rtlocald->dir);
        sleep(2);
    }

    return(0);
}

int realtime_adddir(char *dir)
{
    char wdchar[32 +1];
    win32rtfim *rtlocald;


    if(!syscheck.realtime)
    {
        realtime_start();
    }


    /* Maximum limit for realtime on Windows. */
    if(syscheck.realtime->fd > 256)
    {
        merror("%s: ERROR: Unable to add directory to real time "
               "monitoring: '%s' - Maximum size permitted.", ARGV0, dir);
        return(0);
    }


    os_calloc(1, sizeof(win32rtfim), rtlocald);
    

    rtlocald->h = CreateFile(dir,
                             FILE_LIST_DIRECTORY,
                             FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
                             NULL,
                             OPEN_EXISTING,
                             FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED,
                             NULL);


    if(rtlocald->h == INVALID_HANDLE_VALUE || 
       rtlocald->h == NULL) 
    {
        free(rtlocald);
        rtlocald = NULL;
        merror("%s: ERROR: Unable to add directory to real time "
               "monitoring: '%s'.", ARGV0, dir);
        return(0);
    }

    rtlocald->overlap.Offset = ++syscheck.realtime->fd;



    /* Setting key for hash. */
    wdchar[32] = '\0';
    snprintf(wdchar, 32, "%d", (int)rtlocald->overlap.Offset);


    if(OSHash_Get(syscheck.realtime->dirtb, wdchar))
    {
        merror("%s: ERROR: Entry already in the real time hash: %s", 
               ARGV0, wdchar);
        CloseHandle(rtlocald->overlap.hEvent);
        free(rtlocald);
        rtlocald = NULL;
        return(0);
    }


    /* Adding final elements to the hash. */
    os_strdup(dir, rtlocald->dir);

    OSHash_Add(syscheck.realtime->dirtb, strdup(wdchar), rtlocald);


    /* Adding directory to be monitored. */
    realtime_win32read(rtlocald);


    return(1);
}





#else
int realtime_start()
{
    verbose("%s: ERROR: Unable to initalize real time file monitoring.", ARGV0);
    return(0);
}

int realtime_adddir(char *dir)
{
    return(0);
}

int realtime_process()
{
    return(0);
}

#endif
/* EOF */