Analysis/Listener/TCP.pm untested

filter: Statementstmt 0.0% 0 / 116 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 209 CC 23 SCAR 34.5
CC
23
Cov
0%
_internal_tcp_packet
110.0
tcp_monologue
20.0
teardown
12.0
CRAP 31.6
1 package Net::Analysis::Listener::TCP;
2 # $Id: TCP.pm 133 2005-10-02 18:45:28Z abworrall $
3  
4 use 5.008000;
5 our $VERSION = '0.01';
6 use strict;
7 use warnings;
8  
9 use Carp qw(carp croak confess);
10  
11 use Params::Validate qw(:all);
12  
13 use Net::Analysis::Constants qw(:tcpflags);
14 use Net::Analysis::Packet qw(:all);
15 use Net::Analysis::TCPSession qw(:const);
16  
17 use base qw(Net::Analysis::Listener::Base);
18  
19 # {{{ POD
20  
21 =head1 NAME
22  
23 Net::Analysis::Listener::TCP - listens to packets, emits streams
24  
25 =head1 SYNOPSIS
26  
27 This module subclasses Net::Analysis::Listener::Base, and manages TCP sessions
28 behind the scenes.
29  
30 Listens for:
31 _internal_tcp_packet - note: augments packet, for downstream listeners
32  
33 Emits:
34 tcp_session_start
35 tcp_session_end
36 tcp_monologue - a series of data packets
37  
38 =head1 DESCRIPTION
39  
40 Each raw packet is slotted into the relevant TCP session. The TCPSession module
41 does most of the analysis on the packet, allowing this one to emit
42 C<tcp_monologue> events as they are completed.
43  
44 The tcp_monologue event is the backbone of higher level protocol analysers. It
45 is not a good example for writing your own listener.
46  
47 =head1 CONFIGURATION
48  
49 v - verbosity; a bitmask for logging to stdout:
50 0x01 - per-packet
51 0x02 - per-monologue
52 0x04 - per-session
53  
54 k - a TCP-session key to suddenly get verbose about
55  
56 dump - dumps out monologues as files into the current directory
57  
58 max_session_size - discard packets once this many bytes have been seen
59  
60 =head1 EMITTED EVENTS
61  
62 =head2 C<tcp_session_start>
63  
64 Emitted when we see a new TCP session get successfully estabished. Contains the
65 following arguments:
66  
67 socketpair_key - uniquely identifies the TCP session
68 pkt - the Net::Analysis::Packet which established the session
69  
70 Note that C<pkt> is the final packet in the setup handshake; it is not the
71 initail SYN, or the first data packet. You can get the SYN packets from the
72 TCPSession object if you want to dig around.
73  
74 =head2 C<tcp_session_end>
75  
76 Emitted when we see the end of the session; either because of a proper
77 handshake, or because we ran out of data. Contains the
78 following arguments:
79  
80 socketpair_key - uniquely identifies the TCP session
81 pkt - the Net::Analysis::Packet which closed the session
82  
83 Note that C<pkt> will be C<undef> if we ran out of data.
84  
85 =head2 C<tcp_monologue>
86  
87 As packets travel in one direction, we gather them up. When we see a (data)
88 packet in the other direction, or the end of the TCP session, we combine the
89 gathered packetes into a monologue object and emit this event. Contains the
90 following arguments:
91  
92 socketpair_key - uniquely identifies the TCP session
93 monologue - a Net::Analysis::TCPMonologue object
94  
95 =head1 METHODS
96  
97 You probably don't need to read the rest of this ...
98  
99 =cut
100  
101 # }}}
102  
103 #### Non-standard override stuff
104 #
105 # {{{ new
106  
107 =head2 new ( )
108  
109 Simple wrapper on top of C<Listener::Base::new()>, which ensures that the
110 TCP listener is put first in the queue for listening to events.
111  
112 This queue-jumping is to allow the C<tcp_packet> handler to add extra info to
113 the packet that higher level analysers might want to see. This info is derived
114 from its state in the TCP session.
115  
116 =cut
117  
118 sub new {
119 my $self = shift;
120  
121 return $self->SUPER::new(@_, pos => 'first'); #
122 }
123  
124 # }}}
125  
126  
127 #### Callbacks
128 #
129 # {{{ validate_configuration
130  
131 sub validate_configuration {
132 my $self = shift;
133  
134 my %h = validate (@_, { v => {type => SCALAR,
135 default => 0},
136 dump => {type => SCALAR,
137 default => 0},
138 max_session_size => {type => SCALAR,
139 default => 0},
140 k => {type => SCALAR,
141 default => ''},
142 });
143  
144 return \%h;
145 }
146  
147 # }}}
148  
149 # {{{ setup
150  
151 sub setup {
152 my ($self) = shift;
153  
154 $self->trace ("======[--:--:--.------] TCP setup") if ($self->{v} & 0x08);
155  
156 $self->{active_tcp_sessions} = {};
157 }
158  
159 # }}}
160 # {{{ teardown
161  
162 sub teardown {
163 my ($self) = shift;
164  
165 # If anything is still open, finish it off - we have no more packets
166 foreach my $k (keys %{$self->{active_tcp_sessions}}) {
167 my $sesh = $self->_get_session_object($k);
168  
169 if ($sesh->has_current_monologue()) {
170 $self->emit (name => 'tcp_monologue',
171 args =>{socketpair_key => $k,
172 monologue =>$sesh->current_monologue()});
173 }
174  
175 $self->emit (name => 'tcp_session_end',
176 args => {socketpair_key => $k});
177 }
178  
179 $self->trace ("======[--:--:--.------] TCP teardown") if ($self->{v} & 0x08);
180 }
181  
182 # }}}
183  
184 # {{{ _internal_tcp_packet
185  
186 # _internal_tcp_packet: emits tcp_session_start, tcp_monologue, tcp_session_end
187  
188 sub _internal_tcp_packet {
189 my ($self, $args) = @_;
190 my ($pkt) = $args->{pkt};
191  
192 my @events = (); # The carefully sequenced list of events
193  
194 # Get the TCP session key from the packet.
195 my $k = $pkt->[PKT_SLOT_SOCKETPAIR_KEY];
196  
197 # Establish session object
198 my $sesh = $self->_get_session_object($k);
199  
200 return if (($sesh->{total_bytes} >= $self->{max_session_size}) &&
201 ($self->{max_session_size} > 0));
202  
203 # Feed it packet
204 my $ret = $sesh->process_packet(packet => $pkt);
205 #my $deb = " = ". (($self->{v} & 0x08) ? $pkt->as_string(1) : "$pkt");
206  
207 # Maybe emit events ...
208 if ($ret == PKT_ESTABLISHED_SESSION) {
209 $self->_trace_pkt($pkt,$ret) if ($self->{v} & 0x01);
210 push (@events, {name => 'tcp_session_start',
211 args => {socketpair_key => $k,
212 pkt => $pkt} });
213  
214 } elsif ($ret == PKT_FLIPPED_DIR) {
215 push (@events, {name => 'tcp_monologue',
216 args => {socketpair_key => $k,
217 monologue => $sesh->previous_monologue()}});
218  
219 $self->_trace_pkt($pkt,$ret) if ($self->{v} & 0x01);
220  
221 } elsif ($ret == PKT_TERMINATED_SESSION) {
222 $self->_trace_pkt($pkt) if ($self->{v} & 0x01);
223  
224 # Clear out any remaining data
225 if ($sesh->has_current_monologue()) {
226 push (@events, {name => 'tcp_monologue',
227 args =>{socketpair_key => $k,
228 monologue =>$sesh->current_monologue()}});
229 }
230  
231 # Now end the session nicely.
232 push (@events, {name => 'tcp_session_end',
233 args => {socketpair_key => $k,
234 pkt => $pkt}});
235 $self->_close_down_session ($k);
236  
237 } else {
238 $self->_trace_pkt($pkt,$ret) if ($self->{v} & 0x01 || $self->{k} eq $k);
239 }
240  
241 unshift (@events, {name => 'tcp_packet', args => $args} );
242  
243 foreach (@events) {
244 $self->emit( %{ $_ } );
245 }
246 }
247  
248 # }}}
249  
250 # {{{ tcp_session_start
251  
252 # Fairly pointless; we don't need to listen to this event, really.
253 sub tcp_session_start {
254 my ($self, $args) = @_;
255 my $pkt = $args->{pkt}; # Might well be undef
256 my $k = $args->{socketpair_key};
257  
258 if ($self->{v} & 0x04) {
259 my $t = pkt_time($pkt)->as_string('time');
260 $self->trace (" ====[$t] tcp session start [".
261 $pkt->[PKT_SLOT_FROM]." -> ".
262 $pkt->[PKT_SLOT_TO]."]");
263 }
264 }
265  
266 # }}}
267 # {{{ tcp_session_end
268  
269 # Fairly pointless; we don't need to listen to this event, really.
270 sub tcp_session_end {
271 my ($self, $args) = @_;
272 my $pkt = $args->{pkt}; # Might well be undef
273 my $k = $args->{socketpair_key};
274  
275 if ($self->{v} & 0x04) {
276 my $t = $pkt ? pkt_time($pkt)->as_string('time') : '--:--:--.------';
277 $self->trace(" ====[$t] tcp session end [$k]");
278 }
279 }
280  
281 # }}}
282 # {{{ tcp_monologue
283  
284 # Fairly pointless; we don't need to listen to this event, really.
285 sub tcp_monologue {
286 my ($self, $args) = @_;
287 my $k = $args->{socketpair_key};
288 my $mono = $args->{monologue};
289  
290 $self->{_counters}{$k} ||= 0;
291 $self->{_counters}{$k}++;
292  
293 if ($self->{v} & 0x02) {
294 my $t = $mono->{time}->as_string('time');
295 $self->trace(sprintf (" ==[$t] $mono\n"));
296 }
297  
298 if ($self->{dumps}) {
299 my $fname = "$k.$self->{_counters}{$k}";
300 if (open (MONO, ">$fname")) {
301 print MONO $mono->{data};
302 close (MONO);
303 } else {
304 warn ("open+w '$fname': $!\n");
305 }
306 }
307 }
308  
309 # }}}
310  
311 # {{{ as_string
312  
313 sub as_string {
314 my ($self) = @_;
315 my $s = '';
316  
317 my $n = scalar (keys %{ $self->{active_tcp_sessions} });
318  
319 $s .= "[".ref($self)."], $n open sessions";
320  
321 return $s;
322 }
323  
324 # }}}
325  
326 #### Support funcs
327 #
328 # {{{ _get_session_object
329  
330 sub _get_session_object {
331 my ($self, $k) = @_;
332  
333 my ($sesh) = $self->{active_tcp_sessions}{$k} || undef;
334  
335 if (!defined $sesh) {
336 $sesh = Net::Analysis::TCPSession->new();
337 $self->{active_tcp_sessions}{$k} = $sesh;
338 }
339  
340 return $sesh;
341 }
342  
343 # }}}
344 # {{{ _close_down_session
345  
346 sub _close_down_session {
347 my ($self, $k) = @_;
348  
349 # XXXX Implement 2xMLS TIME_WAIT thing, ideally ...
350  
351 if ($self->{active_tcp_sessions}{$k}{rst}) {
352 $self->{rsts}++;
353 } else {
354 $self->{non_rsts}++;
355 }
356  
357 delete ($self->{active_tcp_sessions}{$k});
358 }
359  
360 # }}}
361 # {{{ _trace_pkt
362  
363 sub _trace_pkt {
364 my ($self, $pkt, $str) = @_;
365 my $deb = " = ". (($self->{v} & 0x08)
366 ? pkt_as_string($pkt,1)
367 : pkt_as_string($pkt));
368  
369 $deb .= " '$str'" if (defined $str);
370  
371 $self->trace($deb);
372 }
373  
374 # }}}
375  
376 1;
377 __END__