forked from gitpan/LaBrea-Tarpit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTarpit.pm
executable file
·1657 lines (1405 loc) · 45.3 KB
/
Tarpit.pm
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
package LaBrea::Tarpit;
#
# 2-5-05, [email protected]
#
BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN }}
$__PACKAGE__::DOWARN = 1;
use strict;
#use diagnostics;
use vars qw($VERSION @ISA @EXPORT_OK);
$VERSION = do { my @r = (q$Revision: 1.36 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
use Fcntl qw(:DEFAULT :flock);
use AutoLoader 'AUTOLOAD';
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
recurse_hash2txt
daemon
bandwidth
midnight
timezone
tz2_sec
their_date
restore_tarpit
log2_mem
process_log
cull_threads
write_cache_file
prep_report
find_old_threads
array2_tarpit
);
use constant defaults => { # seconds
'cull' => 600, # drop threads older than this
'min_age' => 15, # don't cull for at least
'auto_cull' => 900, # cull at least every
's_timeout' => 0.1, # select timeout
'sock_timeout' => 180, # give up on socket response
};
use constant mon => {
qw(jan 0 feb 1 mar 2 apr 3 may 4 jun 5 jul 6 aug 7 sep 8 oct 9 nov 10 dec 11)
};
=head1 NAME
LaBrea::Tarpit - Utilities and web displays for
Tom Liston's LaBrea scanner/worm disruptor
See: http://sourceforge.net/projects/labrea/
=head1 SYNOPSIS
use LaBrea::Tarpit qw( [exportable functions] );
or
require LaBrea::Tarpit;
daemon(%hash or \%hash);
$bandwidth = bandwidth(\%tarpit);
$midnight = midnight($epoch_time,$tz);
$timezone = timezone($now);
$sec = $tz2_sec($tz);
$time_string = their_date($gmtime,$tz);
$rv = restore_tarpit(\%tarpit,path2cache_file);
$rv = log2_mem(\%tarpit,log_line,is_daemon,port_intvls,DShield);
$rv = process_log(\%tarpit,path2log_file,is_daemon,port_intvls);
$rv = cull_threads(\%tarpit,timeout,scanners,port_intvls,DShield);
$rv = write_cache_file(\%tarpit,path2cache_file,umask,flag);
prep_report(\%tarpit,\%hash);
$rv = find_old_threads(\%tarpit,\%report,$age);
=head1 INSTALL
=over 4
=item * Package
Untar the package
perl Makefile.PL
make
make test
make install
To use examples/daemon.pl, configure
the array at the beginning of the script
and set the locations for the cache files.
...typically /var/tmp/labrea.cache
and /var/tmp/DShield.cache
=item * Report/examples/html_report.plx
=item * Report/examples/paged_report.plx
B<html_report> and B<paged_report> will run as a cgi scripts
by simply renaming them B<xxx_report.cgi>. It is highly recommend that
you enable the file caching to minimize load on your system.
Read the comments in the file itself for configuration.
The defaults should work fine, but you must create the
temporary directory used for file caching AND it must
be writable by the web server.
B<html_report> and B<paged_report> are configured to provide B<other_site>
reporting. You must set up the cron job maintain the
B<site_stats> file for reporting. B<See webscan.pl> below:
=item * Get/examples/web_scan.pl
Run B<web_scan.pl> from a cron job hourly or daily to
update the statistics from all know sites running
LaBrea::Tarpit. A report can then be generated showing
the activity worldwide.
# MIN HOUR DAY MONTH DAYOFWEEK COMMAND
30 * * * * ./web_scan.pl ./other_sites.txt ./tmp/site_stats
Also see: LaBrea::Tarpit::Report::other_sites
=item * examples/tell_me.pl AGE
Run B<tell_me.pl> from a cron job daily to send yourself
an email detailing teergrubed hosts that have been
held longer than B<AGE> days. You might actually want
to tell the bad guys that they have a rogue machine.
# MIN HOUR DAY MONTH DAYOFWEEK COMMAND
30 * * * * ./tell_me.pl 60 # default
=item * DShield/examples/mail_dshield.pm
Configure with your DShield UserID, email address, mail agent and
the location of the daemon - DShield cache file, then run periodically from
cron to send reports to DShield.
=back
=head1 DESCRIPTION - LaBrea::Tarpit
A comprehensive Hack Attack reporting module when used in conjunction with
Tom Liston's LaBrea scanner/worm disruptor. When configured with reporting
and stat collection it provides a detailed HTML page containing:
=over 4
=item * Bandwidth consumed by attack/disruption daemon
=item * Summary of previous 5 days of attack/disruption
=item * All IP addresses currently attacking
=item * IP address, port attacked/held, attack start time
=item * As above, but history of terminated attacks
=item * By day detail graphs on port attack intensity
=item * Active summary of known LaBrea::Tarpit sites
=back
For more information on B<LaBrea> see: L<http://sourceforge.net/projects/labrea/>
or contact the author of LaBrea, Tom Liston L<[email protected]>.
The parsed output of either syslog data or STDOUT from LaBrea using -o or -O
options is readily turned into text reports or an html output page.
Basically there are two methods of operation. You can use the B<daemon> mode
to create an almost realtime cache that may be parsed using the report
routines, or you can use the update and report routines to parse the syslog
files on an as needed basis. If you plan to create web page reports, the
daemon model will use less system resources in the long run and avoids
running syslog with the high volume output of LaBrea.
Improvements VERSION 1.00
As of version 1.00, B<daemon.pl> uses network sockets to provide data for
the report modules. This means that the daemon can run on a remote machine
and the report scripts and web server can be somewhere else.
For those of you upgrading from older versions, you B<MUST> upgrade all of
your report scripts as well. Older versions use a pipe or FIFO and this is
no longer supported as there were problems maintaining separate sessions.
=cut
# memory records are kept in the form:
#
# %tarpit # time is kept in seconds since epoch
# {bw} -> bandwidth # bytes per second
#
# {tz} -> timezone # i.e. text string = -800
#
# {now" -> epoch time # only used when writing cache,
# # not current otherwise
# active threads
# {at} -> {srcIP_1} -> {sp1} -> {dip} -> destination IP
# . (src_port1) {dp} -> destination port
# . . {pst} -> protocol type (0,6=tcp)
# for tcp = persistent [true/false]
# . . {ct} -> capture time
# . . {lc} -> last contact time
# . .
# . -> {sp2} -> {dip} -> destination IP
# . (src_port2) {dp} -> destination port
# . {pst} -> protocol type (0,6=tcp)
# for tcp = persistent [true/false]
# . {ct} -> capture time
# . {lc} -> last contact time
# .
# {srcIP_2} -> etc...
# dead threads
# {dt} -> {srcIP} -> {dp} -> last destination port
# {lc} -> last contact time
# .
# port stats
# {ph} -> {timea} -> {port num.x} -> count
# . -> {port num.y} -> count
# . -> {port num.z} -> count
# (timeb} -> etc...
#
# {pt} -> collection_interval
=over 2
=item * recurse_hash2txt(\$txt_buffer,\%hash,$keys_so_far,flag)
Appends to txt_buffer.
Generates a text tree of a hash.
%hash{lvl1}->{lvl2}->{lvl3} = 5; this real hash
flag = 0, ksf = '' with this input
lvl1:lvl2:lvl3:5 produces this text
flag = 1, ksf = ptr this input
ptr->{lvl1}->{lvl2}->{lvl3} = 5; this txt
=cut
# input: txt out pointer, pointer to hash, keys so far, dump | debug
# if the dod flag is 0, this is normal dump mode
# else it's the fancy debug mode
sub recurse_hash2txt {
my ($txp, $p, $ksf,$dod) = @_;
foreach my $key (sort keys %{$p}) {
my $keysnow = $ksf;
$keysnow .= ($dod) ? qq|->{$key}|
: ($ksf)
? ':'. $key
: $key;
if (ref $p->{$key}) {
&recurse_hash2txt($txp,$p->{$key},$keysnow,$dod);
} else {
$keysnow .= ($dod) ? ' = ' : ':';
$keysnow .= ($p->{$key} || 0) . "\n";
$$txp .= $keysnow;
}
}
}
=item * ($LBfh,$version,$kid) = lbd_open($LaBrea,$DEBUG);
Core daemon start routine. Not exported, but can
be replaced externally with:
*LaBrea::Tarpit::lbd_open = sub { stuff };
Returns the pid of the underlying process (if any) and the version number of
that process. It also sets the command line shown by 'ps' like this:
$0 = 'stuff';
input: path to daemon,
STDERR switch
returns: LaBrea file handle,
version,
pid of kid
=cut
sub lbd_open {
my($LaBrea,$DEBUG) = @_;
local *LABREA;
$LaBrea =~ /^([^\s]+)/; # bare path to LaBrea
qx/$1 -V 2>&1/ =~ /(\d+\.[^\s]+)/; # get version
my $version = $1; # save version
# open LaBrea daemon
my $kid = open(LABREA,$LaBrea .' |');
die "Can't open $LaBrea: $!" unless $kid;
unless ($DEBUG) {
open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}
$0 = __PACKAGE__.' '.$0; # set ps(1) name to package name
return(*LABREA,$version,$kid);
}
=item * lbd_close($LBfh,$kid);
Core daemon close routine, not exported but can be
replaced externally with:
*LaBrea::Tarpit::lbd_close = sub { sutff };
Close the daemon and kill off $kid with sig 15
input: filehandle,
pid of kid
returns: nothing
=cut
sub lbd_close {
my($LBfh,$kid) = @_;
kill 15, $kid; # kill LaBrea
close $LBfh;
}
# autoload everything to keep daemon small
sub daemon;
sub bandwidth;
sub midnight;
sub timezone;
sub restore_tarpit;
sub log2_mem;
sub process_log;
sub cull_threads;
sub write_cache_file;
sub prep_report;
sub find_old_threads;
sub array2_tarpit;
# helper subroutines
#sub _cullnsquish;
sub _check4cull;
sub _init_pt;
sub _add_array;
sub _cache2txt;
sub _ex_append;
sub _get_config;
sub DESTROY {};
1;
__END__
=item * daemon(&hash | \%hash)
input parameters: from hash or pointer to hash
{
'LaBrea' => '/usr/local/bin/LaBrea -z -v -p 1000 -h -i eth0 -b -O 2>&1',
# 'd_port' => '8686', # default local comm port
'd_host' => 'localhost', # defaults to ALL interfaces
# NOT recommended
'allowed' => 'localhost,remote.com', # default is ALL
# recommend only 'localhost'
'pid' => '/path/to/pid/file_name',
'cache' => '/path/to/cache/file',
'DShield' => '/path/to/DShield/out_file',
# 'kids' => default 5 # kids to deliver net msgs
# why would you need more??
# 'umask' => default 033, # cache_file umask
# 'cull' => default 600, # seconds to keep old threads
'scanners' => 100, # keep this many dead threads
# 'port_timer' => default 86400, # seconds per collection period
'port_intvls' => 30, # keep #nintvls of port stats
# 0 or missing disables
# this can take lots of memory
# optional exclusion information (required if files exist)
'config' => '/etc/LaBreaConfig',
# or
# 'config' => 'LaBrea.cfg', # windoze (untested)
# or
# 'config' => ['/etc/LaBreaExclude','/etc/LaBreaHardExclude'],
};
=cut
# 'DEBUG' => undef, turn on STDERR in daemon
=pod
The daemon can be run on a remote host with restricted client access and
the data retrieved by another host that has web server capabilities
=back
=over 4
B<scanners> is enabled by setting to a positive number.
Since all IP's that are seen but not captured can
potentially be saved, this list could grow very large.
You can limit the amount of memory used by setting the
number of items that can be saved. There is no default,
a value <= 0 turns of this feature. Scanners are saved on
a fifo basis, when full, the oldest will be deleted first.
=back
=over 2
Signals:
HUP cull then write new cache file
TERM cull, write cache, exit
Killing the daemon with SIG_KILL (-9) will NOT write
a new cache file and will leave LaBrea running.
YOU SHOULD NOT DO THIS
B<daemon operation>:
The daemon parses the output of LaBrea in real time and
collects the information in its memory cache, periodically
pruning away threads that are no longer active to minimize
the memory footprint. Upon receiving a HUP, it immediately
prunes memory of old threads and writes its cache to file.
B<data retrieval>
Usage:
connect to TCP port 8686
send "standard" (endline)
or
send "active" (endline)
or
send "short" (endline)
or
send "config" (endline)
to receive the complete memory cache described above or
only active threads or a truncated version suitable for
making a B<short> report. B<config> sends the daemon
configuration file information to the client.
=cut
# helper routine
#
# check for time to cull cache of old threads
# this does not need to be done often because
# LaBrea holds most indefinetly unless the black
# hat guys give up. Call with a small wait time
# when dumping the cache for use in a web page
#
# input: time between culls
#
# returns: true if cull reduces thread count, else false
#
sub _check4cull {
my ($tp,$ttcp,$wait_time,$cull,$scrs,$ph,$ds) = @_;
my $now = $tp->{now} = time;
if ( $now > $$ttcp + $wait_time ) {
$$ttcp = $now; # reset wait time
return &cull_threads($tp, $cull, $scrs, $ph, $ds);
}
0;
}
# check as above and if there is a tarpit cull,
# collapse the tarpit hash to conserve memory
# 1) write out the hash to disk
# 2) set the tarpit hash to an anon empty array
# 3) reload the tarpit from the disk
#
# returns: true if cull, else false
# fails silently if there is no cache file
#sub _cullnsquish {
# my ($tp,$ttcp,$wait_time,$cull,$scrs,$ph,$ds,$pt,$cache_file,$umask,$version) = @_;
# my $rv;
# if ($rv = &_check4cull($tp,$ttcp,$wait_time,$cull,$scrs,$ph,$ds)) { # cull every few minutes
# my $cache_txt = &write_cache_file($tp,$cache_file,$umask,1); # write cache file and return cache text
# %$tp = (); # collapse tarpit hash;
# my @lines = split("\n",$cache_txt);
# &array2_tarpit($tp,\@lines); # returns true
# $tp->{LaBrea} = $version; # set version number
# $tp->{pt} = $pt || 86400; # default data collection is one day
# }
# $rv;
#}
# input: file name, mark text
# returns: lines of file with ' mark text\n' appended
#
sub _get_config {
my ($f,$mark) = @_;
$mark = ' ' . $mark if $mark;
local *F;
return '' unless open(F,$f);
@_ = (<F>); # slurp lines
close F;
chop @_;
my $rv = join("$mark\n",@_);
$rv .= "$mark\n" if $rv;
};
# make daemon
#
# KILL with signal TERM, -15
# dump cache with SIG_HUP
#
# input: %hash or \%hash above
#
sub daemon {
my $pid;
$_ = ( ref $_[0] ) ? $_[0] : {@_};
my ($LaBrea,$config,$pid_file,$max_kids,$d_port,$d_host,$allowed,$cache_file,$umask,$cull,$scrs, $ph, $pt, $ds, $DEBUG) = @{$_}{
qw(LaBrea config pid kids d_port d_host allowed cache umask cull scanners port_intvls port_timer DShield DEBUG)};
# fork and test
unless ( $pid = fork ) {
# clean up for proper daemon operation
chdir '/'; # allow root dismount
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
unless ( $pid = fork ) {
local(*SERVER,*CLIENT);
require LaBrea::NetIO;
import LaBrea::NetIO qw(
open_listen_sock
reap_kids
set_so_linger
sockaddr_in
inet_ntoa
);
# open server port
die $_ if ($_ = open_listen_sock(*SERVER,$d_host,$d_port));
my $flags = fcntl(SERVER,F_GETFL,0) || die "can't get socket flags";
fcntl(SERVER,F_SETFL,$flags | O_NONBLOCK) || die "can't set socket non-blocking";
require POSIX;
my $tarpit = {};
&POSIX::setsid() or die "Can't start new session: $!";
my($LBfh,$version,$kid) = lbd_open($LaBrea,$DEBUG);
$umask = 033 unless $umask;
$cull = defaults->{cull} unless $cull;
$ph = 0 unless $ph;
my $time2cull = time + $cull; # first cull must wait
##### define signal services within this scope
my $run = 1;
my $hup = 0;
$__PACKAGE__::DOWARN = 0; # quite warnings about
my $quit = sub { # portability of $run, $hup
$run = 0;
};
my $dohup = sub {
$hup = 1;
};
$__PACKAGE__::DOWARN = 1;
# local $SIG{HUP} = $dohup;
# local $SIG{INT} = $dohup;
# local $SIG{TERM} = $quit;
local $SIG{HUP} = sub { $hup = 1; };
local $SIG{INT} = sub { $hup = 1; };
local $SIG{TERM} = sub { $run = 0; };
local $SIG{PIPE} = 'IGNORE';
&restore_tarpit($tarpit,$cache_file) if -e $cache_file;
$tarpit->{LaBrea} = $version; # set version number
$tarpit->{pt} = $pt || 86400; # default data collection is one day
# prepare daemon loop
my $WNOHANG = &POSIX::WNOHANG;
my $rin = '';
vec($rin,fileno($LBfh),1) = 1;
my $timeout = defaults->{s_timeout};
my ($rout,$paddr,%kids);
my @valid_clients;
foreach(split(',', $allowed)) {
(undef,undef,undef,undef,@_) = gethostbyname($_);
push @valid_clients,@_;
}
$max_kids = 5 unless $max_kids;
my $kids = 0; # number of kids alive
while($run) {
# accept for SERVER is not set for 'select', find it with the POLL
my $ready = select($rout=$rin,undef,undef,$timeout);
if ( $ready > 0 ) {
$_ = <$LBfh>; # blocks, but doesn't matter here
last unless $_; # Oops, LaBrea must have died, EXIT
&log2_mem($tarpit,$_,1,$ph,$ds);
# &_cullnsquish($tarpit,\$time2cull,defaults->{auto_cull},$cull,$scrs,$ph,$ds,$pt,$cache_file,$umask,$version);
if (&_check4cull($tarpit,\$time2cull,defaults->{auto_cull},$cull,$scrs,$ph,$ds)) { # cull every few minutes
;
# revert cull operation to previous behavior
# the code below does not seem to improve memory usage
# my $cache_txt = &write_cache_file($tarpit,$cache_file,$umask,1); # write cache file and return cache text
# $tarpit = {}; # collapse tarpit hash;
# my @lines = split("\n",$cache_txt);
# &array2_tarpit($tarpit,\@lines); # returns true
# $tarpit->{LaBrea} = $version; # set version number
# $tarpit->{pt} = $pt || 86400; # default data collection is one day
}
}
elsif ( $hup ) {
# &write_cache_file($tarpit,$cache_file,$umask,1) unless
# &_cullnsquish($tarpit,\$time2cull,defaults->{min_age},$cull,$scrs,$ph,$ds,$pt,$cache_file,$umask,$version); # cull immediate
&_check4cull($tarpit,\$time2cull,defaults->{auto_cull},$cull,$scrs,$ph,$ds); # cull immediate
&write_cache_file($tarpit,$cache_file,$umask,1); # and write cache file
$hup = 0;
}
elsif ( $kids < $max_kids && ($paddr = accept(CLIENT,SERVER)) ) { # client has connected
if ($pid = fork) {
close CLIENT; # close if parent
$kids{$pid} = ++$kids if $pid; # bump kid count, val is not used
} else { # CHILD, service request
close SERVER;
########### CHILD PROCESS #################
local $SIG{ALRM} = sub { die "child connect timeout" };
my $iaddr = (sockaddr_in($paddr))[1];
unless ( ( ! @valid_clients || # allow all
grep($_ == $iaddr,@valid_clients)) && # or small number
set_so_linger(*CLIENT,30)) { # linger 30 seconds to deliver stuff
close CLIENT;
exit 0; # exit silently if not allowed or can't set linger
}
&_check4cull($tarpit,\$time2cull,defaults->{min_age},$cull,$scrs,$ph,$ds); # cull immediate
eval {
my $cache_txt = '';
alarm defaults->{sock_timeout};
my $request = readline *CLIENT;
if ( $request =~ /^standard/ ) { # full tarpit contents
$request = $tarpit;
}
elsif ( $request =~ /^short/ ) { # short totals only
$request = { 'Tarpit' => $VERSION }; # version in format for other end
prep_report($tarpit,$request);
}
elsif ( $request =~ /^active/ ) { # only active threads
$request = { 'at' => $tarpit->{at} };
}
elsif ( $request =~ /^config/ ) { # return config info
if ( $config ) {
if (ref $config) { # if it is array format
@_ = @{$config};
} else {
@_ = ($config);
}
my ($hard_ex,$exclude,$new_config);
if ( $_[0] =~ /Exclude/ ) { # old style
if ( $_[0] =~ /Hard/ ) {
$cache_txt .= &_get_config($_[0],'hardexclude');
} else {
$cache_txt .= &_get_config($_[0],'exclude');
}
if ( @_ > 1 ) { # if second argument
if ( $_[1] =~ /Hard/ ) {
$cache_txt .= &_get_config($_[1],'hardexclude');
} elsif ( $_[1] =~ /Exclude/ ) {
$cache_txt .= &_get_config($_[1],'exclude');
}
}
} elsif ( $_[0] =~ /Config/ ||
/LaBrea\.cfg/ ) { # new style, config true
$cache_txt .= &_get_config($_[0],'');
}
} # end config file info
$cache_txt = "none\n" unless $cache_txt;
} else { # unknown
alarm 0;
close CLIENT;
exit 0;
}
&_cache2txt(\$cache_txt,$request,'daemon') unless $cache_txt;
my $len = length($cache_txt);
my $off = 0;
my $win = '';
my ($wout,$eout);
vec($win,fileno(CLIENT),1) = 1;
my $ein = $win;
while ($len) {
$ready = select(undef,$wout=$win,undef,defaults->{pipe_timeout}); # block until write or error
last unless $ready; # punt if timeout
my $wrote = syswrite(CLIENT,$cache_txt,$len,$off);
last unless defined $wrote; # only errors
# if ( ! defined $wrote ) {
# next if $! == EAGAIN; # would block
# }
$off += $wrote;
$len -= $wrote;
}
};
alarm 0;
close CLIENT;
exit 0; # child dies
}
########### END CHILD #################
}
else {
$kids = reap_kids(\%kids); # dispose of dead kids, return remaining number
}
}
lbd_close($LBfh,$kid);
&_check4cull($tarpit,\$time2cull,defaults->{min_age},$cull,$scrs,$ph,$ds); # cull threads
&write_cache_file($tarpit,$cache_file,$umask,1);
foreach $kid ( keys %kids ) {
kill 15, $kid; # kill remaining children
}
unlink $pid_file;
exit 0;
}
exit 1 unless open(PID,'>'.$pid_file);
print PID $pid, "\n";
close PID;
exit 0;
}
waitpid($pid,0);
}
=item * $bandwidth = bandwidth(\%tarpit);
Returns bandwidth reported by LaBrea or zero
if the -b option is not used or B<bw> is unknown.
=cut
# return the current bandwidth
#
# input: \%tarpit
# return: bandwidth
#
sub bandwidth {
my ($tp) = @_;
return $tp->{bw} || 0;
}
=item * $time = midnight($epoch_time,$tz);
Returns epoch time at 00:00:00 of current day
from any epoch time submitted. Time zone is
calculated (inefficently) each time if omitted.
=cut
sub midnight {
my ($et,$tz) = @_;
$tz = &timezone($et) unless $tz;
my $mn= $et - tz2_sec($tz) - ($et%86400);
if ($mn > $et) {
$mn -= 86400;
} elsif ($et - $mn >= 86400) {
$mn += 86400;
}
$mn;
}
=item * $seconds = $tz2_sec($tz);
Convert time zone into seconds
input: timezone i.e. -0800
returns: seconds i.e. -28800
=cut
sub tz2_sec {
my ($tz) = @_;
my $tza = abs $tz;
my $min = $tza % 100;
my $hr = $tza - $min;
my $sec = ($hr * 36) + $min * 60;
$sec = -$sec if $tz < 0;
$sec;
}
=item * $time_string = their_date($gmtime,$tz);
Returns date string like perl's
localtime(time)
for the specified time zone
=cut
sub their_date {
my ($time,$tz) = @_;
return gmtime($time + tz2_sec($tz)) . ' ' . $tz;
}
=item * $timezone = timezone($now);
Returns the local timezone as a text string
i.e. -0800
uses current time if $now is omitted,
this is the normal method of usage.
=cut
sub timezone {
my $t = $_[0] || time;
my $tt = $t;
my (@lt) = localtime($t);
my (@gt) = gmtime($t);
my $tzmin = ($gt[1] - $lt[1]) + ($gt[2] - $lt[2]) * 60;
if($lt[5] > $gt[5]) {
$tzmin -= 1440;
}
elsif($gt[5] > $lt[5]) {
$tzmin += 1440;
}
else {
$tzmin += ($gt[7] - $lt[7]) * 1440;
}
$tzmin += 60 if $lt[8];
my $time = $t + $tzmin * 60;
my @test = localtime($time + ($tt - $t));
$tzmin -= 60 if $test[2] != $gt[2];
my $tz = abs $tzmin;
my $min = $tz % 60;
my $hr = ($tz - $min) / 60;
$tz = ($tzmin < 0 )
? '+' : '-';
$tz .= sprintf("%02d%02d",$hr,$min);
}
=item * $rv = restore_tarpit(\%tarpit,path2cache_file);
Restore the memory cache from the file cache.
returns true if successful
false if cache_file won't open
File Cache is of the form:
_VERSION:Package::Name version daemon | static
_CACHEDUMP:date of last cache dump
# for each src host
at:ip_addr:sport:dest
at:ip_addr:sport:dport
at:ip_addr:sport:ct
at:ip_addr:sport:last
at:ip_addr:sport:persist
at:ip_addr:sport:DShield:dest:dp:time
bw:number
# for each scanning (gone) host
dt:ip_addr:sport:dport
dt:ip_addr:sport:last
dt:ip_addr:persist
ph:time:dport:count
now:1234567890
tz:-0800
=cut
# build hash from database file
#
# input: \%tarpit, $db_file_path_name
# return: true or false if fail
sub restore_tarpit {
my ($tp,$dbf) = @_;
return undef unless open(DB,$dbf);
my @lines = (<DB>);
close DB;
chop @lines; # no new-lines
&array2_tarpit($tp,\@lines); # returns true
}
=item * array2_tarpit(\%tarpit,\@array);
Restore the memory cache from an array of
lines as described for B<restore_tarpit>. The lines
must already be stripped of return characters
Always returns true;
=cut
sub array2_tarpit {
my ($tp,$ary) = @_;
foreach(@$ary) {
next unless $_ =~ /^[a-zA-Z]/; # must start with alpha tag
my @arg = split(':', $_);
next unless @arg > 1; # must be at least two items
my $inst = '$tp';
foreach(0..$#arg -1) {
$inst .= '->{$arg[' . $_ . ']}';
}
$inst .= ' = $arg[' . $#arg . '];';
eval $inst;
}
1; # return true
}
=item * $rv = log2_mem(\%tarpit,log_line,is_daemon,port_intvls,DShield);
Update memory cache from log output line. Set
B<is_daemon> if the log output is from daemon STDOUT
In order of minimum CPU overhead:
Daemon mode or logs created from STDOUT require the
least cpu overhead.
LaBrea -O is more efficient than Labrea -o.
Logs from STDOUT are more efficient than syslogs.
Standalone syslogs are more efficient than mixed.
All log lines used are of the form:
epoch time (seconds)
or
date text
followed by
[...LaBrea:] # syslog only
one of these
info text bw: bandwidth (bytes/sec)
or
info text: src_ip src_port txt dest_ip dest_port
Or more succinctly:
time text: bandwidth
or
time text: src_ip src_port txt dest_ip dest_port
Returns: true / false on success / fail
=cut
# update the tarpit cache from log line, see comments below for format
#
# input: \%tarpit, log_line, is_daemon, port_intvls, DShield_flag
#
#
sub log2_mem {
my ($tp,$line,$id,$ph,$ds) = @_;
return undef if (!$id && $line !~ /LaBrea:/);
# valid Labrea log line to parse
if ( $line =~ /.+bw:\s+(\d+)\s+/ ) { # if bandwidth line
$tp->{bw} = $1 || 0;
return 1;
}
# extract time / date
my $time;
if ( $line =~ /^(\d+)\s+/ ) {
$time = $1;
} else { # complex form
require Time::Local;
return undef unless $line =~ /(.+)\s+(\d+):(\d+):(\d+)\s+(\w+)\s+/;
@_ = split(/\s+/,$1);
my $day = pop @_;
my $mon = pop @_;
$mon = mon->{"\L$mon"};
my ($hr,$min,$sec,$yr) = ($2,$3,$4,$5);
if ($yr =~ /[^\d]/) {
my ($nowmo,$nowyr) = (localtime(time))[4,5];
$yr = ($mon > $nowmo) # roll over to new year??
? $nowyr -1
: $nowyr;
} elsif ( $yr > 1900 ) { # most likely
$yr -= 1900;
} elsif ( $yr < 70 ) { # yr 2000 or more
$yr += 100;
} # else leave as-is, 70 - 99
$time = &Time::Local::timelocal($sec,$min,$hr,$day,$mon,$yr);
}
# extract ip's and ports src sp dest dp
return undef unless $line =~ /:\s+(\d+\.\d+\.\d+\.\d+)\s+([na\d]+)[^\d]+(\d+\.\d+\.\d+\.\d+)\s+([na\d]+)/;
$tp->{now} = $time if (! $tp->{now}) || $tp->{now} < $time;
my ($src,$sp,$dest,$dp) = ($1,$2,$3,$4);
delete $tp->{dt}->{$src} if $tp->{dt}->{$src}; # remove dead soldiers
$_ = $tp->{at}->{$src}->{$sp} || ($tp->{at}->{$src}->{$sp} = {});
$_->{dip} = $dest;
$_->{dp} = $dp;
$_->{pst} = ($line =~ /Persist/i) ? 6 : 0;
$_->{ct} = $time unless exists $_->{ct};
$_->{lc} = $time;
if ( $ds && $line =~ /Initial/i ) { # mark for DShield
$_->{DShield} = {} unless $_->{DShield};
$_->{DShield}->{$dest} = {} unless $_->{DShield}->{$dest};