#!/usr/bin/perl
#
# A simple tool to parse a PCAP capture file and print out
# mysql queries in it.
#
# -i 	the pcap file you want to parse
# -v	print more information like the TCP headers etc
# -b	print a line of -'s between each packet to improve 
#       readability.
#
# R.I.Pienaar - www.devco.net


use Net::Pcap;
use NetPacket::Ethernet qw(:strip);
use NetPacket::IP qw(:strip);
use NetPacket::TCP;
use NetPacket::UDP;
use Data::Dumper;
use Getopt::Std;

getopts('vbi:');

$firstpacket = "";
$lastpacket = "";

unless (-f $opt_i) {
	print (STDERR "Can't load input file: $opt_i\n");
	exit(1);
}

$pcap = Net::Pcap::open_offline($opt_i, \$err) 
		or die "Can't read '$opt_i': $err\n";

Net::Pcap::loop($pcap, -1, \&process_packet, "just for the demo");	

sub process_packet {
	my($user_data, $hdr, $pkt) = @_;
	
	%header = %{$hdr};

	if ($firstpacket == "") {
		$firstpacket = "$header{tv_sec}";
	} 
	$lastpacket = "$header{tv_sec}";

	my $ip_obj=NetPacket::IP->decode(eth_strip($pkt));
    	my $srcip=$ip_obj->{src_ip};
    	my $dstip=$ip_obj->{dest_ip};
    	my $proto=$ip_obj->{proto};

	if($proto==6){
		$tcp_obj=NetPacket::TCP->decode(ip_strip(eth_strip($pkt)));
		$srcport=$tcp_obj->{src_port};
		$dstport=$tcp_obj->{dest_port};
		$dataset=$tcp_obj->{data};

		# mysql
		$plen = ord(substr($pkt, 66, 3));
		$pnum = ord(substr($pkt, 69, 1));
		$pcmd = ord(substr($pkt, 70, 1));
		$cmd  = substr($pkt, 71);
		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($header{tv_sec});
		$ptime = sprintf("%02i:%02i:%02i", $hour,$min,$sec);

		if ($pcmd == 3) {
			if ($opt_v) {
				print("Packet Header:\n");
				print("\tSource   : $srcip\n");
				print("\tDest     : $dstip\n");
				print("\tS.Port   : $srcport\n");
				print("\tD.Port   : $dstport\n");
				print("\tLength   : $header{len}\n");
				print("\tTimestamp: $header{tv_sec}.$header{tv_usec}\n\n");
				print("MySQL Packet:\n");
				print("\tLength          : $plen\n");
				print("\tPacket Number   : $pnum\n");
				print("\tPacket Command  : $pcmd\n");
				print("\tSQL Command     : $cmd\n");
			} else {
				print("$ptime: $cmd\n");
			}

			if ($opt_b) {
				print("-----------------------------\n");
			}
		}
	}
}

print("First Packet: " . localtime($firstpacket) . "\n");
print("Last Packet : " . localtime($lastpacket) . "\n");
