/
psad
executable file
·11054 lines (9615 loc) · 394 KB
/
psad
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 -w
#
################################################################################
#
# File: psad (/usr/sbin/psad)
#
# URL: http://www.cipherdyne.org/psad/
#
# Purpose: psad makes use of iptables logs to detect port scans,
# probes for backdoors and DDoS tools, and other suspect traffic
# (many signatures were adapted from the Snort intrusion
# detection system). Data is provided by parsing syslog
# firewall messages out of /var/log/messages (or wherever syslog
# is configured to write iptables logs to).
#
# For more information read the psad man page or view the
# documentation provided at: http://www.cipherdyne.org/psad/
#
# Author: Michael Rash (mbr@cipherdyne.org)
#
# Credits: (see the CREDITS file bundled with the psad sources.)
#
# Version: 2.3-pre1
#
# Copyright (C) 1999-2012 Michael Rash (mbr@cipherdyne.org)
#
# Reference: Snort is a registered trademark of Sourcefire, Inc.
#
# License (GNU Public License):
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
# TODO: (see the TODO file bundled with the psad sources.)
#
# Default behavior is as follows. Each of these features can be disabled
# with command line arguments:
#
# - passive OS fingerprinting = yes
# - snort rule matching = yes
# - write fw errors to error log = yes
# - daemon mode = yes
# - reverse dns lookups = yes
# - validate firewall rules = yes
# - whois lookups of scanning IPs = yes
# - parse netstat output for local server ports = yes
#
# Coding Style: All configuration variables from psad.conf are stored in
# the %config hash by keys that are in capital letters. This is
# the only place in the code where capital letters will be used in
# variables names. There are several variables with file-scope, and
# these variables are clearly commented near the top of each of the
# psad daemons. Lines are generally limited to 80 characters for easy
# reading.
#
# Scan hash key explanation:
# absnum - Total number of packets from $src to $dst
# tot_protocols - Total number of IP protocols scanned by $src against $dst
# chain - iptables chain under which the scan packets appear in the
# logs.
# s_time - Start time for the first packet seen from src to dst.
# alerted - An alert has been sent.
# pkts - Number of packets (used for signatures and a packet counter
# for the current interval.
# flags - Keeps track of tcp flags.
# sid - Signature tracking
# abs_sp - Absolute starting port.
# abs_ep - Absolute ending port.
# strtp - Starting port.
# endp - Ending port.
#
# Sample iptables log messages:
#
# Sample tcp packet (rejected by iptables... --log-prefix = "DROP ")
#
# Mar 11 13:15:52 orthanc kernel: DROP IN=lo OUT= MAC=00:00:00:00:00:00:00:00:
# 00:00:00:00:08:00 SRC=127.0.0.1 DST=127.0.0.1 LEN=60 TOS=0x00 PREC=0x00
# TTL=64 ID=0 DF PROTO=TCP SPT=44847 DPT=35 WINDOW=32304 RES=0x00 SYN URGP=0
#
# Sample icmp packet rejected by iptables INPUT chain:
#
# Nov 27 15:45:51 orthanc kernel: DROP IN=eth1 OUT= MAC=00:a0:cc:e2:1f:f2:00:
# 20:78:10:70:e7:08:00 SRC=192.168.10.20 DST=192.168.10.1 LEN=84 TOS=0x00
# PREC=0x00 TTL=64 ID=0 DF PROTO=ICMP TYPE=8 CODE=0 ID=61055 SEQ=256
#
# Sample icmp packet logged through FORWARD chain:
#
# Aug 20 21:23:32 orthanc kernel: SID365 IN=eth2 OUT=eth1 SRC=192.168.20.25
# DST=192.168.10.15 LEN=84 TOS=0x00 PREC=0x00 TTL=63 ID=0 DF PROTO=ICMP TYPE=8
# CODE=0 ID=19467 SEQ=256
#
# Occasionally the kernel klogd ring buffer must become full since log
# entries are sometimes generated by a long port scan like this (note
# there is no 'DPT' field):
#
# Mar 16 23:50:25 orthanc kernel: DROP IN=lo OUT= MAC=00:00:00:00:00:00:00:
# 00:00:00:00:00:08:00 SRC=127.0.0.1 DST=127.0.0.1 LEN=60 TOS=0x00 PREC=0x00
# TTL=64 ID=0 DF PROTO=TCP SPT=39935 DINDOW=32304 RES=0x00 SYN URGP=0
#
# Note on iptables tcp log messages:
#
# iptables reports tcp flags in the following order:
#
# URG ACK PSH RST SYN FIN
#
# Files specification for /var/log/psad/<srcip> directories:
#
# psad creates a new directory "/var/log/psad/<src>" for each new <src>
# from which a scan is detected. Under this directory several files are
# created:
#
# danger_level - Overall danger level aggregated for all scans.
# p0f_guess - Passive OS fingerprint guess for <src>.
# <src/dst>_whois - Whois information for <src> (or <dst> if src
# is a local IP).
# <dst>_email_ctr - Total email alerts sent for <src>.
# <dst>_email_alert - The most recent email alert for <dst>.
# <dst>_packet_ctr - Packet counters for <dst>.
# <dst>_signatures - Signatures detected against <dst>.
#
# Note that some of the files above contain the destination address since a
# single source address may scan several destination addresses.
#
###############################################################################
#
### modules used by psad
use File::Copy;
use File::Path;
use IO::Socket;
use Socket;
use POSIX;
use IO::Handle;
use Data::Dumper;
use Getopt::Long 'GetOptions';
use strict;
### ========================== main =================================
### set the current version
my $version = '2.3-pre1';
### default config file for psad (can be changed with
### --config switch)
my $config_file = '/etc/psad/psad.conf';
### this will be set to either FW_DATA_FILE, ULOG_DATA_FILE
### or IPT_SYSLOG_FILE
my $fw_data_file = '';
### disable debugging by default
my $debug = 0;
my $debug_sid = 0; ### debug a specific signature
my $flush_fw = 0;
### build the iptables blocking configuration out of the
### IPT_AUTO_CHAIN variable
my @ipt_config = ();
### main configuration hash
my %config = ();
my $override_config_str = '';
### local subnets
my @local_nets = ();
### fw search string array
my @fw_search = ();
### socket for --fw-block
my $ipt_sock = '';
### commands hash
my %cmds = ();
### main psad data structure; contains ips, port ranges,
### protocol info, tcp flags, etc.
my %scan = ();
### cache scan danger levels
my %scan_dl = ();
### cache scan email counters
my %scan_email_ctrs = ();
### cache executions of external script (only used if
### ENABLE_EXT_SCRIPT_EXEC is set to 'Y');
my %scan_ext_exec = ();
### cache p0f-based passive os fingerprinting information
my %p0f = ();
### cache p0f-based passive os fingerprinting signature information
my %p0f_ipv4_sigs = ();
my %p0f_ipv6_sigs = ();
### cache TOS-based passive os fingerprinting information
my %posf = ();
### cache TOS-based passive os fingerprinting signature information
my %posf_sigs = ();
### cache valid icmp types and corresponding codes
my %valid_icmp_types = ();
my %valid_icmp6_types = ();
### Cache snort rule messages unless --no-snort-sids switch was
### given. This is only useful if iptables includes rules
### that log things like "SID123". "fwsnort"
### (http://www.cipherdyne.org/fwsnort/) will automatically
### build such a ruleset from snort signatures.
my %fwsnort_sigs = ();
### Cache snort classification.config file for class priorities
my %snort_class_dl = ();
### Cache any individual Snort rule priority definitions from
### the snort_rule_dl file
my %snort_rule_dl = ();
### Cache Snort rule reference configuration
my %snort_ref_baseurl = ();
### cache all scan signatures from /etc/psad/signatures file
my %sigs = ();
my %sig_search = ();
my %sig_ip_objs = ();
### cache iptables prefixes
my %ipt_prefixes = ();
### ignore ports
my %ignore_ports = ();
### ignore protocols
my %ignore_protocols = ();
### ignore interfaces
my %ignore_interfaces = ();
### data array used for dshield.org logs
my @dshield_data = ();
### track the last time we sent an alert to dshield.org
my $last_dshield_alert = '';
### calculate how often a dshield alert will be sent
my $dshield_alert_interval = '';
### dshield stats counters
my $dshield_email_ctr = 0;
my $dshield_lines_ctr = 0;
### get the current timezone for dshield (this is calculated
### and re-calculated since the timezone may change).
my $timezone = '';
### get the current year for dshield
my $year = '';
### keep track of how many CHECK_INTERVALS have elapsed; this is
### useful for TOP_SCANS_CTR_THRESHOLD
my $check_interval_ctr = 0;
### track the number of scan IP pairs for MAX_SCAN_IP_PAIRS thresholding
my $scan_ip_pairs = 0;
### %auto_dl holds all ip addresses that should automatically
### be assigned a danger level (or ignored).
my %auto_dl = ();
my %auto_dl_ip_objs = ();
my %auto_assigned_msg = ();
### cache the source ips that we have automatically blocked
### (if ENABLE_AUTO_IDS == 'Y')
my %auto_blocked_ips = ();
### counter to check psad iptables chains and jump rules
my $iptables_prereq_check = 0;
### cache the addresses we have issued dns lookups against.
my %dns_cache = ();
### cache the addresses we have executed whois lookups against.
my %whois_cache = ();
### cache ports the local machine is listening on (periodically
### updated by get_listening_ports()).
my %local_ports = ();
### cache the ip addresses associated with each interface on the
### local machine.
my %local_ips = ();
### Top attacking statistics
my %top_tcp_ports = ();
my %top_udp_ports = ();
my %top_udplite_ports = ();
my %top_sigs = ();
my %sig_sources = ();
my %top_sig_counts = ();
my %top_packet_counts = ();
my %local_src = ();
### regex to match IP addresses
my $ipv4_re = qr|(?:[0-2]?\d{1,2}\.){3}[0-2]?\d{1,2}|; ### IPv4
### IPv6 - full version in ip6tables logs
my $ipv6_re = qr|(?:[a-f0-9]{4}:){7}(?:[a-f0-9]{4})|i;
### ttl values are decremented depending on the number of hops
### the packet has taken before it hits the firewall. We will
### assume packets will not jump through more than 20 hops on
### average.
my $max_hops = 20;
### initial set of protocol packet counters (may get expanded through
### things like protocol scan detection)
my %protocols = (
'tcp' => '',
'udp' => '',
'udplite' => '',
'icmp' => '',
'icmp6' => ''
);
my %proto_ctrs = ();
my %protocol_strings = ();
### pid file hash
my %pidfiles = ();
### initialize and scope some default variables (command
### line args can override some default values)
my $sigs_file = '';
my $posf_file = '';
my $auto_dl_file = '';
my $snort_rules_dir = '';
my $srules_type = '';
my $cmdline_file = '';
my $analyze_mode = 0;
my $analysis_fields = '';
my $analysis_tokens_ar = [];
my $analysis_match_criteria_ar = [];
my $get_next_rule_id = 0;
my $test_mode = 0;
my $syslog_server = 0;
my $kill = 0;
my $restart = 0;
my $restrict_ip = '';
my $restrict_ip_cmdline = '';
my $status_mode = 0;
my $status_ip = '';
my $status_min_dl = 0;
my $status_summary = 0;
my $fw_list_auto = 0;
my $fw_block_ip = '';
my $fw_rm_block_ip = '';
my $fw_del_chains = 0;
my $gnuplot_mode = 0;
my $gnuplot_year = 0;
my $gnuplot_prev_mon = 0;
my $gnuplot_title = '';
my $gnuplot_legend_title = '';
my $gnuplot_grayscale = 0;
my $gnuplot_x_label = '';
my $gnuplot_x_range = '';
my $gnuplot_y_label = '';
my $gnuplot_y_range = '';
my $gnuplot_z_label = '';
my $gnuplot_z_range = '';
my $gnuplot_3d = 0;
my $gnuplot_view = '';
my $gnuplot_sort_style = 'value';
my $gnuplot_graph_style = '';
my $gnuplot_count_type = '';
my $gnuplot_count_element = -1;
my %gnuplot_cache_uniq = ();
my @gnuplot_data = ();
my $gnuplot_data_file = 'psad_iptables.dat';
my $gnuplot_plot_file = 'psad_iptables.gnu';
my $gnuplot_png_file = 'psad_iptables.png';
my $gnuplot_file_prefix = '';
my $gnuplot_template_file = '';
my $store_file = '';
my $gnuplot_interactive = 0;
my $plot_separator = ', '; ### default to CSV format for plot data
my $csv_mode = 0;
my $csv_stdin = 0;
my $csv_fields = '';
my $csv_print_uniq = 0;
my $csv_line_limit = 0;
my $csv_start_line = 0;
my $csv_end_line = 0;
my $csv_regex = '';
my $csv_neg_regex = '';
my $csv_have_timestamp = 0;
my $pkts_from_stdin = 0;
my $dump_ipt_policy = 0;
my $fw_include_ips = 0;
my $benchmark = 0;
my $num_packets = 0;
my $usr1 = 0;
my $hup = 0;
my $usr1_flag = 0;
my $hup_flag = 0;
my $verbose = 0;
my $print_ver = 0;
my $help = 0;
my $dump_conf = 0;
my $download_sigs = 0;
my $chk_interval = 0;
my $log_len = 23; ### used in scan_logr()
my $fw_analyze = 0;
my $fw_file = '';
my $lib_dir = '';
my $rm_data_ctr = 0;
my $analysis_emails = 0;
my $analysis_whois = 0;
my $enable_analysis_dns = 0;
my $netstat_lkup_ctr = 0;
my $kmsgsd_started = 0;
my $warn_msg = '';
my $die_msg = '';
my $skip_first_loop = 1;
my $cmdl_interface = '';
my $analyze_write_data = 0;
my $local_ips_lkup_ctr = 0;
my $num_hash_marks = 76; ### for gnuplot output
my $imported_syslog_module = 0;
### these flags are used to disable several features
### in psad if specified from the command line
my $no_snort_sids = 0;
my $no_signatures = 0;
my $no_icmp_types = 0;
my $no_icmp6_types = 0;
my $no_auto_dl = 0;
my $no_posf = 0;
my $no_daemon = 0;
my $no_ipt_errors = 0;
my $no_rdns = 0;
my $no_whois = 0;
my $no_netstat = 0;
my $no_fwcheck = 0;
my $no_kmsgsd = 0;
my $no_email_alerts = 0;
my $no_syslog_alerts = 0;
### tcp option types
my $tcp_nop_type = 1;
my $tcp_mss_type = 2;
my $tcp_win_scale_type = 3;
my $tcp_sack_type = 4;
my $tcp_timestamp_type = 8;
my %tcp_p0f_opt_types = (
'N' => $tcp_nop_type,
'M' => $tcp_mss_type,
'W' => $tcp_win_scale_type,
'S' => $tcp_sack_type,
'T' => $tcp_timestamp_type
);
my %ip_options = ();
### for ICMP
my $ICMP_ECHO_REQUEST = 8;
my $ICMP_ECHO_REPLY = 0;
my $ICMP6_ECHO_REQUEST = 128;
my $ICMP6_ECHO_REPLY = 129;
### These are not directly support by psad because they
### do not appear in iptables logs; however, several of
### these options are supported if fwsnort is also running.
my @unsupported_snort_opts = qw(
pcre
fragbits
content-list
rpc
byte_test
byte_jump
distance
within
flowbits
rawbytes
regex
isdataat
uricontent
content
offset
replace
resp
flowbits
ip_proto
); ### the ip_proto keyword could be supported, but would require
### refactoring parse_NF_pkt_str().
### for Snort signature sp/dp matching
my @port_types = (
{'sp' => 'norm', 'dp' => 'norm'},
{'sp' => 'norm', 'dp' => 'neg'},
{'sp' => 'neg', 'dp' => 'norm'},
{'sp' => 'neg', 'dp' => 'neg'},
);
### main packet data structure
my %pkt_NF_init = (
### data link layer
'src_mac' => '',
'dst_mac' => '',
'intf' => '', ### FIXME in and out interfaces?
### network layer
'src' => '',
's_obj' => '',
'dst' => '',
'd_obj' => '',
'proto' => '',
'ip_len' => -1,
'ip_opts' => '', ### v4 or v6
### IPv4
'ip_id' => -1,
'ttl' => -1,
'tos' => '',
'frag_bit' => 0,
### IPv6
'is_ipv6' => 0,
'tc' => -1,
'hop_limit' => -1,
'flow_label' => -1,
### ICMP
'itype' => -1,
'icode' => -1,
'icmp_seq' => -1,
'icmp_id' => -1,
### transport layer
'sp' => -1,
'dp' => -1,
'win' => -1,
'flags' => -1,
'tcp_seq' => -1,
'tcp_ack' => -1,
'tcp_opts' => '',
'udp_len' => -1,
### extra fields for psad internals (DShield reporting, fwsnort
### sid matching, iptables logging prefixes and chains, etc.)
'fwsnort_sid' => 0,
'fwsnort_rnum' => 0,
'fwsnort_estab' => 0,
'chain' => '',
'log_prefix' => '',
'dshield_str' => '',
'syslog_host' => '',
'timestamp' => ''
);
my %gnuplot_non_digit_packet_fields = (
### 'hashentry' - maps the field to an integer based on whether
### it has been seen before
### 'intf2int' - converts interface number to an integer (e.g. eth0 -> 0)
### 'ip2int' - converts IP address to integer representation
### data link layer
'src_mac' => 'hashentry',
'dst_mac' => 'hashentry',
'intf' => 'intf2int',
### network layer
'src' => 'ip2int',
'dst' => 'ip2int',
'proto' => 'proto2int',
'tos' => 'hashentry',
'ip_opts' => 'hashentry',
'frag_bit' => 'hashentry',
### transport layer
'flags' => 'hashentry',
'tcp_opts' => 'hashentry',
### extra fields for psad internals (DShield reporting, fwsnort
### sid matching, iptables logging prefixes and chains, etc.)
'chain' => 'hashentry',
'log_prefix' => 'hashentry',
'dshield_str' => 'hashentry',
'syslog_host' => 'hashentry',
);
my %gnuplot_non_digit_map = ();
my %ip2int_cache = ();
my %gnuplot_ip2int = ();
### packet parsing return values
my $PKT_ERROR = 0;
my $PKT_SUCCESS = 1;
my $PKT_IGNORE = 2;
### icmp header validation
my $BAD_ICMP_TYPE = 1;
my $BAD_ICMP_CODE = 2;
my $SIG_MATCH = 1;
my $NO_SIG_MATCH = 0;
### header lengths
my $TCP_HEADER_LEN = 20; ### excludes options
my $TCP_MAX_OPTS_LEN = 44;
my $UDP_HEADER_LEN = 8;
my $ICMP_HEADER_LEN = 4;
my $IP_HEADER_LEN = 20; ### excludes options
### save a copy of the command line arguments
my @args_cp = @ARGV;
### handle command line args
&getopt_wrapper();
### Everthing after this point must be executed as root (psad
### only needs root if run in auto-blocking mode; should take
### this into account and drop privileges).
&is_root();
### Import all psad configuration and signatures files
### (psad.conf, posf, signatures, psad_icmp_types,
### and auto_dl), and call setup().
&psad_init();
### check to make sure another psad process is not already running.
&unique_pid($config{'PSAD_PID_FILE'});
### get the ip addresses that are local to this machine
&get_local_ips();
### get the current services running on this machine
&get_listening_ports() unless $no_netstat;
### daemonize psad unless running with --no-daemon or an
### analysis mode
unless ($no_daemon or $debug) {
my $pid = fork();
exit 0 if $pid;
die "[*] $0: Couldn't fork: $!" unless defined $pid;
POSIX::setsid() or die "[*] $0: Can't start a new session: $!";
}
### write the current pid associated with psad to the psad pid file
&write_pid($config{'PSAD_PID_FILE'});
### write the command line args used to start psad to $cmdline_file
&write_cmd_line(\@args_cp, $cmdline_file)
unless $debug;
### psad requires that kmsgsd is running to receive any data (unless
### SYSLOG_DAEMON is set to ulogd or psad is configured to acquire data
### from a normal file via IPT_SYSLOG_FILE), so let's start it here for good
### measure (as of 0.9.2 it makes use of the pid files and unique_pid(),
### so we don't have to worry about starting a duplicate copy). While
### we're at it, start psadwatchd as well. Note that this is the best
### place to start the other daemons since we just wrote the psad pid
### to PID_FILE above.
my $cmd;
unless ($config{'ENABLE_SYSLOG_FILE'} eq 'Y'
or $no_kmsgsd
or $config{'SYSLOG_DAEMON'} =~ /ulog/i
or $kmsgsd_started) {
$cmd = $cmds{'kmsgsd'};
$cmd .= " -c $config_file";
$cmd .= " -O $override_config_str"
if $override_config_str;
open KMSGSD, "| $cmd" or die "[*] Could not execute $cmds{'kmsgsd'}";
close KMSGSD;
$kmsgsd_started = 1;
}
unless ($kmsgsd_started) {
my $pid = &is_running($pidfiles{'kmsgsd'});
if ($pid) {
kill 9, $pid unless kill 15, $pid;
}
unlink $pidfiles{'kmsgsd'} if -e $pidfiles{'kmsgsd'};
}
unless ($debug or $no_daemon) {
$cmd = $cmds{'psadwatchd'};
$cmd .= " -c $config_file";
$cmd .= " -O $override_config_str"
if $override_config_str;
open PSADWATCHD, "| $cmd" or die "[*] Could not ",
"execute $cmds{'psadwatchd'}";
close PSADWATCHD;
}
if ($config{'ENABLE_AUTO_IDS'} eq 'Y') {
### always flush old rules (the subsequent renew_auto_blocked_ips()
### will re-instantiate any that should not have been expired).
&flush_auto_blocked_ips() if $config{'FLUSH_IPT_AT_INIT'} eq 'Y';
### Check to see if psad automatically blocked some IPs from
### a previous run. This feature is most useful for preserving
### auto-block rules for IPs after a reboot or after restarting
### psad. (Note that ENABLE_AUTO_IDS is disabled by psad_init()
### if we are running on a syslog server or if we are running
### in -A mode).
&renew_auto_blocked_ips();
}
### Install signal handlers for debugging %scan with Data::Dumper,
### and for reaping zombie whois processes.
$SIG{'__WARN__'} = \&warn_handler;
$SIG{'__DIE__'} = \&die_handler;
$SIG{'CHLD'} = \&REAPER;
$SIG{'USR1'} = \&usr1_handler;
$SIG{'HUP'} = \&hup_handler;
if ($config{'ENABLE_DSHIELD_ALERTS'} eq 'Y') {
$last_dshield_alert = time() unless $last_dshield_alert;
}
### Initialize current time for disk space checking.
my $last_disk_check = time();
if ($config{'IMPORT_OLD_SCANS'} eq 'Y') {
### import old scans and counters from /var/log/psad/
&import_old_scans();
} elsif ($config{'ENABLE_SCAN_ARCHIVE'} eq 'Y') {
&archive_data();
} else {
&remove_old_scans();
}
### zero out the packet counter file (the counters
### are all zero at this point anyway unless we
### imported old scans).
&write_global_packet_counters();
### zero out prefix counters
&write_prefix_counters();
### zero out dshield alert stats (note we do this here regardless of
### whether DShield alerting is enabled since if it isn't we will
### just zero out the counters).
&write_dshield_stats();
my $fw_data_file_size = -s $fw_data_file;
my $fw_data_file_inode = (stat($fw_data_file))[1];
my $fw_data_file_check_ctr = 0;
### Get an open filehandle for the main firewall data file FW_DATA_FILE.
### All firewall drop/reject log messages are written to FW_DATA_FILE
### by kmsgsd (or by ulogd directly).
print STDERR "[+] Opening iptables data file: $fw_data_file\n" if $debug;
open FWDATA, $fw_data_file or die '[*] Could not open ',
"$fw_data_file: $!";
&get_auto_response_domain_sock()
if $config{'ENABLE_AUTO_IDS'} eq 'Y';
###=========================================================###
###### MAIN LOOP ######
###=========================================================###
MAIN: for (;;) {
### scope and clear the firewall data array
my @fw_packets = ();
### for --fw-block <ip>
my @add_ipt_addrs = ();
if ($hup_flag) {
&sys_log('received HUP signal, ' .
're-importing psad.conf');
print STDERR "[+] Received HUP signal, re-importing config...\n"
if $debug;
my $orig_fwdata = $fw_data_file;
my $orig_ipt_sockfile = '';
$orig_ipt_sockfile = $config{'AUTO_IPT_SOCK'}
if $config{'ENABLE_AUTO_IDS'} eq 'Y';
### Re-import all used config files (psad.conf, auto_dl,
### posf, signatures) if we received a HUP signal.
&psad_init();
if ($orig_fwdata ne $fw_data_file) {
close FWDATA;
### re-open the fwdata file
open FWDATA, $fw_data_file or die
"[*] Could not open $fw_data_file: $!";
$skip_first_loop = 1;
}
if ($config{'ENABLE_AUTO_IDS'} eq 'Y') {
if ($orig_ipt_sockfile ne $config{'AUTO_IPT_SOCK'}) {
close $ipt_sock;
&get_auto_response_domain_sock();
$skip_first_loop = 1;
}
}
$hup_flag = 0; ### clear the HUP flag
}
### See if we need to print out the %scan datastructure
### (we received a USR1 signal)
if ($usr1_flag) {
$usr1_flag = 0; ### clear the USR1 flag
&sys_log('received USR1 signal, printing scan ' .
"hashes to $config{'PSAD_DIR'}/scan_hash.$$");
### dump scan hash to filesystem
&print_scan();
}
### allow the contents of the fwdata file to be processed only after
### the first loop has been executed.
if ($skip_first_loop) {
$skip_first_loop = 0;
seek FWDATA,0,2; ### seek to the end of the file
next MAIN;
} else {
### Get any new packets have been written to
### FW_DATA_FILE by kmsgsd for psad analysis.
@fw_packets = <FWDATA>;
if ($config{'ENABLE_AUTO_IDS'} eq 'Y') {
### get IP from the domain socket
my $ipt_add_connection = $ipt_sock->accept();
if ($ipt_add_connection) {
@add_ipt_addrs = <$ipt_add_connection>;
}
}
}
if ($fw_data_file_check_ctr == 10) {
if (-e $fw_data_file) {
my $size_tmp = -s $fw_data_file;
my $inode_tmp = (stat($fw_data_file))[1];
if ($inode_tmp != $fw_data_file_inode
or $size_tmp < $fw_data_file_size) {
close FWDATA;
&sys_log('[+]', "iptables syslog file $fw_data_file " .
"shrank or was rotated, so re-opening");
### re-open the fwdata file
open FWDATA, $fw_data_file or die
"[*] Could not open $fw_data_file: $!";
$skip_first_loop = 1;
### set file size and inode
$fw_data_file_size = $size_tmp;
$fw_data_file_inode = $inode_tmp;
}
}
$fw_data_file_check_ctr = 0;
}
if (@fw_packets) {
if ($config{'ENABLE_DSHIELD_ALERTS'} eq 'Y') {
### calculate the timezone offset
$timezone = sprintf("%.2d", (Timezone())[3]) . ':00';
$year = This_Year();
}
unless ($no_netstat) {
### we don't expect the list of ports the machine is listening
### on to change very often.
if ($netstat_lkup_ctr == 10) {
&get_listening_ports();
$netstat_lkup_ctr = 0;
}
$netstat_lkup_ctr++;
}
### the local machine ip addresses could change (dhcp, etc.)
### but not that often.
if ($local_ips_lkup_ctr == 30) {
&get_local_ips();
$local_ips_lkup_ctr = 0;
}
$local_ips_lkup_ctr++;
### Extract data and summarize scan packets, assign danger level,
### send email/syslog alerts.
&check_scan(\@fw_packets);
}
### log top scans data
my $do_log = 0;
if ($config{'TOP_SCANS_CTR_THRESHOLD'} == 0) {
$do_log = 1;
} elsif ($check_interval_ctr % $config{'TOP_SCANS_CTR_THRESHOLD'} == 0) {
$do_log = 1;
}
if ($do_log) {
### log the top port and signature matches
&log_top_scans();
}
### Write the number of tcp/udp/icmp packets out
### to the global packet counters file
&write_global_packet_counters();
### Write out log prefix counters
&write_prefix_counters();
if ($config{'ENABLE_AUTO_IDS'} eq 'Y') {
### Timeout any auto-blocked IPs that are past due (need to
### check the timeouts against existing IPs in the scan hash
### even if new packets are not found).
if ($config{'AUTO_BLOCK_TIMEOUT'} > 0) {
&timeout_auto_blocked_ips();
}
### see if we need to add any IP address from the domain
### socket
&check_ipt_cmd(\@add_ipt_addrs) if @add_ipt_addrs;
}
### Send logs to dshield in dshield format
if ($config{'ENABLE_DSHIELD_ALERTS'} eq 'Y') {
&dshield_email_log();
}
### Allow disk space utilization checks to be disabled by
### setting DISK_MAX_PERCENTAGE = 0.
if ($config{'DISK_MAX_PERCENTAGE'} > 0
and (time() - $last_disk_check) > $config{'DISK_CHECK_INTERVAL'}) {
### See how we are doing on disk space, and remove data
### if necessary.
if (&disk_space_exceeded() and $config{'ENABLE_SYSLOG_FILE'} ne 'Y') {
close FWDATA;
### truncate fwdata file
&truncate_file($fw_data_file);
### re-open the fwdata file
open FWDATA, $fw_data_file or die
"[*] Could not open $fw_data_file: $!";
}
$last_disk_check = time();
}
&check_auto_response_sock()
if $config{'ENABLE_AUTO_IDS'} eq 'Y';
### Print the number of new packets we saw in FW_DATA_FILE if we are
### running in debug mode
if ($debug) {
print STDERR "[+] MAIN: number of new packets: " .
($#fw_packets+1) . "\n";
}
if ($die_msg) {
&print_sys_msg($die_msg, "$config{'PSAD_ERR_DIR'}/psad.die");
$die_msg = '';
}
if ($warn_msg) {
&print_sys_msg($warn_msg, "$config{'PSAD_ERR_DIR'}/psad.warn");
$warn_msg = '';
}
### see if we need to timeout any old scans
if ($config{'ENABLE_PERSISTENCE'} eq 'N') {
my $do_timeout = 0;
if ($config{'PERSISTENCE_CTR_THRESHOLD'} == 0) {
$do_timeout = 1;
} elsif ($check_interval_ctr % $config{'PERSISTENCE_CTR_THRESHOLD'} == 0) {