#! perl -w
# Network Forensics Puzzle Contest
# Alan Tu <alantu@as2.info>
# August 15, 2009

use strict;
use Digest::MD5;

my $TSHARK = 'c:\progra~1\wireshark\tshark.exe'; # define tshark executable
die "tshark not found\n" unless -f $TSHARK;

# decode session with file transfer payload
my @results = `$TSHARK -r evidence.pcap -R "tcp.len > 0 and tcp.srcport == 5190" -T fields -e tcp.seq -e tcp.len -e data.data`;

# we need to track TCP sequence numbers
# This is error _detection_, not real TCP reassembly.
my($base_seq, undef, undef) = split("\t", $results[0]);
my $expected_seq = $base_seq;
my $file = "";

# for each packet
for my $packet (@results)
{
    chomp $packet;
    my($seq, $tcp_len, $data) = split("\t", $packet);
    die "Out of order packet. Manual intervention required!\n" if $seq != $expected_seq;

    $data =~ s/://g; # remove the colons separating the bytes
    $file .= pack("H*", $data); # build the file
    $expected_seq += $tcp_len;
}
$file = substr($file, 256); # strip the Oscar File Transfer protocol header

printf(STDERR "File length: %d bytes\n", length($file));
printf(STDERR "MD5 hash: %s\n", Digest::MD5::md5_hex($file));
binmode(STDOUT);
print $file;
