-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
analysisd.c
2695 lines (2229 loc) · 78.7 KB
/
analysisd.c
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2015-2019, Wazuh Inc.
* Copyright (C) 2010-2012 Trend Micro Inc.
* All rights reserved.
*
* This program is 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.
*/
/* ossec-analysisd
* Responsible for correlation and log decoding
*/
#ifndef ARGV0
#define ARGV0 "ossec-analysisd"
#endif
#include <time.h>
#include "shared.h"
#include "alerts/alerts.h"
#include "alerts/getloglocation.h"
#include "os_execd/execd.h"
#include "os_regex/os_regex.h"
#include "os_net/os_net.h"
#include "active-response.h"
#include "config.h"
#include "rules.h"
#include "stats.h"
#include "eventinfo.h"
#include "accumulator.h"
#include "analysisd.h"
#include "fts.h"
#include "cleanevent.h"
#include "dodiff.h"
#include "output/jsonout.h"
#include "labels.h"
#include "state.h"
#include "syscheck_op.h"
#ifdef PRELUDE_OUTPUT_ENABLED
#include "output/prelude.h"
#endif
#ifdef ZEROMQ_OUTPUT_ENABLED
#include "output/zeromq.h"
#endif
/** Prototypes **/
void OS_ReadMSG(int m_queue);
RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node, regex_matching *rule_match);
static void LoopRule(RuleNode *curr_node, FILE *flog);
/* For decoders */
void DecodeEvent(Eventinfo *lf, regex_matching *decoder_match);
int DecodeSyscheck(Eventinfo *lf, _sdb *sdb);
int DecodeRootcheck(Eventinfo *lf);
int DecodeHostinfo(Eventinfo *lf);
int DecodeSyscollector(Eventinfo *lf,int *socket);
int DecodeCiscat(Eventinfo *lf, int *socket);
int DecodeWinevt(Eventinfo *lf);
int DecodeSCA(Eventinfo *lf,int *socket);
// Init sdb and decoder struct
void sdb_init(_sdb *localsdb, OSDecoderInfo *fim_decoder);
/* For stats */
static void DumpLogstats(void);
// Message handler thread
void * ad_input_main(void * args);
/** Global definitions **/
int today;
int thishour;
int prev_year;
char prev_month[4];
int __crt_hour;
int __crt_wday;
struct timespec c_timespec;
char __shost[512];
OSDecoderInfo *NULL_Decoder;
rlim_t nofile;
int sys_debug_level;
int num_rule_matching_threads;
EventList *last_events_list;
time_t current_time;
/* execd queue */
static int execdq = 0;
/* Active response queue */
static int arq = 0;
static unsigned int hourly_alerts;
static unsigned int hourly_events;
static unsigned int hourly_syscheck;
static unsigned int hourly_firewall;
void w_free_event_info(Eventinfo *lf);
/* Output threads */
void * w_main_output_thread(__attribute__((unused)) void * args);
/* Archives writer thread */
void * w_writer_thread(__attribute__((unused)) void * args );
/* Alerts log writer thread */
void * w_writer_log_thread(__attribute__((unused)) void * args );
/* Statistical writer thread */
void * w_writer_log_statistical_thread(__attribute__((unused)) void * args );
/* Firewall log writer thread */
void * w_writer_log_firewall_thread(__attribute__((unused)) void * args );
/* FTS log writer thread */
void * w_writer_log_fts_thread(__attribute__((unused)) void * args );
/* Flush logs thread */
void w_log_flush();
/* Decode syscollector threads */
void * w_decode_syscollector_thread(__attribute__((unused)) void * args);
/* Decode syscheck threads */
void * w_decode_syscheck_thread(__attribute__((unused)) void * args);
/* Decode hostinfo threads */
void * w_decode_hostinfo_thread(__attribute__((unused)) void * args);
/* Decode rootcheck threads */
void * w_decode_rootcheck_thread(__attribute__((unused)) void * args);
/* Decode Security Configuration Assessment threads */
void * w_decode_sca_thread(__attribute__((unused)) void * args);
/* Decode event threads */
void * w_decode_event_thread(__attribute__((unused)) void * args);
/* Process decoded event - rule matching threads */
void * w_process_event_thread(__attribute__((unused)) void * id);
/* Do log rotation thread */
void * w_log_rotate_thread(__attribute__((unused)) void * args);
/* Decode winevt threads */
void * w_decode_winevt_thread(__attribute__((unused)) void * args);
typedef struct _clean_msg {
Eventinfo *lf;
char *msg;
} clean_msg;
typedef struct _decode_event {
Eventinfo *lf;
char type;
} decode_event;
typedef struct _osmatch_exec {
Eventinfo *lf;
RuleInfo *rule;
} _osmatch_execute;
/* Archives writer queue */
static w_queue_t * writer_queue;
/* Alerts log writer queue */
static w_queue_t * writer_queue_log;
/* Statistical log writer queue */
static w_queue_t * writer_queue_log_statistical;
/* Firewall log writer queue */
static w_queue_t * writer_queue_log_firewall;
/* FTS log writer queue */
static w_queue_t * writer_queue_log_fts;
/* Decode syscheck input queue */
static w_queue_t * decode_queue_syscheck_input;
/* Decode syscollector input queue */
static w_queue_t * decode_queue_syscollector_input;
/* Decode rootcheck input queue */
static w_queue_t * decode_queue_rootcheck_input;
/* Decode policy monitoring input queue */
static w_queue_t * decode_queue_sca_input;
/* Decode hostinfo input queue */
static w_queue_t * decode_queue_hostinfo_input;
/* Decode event input queue */
static w_queue_t * decode_queue_event_input;
/* Decode pending event output */
static w_queue_t * decode_queue_event_output;
/* Decode windows event input queue */
static w_queue_t * decode_queue_winevt_input;
/* Hourly alerts mutex */
static pthread_mutex_t hourly_alert_mutex = PTHREAD_MUTEX_INITIALIZER;
/* Hourly firewall mutex */
static pthread_mutex_t hourly_firewall_mutex = PTHREAD_MUTEX_INITIALIZER;
/* Do diff mutex */
static pthread_mutex_t do_diff_mutex = PTHREAD_MUTEX_INITIALIZER;
/* Reported variables */
static int reported_syscheck = 0;
static int reported_syscollector = 0;
static int reported_hostinfo = 0;
static int reported_rootcheck = 0;
static int reported_sca = 0;
static int reported_event = 0;
static int reported_writer = 0;
static int reported_winevt = 0;
/* Mutexes */
pthread_mutex_t decode_syscheck_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t process_event_check_hour_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t process_event_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lf_mutex = PTHREAD_MUTEX_INITIALIZER;
/* Reported mutexes */
static pthread_mutex_t writer_threads_mutex = PTHREAD_MUTEX_INITIALIZER;
/* To translate between month (int) to month (char) */
static const char *(month[]) = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
/* CPU Info*/
static int cpu_cores;
/* Print help statement */
__attribute__((noreturn))
static void help_analysisd(void)
{
print_header();
print_out(" %s: -[Vhdtf] [-u user] [-g group] [-c config] [-D dir]", ARGV0);
print_out(" -V Version and license message");
print_out(" -h This help message");
print_out(" -d Execute in debug mode. This parameter");
print_out(" can be specified multiple times");
print_out(" to increase the debug level.");
print_out(" -t Test configuration");
print_out(" -f Run in foreground");
print_out(" -u <user> User to run as (default: %s)", USER);
print_out(" -g <group> Group to run as (default: %s)", GROUPGLOBAL);
print_out(" -c <config> Configuration file to use (default: %s)", DEFAULTCPATH);
print_out(" -D <dir> Directory to chroot into (default: %s)", DEFAULTDIR);
print_out(" ");
exit(1);
}
#ifndef TESTRULE
int main(int argc, char **argv)
#else
__attribute__((noreturn))
int main_analysisd(int argc, char **argv)
#endif
{
int c = 0, m_queue = 0, test_config = 0, run_foreground = 0;
int debug_level = 0;
const char *dir = DEFAULTDIR;
const char *user = USER;
const char *group = GROUPGLOBAL;
uid_t uid;
gid_t gid;
const char *cfg = DEFAULTCPATH;
/* Set the name */
OS_SetName(ARGV0);
thishour = 0;
today = 0;
prev_year = 0;
memset(prev_month, '\0', 4);
hourly_alerts = 0;
hourly_events = 0;
hourly_syscheck = 0;
hourly_firewall = 0;
sys_debug_level = getDefine_Int("analysisd", "debug", 0, 2);
#ifdef LIBGEOIP_ENABLED
geoipdb = NULL;
#endif
while ((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1) {
switch (c) {
case 'V':
print_version();
break;
case 'h':
help_analysisd();
break;
case 'd':
nowDebug();
debug_level = 1;
break;
case 'f':
run_foreground = 1;
break;
case 'u':
if (!optarg) {
merror_exit("-u needs an argument");
}
user = optarg;
break;
case 'g':
if (!optarg) {
merror_exit("-g needs an argument");
}
group = optarg;
break;
case 'D':
if (!optarg) {
merror_exit("-D needs an argument");
}
dir = optarg;
break;
case 'c':
if (!optarg) {
merror_exit("-c needs an argument");
}
cfg = optarg;
break;
case 't':
test_config = 1;
break;
default:
help_analysisd();
break;
}
}
/* Check current debug_level
* Command line setting takes precedence
*/
if (debug_level == 0) {
/* Get debug level */
debug_level = sys_debug_level;
while (debug_level != 0) {
nowDebug();
debug_level--;
}
}
/* Start daemon */
mdebug1(STARTED_MSG);
DEBUG_MSG("%s: DEBUG: Starting on debug mode - %d ", ARGV0, (int)time(0));
srandom_init();
/* Check if the user/group given are valid */
uid = Privsep_GetUser(user);
gid = Privsep_GetGroup(group);
if (uid == (uid_t) - 1 || gid == (gid_t) - 1) {
merror_exit(USER_ERROR, user, group);
}
/* Found user */
mdebug1(FOUND_USER);
/* Initialize Active response */
AR_Init();
if (AR_ReadConfig(cfg) < 0) {
merror_exit(CONFIG_ERROR, cfg);
}
mdebug1(ASINIT);
/* Read configuration file */
if (GlobalConf(cfg) < 0) {
merror_exit(CONFIG_ERROR, cfg);
}
mdebug1(READ_CONFIG);
if (!(Config.alerts_log || Config.jsonout_output)) {
mwarn("All alert formats are disabled. Mail reporting, Syslog client and Integrator won't work properly.");
}
#ifdef LIBGEOIP_ENABLED
Config.geoip_jsonout = getDefine_Int("analysisd", "geoip_jsonout", 0, 1);
/* Opening GeoIP DB */
if(Config.geoipdb_file) {
geoipdb = GeoIP_open(Config.geoipdb_file, GEOIP_INDEX_CACHE);
if (geoipdb == NULL)
{
merror("Unable to open GeoIP database from: %s (disabling GeoIP).", Config.geoipdb_file);
}
}
#endif
/* Fix Config.ar */
Config.ar = ar_flag;
if (Config.ar == -1) {
Config.ar = 0;
}
/* Get server's hostname */
memset(__shost, '\0', 512);
if (gethostname(__shost, 512 - 1) != 0) {
strncpy(__shost, OSSEC_SERVER, 512 - 1);
} else {
char *_ltmp;
/* Remove domain part if available */
_ltmp = strchr(__shost, '.');
if (_ltmp) {
*_ltmp = '\0';
}
}
// Set resource limit for file descriptors
{
nofile = getDefine_Int("analysisd", "rlimit_nofile", 1024, 1048576);
struct rlimit rlimit = { nofile, nofile };
if (setrlimit(RLIMIT_NOFILE, &rlimit) < 0) {
merror("Could not set resource limit for file descriptors to %d: %s (%d)", (int)nofile, strerror(errno), errno);
}
}
/* Check the CPU INFO */
/* If we have the threads set to 0 on internal_options.conf, then */
/* we assign them automatically based on the number of cores */
cpu_cores = get_nproc();
num_rule_matching_threads = getDefine_Int("analysisd", "rule_matching_threads", 0, 32);
if(num_rule_matching_threads == 0){
num_rule_matching_threads = cpu_cores;
}
/* Continuing in Daemon mode */
if (!test_config && !run_foreground) {
nowDaemon();
goDaemon();
}
#ifdef PRELUDE_OUTPUT_ENABLED
/* Start prelude */
if (Config.prelude) {
prelude_start(Config.prelude_profile, argc, argv);
}
#endif
#ifdef ZEROMQ_OUTPUT_ENABLED
/* Start zeromq */
if (Config.zeromq_output) {
#if CZMQ_VERSION_MAJOR == 2
zeromq_output_start(Config.zeromq_output_uri);
#elif CZMQ_VERSION_MAJOR >= 3
zeromq_output_start(Config.zeromq_output_uri, Config.zeromq_output_client_cert, Config.zeromq_output_server_cert);
#endif
}
#endif
/* Set the group */
if (Privsep_SetGroup(gid) < 0) {
merror_exit(SETGID_ERROR, group, errno, strerror(errno));
}
/* Chroot */
if (Privsep_Chroot(dir) < 0) {
merror_exit(CHROOT_ERROR, dir, errno, strerror(errno));
}
nowChroot();
Config.decoder_order_size = (size_t)getDefine_Int("analysisd", "decoder_order_size", MIN_ORDER_SIZE, MAX_DECODER_ORDER_SIZE);
if (!last_events_list) {
os_calloc(1, sizeof(EventList), last_events_list);
OS_CreateEventList(Config.memorysize, last_events_list);
}
/*
* Anonymous Section: Load rules, decoders, and lists
*
* As lists require two-pass loading of rules that makes use of lists, lookups
* are created with blank database structs, and need to be filled in after
* completion of all rules and lists.
*/
{
{
/* Initialize the decoders list */
OS_CreateOSDecoderList();
/* If we haven't specified a decoders directory, load default */
if (!Config.decoders) {
/* Legacy loading */
/* Read default decoders */
Read_Rules(NULL, &Config, NULL);
}
/* New loaded based on file loaded (in ossec.conf or default) */
{
char **decodersfiles;
decodersfiles = Config.decoders;
while ( decodersfiles && *decodersfiles) {
if (!test_config) {
mdebug1("Reading decoder file %s.", *decodersfiles);
}
if (!ReadDecodeXML(*decodersfiles)) {
merror_exit(CONFIG_ERROR, *decodersfiles);
}
free(*decodersfiles);
decodersfiles++;
}
}
/* Load decoders */
SetDecodeXML();
}
{
/* Load Lists */
/* Initialize the lists of list struct */
Lists_OP_CreateLists();
/* Load each list into list struct */
{
char **listfiles;
listfiles = Config.lists;
while (listfiles && *listfiles) {
if (!test_config) {
mdebug1("Reading the lists file: '%s'", *listfiles);
}
if (Lists_OP_LoadList(*listfiles) < 0) {
merror_exit(LISTS_ERROR, *listfiles);
}
free(*listfiles);
listfiles++;
}
free(Config.lists);
Config.lists = NULL;
}
}
{
/* Load Rules */
/* Create the rules list */
Rules_OP_CreateRules();
/* If we haven't specified a rules directory, load default */
if (!Config.includes) {
Read_Rules(NULL, &Config, NULL);
}
/* Read the rules */
{
char **rulesfiles;
rulesfiles = Config.includes;
while (rulesfiles && *rulesfiles) {
if (!test_config) {
mdebug1("Reading rules file: '%s'", *rulesfiles);
}
if (Rules_OP_ReadRules(*rulesfiles) < 0) {
merror_exit(RULES_ERROR, *rulesfiles);
}
free(*rulesfiles);
rulesfiles++;
}
free(Config.includes);
Config.includes = NULL;
}
/* Find all rules that require list lookups and attache the the
* correct list struct to the rule. This keeps rules from having to
* search thought the list of lists for the correct file during
* rule evaluation.
*/
OS_ListLoadRules();
}
}
/* Fix the levels/accuracy */
{
int total_rules;
RuleNode *tmp_node = OS_GetFirstRule();
total_rules = _setlevels(tmp_node, 0);
if (!test_config) {
minfo("Total rules enabled: '%d'", total_rules);
}
}
/* Create a rules hash (for reading alerts from other servers) */
{
RuleNode *tmp_node = OS_GetFirstRule();
Config.g_rules_hash = OSHash_Create();
if (!Config.g_rules_hash) {
merror_exit(MEM_ERROR, errno, strerror(errno));
}
AddHash_Rule(tmp_node);
}
/* Ignored files on syscheck */
{
char **files;
files = Config.syscheck_ignore;
while (files && *files) {
if (!test_config) {
minfo("Ignoring file: '%s'", *files);
}
files++;
}
}
/* Check if log_fw is enabled */
Config.logfw = (u_int8_t) getDefine_Int("analysisd",
"log_fw",
0, 1);
/* Success on the configuration test */
if (test_config) {
exit(0);
}
if (Config.queue_size != 0) {
minfo("The option <queue_size> is deprecated and won't apply. Set up each queue size in the internal_options file.");
}
/* Verbose message */
mdebug1(PRIVSEP_MSG, dir, user);
/* Signal manipulation */
StartSIG(ARGV0);
/* Set the user */
if (Privsep_SetUser(uid) < 0) {
merror_exit(SETUID_ERROR, user, errno, strerror(errno));
}
/* Create the PID file */
if (CreatePID(ARGV0, getpid()) < 0) {
merror_exit(PID_ERROR);
}
/* Set the queue */
if ((m_queue = StartMQ(DEFAULTQUEUE, READ)) < 0) {
merror_exit(QUEUE_ERROR, DEFAULTQUEUE, strerror(errno));
}
/* Whitelist */
if (Config.white_list == NULL) {
if (Config.ar) {
minfo("No IP in the white list for active response.");
}
} else {
if (Config.ar) {
os_ip **wl;
int wlc = 0;
wl = Config.white_list;
while (*wl) {
minfo("White listing IP: '%s'", (*wl)->ip);
wl++;
wlc++;
}
minfo("%d IPs in the white list for active response.", wlc);
}
}
/* Hostname whitelist */
if (Config.hostname_white_list == NULL) {
if (Config.ar)
minfo("No Hostname in the white list for active response.");
} else {
if (Config.ar) {
int wlc = 0;
OSMatch **wl;
wl = Config.hostname_white_list;
while (*wl) {
char **tmp_pts = (*wl)->patterns;
while (*tmp_pts) {
minfo("White listing Hostname: '%s'", *tmp_pts);
wlc++;
tmp_pts++;
}
wl++;
}
minfo("%d Hostname(s) in the white list for active response.",wlc);
}
}
/* Startup message */
minfo(STARTUP_MSG, (int)getpid());
// Start com request thread
w_create_thread(asyscom_main, NULL);
/* Going to main loop */
OS_ReadMSG(m_queue);
exit(0);
}
/* Main function. Receives the messages(events) and analyze them all */
#ifndef TESTRULE
__attribute__((noreturn))
void OS_ReadMSG(int m_queue)
#else
__attribute__((noreturn))
void OS_ReadMSG_analysisd(int m_queue)
#endif
{
Eventinfo *lf = NULL;
int i;
/* Initialize the logs */
OS_InitLog();
/* Initialize the integrity database */
if (!fim_init()) merror_exit("fim: Initialization failed");
/* Initialize Rootcheck */
RootcheckInit();
/* Initialize Syscollector */
SyscollectorInit();
/* Initialize CIS-CAT */
CiscatInit();
/* Initialize host info */
HostinfoInit();
/* Initialize windows event */
WinevtInit();
/* Initialize Security Configuration Assessment event */
SecurityConfigurationAssessmentInit();
/* Initialize the Accumulator */
if (!Accumulate_Init()) {
merror("accumulator: ERROR: Initialization failed");
exit(1);
}
/* Start the active response queues */
if (Config.ar) {
/* Waiting the ARQ to settle */
sleep(3);
#ifndef LOCAL
if (Config.ar & REMOTE_AR) {
if ((arq = StartMQ(ARQUEUE, WRITE)) < 0) {
merror(ARQ_ERROR);
/* If LOCAL_AR is set, keep it there */
if (Config.ar & LOCAL_AR) {
Config.ar = 0;
Config.ar |= LOCAL_AR;
} else {
Config.ar = 0;
}
} else {
minfo(CONN_TO, ARQUEUE, "active-response");
}
}
#else
/* Only for LOCAL_ONLY installs */
if (Config.ar & REMOTE_AR) {
if (Config.ar & LOCAL_AR) {
Config.ar = 0;
Config.ar |= LOCAL_AR;
} else {
Config.ar = 0;
}
}
#endif
if (Config.ar & LOCAL_AR) {
if ((execdq = StartMQ(EXECQUEUE, WRITE)) < 0) {
merror(ARQ_ERROR);
/* If REMOTE_AR is set, keep it there */
if (Config.ar & REMOTE_AR) {
Config.ar = 0;
Config.ar |= REMOTE_AR;
} else {
Config.ar = 0;
}
} else {
minfo(CONN_TO, EXECQUEUE, "exec");
}
}
}
mdebug1("Active response Init completed.");
/* Get current time before starting */
gettime(&c_timespec);
Start_Time();
/* Start the hourly/weekly stats directories*/
if(Init_Stats_Directories() < 0) {
Config.stats = 0;
}
/* Initialize the logs */
{
os_calloc(1, sizeof(Eventinfo), lf);
os_calloc(Config.decoder_order_size, sizeof(DynamicField), lf->fields);
lf->year = prev_year;
strncpy(lf->mon, prev_month, 3);
lf->day = today;
if (OS_GetLogLocation(today,prev_year,prev_month) < 0) {
merror_exit("Error allocating log files");
}
Free_Eventinfo(lf);
}
/* Initialize label cache */
if (!labels_init()) merror_exit("Error allocating labels");
Config.label_cache_maxage = getDefine_Int("analysisd", "label_cache_maxage", 0, 60);
Config.show_hidden_labels = getDefine_Int("analysisd", "show_hidden_labels", 0, 1);
if (Config.custom_alert_output) {
mdebug1("Custom output found.!");
}
w_init_queues();
/* Queue stats */
w_get_initial_queues_size();
int num_decode_event_threads = getDefine_Int("analysisd", "event_threads", 0, 32);
int num_decode_syscheck_threads = getDefine_Int("analysisd", "syscheck_threads", 0, 32);
int num_decode_syscollector_threads = getDefine_Int("analysisd", "syscollector_threads", 0, 32);
int num_decode_rootcheck_threads = getDefine_Int("analysisd", "rootcheck_threads", 0, 32);
int num_decode_sca_threads = getDefine_Int("analysisd", "sca_threads", 0, 32);
int num_decode_hostinfo_threads = getDefine_Int("analysisd", "hostinfo_threads", 0, 32);
int num_decode_winevt_threads = getDefine_Int("analysisd", "winevt_threads", 0, 32);
if(num_decode_event_threads == 0){
num_decode_event_threads = cpu_cores;
}
if(num_decode_syscheck_threads == 0){
num_decode_syscheck_threads = cpu_cores;
}
if(num_decode_syscollector_threads == 0){
num_decode_syscollector_threads = cpu_cores;
}
if(num_decode_rootcheck_threads == 0){
num_decode_rootcheck_threads = cpu_cores;
}
if(num_decode_sca_threads == 0){
num_decode_sca_threads = cpu_cores;
}
if(num_decode_hostinfo_threads == 0){
num_decode_hostinfo_threads = cpu_cores;
}
if(num_decode_winevt_threads == 0){
num_decode_winevt_threads = cpu_cores;
}
/* Initiate the FTS list */
if (!FTS_Init(num_rule_matching_threads)) {
merror_exit(FTS_LIST_ERROR);
}
/* Create message handler thread */
w_create_thread(ad_input_main, &m_queue);
/* Create archives writer thread */
w_create_thread(w_writer_thread,NULL);
/* Create alerts log writer thread */
w_create_thread(w_writer_log_thread,NULL);
/* Create statistical log writer thread */
w_create_thread(w_writer_log_statistical_thread,NULL);
/* Create firewall log writer thread */
w_create_thread(w_writer_log_firewall_thread,NULL);
/* Create FTS log writer thread */
w_create_thread(w_writer_log_fts_thread,NULL);
/* Create log rotation thread */
w_create_thread(w_log_rotate_thread,NULL);
/* Create decode syscheck threads */
for(i = 0; i < num_decode_syscheck_threads;i++){
w_create_thread(w_decode_syscheck_thread,NULL);
}
/* Create decode syscollector threads */
for(i = 0; i < num_decode_syscollector_threads;i++){
w_create_thread(w_decode_syscollector_thread,NULL);
}
/* Create decode hostinfo threads */
for(i = 0; i < num_decode_hostinfo_threads;i++){
w_create_thread(w_decode_hostinfo_thread,NULL);
}
/* Create decode rootcheck threads */
for(i = 0; i < num_decode_rootcheck_threads;i++){
w_create_thread(w_decode_rootcheck_thread,NULL);
}
/* Create decode Security Configuration Assessment threads */
for(i = 0; i < num_decode_sca_threads;i++){
w_create_thread(w_decode_sca_thread,NULL);
}
/* Create decode event threads */
for(i = 0; i < num_decode_event_threads;i++){
w_create_thread(w_decode_event_thread,NULL);
}
/* Create the process event threads */
for(i = 0; i < num_rule_matching_threads;i++){
w_create_thread(w_process_event_thread,(void *) (intptr_t)i);
}
/* Create decode winevt threads */
for(i = 0; i < num_decode_winevt_threads;i++){
w_create_thread(w_decode_winevt_thread,NULL);
}
/* Create State thread */
w_create_thread(w_analysisd_state_main,NULL);
mdebug1("Startup completed. Waiting for new messages..");
while (1) {
sleep(1);
}
}
/* Checks if the current_rule matches the event information */
RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node, regex_matching *rule_match)
{
/* We check for:
* decoded_as,
* fts,
* word match (fast regex),
* regex,
* url,
* id,
* user,
* maxsize,
* protocol,
* srcip,
* dstip,
* srcport,
* dstport,
* time,
* weekday,
* status,
*/
RuleInfo *rule = curr_node->ruleinfo;
int i;
const char *field;
/* Can't be null */
if (!rule) {
merror("Inconsistent state. currently rule NULL");
return (NULL);
}
#ifdef TESTRULE
if (full_output && !alert_only)
print_out(" Trying rule: %d - %s", rule->sigid,
rule->comment);
#endif
/* Check if any decoder pre-matched here for syscheck event */
if(lf->decoder_syscheck_id != 0 && (rule->decoded_as &&
rule->decoded_as != lf->decoder_syscheck_id)){
return (NULL);
}
/* Check if any decoder pre-matched here for non-syscheck events*/
else if (lf->decoder_syscheck_id == 0 && (rule->decoded_as &&