Inspect/L4/TCP.pm untested

filter: Statementstmt 0.0% 0 / 186 Branchbran 0.0% 0 / 88 Conditioncond 0.0% 0 / 38 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 328 CC 45 SCAR 74.3
CC
45
Cov
0%
pktin
2070.0
new
2.0
syn
2.0
CRAP 1694.0
1 ############################################################################
2 # TCP
3 # opens und closes connections and feeds data into them
4 # reorders packets based on sequence number
5 ############################################################################
6 use strict;
7 use warnings;
8 package Net::Inspect::L4::TCP;
9 use base 'Net::Inspect::Flow';
10 use fields qw(conn);
11 use Net::Inspect::Debug qw( debug trace );
12  
13 # field conn
14 # hash indexed by {saddr,sport,daddr,dport} with values
15 # [ \@d0,\@d1,$conn ]
16 # $conn - connection object
17 # \@d0,\@d1 - information about data from client(0) or server(1).
18 # [$sn,\%pkt,\@buf,$state]
19 # $sn - all packets received up to this sequence number
20 # \%pkt - packets which are not added to \@buf (out of order, missing
21 # packet in between): sn -> [pkt,time]
22 # \@buf - ordered data which are not yet forwarded to attached flows [pkt,time]
23 # $state - bitmask ( 0b0000FfSs : Fin+ack|Fin|Syn+ack|Syn)
24  
25 use constant {
26 D_SN => 0,
27 D_OPKT => 1,
28 D_BUF => 2,
29 D_STATE => 3,
30 D_TTL => 4,
31  
32 C_DIR0 => 0,
33 C_DIR1 => 1,
34 C_OBJ => 2,
35  
36 P_DATA => 0,
37 P_TIME => 1,
38 };
39  
40 sub new {
41 my ($class,$flow) = @_;
42 my $self = $class->SUPER::new($flow);
43 $self->{conn} = {};
44 return $self;
45 }
46  
47 sub pktin {
48 my Net::Inspect::L4::TCP $self = shift;
49 my ($pkt,$meta) = @_;
50 return if $meta->{proto} != 6; # does only handle tcp
51  
52 # extract TCP header
53 my ($sport,$dport,$sn,$asn,$doc,$window,$cksum,$up)
54 = unpack('nnNNnnnn',$pkt);
55  
56 # payload
57 my $do = ( $doc >> 12 )*4;
58 my $buf = substr($pkt,$do);
59  
60 # flags
61 my $urg = $doc & 0b100000 && 1;
62 my $ack = $doc & 0b010000 && 1;
63 my $psh = $doc & 0b001000 && 1;
64 my $rst = $doc & 0b000100 && 1;
65 my $syn = $doc & 0b000010 && 1;
66 my $fin = $doc & 0b000001 && 1;
67  
68 debug("%s%s%ssn=%u len=%d",
69 $syn ? 'SYN ':'',
70 $fin ? "FIN ":'',
71 $ack ? "ACK=$asn ":'',
72 $sn,
73 length($buf));
74  
75 my $saddr = $meta->{saddr};
76 my $daddr = $meta->{daddr};
77  
78 # find or create connection
79 my ($conn,$dir);
80 if ( $conn = $self->{conn}{$saddr,$sport,$daddr,$dport} ) {
81 $dir = 0;
82 debug("found conn $conn $saddr.$sport(%04b) -> $daddr.$dport(%04b)",
83 $conn->[C_DIR0][D_STATE],$conn->[C_DIR1][D_STATE] );
84 } elsif ( $conn = $self->{conn}{$daddr,$dport,$saddr,$sport} ) {
85 $dir = 1;
86 # saddr should point to client all time..
87 ($saddr,$sport,$daddr,$dport) = ($daddr,$dport,$saddr,$sport);
88 debug("found conn $conn $saddr.$sport(%04b) <- $daddr.$dport(%04b)",
89 $conn->[C_DIR0][D_STATE],$conn->[C_DIR1][D_STATE] );
90 } else {
91 $dir = 0
92 }
93  
94 # new connection, ISN = $sn
95 if ( $syn ) {
96 if ( $fin ) {
97 # invalid combination
98 trace("FIN+SYN($dir) for connection $saddr.$sport -> $daddr.$dport - ignoring");
99 return 1;
100 }
101  
102 debug("SYN($dir) for new flow $saddr.$sport -> $daddr.$dport");
103 if ( $conn and $conn->[$dir][D_STATE] & 0b0001 ) {
104 # SYN already received, duplicate?
105 trace("duplicate SYN($dir) for connection $saddr.$sport -> $daddr.$dport - ignoring");
106 return 1;
107 }
108 if ( ! $conn ) {
109 my $rv = $self->syn({
110 time => $meta->{time},
111 saddr => $saddr,
112 sport => $sport,
113 daddr => $daddr,
114 dport => $dport,
115 dir => $dir,
116 proto => 6,
117 });
118 if ( defined $rv && ! $rv ) {
119 # we don't want a connection for this
120 debug("ignored syn $saddr.$sport -> $daddr.$dport because of syn-hook");
121 return 1;
122 }
123 }
124  
125 # dok for structure see top of file
126 if ( ! $conn ) {
127 $conn = [
128 [ undef,{},[],0], # C_DIR0: D_SN, D_OPKT, D_BUF, D_STATE
129 [ undef,{},[],0], # C_DIR1: D_SN, D_OPKT, D_BUF, D_STATE
130 undef # C_OBJ
131 ];
132 # register new connection
133 debug("register conn $saddr.$sport -> $daddr.$dport $conn");
134 $self->{conn}{$saddr,$sport,$daddr,$dport} = $conn;
135 }
136  
137 # set ISN and state for direction
138 $conn->[$dir][D_SN] = $sn+1;
139 $conn->[$dir][D_STATE] = 0b0001;
140 }
141  
142 # must have $conn here or ignore packet
143 if ( ! $conn ) {
144 debug("no established connection $saddr.$sport <-> $daddr.$dport");
145 return 1;
146 }
147  
148 if ( $buf ne '' or $fin ) {
149  
150 # add buf to packets P_DATA,P_TIME
151 $conn->[$dir][D_OPKT]{$sn} = [$buf,$meta->{time}] if $buf ne '';
152  
153 # set FIN flag - no more data expected from peer after this point
154 # but outstanding packets might still come in
155 if ( $fin ) {
156 if ( not $conn->[$dir][D_STATE] & 0b0100 ) {
157 debug("shutdown dir $dir $saddr.$sport -> $daddr.$dport");
158 $conn->[$dir][D_STATE] |= 0b0100; # fin received
159 # must increase sn for ACK
160 $conn->[$dir][D_OPKT]{ ( $sn+length($buf) ) % 2**32 }
161 = [ '',$meta->{time} ];
162 } else {
163 # probably duplicate
164 debug("ignore duplicate FIN($dir) $saddr.$sport -> $daddr.$dport");
165 return 1;
166 }
167 }
168 }
169  
170 if ( $ack ) {
171 my $odir = $dir?0:1;
172  
173 # reorder and concat packets up to acknowledged value and forward
174 # to attached flows
175 my $pkts = $conn->[$odir][D_OPKT];
176 my $eof = 0;
177 if ( %$pkts ) {
178 my $xsn = $conn->[$odir][D_SN];
179 my $obuf = $conn->[$odir][D_BUF];
180 while ( $xsn != $asn and $pkts->{$xsn} ) {
181 my $pkt = delete $pkts->{$xsn};
182  
183 # apply ACK to $pkt
184 if ( $pkt->[P_DATA] ne '' ) {
185 my $acklen = ($xsn <= $asn) ? $asn - $xsn : 2**32 - $xsn + $asn;
186 if ($acklen >= length($pkt->[P_DATA])) {
187 # ACK for full length
188 $xsn = ( $xsn + length($pkt->[P_DATA]) ) % 2**32;
189 # ACK to FIN might ack previous packets too, so insert
190 # empty dummy packet for FIN if necessary
191 $pkts->{$xsn} ||= [ '',$pkt->[P_TIME] ];
192 } else {
193 # Only part of $pkt got acked. Put rest back with new xsn.
194 $xsn = ( $xsn + $acklen ) % 2**32;
195 $pkts->{$xsn} and die "have already D_OPKT entry for $xsn";
196 $pkts->{$xsn} = $pkt;
197 $pkt = [ substr($pkt->[P_DATA],0,$acklen,''), $pkt->[P_TIME] ];
198 }
199  
200 } else {
201 debug("got ACK for FIN($odir)");
202 $xsn = ( $xsn + 1 ) % 2**32;
203  
204 # eof - set to 2 if both sides closed
205 $eof = $conn->[$dir][D_STATE] & 0b1000 ? 2:1;
206 }
207  
208 # Add $pkt to D_BUF
209 # merge packets which came later but are earlier in the stream
210 # into $pkt
211 if ( @$obuf && $obuf->[-1][P_TIME] >= $pkt->[P_TIME] ) {
212 # merge with existing entry
213 $obuf->[-1][P_DATA] .= $pkt->[P_DATA]
214 } else {
215 # create new entry in obuf
216 push @$obuf,$pkt
217 }
218  
219 if ($eof) {
220 # upper flow needs to process all remaining data on eof, so
221 # pack them together
222 if (@$obuf>1) {
223 $pkt = shift(@$obuf);
224 $pkt->[P_DATA] .= $_->[P_DATA] for(@$obuf);
225 @$obuf = $pkt;
226 }
227  
228 # ignore data after fin
229 if ( %$pkts) {
230 trace("ignoring packets after FIN($odir) $saddr.$sport -> $daddr.$dport");
231 %$pkts = ();
232 }
233  
234 last;
235 }
236 }
237  
238 # lost packets or ack points in the middle of packet
239 if ( $xsn != $asn ) {
240 trace("lost packets before ACK($odir)=$asn SN($odir)=$xsn $saddr.$sport -> $daddr.$dport");
241 delete $self->{conn}{$saddr,$sport,$daddr,$dport};
242 if ( my $obj = $conn->[C_OBJ] ) {
243 $obj->fatal( "lost packets before ACK($odir)=$asn, SN($odir)=$xsn",
244 $dir,$meta->{time});
245 }
246 return 1;
247 }
248  
249 # update sn etc
250 $conn->[$odir][D_SN] = $xsn;
251 $conn->[$odir][D_STATE] |= 0b1000 if $eof;
252  
253 # forward data
254 if ( my $obj = $conn->[C_OBJ] ) {
255 while ( my $buf = shift(@$obuf) ) {
256 my $n = ($eof || $buf->[P_DATA] ne '')
257 ? $obj->in($odir,$buf->[P_DATA],$eof,$buf->[P_TIME])
258 : 0;
259  
260 if ( ! defined $n ) {
261 # error processing -> close
262 # don't call fatal, hook probably reported error already
263 trace("error processing data in hook in $saddr.$sport -> $daddr.$dport");
264 delete $self->{conn}{$saddr,$sport,$daddr,$dport};
265 return 1;
266 } elsif ( $n == length($buf->[P_DATA]) ) {
267 # everything processed
268 next;
269 } elsif ( $eof ) {
270 $obj->fatal("handler did not eat all data on eof",$dir,$meta->{time});
271 return 1;
272 } elsif (!$n) {
273 # Processed nothing, which means we need more data.
274 # Try to merge this buffer into next one in the hope
275 # that we can process the data together
276 if (@$obuf) {
277 $obuf->[0][P_DATA] =
278 $buf->[P_DATA] . $obuf->[0][P_DATA];
279 debug("merge %d bytes into next buffer for $odir - new len %d",
280 length($buf->[P_DATA]),length($obuf->[0][P_DATA]));
281 next;
282 }
283  
284 # no more data yet:
285 # put buffer back and wait for more data
286 debug("keep full buffer (%d bytes) for $odir",length($buf->[P_DATA]));
287 unshift @$obuf,$buf;
288 last;
289  
290 } else {
291 # keep bytes in $buf which were not processed
292 substr($buf->[P_DATA],0,$n,'');
293 debug("keep %d bytes in buffer for $odir",length($buf->[P_DATA]));
294 unshift @$obuf,$buf;
295 last;
296 }
297 }
298 }
299  
300 # eof: if other side fin+acked too reap connection
301 if ( $eof == 2 ) {
302 debug("connection $saddr.$sport -> $daddr.$dport closed");
303 delete $self->{conn}{$saddr,$sport,$daddr,$dport};
304 return 1;
305 }
306 }
307  
308 # check for ACK to SYN
309 my $osn = $conn->[$odir][D_SN];
310 if ( ! defined $osn ) {
311 # got ack w/o syn?
312 trace("received ACK w/o SYN for dir=$odir $saddr.$sport -> $daddr.$dport");
313 return 1;
314 }
315  
316 # ACK for SYN?
317 if ( not $conn->[$odir][D_STATE] & 0b0010 ) {
318 # check that ACK matches ISN from SYN
319 if ( $osn % 2**32 != $asn ) {
320 trace("got ACK($asn) which does not match SYN($osn)");
321 return 1;
322 }
323 # ack ok
324 $conn->[$odir][D_STATE] |= 0b0010;
325 $conn->[$dir][D_TTL] = $meta->{ttl};
326 debug("got ACK for SYN($odir)");
327  
328 # got other side syn+ack too? -> new connection
329 if ( $conn->[$dir][D_STATE] & 0b0010 ) {
330 # make connection object
331 my $obj = $self->new_connection({
332 time => $meta->{time},
333 saddr => $saddr,
334 sport => $sport,
335 daddr => $daddr,
336 dport => $dport,
337 ttl => $conn->[1][D_TTL],
338 });
339 if ( ! $obj ) {
340 # hook says ignore connection
341 debug("ignoring connection $saddr.$sport -> $daddr.$dport because of hook");
342 delete $self->{conn}{$saddr,$sport,$daddr,$dport};
343 return 1;
344 }
345 debug("created object for $saddr.$sport -> $daddr.$dport $obj");
346 $conn->[C_OBJ] = $obj;
347 }
348 }
349 }
350  
351 return 1;
352 }
353  
354 sub syn { shift->{upper_flow}->syn(@_) }
355 sub new_connection { shift->{upper_flow}->new_connection(@_) }
356  
357 sub expire {
358 my ($self,$time) = @_;
359 while (my ($k,$c) = each %{$self->{conn}} ) {
360 $c->[C_OBJ] or next;
361 $c->[C_OBJ]->expire($time) or next;
362 delete $self->{conn}{$k}
363 }
364 }
365  
366  
367 1;
368  
369 __END__