Having problems with SHA256 Javascript encryption

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Having problems with SHA256 Javascript encryption

Post by Sequalit »

Hello guys, im using the SHA256 encryption file to create a more secure login that is given on this forums, and im having difficulties with it

i created a login around everything and it should be working fine

but it seems that the javascript isnt running and sending the right values to my login script...

here are each of my programs.

when i run my login, it works fine but it doesnt use the javascript... why is it skipping my javascript?


index.php - my template file

Code: Select all

<?php
session_start();
session_register('auth');
session_register('logname');
session_register('loghost');
session_register('access');
session_register('pageviews');
session_register('challenge');
define("x",null);
include('batch_action.php');
require_once('sha256.inc.php');
$challenge = SHA256::hash(uniqid(mt_rand,true));
setChallenge($challenge);
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">


<title>Home</title>
<!--
    Include a javascript implementation of the SHA256 algorithim
    Download from: http://www.mad-teaparty.com/Chrstph/sha256.html
-->
<script language="javascript" src="sha256.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
<!--
  function doChallengeResponse() {
    str = document.login_form.eusername.value.toLowerCase() + ":" +
    sha256_digest(document.login_form.epassword.value) + ":" +
    document.login_form.echallenge.value;
    document.login_form.epassword.value = "";
    document.login_form.echallenge.value = "";
    document.login_form.response.value = sha256_digest(str);
    return false;
  }
// -->
</script><?php
session_start();
session_register('auth');
session_register('logname');
session_register('loghost');
session_register('access');
session_register('pageviews');
session_register('challenge');
define("x",null);
include('batch_action.php');
require_once('sha256.inc.php');
$challenge = SHA256::hash(uniqid(mt_rand,true));
setChallenge($challenge);
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">


<title>Home</title>
<!--
    Include a javascript implementation of the SHA256 algorithim
    Download from: http://www.mad-teaparty.com/Chrstph/sha256.html
-->
<script language="javascript" src="sha256.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
<!--
  function doChallengeResponse() {
    str = document.login_form.eusername.value.toLowerCase() + ":" +
    sha256_digest(document.login_form.epassword.value) + ":" +
    document.login_form.echallenge.value;
    document.login_form.epassword.value = "";
    document.login_form.echallenge.value = "";
    document.login_form.response.value = sha256_digest(str);
    return false;
  }
// -->
</script>

//// just tables and stufff, my template for the site

//login area of the table.

<th height="23" colspan="2" scope="col">
	<?php 
		
		if($auth != "yes"){
			$pageviews=0;
			include('login.php');
		}
		elseif($auth == "yes"){
			if($pageviews<1){
				//sets up the session variables.
			}else{
				echo "Welcome $logname!";
			}
			$pageviews++;
		}
	?></th>
  </tr>
  <tr>
    <th width="684" height="41" colspan="2" align="left" valign="top" scope="col">
    <?php
	  	//displays the contents of a main page... home.php for example.
		
	  ?></th>
batch_action.php - my function file

Code: Select all

<?php
if(!defined("x")){
	die("Hacking attempt...");
}
//set forwarding array and database info

function setChallenge($challenge){
	mysql_connect(localhost,"username","pass");
	@mysql_select_db("database") or die("Unable to connect to database");
	$query="DELETE FROM challenge_record WHERE 
				sess_id='".session_id()."' OR 
				timestamp < ". time();
	$result=mysql_query($query);
	if(!$result){queryError($query);}
	mysql_close();
	
	mysql_connect(localhost,"username","pass");
	@mysql_select_db("database") or die("Unable to connect to database");
	$query2="INSERT INTO challenge_record (sess_id, challenge, timestamp) 
			VALUES ('".session_id()."','".$challenge."',".(time()+360).")";
	$result2=mysql_query($query2);
	if(!$result2){queryError($query2);}
	mysql_close();
}


function selectPageInfo($pagename, $location, $i){
	//displays the actual page (I.E home.php)
}
function queryError($query){
	echo "Unable to process query<br>";
	$message  = 'Invalid query: ' . mysql_error() . "\n";
	$message .= 'Whole query: ' . $query;
	die($message);
}
function loginForm(){
	$message="<form action='index.php?action=login' method='post' name='login_form' id='login_form onSubmit='doChallengeResponse()'>
		Username:<input name='eusername' id='eusername' size='16' type='text'>
		Password:<input name='epassword' id='epassword' size='16' type='password'>
		<input name='submit' id='submit' type='submit' value='Login'>
		<input name='echallenge' id='echallenge' type='hidden' value='$challenge'>
		<input name='response' id='response' type='hidden' value=''>
		</form>";
		echo $message;
}
?>
login.php - my login script (showed through index.php where include(login.php) is located.)

Code: Select all

if(!defined("x")){
	die("Hacking attempt...");
}

switch($action){
	case "login":
		if(isset($_POST['response']) && !empty($_POST['response']) && 
						(!ctype_alnum($_POST['eusername']) || !ctype_alnum($_POST['response']))){
			die("Bad Input: response or username are not alphanumeric!");}
		if(isset($_POST['epassword']) && !empty($_POST['epassword']) && 
						(!ctype_alnum($_POST['eusername']) || !ctype_alnum($_POST['epassword']))){
			die("Bad Input: Password or username are not alphanumeric!");}
			
		mysql_connect(localhost,$username,$password);
		@mysql_select_db($database) or die("Unable to connect to database");
		
		$result = mysql_query("SELECT challenge FROM challenge_record WHERE sess_id='".session_id()."' AND timestamp > ". time())
					or die("Invalid query: " . mysql_error());
		
		if(mysql_num_rows($result)==0){
			//unset($action);
			$message="Your login has timedout.<br>";
			echo $message;
			loginForm();
			break;
			//echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=index.php'>";
		}
		$cArray = mysql_fetch_assoc($result);
		$result = mysql_query("SELECT loginName, password FROM godschildren WHERE loginName='".$_POST['eusername']."'")
					or die("Invalid query: ".mysql_error());
		if(mysql_num_rows($result)==0){
			$message="Your login is incorrect.<br>";
			echo $message;
			loginForm();
		}
		$user = mysql_fetch_assoc($result);
		$response_string = strtolower($user['loginName']).':'.$user['password'].':'.$c_array['challenge'];
		$expected_response = SHA256::hash($response_string);
		
		if($_POST['response'] == $expected_response){
			$auth="yes";
			$logname=$_POST['eusername'];
			echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=index.php'>";
		}elseif(isset($_POST['epassword']) && !empty($_POST['epassword'])){
			if(SHA256::hash($_POST['epassword']) == $user['password']){
				$auth="yes";
				$logname=$_POST['eusername'];
				echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=index.php'>";
			}else{
				$message="Your password is incorrect.<br>";
				echo $message."<br>Recieved: ".$_POST['response']."<br>Expected: ".$expected_response."<br>Password: ".
				$_POST['epassword'];
				loginForm();
			}
		}else{
			$message="Your response is incorrect.<br>";
			echo $message."<br>Recieved: ".$_POST['response']."<br>Expected: ".$expected_response."<br>Password: ".
			$_POST['epassword'];
			loginForm();
		}
		mysql_close();
Last edited by Sequalit on Thu Oct 13, 2005 11:02 pm, edited 1 time in total.
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

doChallengeResponse always returns False?
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Post by Sequalit »

yeah, it does, but it should reset the epassword and set the responce variable, but it doesnt seem to be doing that.

from the tutorial here : viewtopic.php?t=38810

the false means just to continue submitting or something like that.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

You mean people are reading it? ;) I get so little feedback...

There are a few problems with your scripts. First (and I blame PHP for their incredibly poor documentation in this area) you should be using $_SESSION to set session value, not session_register(). Second - ensure all login_form fields have both a "name" and "value" attribute for the javascript to manipulate (I believe eusername is missing an empty "value" attribute.

Few other questions:

Is the userpassword stored as a hash, or as plain text on the database?
Does the original tutorial script work as expected?
Why are you saving the Challenge to the session? (only needed on the database for storage)

You should also try echoing the $_POST['response'] whenever the script is submitted (for testing) to ensure its getting set by the client browser.
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Post by Sequalit »

okay ill do some research on using $_SESSION to set the variables... i put challenge in a session just because i could, i know i dont have too... i havnt tried the original script because i still have to set up my MySQL tables for it...

the userpass is stored as a hash on the server. i did make those changes to session and the form, still not getting a response from the page... *sigh* i really cant think of what it could be, ima set up the test script and see if that works... if you have any idea's plz elt me know
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Post by Sequalit »

the test script works like a charm.... *sigh bangs head on keyboard*

im thinking i should just start over from scratch and reprogram everything based around this type of login... it could probably be something silly like i misspelled a word somewhere or the fact that im including the form from batchaction from the login into the index page and mabye the form doesnt like using javascript when its working that way or something i dont know, this hurts my head...
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

lol.

Keep it simple - use what I have as a skeleton (its free to use for any purpose) and bulk it up with extra code you need. Just try and keep the core code together with as few changes as necessary and it should be fine. ;)
Sequalit
Forum Commoner
Posts: 75
Joined: Wed Oct 12, 2005 9:57 pm
Location: Texas

Post by Sequalit »

yeah, thats kinda what i did... i already had my login proccess created and stuff for the site, but then after reading your tutorial, i was like "this is awsome im going to implement it" and i just made sure everything in my login process looked the exact same as yours, even though its spread over three files not two... and bam the javascript doesnt work for the form when i do it the way i already have the site done...
Last edited by Sequalit on Tue Oct 25, 2005 8:19 pm, edited 1 time in total.
magicwizard
Forum Newbie
Posts: 5
Joined: Sat Oct 15, 2005 3:49 pm

Post by magicwizard »

same here, had the first version of my login-class ready and then read his tutorial ... the "aww, that is awesome - i must implement"-effect hit me too ;)
Post Reply