| 1 | ############################################################################ | ||
| 2 | # UDP | ||
| 3 | # handles single udp packets, but can also maintain virtual flows | ||
| 4 | # between the same src,dst ip:port | ||
| 5 | ############################################################################ | ||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | package Net::Inspect::L4::UDP; | ||
| 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 connection object as value | ||
| 15 | |||
| 16 | sub new { | ||
| 17 | my ($class,$flow) = @_; | ||
| 18 | my $self = $class->SUPER::new($flow); | ||
| 19 | $self->{conn} = {}; | ||
| 20 | return $self; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub pktin { | ||
| 24 | my Net::Inspect::L4::UDP $self = shift; | ||
| 25 | my ($pkt,$meta) = @_; | ||
| 26 | return if $meta->{proto} != 17; # handles only udp | ||
| 27 | |||
| 28 | # extract UDP header | ||
| 29 | my ($sport,$dport,$len,$chksum) = unpack('nnnn',$pkt); | ||
| 30 | |||
| 31 | # payload | ||
| 32 | my $buf = substr($pkt,8); | ||
| 33 | |||
| 34 | my $saddr = $meta->{saddr}; | ||
| 35 | my $daddr = $meta->{daddr}; | ||
| 36 | |||
| 37 | # find or create connection | ||
| 38 | my ($conn,$dir); | ||
| 39 | if ( $conn = $self->{conn}{$saddr,$sport,$daddr,$dport} ) { | ||
| 40 | $dir = 0; | ||
| 41 | debug("found conn $conn $saddr.$sport -> $daddr.$dport"); | ||
| 42 | } elsif ( $conn = $self->{conn}{$daddr,$dport,$saddr,$sport} ) { | ||
| 43 | $dir = 1; | ||
| 44 | # saddr should point to client all time.. | ||
| 45 | ($saddr,$sport,$daddr,$dport) = ($daddr,$dport,$saddr,$sport); | ||
| 46 | debug("found conn $conn $saddr.$sport <- $daddr.$dport"); | ||
| 47 | } else { | ||
| 48 | $dir = 0 | ||
| 49 | } | ||
| 50 | |||
| 51 | # if we have an existing connection we are done after forwarding data | ||
| 52 | # thru it | ||
| 53 | if ( $conn ) { | ||
| 54 | $conn->pktin($dir,$buf,$meta->{time}); | ||
| 55 | return 1; | ||
| 56 | } | ||
| 57 | |||
| 58 | # otherwise just forward packet | ||
| 59 | $conn = $self->{upper_flow}->pktin($buf,{ | ||
| 60 | %$meta, | ||
| 61 | sport => $sport, | ||
| 62 | dport => $dport, | ||
| 63 | }); | ||
| 64 | |||
| 65 | # if pktin returns an connection object set the connection for | ||
| 66 | # further packets | ||
| 67 | $self->{conn}{$saddr,$sport,$daddr,$dport} = $conn if $conn; | ||
| 68 | |||
| 69 | return 1; | ||
| 70 | } | ||
| 71 | |||
| 72 | sub expire { | ||
| 73 | my ($self,$time) = @_; | ||
| 74 | while (my ($k,$conn) = each %{$self->{conn}} ) { | ||
| 75 | $conn->expire($time) or next; | ||
| 76 | delete $self->{conn}{$k} | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | |||
| 81 | 1; | ||
| 82 | |||
| 83 | __END__ |