/
pandora_agent
2407 lines (1959 loc) · 73.2 KB
/
pandora_agent
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
#!/usr/bin/perl
# **********************************************************************
# Pandora FMS Generic Unix/Perl Agent
# (c) 2009-2011 Artica Soluciones Tecnológicas
# with the help of many people. Please see http://pandorafms.org
# This code is licensed under GPL 2.0 license.
# **********************************************************************
=head1 NAME
pandora_agent - Pandora FMS Agent
=head1 VERSION
Version 5.0
=head1 USAGE
<< pandora_agent F<pandora home> >>
=cut
use strict;
use warnings;
use POSIX qw(strftime floor);
use Sys::Hostname;
use File::Basename;
use File::Copy;
use IO::Socket;
use Sys::Syslog;
# Agent XML data
my $Xml;
# Semaphore used to acces $Xml
my $Sem = undef;
# Semaphore used to control the number of threads
my $ThreadSem = undef;
use constant AGENT_VERSION => '5.1SP4';
use constant AGENT_BUILD => '160207';
# Commands to retrieve total memory information in kB
use constant TOTALMEMORY_CMDS => {
linux => 'cat /proc/meminfo | grep MemTotal: | awk \'{ print $2 }\'',
solaris => '/usr/sbin/prtconf | awk \'/Memory/ { print $3 * 1024 }\'',
hpux => 'swapinfo -t | grep memory | awk \'{print $2}\'',
freebsd => '/sbin/sysctl hw.physmem | awk \'{print $2 / 1024}\'',
};
# Commands to retrieve free memory information in kB
use constant FREEMEMORY_CMDS => {
linux => 'cat /proc/meminfo | grep MemFree: | awk \'{ print $2 }\'',
solaris => 'vmstat 1 2 | tail -1 | awk \'{ print $5 }\'',
hpux => 'swapinfo -t | grep memory | awk \'{print $4}\'',
freebsd => '/sbin/sysctl -n vm.stats.vm.v_page_size vm.stats.vm.v_free_count | tr "\n" " " | awk \'{ print $1 * $2 / 1024 }\'',
};
# Commands to retrieve cpu information
use constant CPUUSAGE_CMDS => {
linux => 'vmstat 1 2 | tail -1 | awk \'{ print $13 }\'',
solaris => 'vmstat 1 2 | tail -1 | awk \'{ print $21 }\'',
hpux => 'vmstat 1 2 | tail -1 | awk \'{ print $16 }\'',
freebsd => 'vmstat -n 0 1 2 | tail -1 | awk \'{ print $15 }\''
};
# Commands to retrieve process information
use constant PROC_CMDS => {
# cpu usage, memory usage, command name
linux => 'ps aux | awk \'NR > 1 {ps = ""; for (i = 11; i <= NF; ++i) {ps = (ps " " $i) }; print $3, $6, ps}\'',
solaris => 'prstat 1 1 | awk \'NR > 1 {split ($10, ps, "/"); cpu = substr ($9, 1, length ($9) - 1); mem = substr ($3, 1, length ($3) - 1); print cpu, mem, ps[1]}\'',
hpux => 'ps -elf | awk \'NR > 1 {ps = ""; for (i = 15; i <= NF; ++i) {ps = (ps " " $i) }; print 0, $10, ps}\'',
aix => 'ps aux | awk \'NR > 1 {print $3, $6, $11}\'',
freebsd => 'ps axww -o %cpu= -o %mem= -o command= | sed -e "s/^ *//"',
};
# Commands to retrieve partition information in kB
use constant PART_CMDS => {
# total, available, mount point
linux => 'df -P | awk \'NR > 1 {print $2, $4, $6}\'',
solaris => 'df -k | awk \'NR > 1 {print $2, $4, $6}\'',
hpux => 'df -P | awk \'NR > 1 {print $2, $4, $6}\'',
aix => 'df -kP | awk \'NR > 1 {print $2, $4, $6}\'',
freebsd => 'df -k | awk \'NR > 1 {print $2, $4, $6}\''
};
# Commands to call df with POSIX output format
use constant DF_CMDS => {
# total, available, mount point
linux => 'df -P',
solaris => 'df -k',
hpux => 'df -P',
aix => 'df -kP',
freebsd => 'df -k'
};
# OS and OS version
my $OS = $^O;
my $OS_VERSION;
# Used to calculate the MD5 checksum of a string
use constant MOD232 => 2**32;
# Directory where pandora_agent.conf is located
my $ConfDir = '';
# Pandora FMS agent configuration file
my $ConfFile = 'pandora_agent.conf';
# Set to 1 if broker agents are enabled.
my $BrokerEnabled = 0;
# Broker agent configuration files
my @BrokerPid;
# Configuration tokens
my %DefaultConf = (
'server_ip' => 'localhost',
'server_path' => '/var/spool/pandora/data_in',
'logfile' =>'/var/log/pandora/pandora_agent.log',
'temporal' => '/var/spool/pandora',
'interval' => 300,
'debug' => 0,
'agent_name' => hostname (),
'agent_name_cmd' => '',
'description' => '',
'group' => '',
'encoding' => 'UTF-8',
'server_port' => 41121,
'transfer_mode' => 'tentacle',
'server_pwd' => '',
'server_ssl' => 'no',
'server_opts' => '',
'delayed_startup' => 0,
'pandora_nice' => 10,
'cron_mode' => 0,
'remote_config' => 0,
'secondary_mode' => 'never',
'secondary_server_ip' => 'localhost',
'secondary_server_path' => '/var/spool/pandora/data_in',
'secondary_server_port' => 41121,
'secondary_transfer_mode' => 'tentacle',
'secondary_server_pwd' => '',
'secondary_server_ssl' => 'no',
'secondary_server_opts' => '',
'autotime' => 0,
'temporal_min_size' => 1,
'timezone_offset' => 0,
'pandora_exec' => 'pandora_agent_exec',
'agent_threads' => 1,
'udp_server_port' => 41122,
'udp_server_auth_address' => '0.0.0.0',
'udp_server' => 0,
'proxy_mode' => 0,
'proxy_max_connection' => 10,
'proxy_timeout' => 1,
'intensive_interval' => 0,
'timestamp' => 0,
'xml_buffer' => 0,
'custom_id' => '',
'url_address' => '',
);
my %Conf = %DefaultConf;
# Modules
my @Modules;
# Logfile file handle
my $LogFileFH;
# Agent name MD5;
my $AgentMD5;
# Remote configuration file name
my $RemoteConfFile;
# Remote md5 file name
my $RemoteMD5File;
# Process data
my %Procs = (
'__utimestamp__' => 0
);
# Partition data
my %Parts = (
'__utimestamp__' => 0
);
# Collections
my %Collections;
# Custom fields
my %Customfields;
# $DevNull
my $DevNull = '/dev/null';
# Shell command separator
my $CmdSep = ';';
# Global macros
my %Macros;
# PID of tentacle proxy, used in proxy mode
my $tentacle_pid = undef;
# PID of udp_server
my $udp_server_pid = undef;
################################################################################
# Print usage information and exit.
################################################################################
sub print_usage () {
print "\nUsage: $0 <Pandora home>\n\n";
print "\tPandora home is the directory where pandora_agent.conf is located,\n";
print "\tby default /etc/pandora.\n\n";
exit 1;
}
################################################################################
# Print an error message and exit.
################################################################################
sub error ($) {
my $msg = shift;
print ("[ERROR] $msg\n\n");
`logger -i -t pandora_agent_daemon [ERROR] $msg 2>/dev/null`;
exit 1;
}
################################################################################
# Check a regular expression. Returns 1 if its valid, 0 otherwise.
################################################################################
sub valid_regexp ($) {
my $regexp = shift;
eval {
'' =~ /$regexp/;
};
# Something went wrong
return 0 if ($@);
return 1;
}
################################################################################
# Recursively delete files and directories.
################################################################################
sub rmrf {
my $path = shift;
local *DIR;
if (-d $path) {
opendir (DIR, $path) || return;
while (defined (my $file_name = readdir(DIR))) {
next if ($file_name eq '.' || $file_name eq '..');
rmrf ("$path/$file_name");
}
closedir (DIR);
rmdir ($path);
} else {
unlink ($path);
}
}
################################################################################
# Recursively set file permissions.
################################################################################
sub chmodr {
my ($perm, $path) = @_;
local *DIR;
if (-d $path) {
opendir (DIR, $path) || return;
while (defined (my $file_name = readdir(DIR))) {
next if ($file_name eq '.' || $file_name eq '..');
chmodr ($perm, "$path/$file_name");
}
closedir (DIR);
}
chmod ($perm, $path);
}
################################################################################
# Open the agent logfile and start logging.
################################################################################
sub start_log (;$) {
my $quiet = shift;
# Get the logfile
$Conf{'logfile'} = read_config ('logfile');
$Conf{'logfile'} = '/var/log/pandora/pandora_agent.log' unless defined ($Conf{'logfile'});
# Open it
if ($Conf{'logfile'} eq 'syslog') {
openlog('pandora_agent', 'nowait', 'daemon');
} else {
open ($LogFileFH, "> $Conf{'logfile'}") or error ("Could not open log file $Conf{'logfile'} for writing: $!.");
print "Logging to $Conf{'logfile'}\n" if (!defined ($quiet));
}
}
################################################################################
# Close the agent logfile and stop logging.
################################################################################
sub stop_log () {
if ($Conf{'logfile'} eq 'syslog') {
closelog();
} else {
close ($LogFileFH);
}
}
################################################################################
# Log a message to the agent logfile.
################################################################################
sub log_message ($$;$) {
my ($source, $msg, $dest) = @_;
if (defined ($dest)) {
print $dest strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
} elsif ($Conf{'logfile'} eq 'syslog') {
syslog('info', $msg);
} else {
#Trying to write into log file to test its writable
syswrite ($LogFileFH, "");
#If no error, the file is writable
if (!$!) {
print $LogFileFH strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
} else {
#If error then log into syslog!
`logger -i -t pandora_agent_daemon [ERROR] $msg 2>/dev/null`;
}
}
}
################################################################################
# Parse configuration file (modules, plugins and collections)
################################################################################
sub parse_conf_modules($) {
my ($param) = @_;
# Mark the start of a module definition
my $module_begin = 0;
# Skeleton for modules
my $module = {};
foreach my $line (@{$param}) {
next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
# Module definition
if ($line =~ /^\s*module_begin\s*$/) {
$module_begin = 1;
init_module ($module);
} elsif ($line =~ /^\s*module_name\s+(.+)$/) {
$module->{'name'} = $1;
$module->{'name'} =~ s/\s+$//g;
$module->{'name'} =~ s/^\s+//g;
} elsif ($line =~ /^\s*module_description\s+(.+)$/) {
$module->{'description'} = $1;
} elsif ($line =~ /^\s*module_type\s+(\S+)\s*$/) {
$module->{'type'} = $1;
}elsif ($line =~ /^\s*module_precondition\s+(.*)$/) {
my $action = $1;
# Numeric comparison
if ($action =~ /^\s*([<>!=]+)\s+(\d+(?:\.\d*)?)\s+(.*)$/) {
push (@{$module->{'precondition'}}, {'operator' => $1, 'value_1' => $2, 'command' => $3});
# Interval
} elsif ($action =~ /^\s*[(]\s*(\d+(?:\.\d*)?)\s*,\s*(\d+(?:\.\d*)?)\s*[)]\s+(.*)$/) {
push (@{$module->{'precondition'}}, {'operator' => '()', 'value_1' => $1, 'value_2' => $2, 'command' => $3});
# Regular expression
} elsif ($action =~ /^\s*=~\s+(\S*)\s+(.*)$/) {
if (valid_regexp ($1)) {
push (@{$module->{'precondition'}}, {'operator' => '=~', 'value_1' => $1, 'command' => $2});
} else {
log_message ('setup', "Invalid regular expression in module precondition: $line");
}
}
} elsif ($line =~ /^\s*module_exec\s+(.+)$/) {
$module->{'func'} = \&module_exec;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_cpuusage\s+(.*)$/) {
$module->{'func'} = \&module_cpuusage;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_freememory\s+(.*)$/) {
$module->{'func'} = \&module_freememory;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_freepercentmemory\s+(.*)$/) {
$module->{'func'} = \&module_freepercentmemory;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*(module_proc|module_service)\s+(.+)$/) {
$module->{'func'} = \&module_proc;
$module->{'params'} = $2;
} elsif ($line =~ /^\s*module_cpuproc\s+(.+)$/) {
$module->{'func'} = \&module_cpuproc;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_memproc\s+(.+)$/) {
$module->{'func'} = \&module_memproc;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_freedisk\s+(.*)$/) {
$module->{'func'} = \&module_freedisk;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_freepercentdisk\s+(.*)$/) {
$module->{'func'} = \&module_freepercentdisk;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_occupiedpercentdisk\s+(.*)$/) {
$module->{'func'} = \&module_occupiedpercentdisk;
$module->{'params'} = $1;
} elsif ($line =~ /^\s*module_max\s+(.*)\s*$/) {
$module->{'max'} = $1;
} elsif ($line =~ /^\s*module_min\s+(.*)\s*$/) {
$module->{'min'} = $1;
} elsif ($line =~ /^\s*module_postprocess\s+(.*)\s*$/) {
$module->{'post_process'} = $1;
} elsif ($line =~ /^\s*module_interval\s+(\d+)\s*$/) {
$module->{'interval'} = $1;
} elsif ($line =~ /^\s*module_timeout\s+(\d+)\s*$/) {
$module->{'timeout'} = $1;
} elsif ($line =~ /^\s*module_save\s+(\w+)$/) {
$module->{'save'} = $1;
} elsif ($line =~ /^\s*module_alert_template\s+(.*)$/) {
$module->{'alert_template'} = $1;
} elsif ($line =~ /^\s*module_condition\s+(.*)$/) {
my $action = $1;
# Numeric comparison
if ($action =~ /^\s*([<>!=]+)\s+(\d+(?:\.\d*)?)\s+(.*)$/) {
push (@{$module->{'conditions'}}, {'operator' => $1, 'value_1' => $2, 'command' => $3});
# Interval
} elsif ($action =~ /^\s*[(]\s*(\d+(?:\.\d*)?)\s*,\s*(\d+(?:\.\d*)?)\s*[)]\s+(.*)$/) {
push (@{$module->{'conditions'}}, {'operator' => '()', 'value_1' => $1, 'value_2' => $2, 'command' => $3});
# Regular expression
} elsif ($action =~ /^\s*=~\s+(\S*)\s+(.*)$/) {
if (valid_regexp ($1)) {
push (@{$module->{'conditions'}}, {'operator' => '=~', 'value_1' => $1, 'command' => $2});
} else {
log_message ('setup', "Invalid regular expression in module condition: $line");
}
}
} elsif ($line =~ /^\s*module_intensive_condition\s+(.*)$/) {
my $action = $1;
$module->{'is_intensive'} = 1;
# Numeric comparison
if ($action =~ /^\s*([<>!=]+)\s+(\d+(?:\.\d*)?)\s*$/) {
push (@{$module->{'intensive_conditions'}}, {'operator' => $1, 'value_1' => $2});
# Interval
} elsif ($action =~ /^\s*[(]\s*(\d+(?:\.\d*)?)\s*,\s*(\d+(?:\.\d*)?)\s*[)]\s*$/) {
push (@{$module->{'intensive_conditions'}}, {'operator' => '()', 'value_1' => $1, 'value_2' => $2});
# Regular expression
} elsif ($action =~ /^\s*=~\s+(\S*)\s*$/) {
if (valid_regexp ($1)) {
push (@{$module->{'intensive_conditions'}}, {'operator' => '=~', 'value_1' => $1});
} else {
log_message ('setup', "Invalid regular expression in intensive condition: $line");
}
}
} elsif ($line =~ /^\s*module_crontab\s+(((\*|(\d+(-\d+){0,1}))\s*){5}).*$/) {
$module->{'cron'} = $1;
} elsif ($line =~ /^\s*module_cron_interval\s+(\d+).*$/) {
$module->{'cron_interval'} = $1;
} elsif ($line =~ /^\s*module_end\s*$/) {
$module_begin = 0;
# Check for invalid modules
next unless (($module->{'name'} ne '' && $module->{'func'} != 0) || $module->{'func'} == \&module_plugin);
# Set the intensive interval
if ($module->{'is_intensive'} == 1) {
$module->{'intensive_interval'} = $module->{'interval'};
} else {
$module->{'intensive_interval'} = $module->{'interval'} * ($Conf{'interval'} / $Conf{'intensive_interval'});
}
# Make the module run the first time
$module->{'counter'} = $module->{'intensive_interval'};
# Replace macros
replace_macros ($module);
push (@Modules, {%{$module}});
# Plugin
} elsif ($line =~ /^\s*module_plugin\s+(.+)$/) {
# Single line plugin definition
if ($module_begin == 0) {
# Set default values for the module configuration
init_module ($module);
# Configure the plugin
$module->{'func'} = \&module_plugin;
$module->{'params'} = $1;
# Set the intensive interval
if ($module->{'is_intensive'} == 1) {
$module->{'intensive_interval'} = $module->{'interval'};
} else {
$module->{'intensive_interval'} = $module->{'interval'} * ($Conf{'interval'} / $Conf{'intensive_interval'});
}
# Make the module run the first time
$module->{'counter'} = $module->{'intensive_interval'};
push (@Modules, {%{$module}});
} else {
$module->{'func'} = \&module_plugin;
$module->{'params'} = $1;
}
# Module proc command redefinition
} elsif ($line =~ /^\s*module_proc_cmd\s+(.+)$/) {
PROC_CMDS->{$OS} = $1;
# Module freedisk command redefinition
} elsif ($line =~ /^\s*module_freedisk_cmd\s+(.+)$/) {
PART_CMDS->{$OS} = $1;
# Collection
} elsif ($line =~ /^\s*file_collection\s+(.+)$/) {
my $collection = $1;
# Prevent path traversal attacks
if ($collection !~ m/(\.\.)|\//) {
$Collections{$collection} = 0;
}
# Min critical
} elsif ($line =~ /^\s*module_min_critical\s+(.*)\s*$/) {
$module->{'min_critical'} = $1;
# Max critical
} elsif ($line =~ /^\s*module_max_critical\s+(.*)\s*$/) {
$module->{'max_critical'} = $1;
# Min warning
} elsif ($line =~ /^\s*module_min_warning\s+(.*)\s*$/) {
$module->{'min_warning'} = $1;
# Max warning
} elsif ($line =~ /^\s*module_max_warning\s+(.*)\s*$/) {
$module->{'max_warning'} = $1;
# Disabled
} elsif ($line =~ /^\s*module_disabled\s+(.*)\s*$/) {
$module->{'disabled'} = $1;
# Min ff event
} elsif ($line =~ /^\s*module_min_ff_event\s+(.*)\s*$/) {
$module->{'min_ff_event'} = $1;
# Unit
} elsif ($line =~ /^\s*module_unit\s+(.*)\s*$/) {
$module->{'unit'} = $1;
# Module_group
} elsif ($line =~ /^\s*module_group\s+(.*?)\s*$/) {
$module->{'module_group'} = $1;
# Custom id
} elsif ($line =~ /^\s*module_custom_id\s+(.*)\s*$/) {
$module->{'custom_id'} = $1;
# Str warning
} elsif ($line =~ /^\s*module_str_warning\s+(.*)\s*$/) {
$module->{'str_warning'} = $1;
# Str critical
} elsif ($line =~ /^\s*module_str_critical\s+(.*)\s*$/) {
$module->{'str_critical'} = $1;
# Critical instructions
} elsif ($line =~ /^\s*module_critical_instructions\s+(.*)\s*$/) {
$module->{'critical_instructions'} = $1;
# Warning instructions
} elsif ($line =~ /^\s*module_warning_instructions\s+(.*)\s*$/) {
$module->{'warning_instructions'} = $1;
# Unknown instructions
} elsif ($line =~ /^\s*module_unknown_instructions\s+(.*)\s*$/) {
$module->{'unknown_instructions'} = $1;
# Tags
} elsif ($line =~ /^\s*module_tags\s+(.*)\s*$/) {
$module->{'tags'} = $1;
# Critical inverse
} elsif ($line =~ /^\s*module_critical_inverse\s+(\S+)\s*$/) {
$module->{'critical_inverse'} = $1;
# Warning inverse
} elsif ($line =~ /^\s*module_warning_inverse\s+(\S+)\s*$/) {
$module->{'warning_inverse'} = $1;
# Quiet
} elsif ($line =~ /^\s*module_quiet\s+(\S+)\s*$/) {
$module->{'quiet'} = $1;
# FF interval
} elsif ($line =~ /^\s*module_ff_interval\s+(\S+)\s*$/) {
$module->{'module_ff_interval'} = $1;
# Macros
} elsif ($line =~ /^\s*module_macro(\S+)\s+(.*)\s*$/) {
$module->{'macros'}{$1} = $2;
}
}
return;
}
################################################################################
# Create configuration file for broker agents.
################################################################################
sub write_broker_conf($){
my ($broker_agent) = @_;
my $content = '';
open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
open (BROKER_FILE, ">$ConfDir/${broker_agent}.conf") or error ("Could not write configuration file: $!");
while (my $line = <CONF_FILE>){
# Skip broker definitions
if ($line =~ m/^\s*broker_agent/) {
next;
}
# Change the agent name
if ($line =~ m/^\s*#*\s*agent_name\s+/) {
$line = "agent_name $broker_agent\n";
}
# Change the logfile
elsif ($line =~ m/^\s*logfile\s+(.*)/) {
$line = 'logfile ' . dirname ($1) . "/$broker_agent.log\n";
}
print BROKER_FILE $line;
}
close (BROKER_FILE);
close (CONF_FILE);
}
################################################################################
# Read configuration file. Exit on error.
################################################################################
sub read_config (;$) {
my $token = shift;
my @found_tokens;
my $module;
error ("File '$ConfDir/$ConfFile' not found.") unless (-e "$ConfDir/$ConfFile");
open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
my @file = <CONF_FILE>;
close(CONF_FILE);
foreach my $line (@file){
# Skip comments and empty lines
next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
# Replace CRLF with LF
$line =~ s/\r\n/\n/g;
# Store the custom fields
if (($line =~ m/^(custom_field\d+_name)\s+(.*)/) or ($line =~ m/^(custom_field\d+_value)\s+(.*)/)) {
$Customfields{$1} = $2;
next;
}
# Save global macros
if ($line =~ m/^macro(\S+)\s+(.*)/) {
$Macros{$1} = $2;
next;
}
# Token search
if (defined ($token)) {
if ($line =~ /^\s*(\S+)\s+(.*)$/ && $1 eq $token) {
# Multiple value token
if (wantarray ()) {
push (@found_tokens, $2);
}
# Single value token
else {
return $2;
}
}
next;
}
next if ($line =~ /^module\s*\w*/);
#Configuration token
if ($line =~ /^\s*(\S+)\s+(.*)$/) {
log_message ('setup', "$1 is $2");
$Conf{$1} = $2;
# Look for broker agents.
if ($1 eq 'broker_agent') {
$BrokerEnabled = 1;
}
# Remove trailing spaces
$Conf{$1} =~ s/\s*$//;
}
}
# Token search
if (defined ($token)) {
# Multiple value token
if (wantarray ()) {
return @found_tokens;
}
# Single value token not found.
return undef;
}
# Set the intensive interval
if ($Conf{'intensive_interval'} == 0) {
$Conf{'intensive_interval'} = $Conf{'interval'};
}
# Search for includes after all other variables have been set
foreach my $line (@file) {
# Skip comments and empty lines
next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
# Replace CRLF with LF
$line =~ s/\r\n/\n/g;
# Additional configuration file
if ($line =~ /^include\s+(.*)\s*/) {
$Conf{'include'} = $Conf{'include'} ? "$Conf{'include'} $1" : $1;
foreach my $file_name (glob("$1")) {
open (FILE, "$file_name") or next;
log_message ('setup', "reading $file_name");
my @file_conf = <FILE>;
parse_conf_modules(\@file_conf);
close (FILE);
}
next;
}
}
# Module, plugin and collection definitions
parse_conf_modules(\@file);
# If agent_name_cmd is defined, agent_name is set by command result.
if ($Conf{'agent_name_cmd'} ne '') {
my $result = `$Conf{'agent_name_cmd'}`;
# Use only the first line.
my ($temp_agent_name, $remain) = split(/\n/, $result);
chomp ($temp_agent_name);
# Remove white spaces of the first and last.
$temp_agent_name =~ s/^ *(.*?) *$/$1/;
$Conf{'agent_name'} = $temp_agent_name if ($temp_agent_name ne '');
}
# Update the agent MD5 since agent_name may have changed
$AgentMD5 = md5 ($Conf{'agent_name'});
$RemoteConfFile = "$AgentMD5.conf";
$RemoteMD5File = "$AgentMD5.md5";
# Load thread support if agent_threads is greater than 1.
if ($Conf{'agent_threads'} > 1) {
eval {
local $SIG{__DIE__};
require threads;
require threads::shared;
require Thread::Semaphore;
};
if (!$@) {
$Sem = Thread::Semaphore->new;
$ThreadSem = Thread::Semaphore->new ($Conf{'agent_threads'});
threads::shared::share (\$Xml);
threads::shared::share (\$Sem);
log_message ('log', 'Using thread library.');
} else {
log_message ('log', 'Thread library is not available. agent_threads is set to 1 (disabled).');
$Conf{'agent_threads'} = 1;
$Sem = undef;
$ThreadSem = undef;
}
} else {
$Sem = undef;
$ThreadSem = undef;
log_message ('log', 'Thread is disabled.');
}
# Set tentacle client options
if ($Conf{'transfer_mode'} eq 'tentacle') {
$Conf{'server_opts'} = '-x \'' . $Conf{'server_pwd'} . '\' ' . $Conf{'server_opts'} if ($Conf{'server_pwd'} ne '');
$Conf{'server_opts'} = '-c ' . $Conf{'server_opts'} if ($Conf{'server_ssl'} eq 'yes');
}
# Set tentacle client options for secondary server
if ($Conf{'secondary_transfer_mode'} eq 'tentacle') {
$Conf{'secondary_server_opts'} = '-x \'' . $Conf{'secondary_server_pwd'} . '\' ' . $Conf{'secondary_server_opts'} if ($Conf{'secondary_server_pwd'} ne '');
$Conf{'secondary_server_opts'} = '-c ' . $Conf{'secondary_server_opts'} if ($Conf{'secondary_server_ssl'} eq 'yes');
}
}
#################################################################################
## Remove any trailing / from directory names.
#################################################################################
sub fix_directory ($) {
my $dir = shift;
my $char = chop ($dir);
return $dir if ($char eq '/');
return $dir . $char;
}
################################################################################
# Sends a file to the server.
################################################################################
#sub send_file ($;$) {
sub send_file {
my ($file, $secondary) = @_;
my $output;
if ($Conf{'transfer_mode'} eq 'tentacle') {
$output = `tentacle_client -v -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} "$file" 2>&1 >$DevNull`;
} elsif ($Conf{'transfer_mode'} eq 'ssh') {
$output = `scp -P $Conf{'server_port'} "$file" pandora@"$Conf{'server_ip'}:$Conf{'server_path'}" 2>&1 >$DevNull`;
} elsif ($Conf{'transfer_mode'} eq 'ftp') {
my $base = basename ($file);
my $dir = dirname ($file);
$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >$DevNull <<FEOF1
quote USER pandora
quote PASS $Conf{'server_pwd'}
lcd "$dir"
cd "$Conf{'server_path'}"
put "$base"
quit
FEOF1`
} elsif ($Conf{'transfer_mode'} eq 'local') {
$output = `cp "$file" "$Conf{'server_path'}/" 2>&1 >$DevNull`;
}
# Get the errorlevel
my $rc = $? >> 8;
if ($rc != 0) {
log_message ('error', "Error sending file '$file': $output");
}
return $rc unless (defined ($secondary));
# Send the file to the secondary server
return $rc unless ($Conf{'secondary_mode'} eq 'always' || ($Conf{'secondary_mode'} eq 'on_error' && $rc != 0));
swap_servers ();
$rc = send_file ($file);
swap_servers ();
return $rc;
}
################################################################################
# Send buffered XML files.
################################################################################
sub send_buffered_xml_files () {
# Read XML files from the temporal directory
opendir(TEMPORAL, $Conf{'temporal'}) or return;
while (my $xml_file = readdir(TEMPORAL)) {
# Skip non data files and symlinks
next if ($xml_file !~ m/\.data$/ || -l "$Conf{'temporal'}/$xml_file");
my $rc = send_file ("$Conf{'temporal'}/$xml_file", 1);
unlink ("$Conf{'temporal'}/$xml_file") if ($rc == 0);
}
}
################################################################################
# Swap primary and secondary servers.
################################################################################
sub swap_servers () {
($Conf{'server_ip'}, $Conf{'secondary_server_ip'}) = ($Conf{'secondary_server_ip'}, $Conf{'server_ip'});
($Conf{'server_path'}, $Conf{'secondary_server_path'}) = ($Conf{'secondary_server_path'}, $Conf{'server_path'});
($Conf{'server_port'}, $Conf{'secondary_server_port'}) = ($Conf{'secondary_server_port'}, $Conf{'server_port'});
($Conf{'transfer_mode'}, $Conf{'secondary_transfer_mode'}) = ($Conf{'secondary_transfer_mode'}, $Conf{'transfer_mode'});
($Conf{'server_pwd'}, $Conf{'secondary_server_pwd'}) = ($Conf{'secondary_server_pwd'}, $Conf{'server_pwd'});
($Conf{'server_ssl'}, $Conf{'secondary_server_ssl'}) = ($Conf{'secondary_server_ssl'}, $Conf{'server_ssl'});
($Conf{'server_opts'}, $Conf{'secondary_server_opts'}) = ($Conf{'secondary_server_opts'}, $Conf{'server_opts'});
}
################################################################################
# Receive a file from the server.
################################################################################
sub recv_file ($) {
my $file = shift;
my $output;
if ($Conf{'transfer_mode'} eq 'tentacle') {
$output = `cd "$Conf{'temporal'}"$CmdSep tentacle_client -v -g -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} $file 2>&1 >$DevNull`
} elsif ($Conf{'transfer_mode'} eq 'ssh') {
$output = `scp -P $Conf{'server_port'} pandora@"$Conf{'server_ip'}:$Conf{'server_path'}/$file" $Conf{'temporal'} 2>&1 >$DevNull`;
} elsif ($Conf{'transfer_mode'} eq 'ftp') {
my $base = basename ($file);
my $dir = dirname ($file);
$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >$DevNull <<FEOF1
quote USER pandora
quote PASS $Conf{'server_pwd'}
lcd "$Conf{'temporal'}"
cd "$Conf{'server_path'}"
get "$file"
quit
FEOF1`
} elsif ($Conf{'transfer_mode'} eq 'local') {
$output = `cp $Conf{'server_path'}/$file $Conf{'temporal'} 2>&1 >$DevNull`;
}
# Get the errorlevel
my $rc = $? >> 8;
if ($rc != 0) {
log_message ('error', "Error retrieving file: $output");
}
return $rc;
}
################################################################################
# Check the server for a remote configuration.
################################################################################
sub check_remote_config () {
return unless ($Conf{'remote_config'} eq '1');
# Calculate the configuration file MD5 digest
open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
binmode(CONF_FILE);
my $conf_md5 = md5 (join ('', <CONF_FILE>));
close (CONF_FILE);
# Remove temporary files if they exist as symlink to avoid symlink attack
for my $file ("$Conf{'temporal'}/$RemoteMD5File", "$Conf{'temporal'}/$RemoteConfFile") {
error ("File '$file' already exists as a symlink and could not be removed: $!") if (-l $file && ! unlink($file));
}
# Get the remote MD5 file
if (recv_file ($RemoteMD5File) != 0) {
open (MD5_FILE, "> $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
print MD5_FILE $conf_md5;
close (MD5_FILE);
copy ("$ConfDir/$ConfFile", "$Conf{'temporal'}/$RemoteConfFile");
send_file ("$Conf{'temporal'}/$RemoteConfFile");
send_file ("$Conf{'temporal'}/$RemoteMD5File");
log_message ('remote config', 'Uploading configuration for the first time.');
unlink ("$Conf{'temporal'}/$RemoteConfFile");
unlink ("$Conf{'temporal'}/$RemoteMD5File");
return;
}
open (MD5_FILE, "< $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
my $remote_conf_md5 = <MD5_FILE>;
close (MD5_FILE);
# No changes
return if ($remote_conf_md5 eq $conf_md5);
# Get the new configuration file
return if (recv_file ($RemoteConfFile) != 0);
log_message ('remote config', 'Configuration has changed!');
# Save the new configuration
move ("$Conf{'temporal'}/$RemoteConfFile", "$ConfDir/$ConfFile");
# Empty macros, modules, plugins and collections
%Macros = ();
@Modules = ();
%Collections = ();
%Conf = %DefaultConf;
# Reload the new configuration
read_config ();
# Log file may have changed
stop_log ();
start_log ('quiet');
#Set nice of the pandora_agent
my $PID = $$;
`renice "$Conf{'pandora_nice'}" "$PID"`;
}
################################################################################
# SUB launch_tentacle_proxy
# Launchs tentacle server in proxy mode.
################################################################################
sub launch_tentacle_proxy () {
# Check if proxy server ip is right.
if ($Conf{'server_ip'} ne "localhost") {
#Create a new process and launch tentacle.
$tentacle_pid = fork();
if ($tentacle_pid == 0) {
#Execute tentacle server as a daemon