#!/usr/bin/perl

# sqlninja debug script generator
# Copyright (C) 2008 icesurfer <r00t@northernfortress.net>
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# This software is a part of sqlninja.
# For its goal and utilization, check the README file that you should
# have received with this file.
# For more information, check http://sqlninja.sourceforge.net

use strict;
use Getopt::Std;

my %options;
getopts('i:o:s',\%options);
my $file = $options{i};
my $silent = $options{s};
my $output = $options{o};

unless ($silent == 1) {
	print "sqlninja debug script generator\n";
	print "Copyright (C) 2008 icesurfer <r00t\@northernfortress.net>\n\n";
}

if ($file eq "") {
	print "Usage: ".$0." -i <input file> [-o <output file>]\n\n";
	exit(0);
}

my $script = "n %TEMP%\\#temp#\nr cx\n";

my $filesize = -s $file;
if ($filesize > 65535) {
	die "[-] file is too big for debug.exe\n";
}
$filesize = sprintf("%x",$filesize);
$script .= $filesize."\n";
$script .= "f 0100 ffff 00\n";

my $record;
my @a;
my $template = "C";
my $counter = 256;
my $counter2 = 0;
my $b;
my $string = "";
open (FILE, "<".$file);
while (read(FILE,$record,1)) {
	@a = unpack($template,$record);
	foreach (@a)  {
		$b = sprintf("%02x",$_);
		if ($_ ne "0") {
		$counter2++;
			if ($string eq "") {
				$string = "e ".sprintf("%x",$counter)." ".$b;
			} else {
				$string .= " ".$b;
			}
		} else {
			if ($string ne "") {
				$script .= $string."\n";
				$string = "";
				$counter2 = 0;
			}
		}
	}
	$counter++;
	if ($counter2 == 20) {
		$script .= $string."\n";
		$string = "";
		$counter2 = 0;
	}
}
$script .= "w\nq\n";
if ($output eq "") {
	print $script;
} else {
	open (OUT, ">".$output) or die "Can't write to ".$output."\n";
	print OUT $script;
	unless ($silent == 1) {
	        print "Debug script created successfully\n";
	}

}
close FILE;
close OUT;

