-
Notifications
You must be signed in to change notification settings - Fork 0
/
flows
executable file
·1322 lines (1245 loc) · 37.5 KB
/
flows
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
#!/bin/bash
################################################################################
##
## Flows - A simple wrapper around nfdump
## --------------------------------------
##
## Description:
## Simply got tired of searching through various directories and writing long
## tedious dates and other stuff. User may specify various simple parameters to
## change the search criteria. Hard core users will see that this is not a
## complete replacement for using nfdump to search through flows, but it's a
## more convenient way to do simple searches.
##
## Author:
## Tor Inge Skaar (tor.inge.skaar|gmail.com)
##
################################################################################
# Configuration
ROOT_FLOW_DIR="/var/log/netflow"
NFDUMP=`which nfdump`
BASE_NFDUMP_CMD="$NFDUMP -O tstart"
CMD_LOG_FILE="/usr/local/log/flows.cmd.log"
USING_NFSEN=true
ALERT_META_PATH="/var/log/nfsen/profiles-stat"
CACHE_DIR="/var/cache/flows/"
CACHE_TIME="14"
TMP_DIR="/tmp/flows"
OUTPUT="fmt:%ts %td %pr %sap -> %dap %sas -> %das %flg %pkt %byt %pps %bps %fl"
FILTERDIR="/usr/local/share/filter"
WIDTH=`tput cols`
LOCALCORES=`cat /proc/cpuinfo | grep processor | wc -l`
CLUSTER="$LOCALCORES/:"
#CLUSTER="4/:,8/flows@node01.local"
PRIVKEY="/usr/local/share/flows/ssh/id_flows"
REVISION="1"
################################################################################
# Configuration check
if [ ! -d $ROOT_FLOW_DIR ]; then
echo "[ERROR] No netflow directory specified ($ROOT_FLOW_DIR)" >&2
exit 1
fi
if [ -z $NFDUMP ]; then
echo "[ERROR] Nfdump binary was not found ($NFDUMP)" >&2;
exit 1
fi
if [ ! -x $NFDUMP ]; then
echo "[ERROR] Nfdump binary is not executeable ($NFDUMP)" >&2
exit 1
fi
if [ ! -d $FILTERDIR ]; then
echo "[ERROR] Filter directory not found ($FILTERDIR)" >&2
exit 1
fi
# Start of execution
t_a=`date +%s`
function printusage {
echo -e "\nFlows (rev. $REVISION) - A simple wrapper around nfdump\n";
echo -e "Usage: flows [options] ['Filter']\n";
echo -e " Most commonly used options (use -h to show all available options):";
echo -e " -a | --aggr | Aggregate flow data";
echo -e " -d <num> | --days | Number of complete days ago (default 1)";
echo -e " -E <date> | --end | End time for flow search: YYYY-mm-dd(-HH)(-MM)";
echo -e " -h | --help | Show all options (this output is just some of them)";
echo -e " -l | --list | List available (active) probes";
echo -e " -n <num> | | Used with -s to define number (default 10)";
echo -e " -p <name> | --probe | Limit search to a probe name (use multiple -p";
echo -e " | | to specify several probes. Skip to search all)";
echo -e " -q | --quiet | Suppress meta-output from script and nfdump";
echo -e " -r<num> | --recent | Search in recent <num> of minutes (default 5).";
echo -e " | | As this has an optional argument, you have to write";
echo -e " | | -r10 (no space between) to search last 10 minutes";
echo -e " | | Note: Cache is not used when using recent-search";
echo -e " -s | --stats | Generate Top statistics (see nfdump -h)";
echo -e " -S <date> | --start | Start time for flow search: YYYY-mm-dd(-HH)(-MM)";
echo -e " -t <slot> | --timeslot | Provide a single timeslot interval (YYYYmmddHHMM) to";
echo -e " | | search in. This option has precedence over S/E and d";
echo -e " -T <trig> | --trigger | Used to dig into alerts generated by Nfsen. Simply";
echo -e " | | specify the triggername as input (use nfalert -l to";
echo -e " | | list available triggers). You can also use the whole";
echo -e " | | trigger-string with timestamp included to search";
echo -e " | | only in that timeframe <trigger-name>@<timestamp>";
echo -e "\n Filter: \n \tnfdump has a powerful and fast filter engine. All flow are filtered";
echo -e " \tbefore they are further processed. If no filter is given, any flow";
echo -e " \twill be processed. The filter is specified on the command line as";
echo -e " \tlast argument enclosed in \'. The filter syntax used is heavily";
echo -e " \tbased on standard BPF syntax. Filter specified on the command line";
echo -e " \twill always override -f.";
echo -e "\n Examples:\n \tflows 'srcip 192.168.1.2 and port 443'";
echo -e "\tflows -d5 \"net 10.20.30.0/24\"";
echo -e "\tflows -p router01 -vd7 -s srcip";
echo -e "\tflows -S 2008-12-24-15-35 -E 2008-12-28 \"host google.com\"";
echo -e "\tflows -p router04 -r30 \"as 1234\"";
echo "";
exit 1
}
function print_full_usage {
echo -e "\nFlows (rev. $REVISION) - A simple wrapper around nfdump\n"
echo -e "Usage: flows [options] ['Filter']\n"
echo -e " Options:"
echo -e " -24 | | Same as -r1440"
echo -e " -a | --aggr | Aggregate flow data"
echo -e " -C | --color | Use colors in output to terminal"
echo -e " -cc <c,t> | --country | Specify ISO-3166-1 alpha-2 country code as a"
echo -e " | | filter (c). And set type (t) to either ASN or IP."
echo -e " | | It defaults to ASN if no type is set"
echo -e " -d <num> | --days | Number of complete days ago (default 1)"
echo -e " -E <date> | --end | End time for flow search: YYYY-mm-dd(-HH)(-MM)"
echo -e " -f <file> | --filter | Path to filter file (use multiple -f to specify"
echo -e " | | several files which will be combined)"
echo -e " -h | --help | You're looking at it! (You may also consult the"
echo -e " | | man pages for this command, by running \"man flows\""
echo -e " -H | --hitsonly | Output only results with flow hits"
echo -e " -i | | Use intersection when combining multiple filter"
echo -e " | | files with -f or -cc (default behaviour is union)"
echo -e " -j | | Disable parallel execution"
echo -e " -J | | Disable cluster execution when running in parallel"
echo -e " -l | --list | List available (active) probes"
echo -e " -L | --last | List last 10 flows commands used"
echo -e " -n <num> | | Used with -s to define number (default 10)"
echo -e " -N | --nfresolve | Let nfdump do DNS resolution"
echo -e " -o <type> | --output | Output format [raw,line,long,extended,pipe,fmt]"
echo -e " -p <name> | --probe | Limit search to a probe name (use multiple -p"
echo -e " | | to specify several probes. Skip to search all)"
echo -e " -P <a:v> | --proxy | Proxy argument:value to nfdump"
echo -e " -q | --quiet | Suppress meta-output from script and nfdump"
echo -e " -r<num> | --recent | Search in recent <num> of minutes (default 5)."
echo -e " | | As this has an optional argument, you have to write"
echo -e " | | -r10 (no space between) to search last 10 minutes"
echo -e " | | Note: Cache is not used when using recent-search"
echo -e " -R | --no-cache | Do not use result cache"
echo -e " -s <type> | --stats | Generate Top statistics (see nfdump -h)"
echo -e " -S <date> | --start | Start time for flow search: YYYY-mm-dd(-HH)(-MM)"
echo -e " -t <slot> | --timeslot | Provide a single timeslot interval (YYYYmmddHHMM) to"
echo -e " | | search in. This option has precedence over S/E and d"
echo -e " -T <trig> | --trigger | Used to dig into alerts generated by Nfsen. Simply";
echo -e " | | specify the triggername as input (use nfalert -l to";
echo -e " | | list available triggers). You can also use the whole";
echo -e " | | trigger-string with timestamp included to search";
echo -e " | | only in that timeframe <trigger-name>@<timestamp>";
echo -e " -v | --verbose | More verbose script output (debug). Several v's may"
echo -e " | | be specified to get even more debugging output"
echo -e " -V | --version | Print script revision number"
echo -e " -x | | Output awesome ascii-art header!"
echo -e "\n Filter: \n \tnfdump has a powerful and fast filter engine. All flow are filtered"
echo -e " \tbefore they are further processed. If no filter is given, any flow"
echo -e " \twill be processed. The filter is specified on the command line as"
echo -e " \tlast argument enclosed in \'. The filter syntax used is heavily"
echo -e " \tbased on standard BPF syntax. Filter specified on the command line"
echo -e " \twill always override -f."
echo -e "\n Examples:\n \tflows 'srcip 192.168.1.2 and port 443'"
echo -e "\tflows -d5 \"net 10.20.30.0/24\""
echo -e "\tflows -p router01 -vd7 -s srcip";
echo -e "\tflows -S 2008-12-24-15-35 -E 2008-12-28 \"host google.com\"";
echo -e "\tflows -p router04 -r30 \"as 1234\"";
echo ""
exit 1
}
##
# Print debug messages if flag is enabled
#
function debug {
if [ $verbose -ne 0 ]; then
echo "[DEBUG] $1" >&2
fi
}
##
# Output a list of all active probes. (From the database)
#
function list_probes {
list=`ls -l $ROOT_FLOW_DIR | grep -e "^d" | awk '{print $9}'`;
if [ -z "$list" ]; then
echo "[ERROR] Failed to retrive a list of probes" >&2
exit 1;
fi
for p in $list; do
echo $p;
done;
}
##
# Output the last 10 flows commands
#
function show_last_cmds {
if [ ! -e $CMD_LOG_FILE ]; then
echo "[WARNING] $CMD_LOG_FILE does not exist" >&2
exit 1
fi
if [ ! -r $CMD_LOG_FILE ]; then
echo "[WARNING] $CMD_LOG_FILE is not readable" >&2
exit 1
fi
echo "Last 10 flows commands used on `hostname`:";
echo "";
tail -n 10 $CMD_LOG_FILE | cut -d\; -f3
echo "";
}
##
# Output version number
#
function show_version {
echo "Flows revision number: $REVISION";
}
##
# Check if input string is an IP
#
function is_IP {
cmd="echo '$1' | egrep -c \"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$\"";
ip=`eval $cmd`;
if [ $ip -eq 1 ]; then
return 1;
else
return 0;
fi
}
##
# Resolve all domains in the given filter (input parameter), i.e. get their IP addresses.
# Domains that resolve to many IPs are expanded in the filter. Domains that do not resolve
# are functionally removed from the filter by setting the host string to IF 0. This was the
# easiest hack, without breaking the filter in über-complex parsing.
#
function resolve {
hosts="";
tmp=`echo $1 | tr [:upper:] [:lower:] | egrep -o "host [a-zæøå0-9.\_\\-]+" | sed 's/^host //g'`;
for h in $tmp; do
is_IP "$h";
if [ $? -eq 0 ]; then
hosts=${hosts}${h}" ";
fi
done
if [ -n "$hosts" ]; then
for host in $hosts; do
output=`host -t A $host | grep "has address"`;
if [ $? -eq 0 ]; then
declare -a ips;
ORGIFS=$IFS
IFS=`echo -en "\n\b"`;
for line in $output; do
ip=`echo $line | awk '{print $4}'`;
ips=( "${ips[@]}" $ip );
done
IFS=$ORGIFS;
if [ ${#ips[@]} -gt 1 ]; then
for (( i=0; i < ${#ips[@]}; i++ )); do
ipstxt=$ipstxt"ip "${ips[$i]}" or ";
done
ipstxt=`echo $ipstxt | sed 's/ or$//g'`;
else
ipstxt="ip "${ips[0]};
fi
cmd="echo \"$filter\" | sed 's/host $host/$ipstxt/g'";
filter=`eval $cmd`;
unset ips ipstxt
else
echo "[WARNING] Failed to resolve $host. Inserting IF 0 as substitute" >&2;
cmd="echo \"$filter\" | sed 's/host $host/IF 0/g'";
filter=`eval $cmd`;
fi
done
fi
}
##
# Syntax check of the timeslot definition.
#
function ts_check {
tcheck=`echo $timeslot | grep -c -e "^[0-9]\{12\}$"`
if [ $tcheck -eq 0 ]; then
tcheck=`echo $timeslot | grep -c -e "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} [0-9]\{2\}:[0-9]\{2\}$"`
if [ $tcheck -eq 0 ]; then
echo "[ERROR] Invalid format. Use YYYYMMDDHHmm or \"YYYY-MM-DD HH:mm\"" >&2
exit 1;
else
# Reformat input
timeslot=`echo $timeslot | tr -d "\-: "`;
fi
fi
}
##
# Determine the timestamp of the most current data.
# After calling this function, the time can be found in the
# variable "LAST_AVAIL_DATA"
#
function last_avail_data {
now=`date "+%Y-%m-%d-%H-%M-%S"`
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Now: $now" >&2
fi
now_Y=`echo $now | cut -d- -f1`;
now_m=`echo $now | cut -d- -f2`;
now_d=`echo $now | cut -d- -f3`;
now_H=`echo $now | cut -d- -f4`;
now_M=`echo $now | cut -d- -f5`;
now_M1=${now_M:0:1};
now_M2=${now_M:1:1};
data_Y=$now_Y; data_m=$now_m; data_d=$now_d; data_H=$now_H; data_M1=$now_M1; data_M2=$now_M2;
if [ $now_M2 -ge 0 -a $now_M2 -le 4 ]; then
data_M2=5
data_M1=$(( now_M1 - 1 ))
if [ $data_M1 -lt 0 ]; then
data_M1=5
data_H=$(( now_H - 1 ))
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Adjusted hour to: $data_H" >&2
fi
if [ $data_H -lt 10 -a $data_H -ge 0 ]; then
data_H="0"$data_H
elif [ $data_H -lt 0 ]; then
data_H=23;
data_d=$(( now_d - 1 ))
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Adjusted day to: $data_d" >&2
fi
if [ $data_d -lt 10 -a $data_d -gt 0 ]; then
data_d="0"$data_d
elif [ $data_d -eq 0 ]; then
data_d=`date -d "yesterday" +%d`
data_m=`date -d "yesterday" +%m`
data_Y=`date -d "yesterday" +%Y`
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Flipped date to: $data_d-$data_m-$data_Y" >&2
fi
fi
fi
fi
elif [ $now_M2 -ge 5 -a $now_M2 -le 9 ]; then
data_M2=0
else
if [ $useguru -eq 1 ]; then
guru 2
else
echo "[ERROR] Internal error 2" >&2
exit 1
fi
fi
# Make sure collector has had time to relocate data file to hierarcy
now_S=`echo $now | cut -d- -f6`
now_S1=${now_S:0:1}
if [ $now_M2 -eq 0 -o $now_M2 -eq 5 ]; then
if [ $now_S1 -eq 0 ]; then
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Sleeping 5 sec to allow collector to flush data" >&2
fi
sleep 5
fi
fi
LAST_AVAIL_DATA=$data_Y"-"$data_m"-"$data_d" "$data_H":"${data_M1}${data_M2}
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Last available data @ $LAST_AVAIL_DATA" >&2
fi
}
##
# Aligns the given timestamp (YYYY-mm-dd-HH-MM) to the lower 0 or 5.
# Note that this function takes a variable reference as input, i.e.
# the name of the variable, and not its value. E.g align_time myvar
# and not align_time $myvar
#
function align_time {
time_in=${!1}
check=`echo $time_in | grep -c -e "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}$"`
if [ $check -eq 0 ]; then
echo "[ERROR] Invalid syntax on input time in function align_time" >&2
fi
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Input time: $time_in" >&2
fi
t_M=`echo $time_in | cut -d- -f5`
t_M1=${t_M:0:1}
t_M2=${t_M:1:1}
if [ $t_M2 -ge 1 -a $t_M2 -le 4 ]; then
t_M2=0
elif [ $t_M2 -ge 6 -a $t_M2 -le 9 ]; then
t_M2=5
fi
time_aligned=`echo $time_in | cut -d- -f1-4`"-"${t_M1}${t_M2};
if [ $verbose -ge 1 ]; then
echo "[DEBUG] Aligned time: $time_aligned" >&2
fi
eval "$1=$time_aligned"
}
##
# Defining a proper search window for the recent X minutes.
# Input argument to this function is the value of X. The function
# will properly set the variable "customstart".
#
function recent {
rtime=$1
if [ $rtime -le 0 ]; then
echo "[ERROR] Recent-search must be non-zero and positive" >&2
exit 1
fi
if [ $rtime -gt 1440 ]; then
echo "[ERROR] Recent-search upper limit is 24h (1440 min)" >&2
exit 1
fi
# Get timestamp of most current data
last_avail_data
# Determine start time of the requested search
dtime1=`date -d "$LAST_AVAIL_DATA" +"%s"`
dtime2=$(( dtime1 + 300 ))
rtime_real=$(( dtime2 - ( rtime * 60 ) ))
rtime_real=`date -d "@$rtime_real" +"%Y-%m-%d-%H-%M"`
# Align time
align_time rtime_real
customstart=$rtime_real
}
##
# Print a given text using the awesome toilet library!
#
function flush {
text=$1
if [ -z "$text" ]; then
return 1
fi
toilet=`which toilet`
fontdir="/usr/share/figlet"
badfont="bigmono12|circle|mono12|smbraille"
# Select random font
cmd="find $fontdir -type f | egrep -v \"$badfont\" | sort -R | basename \`tail -1\` | cut -d. -f1"
font=`eval $cmd`
# Select random style
style=`echo -e "metal\ngay\nnone" | sort -R | tail -1`
if [ "$style" = "none" ]; then
style=""
else
style="--"$style
fi
$toilet -f $font $style $text
}
################################################################################
# Default parameter values
r24=0; # -24
logo=0; # -x
fuse=0; # Filter specified on CLI
duse=0; # -d
ouse=0; # -o
ause=0; # -a
suse=0; # -s
ffuse=0; # -f (filter file specified)
quiet=0; # -q
verbose=0; # -v
nocolor=1; # -C
nocache=0; # -r / -R / -24
hitsonly=0; # -H
union=1; # -i
nfresolve=0; # -N
parallel=1; # -j
nocluster=0; # -J
DEFAULT_TIME=1; # Default number of days ago
declare -a ffiles # Array containing file paths
# Use guru errors if lib available
if [ -r /usr/local/lib/guru.sh ]; then
source "/usr/local/lib/guru.sh"
useguru=1
else
useguru=0
fi
# No options, no fun...
if [ $# -eq 0 ]; then printusage; fi
# Create temporary working dir
mkdir -p $TMP_DIR
if [ $? -ne 0 ]; then
echo "[ERROR] Failed to create temporary working directory: $TMP_DIR" >&2
exit 1
fi
# If you add new options, remember to update the OPTSTRING below. Single colon
# following the option specifies required argument, double colon is optional
# argument, while no colon defines that this option has no argument.
_ARGS=`getopt -a -o aCd:E:f:hHijJlLn:No:p:P:qr::Rs:S:t:T:vVx -l 24,aggr,color,cc:,country:,days:,end:,filter:,guru,help,hitsonly,list,last,nfresolve,output:,probe:,proxy:,quiet,recent::,no-cache,stats:,start:,timeslot:,trigger:,verbose,vv,version -n 'flows' -- "$@"`
if [ $? != 0 ]; then
echo "[ERROR] Parsing of command options failed" >&2 ;
printusage;
fi
eval set -- "$_ARGS"
# Process defined options and arguments
cmdlog=`basename $0`
cmdsig=""
days=0
while true ; do
case "${1}" in
-h | --help)
print_full_usage;
shift
;;
-d | --days)
days=$2;
timestr="$2 days ago";
duse=1;
cmdlog=$cmdlog" -d $2"
cmdsig=$cmdsig" -d $2"
shift 2
;;
-p | --probe)
probe="$2";
plist=( "${plist[@]}" $probe );
cmdlog=$cmdlog" -p $2"
cmdsig=$cmdsig" -p $2"
shift 2
;;
-s | --stats)
spm="-s $2";
suse=1;
cmdlog=$cmdlog" -s $2"
cmdsig=$cmdsig" -s $2"
shift 2
;;
-o | --output)
opm="-o $2";
ouse=1;
cmdlog=$cmdlog" -o $2"
cmdsig=$cmdsig" -o $2"
shift 2
;;
-v | --verbose)
verbose=1;
cmdlog=$cmdlog" -v"
shift
;;
--vv )
verbose=2;
cmdlog=$cmdlog" -vv"
shift
;;
-n)
npm="-n $2";
cmdlog=$cmdlog" -n $2"
cmdsig=$cmdsig" -n $2"
shift 2
;;
-N | --nfresolve)
nfresolve=1;
cmdlog=$cmdlog" -N"
cmdsig=$cmdsig" -N"
shift
;;
-q | --quiet)
quiet=1;
qpm="-q";
cmdlog=$cmdlog" -q"
cmdsig=$cmdsig" -q"
shift
;;
--guru)
if [ $useguru -eq 1 ]; then
guru 0
else
echo "No guru here..."
fi
shift
;;
-a | --aggr)
apm="-a";
ause=1;
cmdlog=$cmdlog" -a"
cmdsig=$cmdsig" -a"
shift
;;
-l | --list)
list_probes;
exit 0
shift
;;
-f | --filter)
ffpath=$2;
if [ ! -r $ffpath ]; then
echo "[ERROR] Cannot read filter file: $ffpath" >&2
exit 1
fi
fpm=$fpm" -f $ffpath";
ffiles=( "${ffiles[@]}" $ffpath );
ffuse=1;
cmdlog=$cmdlog" -f $2"
cmdsig=$cmdsig" -f $2"
shift 2
;;
-V | --version)
show_version;
exit 0
shift
;;
-S | --start)
customstart=$2;
dcheck=`echo $customstart | grep -c -e "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\(-[0-9]\{2\}\)\?\(-[0-9]\{2\}\)\?$"`
if [ $dcheck -eq 0 ]; then
echo "[ERROR] Invalid start date, use: YYYY-MM-DD(-HH)(-ii)" >&2
exit 1;
fi
smin=`echo $customstart | cut -d- -f5`;
if [ -n "$smin" ]; then
if [ ${smin:1:1} -ne 0 -a ${smin:1:1} -ne 5 ]; then
echo "[ERROR] When specifying minutes in start date, it must be aligned on 0 or 5" >&2
exit 1;
fi
fi
cmdlog=$cmdlog" -S $customstart"
cmdsig=$cmdsig" -S $customstart"
shift 2
;;
-E | --end)
customend=$2;
dcheck=`echo $customend | grep -c -e "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\(-[0-9]\{2\}\)\?\(-[0-9]\{2\}\)\?$"`
if [ $dcheck -eq 0 ]; then
echo "[ERROR] Invalid end date, use: YYYY-MM-DD(-HH)(-ii)" >&2
exit 1;
fi
emin=`echo $customend | cut -d- -f5`;
if [ -n "$emin" ]; then
if [ ${emin:1:1} -ne 0 -a ${emin:1:1} -ne 5 ]; then
echo "[ERROR] When specifying minutes in end date, it must be aligned on 0 or 5" >&2
exit 1;
fi
fi
cmdlog=$cmdlog" -E $customend"
cmdsig=$cmdsig" -E $customend"
shift 2
;;
-L | --last)
show_last_cmds;
exit 0
shift
;;
-C | --color)
nocolor=0;
cmdlog=$cmdlog" -C"
shift
;;
-j )
parallel=0;
cmdlog=$cmdlog" -j"
shift
;;
-J )
nocluster=1
cmdlog=$cmdlog" -J"
shift
;;
-r | --recent)
rtime=$2
nocache=1;
if [ -z "$rtime" ]; then
rtime=5
fi
recent $rtime
cmdlog=$cmdlog" -r $rtime"
shift 2
;;
-R | --no-cache)
nocache=1;
cmdlog=$cmdlog" -R"
shift
;;
--24)
nocache=1;
r24=1
recent 1440
cmdlog=$cmdlog" -24"
shift
;;
-t | --timeslot)
timeslot=$2;
ts_check;
cmdlog=$cmdlog" -t $timeslot"
cmdsig=$cmdsig" -t $timeslot"
shift 2
;;
-T | --trigger)
if [ !$USING_NFSEN ]; then
echo "[ERROR] Nfsen functionality has been disabled (see configuration)" >&2
exit 1;
fi
trigvalue=$2;
Tcheck=`echo $trigvalue | grep -c -e "^[0-9A-Za-z_]*@[0-9]\{12\}$"`
if [ $Tcheck -eq 0 ]; then
Tcheck=`echo $trigvalue | grep -c -e "^[0-9A-Za-z_]*$"`
if [ $Tcheck -eq 0 ]; then
echo "[ERROR] Invalid trigger syntax. Use \"<trigger_name>[@YYYYMMDDHHmm]\"" >&2
exit 1;
fi
trigname="$trigvalue"
else
trigname=`echo $trigvalue | cut -d@ -f1`;
timeslot=`echo $trigvalue | cut -d@ -f2`;
fi
ffpath="$ALERT_META_PATH/~$trigname/$trigname-filter.txt";
if [[ ! -r "$ffpath" ]]; then
ffpath="$ALERT_META_PATH/~$trigname*"
tcount=`ls -d $ffpath 2>/dev/null | wc -l`
if [ $tcount -eq 0 ]; then
echo "[ERROR] Unable to find trigger with name: ${trigname}. Check with nfalert -l" >&2
exit 1;
fi
if [ $tcount -gt 1 ]; then
echo "[ERROR] Trigger name is too ambiguous. There are $tcount triggers matching:" >&2
for f in `ls -d $ffpath`; do
echo $f | cut -d~ -f2 | sed 's/^/ * /g';
done
exit 1;
fi
trigname=`ls -d $ffpath | cut -d~ -f2`
ffpath="$ALERT_META_PATH/~$trigname/$trigname-filter.txt";
fi
fpm=" -f $ffpath";
ffiles=( "${ffiles[@]}" $ffpath );
ffuse=1;
cmdlog=$cmdlog" -T $2"
cmdsig=$cmdsig" -T $2"
shift 2
;;
-P | --proxy)
double=`echo $2 | egrep -c ","`
if [ $double -eq 1 ]; then
p_arg=`echo $2 | cut -d: -f1`;
p_val=`echo $2 | cut -d: -f2`;
proxy=$proxy" -"$p_arg" "$p_val;
else
proxy=$proxy" -"$2
fi
cmdlog=$cmdlog" -P $2"
cmdsig=$cmdsig" -P $2"
shift 2
;;
-x)
logo=1
cmdlog=$cmdlog" -x"
shift
;;
--cc | --country)
double=`echo $2 | egrep -c ","`
if [ $double -eq 1 ]; then
cc=`echo $2 | cut -d, -f1 | tr "[:lower:]" "[:upper:]" | egrep "^[A-Z]{2}$"`
if [ $? -ne 0 ]; then
echo "[ERROR] Invalid country code. Use ISO-3166-1 alpha-2 codes." >&2
exit 1
fi
cctype=`echo $2 | cut -d, -f2 | tr "[:lower:]" "[:upper:]" | egrep "^(ASN|IP)$"`
if [ $? -ne 0 ]; then
echo "[ERROR] Invalid country filter type. Must be either ASN or IP." >&2
exit 1
fi
else
cc=`echo $2 | tr "[:lower:]" "[:upper:]" | egrep "^[A-Z]{2}$"`
if [ $? -ne 0 ]; then
echo "[ERROR] Invalid country code. Use ISO-3166-1 alpha-2 codes." >&2
exit 1
fi
cctype="ASN"
fi
ffpath=$FILTERDIR"/country/"$cc"."$cctype".filter"
if [ ! -r $ffpath ]; then
echo "[ERROR] Country filter not readable ($ffpath)" >&2
exit 1
fi
fpm=$fpm" -f $ffpath";
ffiles=( "${ffiles[@]}" $ffpath );
ffuse=1;
cmdlog=$cmdlog" -cc $2"
cmdsig=$cmdsig" -cc $2"
shift 2
;;
-i)
union=0;
cmdlog=$cmdlog" -i"
cmdsig=$cmdsig" -i"
shift
;;
-H | --hitsonly )
hitsonly=1
cmdlog=$cmdlog" -H"
cmdsig=$cmdsig" -H"
shift
;;
--)
filter=$2;
shift;
break ;;
*) echo "[ERROR] Undefined $1" ; exit 1 ;;
esac;
done;
cmdlog=$cmdlog" \"$filter\""
cmdsig=$cmdsig" \"$filter\""
# Execution ID
eid=`date +"%s"`
debug "Execution ID set to $eid"
fcount=${#ffiles[@]}
# Merge multiple filter files
debug "Size of filter file array: $fcount"
if [ $fcount -gt 1 ]; then
if [ $union -eq 1 ]; then
debug "Union of multiple filter files (default behaviour)"
mop="or"
else
debug "Intersection of multiple filter files (-i)"
mop="and"
fi
fmerge=$TMP_DIR/$eid".merge.filter"
echo "" > $fmerge
if [ ! -e $fmerge ]; then
echo "[ERROR] Failed to create $fmerge" >&2
exit 1
fi
for (( fi = 0 ; fi < ${#ffiles[@]} ; fi++ )); do
content=$( cat ${ffiles[$fi]} | sed 's/#.*$//' | sed 's/^[ \t]*//;s/[ \t]*$//' )
if [ -z "$content" ]; then
echo "[WARNING] Empty filter file: ${ffiles[$fi]}" >&2
continue
fi
echo -n "( " >> $fmerge
echo "$content" | sed ':a;N;$!ba;s/\n/ /g' >> $fmerge
echo -n " ) $mop " >> $fmerge
done
cat $fmerge | sed "s/ $mop $//g" > $TMP_DIR/$eid".merge.last"
mv $TMP_DIR/$eid".merge.last" $fmerge
fpm=" -f $fmerge"
fi
if [ $verbose -ge 1 -a -n "$fpm" ]; then
tmpffile=`echo "$fpm" | awk '{print $2}'`
tmpfstring=`cat $tmpffile | sed 's/#.*$//' | sed ':a;N;$!ba;s/\n/ /g'`
debug "Filter string: $tmpfstring"
fi
# Argument post-processing and command overrides
if [ $logo -eq 1 ]; then
which toilet &>/dev/null
if [ $? -ne 0 ]; then
echo "[WARNING] TOIlet not located!" >&2
logo=0
else
flush `basename $0`
fi
fi
if [ $suse -eq 1 ]; then apm=""; fi
if [ $quiet -eq 1 ]; then verbose=0; fi
if [ $r24 -eq 1 ]; then debug "Entering Jack-Bauer-mode!"; fi
if [ $hitsonly -eq 1 ]; then nocolor=1; fi
if [[ $parallel -eq 0 && $nocluster -eq 1 ]]; then
echo "[ERROR] It makes no sense to use both -j and -J at the same time" >&2
exit 1
fi
# Check if command log exists
if [ ! -e $CMD_LOG_FILE ]; then
debug "Creating $CMD_LOG_FILE"
touch $CMD_LOG_FILE >/dev/null 2>&1;
if [ $? -ne 0 ]; then
echo "[ERROR] Failed to create $CMD_LOG_FILE" >&2
exit 1
fi
fi
if [ -w $CMD_LOG_FILE ]; then
debug "Logging commands to $CMD_LOG_FILE"
do_log=1;
else
echo "[WARNING] Command log file not writeable ($CMD_LOG_FILE)" >&2
do_log=0;
fi
# Deal with caching
if [ $nocache -eq 0 ]; then
# Cache directory maintainance
debug "Cache directory: $CACHE_DIR"
if [ ! -d $CACHE_DIR ]; then
mkdir -p $CACHE_DIR
if [ $? -eq 0 ]; then
debug "Cache directory $CACHE_DIR created"
else
echo "[WARNING] Failed to create cache directory $CACHE_DIR" >&2
fi
else
obsolete=$( find $CACHE_DIR -type f -mtime +$CACHE_TIME | wc -l )
if [ $obsolete -gt 0 ]; then
debug "Cache cleanup ($obsolete files are older than $CACHE_TIME days)"
find $CACHE_DIR -type f -mtime +$CACHE_TIME -exec rm -f {} \;
if [ $? -ne 0 ]; then
echo "[WARNING] Failed to clean cache" >&2
fi
fi
fi
# Create a signature representing this execution (current set of params)
cmdsig=`echo $cmdsig | sed 's/^ //g'`
debug "Input to signature: $cmdsig"
runtimesig=`echo "$cmdsig" | md5sum | awk '{print $1}'`;
debug "Runtime signature: $runtimesig"
if [ ! -w $CACHE_DIR ]; then
echo "[ERROR] Cache directory $CACHE_DIR not writeable. Fix it, or use -R." >&2;
exit 1;
else
if [ -r $CACHE_DIR"/"$runtimesig ]; then
# Cache hit!
echo "Using Cache: "$runtimesig;
cat $CACHE_DIR"/"$runtimesig;
if [ $nocolor -eq 0 ]; then
echo -e "\n\033[36;1m*** CACHED DATA ***\033[0m\n"
else
echo -e "\n*** CACHED DATA ***\n";
fi
exit 0;
fi
fi
else
debug "Result cache is disabled"
fi
if [ $ouse -eq 0 ]; then
# No output format specified. Default to my custom format!
opm="-o \"$OUTPUT\"";
fi
# Calculating time parameters
customstart_full=$customstart;
customend_full=$customend;
customstart=`echo $customstart | cut -d- -f1-3`;
customend=`echo $customend | cut -d- -f1-3`;
if [ -n "$customstart" ]; then
# Custom start has been defined
if [ -n "$customend" ]; then
# Custom end has also been defined
timestart=$customstart;
timeend=$customend;
elif [ $duse -eq 1 ]; then
# Days parameter defined
startint=`date -d "$customstart" +"%s"`;
endint=$(( startint + days * 86400 ));
timestart=$customstart;
timeend=`date -d "@$endint" +"%Y-%m-%d"`;
else
# Defaulting to end = now
timestart=$customstart;
timeend=`date +"%Y-%m-%d"`;
fi
else
# No custom start
if [ -n "$customend" ]; then
# Custom end has been defined
if [ $duse -eq 1 ]; then
# Days parameter defined
endint=`date -d "$customend" +"%s"`;
startint=$(( endint - days * 86400 ));
timestart=`date -d "@$startint" +"%Y-%m-%d"`;
timeend=$customend;
else
# Defaulting to DEFAULT_TIME
endint=`date -d "$customend" +"%s"`;
startint=$(( endint - DEFAULT_TIME * 86400 ));
timestart=`date -d "@$startint" +"%Y-%m-%d"`;
timeend=$customend;
fi
else
# No custom end
if [ $duse -eq 1 ]; then
# Days parameter defined
endint=`date +"%s"`;
startint=$(( endint - days * 86400 ));
timestart=`date -d "@$startint" +"%Y-%m-%d"`;
timeend=`date -d "@$endint" +"%Y-%m-%d"`;