#!/usr/bin/perl -w

#####################################################################################
# All information, data, source code, compiled binaries, information, documentation #
# contained within this document is the sole property of "WhiteHat Security, Inc"   #     
# and may not be sold, reused or distributed.                                       #
# Copyright 2002 WhiteHat Security, Inc.  ALL RIGHTS RESERVED                       #
#####################################################################################

use strict;
use File::Path;
require "Subs.pm";


### GLOBAL VARIABLES ############################################################
my $Debug = 0;	# Debug Variable (0 = OFF | 1 = ON)
$|++;		# Flush Outp	

my %FORM;	# FORM Input Array

# WHArsenal Directories
my $doc_root = $ENV{'DOCUMENT_ROOT'} || "/home/apache/htdocs";	# Document Root Directory
my $session_dir = $doc_root . "/" . "wharsenal/sessions/";	# Session Directory
my $description_filename = "description.txt"; # Description filename

# Log file descriptions
my %desc = ("ATTEMPTS" => "Log file report of all ripper penetration attempts.",
		"SPIDER" => "Log file report of all spidered HTML web page results",
		"CGI" => "Log file report of describing all web applications found during spidering.",
		"DIR" => "Log file of Forced Browsing scan.",
		"HTML" => "Last HTML response from Ripper.",
		"SESSION" => "Text file with session description.");

my $session_threshhold = 3;
my $cs = 0;

### Page Properties ###
my $bgcolor = "FFFFFF";			# Page BGCOLOR
my $link = "FF3300";			# Page LINK COLOR
my $vlink = "3300FF";			# Page VLINK COLOR

#################################################################################

### MAIN ########################################################################
print "Content-Type: text/html\n\n";	# Content Type

# Start HTML 
print "<HTML><TITLE>WhiteHat Arsenal 1.07 Beta Session Manager</TITLE>\n";
print "<BODY BGCOLOR=\"#$bgcolor\" LINK=\"$link\" VLINK=\"$vlink\">\n";

	
print <<EOF;

	<SCRIPT>
		function setSession(key) {
		
			for (var x = 0; x < parent.menubar.document.SESSIONS.SESSION.options.length; x++) {
			
				if (parent.menubar.document.SESSIONS.SESSION.options[x].value == key) {
					//alert(parent.menubar.document.SESSIONS.SESSION.options[x].value + key);
					parent.menubar.document.SESSIONS.SESSION.options[x].selected = true;
				}
			}
		}
	</SCRIPT>
		
EOF

print "<CENTER><TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0><TR><TD BGCOLOR=000000>\n";
print "<TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0 WIDTH=600><TR><TD BGCOLOR=FFFFFF VALIGN=TOP ALIGN=CENTER>\n";

titlebarHTMLBlock("Session Management", "The Session Management system used to keep track of current session in use. Useful for organizing logfiles and other information while testing.");

RequestMethod();
sanityCheck();
controller(); 		# Control Function
newSessionButton(); 	# Print new session HTML Button

print "</TD></TR></TABLE>\n";
print "</TD></TR></TABLE></CENTER>\n";

print "</BODY></HTML>\n"; # End HTML
exit;
###########################################################################################



##################
### Controller ###
##################
# Control Subroutine / Follow "cmd" value
sub controller {

	# Check If a command was given
	if (defined $FORM{'cmd'}) { # No Command Given
		if($FORM{'cmd'} eq "list") { # List existing sessions
			print "LIST: $FORM{'cmd'}<BR>\n" if ($Debug == 1); # Print CTRL Value
			listSessions(); # List Sessions
		} elsif ($FORM{'cmd'} eq "create") { # Create a new session
			print "CREATE NEW: $FORM{'cmd'}<BR>\n" if ($Debug == 1); # Print CTRL Value
			
			if ($cs >= $session_threshhold) {
				print "<FONT COLOR=RED><B>Error:</B></FONT> You have exceeded the amount of sessions you may have at one time. Please delete an existing session and then create a new session.<BR>\n";
				listSessions();
			} else {
				createNewSession();
			}
						
		} elsif ($FORM{'cmd'} eq "pnew") { # Print New Session HTML form
			print "PRINT NEW:$FORM{'cmd'}<BR>\n" if ($Debug == 1); # Print CTRL Value
			
			if ($cs >= $session_threshhold) {
				print "<FONT COLOR=RED><B>Error:</B></FONT> Too many existing sessions to create a new session. Please delete an existing session and then create a new session.<BR>\n";
				listSessions();
			} else {
				newSessionHTMLForm();
				listSessions(); # List Sessions
			}
				
		} elsif ($FORM{'cmd'} eq "del") { # Confirm Session Delete
			print "DELETE Double Check: $FORM{'cmd'}\n" if ($Debug == 1); # Print CTRL Value
			deleteSession(1); # Delete Session
		} elsif ($FORM{'cmd'} eq "delete") { # Delete Session
			print "DELETE: $FORM{'cmd'}\n" if ($Debug == 1); # Print CTRL Value
			deleteSession(2); # Delete Session
		} elsif ($FORM{'cmd'} eq "del_file") { # Confirm file deletion
			print "DELETE FILE OK:$FORM{'cmd'} $FORM{'session'} : $FORM{'filename'}\n" if ($Debug == 1); # Print CTRL Value
			deleteFile(1); # Delete Session
		} elsif ($FORM{'cmd'} eq "delete_file") { # Delete file
			print "DELETE FILE: $FORM{'cmd'} $FORM{'session'} : $FORM{'filename'}\n" if ($Debug == 1); # Print CTRL Value
			deleteFile(2);
		} else { # All other values list sessions
			print "DEfAULT:  $FORM{'cmd'}<BR>\n" if ($Debug == 1); # Print CTRL Value
			listSessions(); # List Sessions
		} # End If
	} else { # No Command given
		print "DEfAULT:  <BR>\n" if ($Debug == 1); # Print CTRL Value
		listSessions(); # List Sessions
	} # End Check command given if
} # End Subroutine




#####################
### List Sessions ###
#####################
# List out created sessions and log files

sub listSessions {
	my %sessions; # Create Session Array

	# Load in Session files and information
	print "Session Directory: $session_dir\n" if ($Debug == 1);
	opendir(DIR, "$session_dir") || die "can't opendir $session_dir: $!"; # Open Session Directory
	print "OPEN DIR: $session_dir<BR>\n" if ($Debug == 1);
	my @session_list = readdir(DIR); # Read in a store session names
	closedir(DIR); # Close Session Directory

	my $description_path = "";	# Description Path
	my $description = "";		# Description String

	foreach my $lin (@session_list) { # Step thru session names
		print "LIST: $lin<BR>\n" if ($Debug == 1);
		my $s_dir = $session_dir . "/" . $lin;
		unless (($lin =~ /(^\.)/) || (!-d $s_dir)) { # Ignore Hidden Files
			print "Session: $lin<BR>\n" if ($Debug == 1); # Print Session Name
			$description_path = $session_dir . "/" . $lin . "/" . $description_filename; # Set Description Path
			print "$description_path<BR>\n" if ($Debug == 1); # Print Description Path
			
			if (-r $description_path) {
				open(DESC, "$description_path"); # Open Description Path
				$description = <DESC>; # Load in Description
				close(DESC); # Close Description
			} else {
				$description = "No Description";
			}
			
			print "Description: $description<BR><BR>\n" if ($Debug == 1); # Print Description

			$sessions{$lin} = $description; # Make Session Name and Description Hash Array
		} # End Unless
	} # End Foreach

	foreach my $key (keys %sessions) { # List out Sessions and Descriptions

print <<EOF;
<TABLE BGCOLOR="#fdbe50" BORDER="0" CELLSPACING="2" CELLPADDING="0">
<TR><TD WIDTH="450" ALIGN="LEFT" VALIGN="TOP">
	
	<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="1">
	<TR><TD BGCOLOR="#FFFFFF" ALIGN="LEFT" VALIGN="TOP">
	
		<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="2">
EOF
	 
									
		print "<TR WIDTH=\"450\" BGCOLOR=\"#fdbe50\"><TD ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
		printFont("<B>Session: <A HREF=\"javascript:void(0)\;\" OnClick=\"setSession(\'$key\'); alert(\'Session $key is now Active\')\;\">$key</A></B>", "14");
		print "</TD></TR>\n";
	
		print "<TR BGCOLOR=\"#fdbe50\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
		print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
		printFont("<B>Description:</B> ", "14");
		printFont(" $sessions{$key}", "12");
		print "</TD></TR>\n";
	
	

		my $session_path = $session_dir . "/" . $key;
		opendir(DIR, "$session_path") || die "can't opendir $session_path: $!"; # Open Session Directory
		my @file_list = readdir(DIR); # Read in a store session names
		closedir(DIR); # Close Session Directory

	
		foreach my $file (@file_list) {
			my $f = $session_path . "/" . $file;
			my $byte_size = (-s $f);
			my $kbyte_size = SizeConvert($byte_size);
			
			unless ($file =~ /(^\.)/) {
				print "<TR BGCOLOR=\"#fef5c7\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
				print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
				
				print "<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\">\n";
				print "<TD WIDTH=\"300\" ALIGN=\"LEFT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\">\n";
				printFont("<B><A HREF=\"/wharsenal/sessions/$key\/$file\">$file</A> </B>($kbyte_size)", "12");
				print "</TD>\n";
			
				print "<TD WIDTH=\"150\" ALIGN=\"RIGHT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\"> \n";
				print "<FORM METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n" unless ($file =~ /^description/i);
				print "<INPUT TYPE=\"SUBMIT\" VALUE=\"Delete\" style=\"font-size: 10px\; font-family:arial,sans-serif\">\n" unless ($file =~ /^description/i);
				print "<INPUT TYPE=\"HIDDEN\" NAME=\"cmd\" VALUE=\"del_file\">\n" unless ($file =~ /^description/i);
				print "<INPUT TYPE=\"HIDDEN\" NAME=\"name\" VALUE=\"$key\">\n" unless ($file =~ /^description/i);
				print "<INPUT TYPE=\"HIDDEN\" NAME=\"filename\" VALUE=\"$file\">\n" unless ($file =~ /^description/i);
				print "</FORM>\n" unless ($file =~ /^description/i);
				print "</TD>\n";
			
				print "</TR>\n";
				print "</TABLE>\n";
				
				print "</TD></TR>\n";
				
				print "<TR BGCOLOR=\"#fef5c7\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
				print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
				
				
				if($file =~ /^attempts/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'ATTEMPTS'}<BR><BR>", "10");
				} elsif ($file =~ /^spider/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'SPIDER'}<BR><BR>", "10");
				} elsif ($file =~ /^webapplication/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'CGI'}<BR><BR>", "10");
				} elsif ($file =~ /^description/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'SESSION'}<BR><BR>", "10");
				} elsif ($file =~ /^forcedbrowsing/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'DIR'}<BR><BR>", "10");
				} elsif ($file =~ /^html/) {
					printFont("&nbsp\;&nbsp\;&nbsp\;$desc{'HTML'}<BR><BR>", "10");
				}
				
				print "</TD></TR>\n";
	
				
			}
		} # End Foreach
		
		print "<TR BGCOLOR=\"#fdbe50\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
		print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
				
		print "<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"2\">\n";
		print "<TD WIDTH=\"300\" ALIGN=\"LEFT\" VALIGN=\"TOP\" BGCOLOR=\"#fdbe50\">\n";
		
		print "</TD>\n";
			
		print "<TD WIDTH=\"150\" ALIGN=\"RIGHT\" VALIGN=\"TOP\" BGCOLOR=\"#fdbe50\">\n";
		print "<FORM NAME=\"DELETE\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n"; #Add Delete Button
		
		print "<INPUT TYPE=BUTTON NAME=\"SESSION\" VALUE=\"Select\" OnClick=\"setSession(\'$key\'); alert(\'Session $key is now Active.\')\;\">\n";
		print "<INPUT TYPE=SUBMIT VALUE=\"Delete\"  OnClick=\"parent.menubar.document.SESSIONS.SESSION.value = \'NO SESSION\'\;\">\n";
		
		print "<INPUT TYPE=HIDDEN NAME=\"cmd\" VALUE=\"del\">\n";
		print "<INPUT TYPE=HIDDEN NAME=\"name\" VALUE=\"$key\">\n";
		
		print "</FORM>" ;
		print "</TD>\n";
			
		print "</TD>\n";
		print "</TR>\n";
		print "</TABLE>\n";
				
		print "</TD></TR>\n";
				
				
	
print <<EOF;


		</TABLE>
		
	</TD></TR>
	</TABLE>
		
</TD></TR>
</TABLE>
<BR>
EOF
	
	} # End Foreach

} # End List Sessions Subroutine


#############################
### New Session HTML Form ###
#############################
# Prints New Session HTML Form
sub newSessionHTMLForm { # Print New Session HTML FORM

	print "<FORM NAME=\"CREATE\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
	print "<INPUT TYPE=HIDDEN NAME=\"cmd\" VALUE=\"create\"><BR>\n"; # Add CTRL value

	print <<EOF;
<TABLE BGCOLOR="#fdbe50" BORDER="0" CELLSPACING="2" CELLPADDING="0">
<TR><TD WIDTH="450" ALIGN="LEFT" VALIGN="TOP">
	
	<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="1">
	<TR><TD BGCOLOR="#FFFFFF" ALIGN="LEFT" VALIGN="TOP">
	
		<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="2">
EOF
	
		
		print "<TR WIDTH=\"450\" BGCOLOR=\"#fdbe50\"><TD ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
		printFont("<B>Create New Session</B>", "14");
		print "</TD></TR>\n";
	
		print "<TR BGCOLOR=\"#fef5c7\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
		print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
				
		print "<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"3\">\n";
		
		print "<TR>\n";
		print "<TD WIDTH=\"100\" ALIGN=\"LEFT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\">\n";
		printFont("<B>Name</B>:", "12");
		print "</TD>\n";
			
		print "<TD WIDTH=\"300\" ALIGN=\"RIGHT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\">\n";
		print "<INPUT TYPE=TEXT SIZE=20 NAME=\"name\" VALUE=\"\" style=\"WIDTH: 300px; font-size: 10px; font-family:arial,sans-serif\">\n";
		print "</TD>\n";
		print "</TR>\n";
		
		print "<TR WIDTH=\"400\" BGCOLOR=\"#fef5c7\"><TD ALIGN=\"LEFT\" VALIGN=\"TOP\" COLSPAN=2>\n";
		printFont("Session name must contain only alpha-numeric characters (with spaces), be no longer than 32 characters, and not contain special characters.", "12");
		print "</TD></TR>\n";
		
		print "</TABLE>\n";
		
			
		print "</TD></TR>\n";
		
		print "<TR BGCOLOR=\"#fef5c7\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n"; 
		print "<TD WIDTH=\"450\" ALIGN=\"LEFT\" VALIGN=\"TOP\">\n";
				
		print "<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"3\">\n";
		
		print "<TR>\n";
		print "<TD WIDTH=\"100\" ALIGN=\"LEFT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\">\n";
		printFont("<B>Description</B>:", "12");
		print "</TD>\n";
			
		print "<TD WIDTH=\"300\" ALIGN=\"RIGHT\" VALIGN=\"TOP\" BGCOLOR=\"#fef5c7\">\n";
		print "<INPUT TYPE=TEXT SIZE=20 NAME=\"description\" VALUE=\"\" style=\"WIDTH: 300px; font-size: 10px; font-family:arial,sans-serif\">\n";
		print "</TD>\n";
		print "</TR>\n";
		
		
		
		print "<TR WIDTH=\"400\" BGCOLOR=\"#fef5c7\"><TD ALIGN=\"LEFT\" VALIGN=\"TOP\" COLSPAN=2>\n";
		printFont("Session Description may contain certain special characters (@ # \$ % & , . ?) as well as alpha-numeric character, but be no longer than 64 characters.", "12");
		print "</TD></TR>\n";
		
		
		
		print "</TABLE>\n";
		
			
		print "</TD></TR>\n";
		
				
		
		print "<TR WIDTH=\"450\" BGCOLOR=\"#fdbe50\"><TD ALIGN=\"CENTER\" VALIGN=\"TOP\">\n";
		print "<INPUT TYPE=SUBMIT VALUE=\"Create New Session\">\n";
		print "</TD></TR>\n";
	
print <<EOF;


		</TABLE>
		
	</TD></TR>
	</TABLE>
		
</TD></TR>
</TABLE>
<BR>
EOF
	
	print "</FORM>\n";
	
} # End New Session HTML Form Subroutine


##########################
### Create New Session ###
##########################
# Creates a New Session
sub createNewSession { # New Session Creation 

	# Set & Sanity Check Session Name
        if($FORM{'name'} =~ /^([\w\d\s]{1,32})$/) { # Input Valid
                print "Session Name is AOK<BR>\n" if ($Debug == 1);
		
		# Set & Sanity Check Session Description
		if($FORM{'description'} =~ /^(([\w\d\s!@#\$%\^\&\*,\.\?]+){1,64})$/) { # Input Valid
			print "Session Description is AOK<BR>\n" if ($Debug == 1);
                
			my $session = $session_dir . "/" . $FORM{'name'};		# set session name path
			my $session_desc = $session . "/" . $description_filename;	# set session description path
			
			# Check if session already exists
			if(-e $session) {
				print "<FONT COLOR=RED><B>Error:</B></FONT> Session already exists<BR>\n";
				newSessionHTMLForm();
				listSessions();
			} else {
	        		mkdir($session, 0777) || die "can't make dir $session $!";
				open(DESC, ">$session_desc") || die "can't open: $!";
				print DESC $FORM{'description'};	
				close(DESC);
				listSessions();

				print "<SCRIPT>\n";
				print "var nOption = new Option(\"$FORM{'name'}\", \"$FORM{'name'}\");\n";
				print "var x = parent.menubar.document.SESSIONS.SESSION.options.length;\n";
				print "parent.menubar.document.SESSIONS.SESSION.options[x]=nOption;\n";
				print "parent.menubar.document.SESSIONS.SESSION.options[x].selected = true;\n";
				print "</SCRIPT>\n";

				
			}
			
			
        	} elsif ($FORM{'description'} eq "") { # Input Must Contain a Name
                	print "<FONT COLOR=RED><B>Error:</B></FONT> Description must contain a name<BR>\n";
			newSessionHTMLForm();
			listSessions();
        	} else { # Input Contains Illegal Characters
                	print "<FONT COLOR=RED><B>Error:</B></FONT> Description contains illegal characters or description is too long. Limit 64.<BR>\n";
			newSessionHTMLForm();
			listSessions();
        	} # End If
	
        } elsif ($FORM{'name'} eq "") { # Input Error No Name
                print "<FONT COLOR=RED><B>Error:</B></FONT> No session name given.<BR>\n";
		newSessionHTMLForm();
		listSessions();
        } else { # Input Contains Illegal Characters
                print "<FONT COLOR=RED><B>Error:</B></FONT> Session Name contains illegal characters or name is too long. Session name is alpha numeric (with spaces) and Limit 32 characters.<BR>\n";
                newSessionHTMLForm();
		listSessions();
        } # End If
	
	
} # End Create New Session Subroutine


######################
### Delete Session ###
######################
# Prints user confirm session delete HTML form or delete session
sub deleteSession { # Delete Session 
	my $flag = shift || "1"; # Flag 1 = Confirm with user, Flag 2 = Delete File
	
	if (defined $FORM{'name'}) {
		# Set & Sanity Check Session Name
       		if($FORM{'name'} =~ /^([\w\d\s]{1,32})$/) { # Input Valid

			my $session = $session_dir . "/" . $FORM{'name'}; # set session name path
			
			# Check if session exists
			if(-e $session) {
				if(-d $session) {
					if(-w $session) {
						if ($flag == 1) {
							printFont("Are you you sure you want to delete <B>\"$FORM{'name'}\"?</B><BR>", "12");
							
		
							print "<BR><FORM NAME=\"double_check\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
							print "<INPUT TYPE=SUBMIT VALUE=\"Yes\" style=\"WIDTH: 50px\; font-size: 12px\; font-family:arial,sans-serif\">\n";
							print "<INPUT TYPE=HIDDEN NAME=\"cmd\" VALUE=\"delete\">\n";
							print "<INPUT TYPE=HIDDEN NAME=\"name\" VALUE=\"$FORM{'name'}\">\n";
							print "</FORM>\n";
		
							print "<FORM NAME=\"list\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
							print "<INPUT TYPE=SUBMIT VALUE=\"No\" style=\"WIDTH: 50px\; font-size: 12px\; font-family:arial,sans-serif\">\n";
							print "</FORM>\n";
							
						} elsif ($flag == 2) {
							rmtree($session) || die "can't remove $session: $!"; # Remove Session Directory
							listSessions();
							

							print "<SCRIPT>\n";
							print "for (var x = 0; x < parent.menubar.document.SESSIONS.SESSION.options.length; x++) {\n";
							print "if (parent.menubar.document.SESSIONS.SESSION.options[x].value == \"$FORM{'name'}\") {\n";
							print "parent.menubar.document.SESSIONS.SESSION.options[x] = null;\n";
							print "}\n";
							print "}\n";
							print "</SCRIPT>\n";
						
						} else {
							listSessions();
						}
					} else {
						print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete session because permissions are not properly set. Please set the sessions directory permissions to be writable by the webserver.<BR>\n";
						listSessions();
					}
				} else {
					print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete session because session is not a directory.<BR>\n";
					listSessions();
				}
			} else {
				print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete session because session does not exist.<BR>\n";
				listSessions();
			}
		} else {
			print "<FONT COLOR=RED><B>Error:</B></FONT> Session name invalid.<BR>\n";
			listSessions();
		}
	} else {
		print "<FONT COLOR=RED><B>Error:</B></FONT> No session name given.<BR>\n";
		listSessions();
	}
	

} # End Delete Session Subroutine



####################
### Delete File  ###
####################
# Prints user confirm delete file HTML form or Deletes the file
sub deleteFile { # Delete File Double Check

	my $flag = shift || "1"; # Flag 1 = Confirm with user, Flag 2 = Delete File
	
	if (defined $FORM{'name'}) {
		# Set & Sanity Check Session Name
       		if($FORM{'name'} =~ /^([\w\d\s]{1,32})$/) { # Input Valid
		
		
			my $session = $session_dir . "/" . $FORM{'name'}; # set session name path
			
			# Check if session exists
			if(-e $session) {
				if(-d $session) {
					if(-w $session) {
						if ((defined $FORM{'filename'}) && ($FORM{'filename'} ne "")) {
							if ($FORM{'filename'} =~ /^(forcedbrowsing|attempts|spider|webapplications)([\.])(xml|html)$/) {
								my $file_path = $session . "/" . $FORM{'filename'};
								print "FILENAME OK: $file_path<BR>\n" if ($Debug == 1);
							
								if(-e $file_path) { # If Session Path Exists
								
									if ($flag == 1) {
										printFont("Are you you sure you want to delete <B>\"$FORM{'filename'}\"?</B><BR>", "12");
									
										print "<BR><FORM NAME=\"double_check\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
										print "<INPUT TYPE=SUBMIT VALUE=\"Yes\" style=\"WIDTH: 50px\; font-size: 12px\; font-family:arial,sans-serif\">\n";
										print "<INPUT TYPE=HIDDEN NAME=\"cmd\" VALUE=\"delete_file\">\n";
										print "<INPUT TYPE=HIDDEN NAME=\"filename\" VALUE=\"$FORM{'filename'}\">\n";
										print "<INPUT TYPE=HIDDEN NAME=\"name\" VALUE=\"$FORM{'name'}\">\n";
										print "</FORM>\n";
		
										print "<FORM NAME=\"list\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
										print "<INPUT TYPE=SUBMIT VALUE=\"No\" style=\"WIDTH: 50px\; font-size: 12px\; font-family:arial,sans-serif\">\n";
										print "</FORM>\n";
									} elsif ($flag == 2) {
										unlink $file_path;
										listSessions();
									} else {
										listSessions();
									}
			
								} else {
									print "<FONT COLOR=RED><B>Error:</B></FONT> Filename does not exist.<BR>\n";
									listSessions();
								}
							} else {
								print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete file because filename is invalid.<BR>\n";
								listSessions();
							}
						} else {
							print "<FONT COLOR=RED><B>Error:</B></FONT> No filename given.<BR>\n";
							listSessions();
						}
					} else {
						print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete file because permissions are not properly set. Please set permission to be writable by the webserver.<BR>\n";
						listSessions();
					}
				} else {
					print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete file because session is not a directory.<BR>\n";
					listSessions();
				}
			} else {
				print "<FONT COLOR=RED><B>Error:</B></FONT> Could not delete file because session does not exist.<BR>\n";
				listSessions();
			}
		} else {
			print "<FONT COLOR=RED><B>Error:</B></FONT> Session name invalid.<BR>\n";
			listSessions();
		}
	} else {
		print "<FONT COLOR=RED><B>Error:</B></FONT> No session name given for file deletion.<BR>\n";
		listSessions();
	}
	
	
	
} # End Delete File OK HTML Form Subroutine


##########################
### New Session Button ###
##########################
# Prints New Session HTML Form Button
sub newSessionButton { # Print New Session HTML Button

	# Check for Threshold limit
	unless ($cs >= $session_threshhold) { # Did not exceed threshhold, print new session button
		print "<FORM NAME=\"CBUTTON\" METHOD=\"POST\" ACTION=\"/cgi-bin/wharsenalcgi/session.pl\">\n";
		print "<INPUT TYPE=HIDDEN NAME=\"cmd\" VALUE=\"pnew\"><BR>\n"; # Add CTRL value
		print "<INPUT TYPE=SUBMIT VALUE=\"New Session\" style=\"font-size: 12px\; font-family:arial,sans-serif\">\n";
		print "</FORM>\n";
	} # End Threshhold check unless
	
} # End  New Session Button Subroutine

####################
### Sanity Check ###
####################
# Sanity Check Docuent Root and Session Directory

sub sanityCheck {

	# Check for document root
	if(defined $doc_root) { # Document Root Defined
	
		# Check if Document Root Exists
        	if(-e $doc_root) { # Document Root Exists
		
			# Check If Session Directory Exists
			if(-e $session_dir) { # Session Directory exists
			
				# Check if Session Directory is a directory
				if(-d $session_dir) { # Session Directory is a directory
				
					# Check if Session Directory is writable
					if(-w $session_dir) { # Session Directory is writable
			
						# Set total number of existing sessions
						# Load in Session files and information
						print "Session Directory: $session_dir\n" if ($Debug == 1);
						opendir(DIR, "$session_dir") || die "can't opendir $session_dir: $!"; # Open Session Directory
						my @session_list = readdir(DIR); # Read in a store session names
						closedir(DIR); # Close Session Directory

						my @ss;	
	
						foreach my $lin (@session_list) { # Step thru session names
						my $s_dir = $session_dir . "/" . $lin;
		
							if (($lin =~ /(^\.)/) || (!-d $s_dir)) { # Ignore Hidden Files
			
							} else {
								push(@ss, $lin);
							}
						} # End Foreach

						$cs = scalar @ss;
						print "Total existing sessions: $cs<BR>\n" if ($Debug == 1);
	
	
					} else { # Session directory is not writable
						my $error_string = HTMLEsc("Session Directory \"$session_dir\" is not writable. Please make sure the permission are set to be writable by the webserver.");
						errorOut("$error_string");
					} # End session directory is writable If
					
				} else { # Session directory is not a directory
					my $error_string = HTMLEsc("Session Directory \"$session_dir\" is not a directory. Please re-create a new session directory with permissions of the webserver.");
					errorOut("$error_string");
				} # End session directory is a directory If
				
			} else { # Session directory does not exist
				my $error_string = HTMLEsc("Session Directory \"$session_dir\" does not exist. Please create a new session directory with permissions of the webserver.");
				errorOut("$error_string");
			} # End session directory exists If
			
		} else { # Document Root does not exist
			my $error_string = HTMLEsc("Document Root \"$doc_root\" DOES NOT EXIST");
			errorOut("$error_string");
		} # End session directory is exists If
		
        } else { # Session directory is not given
		my $error_string = HTMLEsc("Document Root \"$doc_root\" DOES NOT EXIST");
		errorOut("$error_string");
        } # End session directory given If
} # End Sanity Check Sub Routine

#####################
### RequestMethod ###
#####################
# This will populate the %FORM hash with paramaters and values.
sub RequestMethod {
	# Determine the request method and then get the input
	
	my $buffer = "";
	
	if (!defined $ENV{'REQUEST_METHOD'}) {
		$ENV{'REQUEST_METHOD'} = "GET";
	}
	
	if ($ENV{'REQUEST_METHOD'} eq 'POST') {
        	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); # For POST methods
	} else {        
        	$buffer = $ENV{'QUERY_STRING'} || ""; # for GET methods
	} # end if
	
	# Data Clean-up
	if ($buffer ne "") {
		$buffer =~ s/(\0|%00)//g;	# Remove Hidden Nulls
        	$buffer =~ s/[\n]/%0A/g;	# URL Encode Newline
        	$buffer =~ s/[\r]/%0D/g; 	# URL Encode Carriage Returns
	}
	
	# Split the name-value pairs
	my @pairs = split(/&/, $buffer);
 
	foreach my $pair (@pairs) {
        	my ($name, $value) = split(/=/, $pair);
 
		# What happens to Lack of name or value after/before the equals?
		
       		# Un-Webify plus signs and %-encoding
        	$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; # URL Decode Name

        	$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; # URL Decode Name
		$name =~ s/[\n\r]//g;	# Don't allow newlines
		
		print "NAME: $name VALUE: $value<BR>\n" if ($Debug == 1);
		
                $FORM{$name} = $value; # Build a hash the input parameters
		
	} # end foreach


} # End sub RequestMethod
