Tuesday, January 12, 2010

Parsing tcp data without NetPacket::*

Just some code that i wrote that demonstrates how to extract the data contents of a packet without using the NetPackets::* suite of modules. Note that you would have to know the byte starting position(offset) of the data contents of the packet type in order to correctly extract what you will need. In this example, the offset that im using for DNS data is 55 (14 bytes for Ethernet, 20 for IP header, 8 for UDP header and 12 for some dns flags ). Therefore the DNS quesries start at the 55th byte in DNS query packets.

#!/usr/local/bin/perl
#
#
#
use strict;
use Net::Pcap;
##################

my $dev=$ARGV[0];
my $filter = 'udp dst port 53';
my $object;
my $filter_t;
my ($net,$mask,$err,$object);
##################

unless (defined $dev){
print 'Interface not set or is incorrect';
}

print "Sniffing on interface: $dev\n";

if (Net::Pcap::lookupnet($dev, \$net, \$mask, \$err) == -1){
die "Net::Pcap::lookupnet failed - $err";
}

$object = Net::Pcap::open_live($dev, 1500, 0 , 0, \$err );
unless (defined $object){
print 'Unable to create packet cxapture on device - ', $dev, ' - ', $err;
}

if (Net::Pcap::compile($object, \$filter_t, $filter, 1, $mask) == -1){
die 'Unable to compile filter string - ', $filter;
}

Net::Pcap::setfilter($object,$filter_t);
Net::Pcap::loop($object, -1, \&process_packets, 0);
Net::Pcap::close($object);
##########################################

sub process_packets{
my($user_data, $hdr, $pkt) = @_;
my $len = length($pkt);
for (my $count = 55; $count <= $len; $cout++){
my ($data) = sprintf ("%s", chr(ord(substr($pkt,$count,1))));
print "$data";
}
print "\n";
}

No comments:

Post a Comment