...

View Full Version : Can someone explain this PHP script?



auriaks
06-23-2010, 11:41 PM
Here is the script:

<?php
function regenerateSession($reload = false)
{
// This token is used by forms to prevent cross site forgery attempts
if(!isset($_SESSION['nonce']) || $reload)
$_SESSION['nonce'] = md5(microtime(true));

if(!isset($_SESSION['IPaddress']) || $reload)
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

if(!isset($_SESSION['userAgent']) || $reload)
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

//$_SESSION['user_id'] = $this->user->getId();

// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;

// Create new session without destroying the old one
session_regenerate_id(false);

// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();

// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();

// Don't want this one to expire
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}

function checkSession()
{
try{
if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
throw new Exception('Attempt to use expired session.');

if(!is_numeric($_SESSION['user_id']))
throw new Exception('No session started.');

if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
throw new Exception('IP Address mixmatch (possible session hijacking attempt).');

if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
throw new Exception('Useragent mixmatch (possible session hijacking attempt).');

if(!$this->loadUser($_SESSION['user_id']))
throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);

if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
{
$this->regenerateSession();
}

return true;

}catch(Exception $e){
return false;
}
}

?>

as you can see - this is script for sessions... What I have to change to use it into my website?

Thanks in advance...

Keleth
06-24-2010, 12:45 AM
The first function looks like its made to create more "secure" sessions, while the second looks like its to test if the session is set, but they look like they might be part of a class? At least the second one? Remove the $this-> and i don't see why it shouldn't work?

And there's no way we could know what you need to change to use it on your site... we don't know whats on your site, what you wanna do, etc. So... yah...

auriaks
06-24-2010, 10:55 AM
<?php
function regenerateSession($reload = false)
{
// This token is used by forms to prevent cross site forgery attempts
if(!isset($_SESSION['nonce']) || $reload)
$_SESSION['nonce'] = md5(microtime(true));

if(!isset($_SESSION['IPaddress']) || $reload)
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

if(!isset($_SESSION['userAgent']) || $reload)
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

//$_SESSION['user_id'] = user->getId();

// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;

// Create new session without destroying the old one
session_regenerate_id(false);

// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();

// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();

// Don't want this one to expire
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}

function checkSession()
{
try{
if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
throw new Exception('Attempt to use expired session.');

if(!is_numeric($_SESSION['user_id']))
throw new Exception('No session started.');

if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
throw new Exception('IP Address mixmatch (possible session hijacking attempt).');

if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
throw new Exception('Useragent mixmatch (possible session hijacking attempt).');

if(!loadUser($_SESSION['user_id']))
throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);

if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
{
regenerateSession();
}

return true;

}catch(Exception $e){
return false;
}
}
?>

Like this? What is more, I would like to add $_SESSION['authID'] = $r['userid'];... Where in the script should I add it?

But this script does not create session? It just checks it?

kar2905
06-24-2010, 02:10 PM
Could you be more specific as to what you want ?

auriaks
06-24-2010, 05:09 PM
I want to keep one variable in this session... Like name.

Keleth
06-24-2010, 05:36 PM
Why do you need either of those functions do to that?

Start a session, store the variable in the session, done? Neither function destroys sessions... they simply regenerate them, randomly changing the ID (for some reason?). There's no reason you can't just store w/e variables you want and use them as usual.

The purpose of using those functions is whats confusing us... why do you wanna use that? What is your aim/goal? It seems like added work without much gain unless you're super intent on security, in which case, you're better off understanding that function then simply using it. For example, what is the loadUser function? What class does this come from?

auriaks
06-24-2010, 07:02 PM
OK, there is my login page:
I use simple PHP sessions, but I want to increase security to my session... Who can update my script?

<?php
if(isset($_POST['enter'])) {
include $_SERVER['DOCUMENT_ROOT'] . '/connect/db_conn.php';
$password = md5($_POST['password']);
$nick = $_POST['nick'];

$password = mysql_real_escape_string($password);
$nick = mysql_real_escape_string($nick);
$nick = strtolower($nick);

if($password == '') {
$error .= "<li>Enter your password!</li>";
}
if($nick == '') {
$error .= "<li>Enter your Nick!</li>";
}
if(preg_match('/\W/', $password)) {
$error .= "<li>!!! No symbols !!!</li>";
} else {
if(preg_match('/\W/', $nick)) {
$error .= "<li>!!! No symbols !!!</li>";}}

$check = mysql_query("SELECT * FROM `test_sessions` WHERE nick='$nick' AND pass='$password'") or die(mysql_error());
if(mysql_num_rows($check) == 0) {
$error .= "<li>Wrong password or Nick!</li>";
}

if(isset($error)) {
$eroras = '<center><font color="grey">Mistakes:<br/><br/><font color="blue">'.$error.'</font></center>';
} else {

$r = mysql_fetch_array( $check ) or die(mysql_error());

session_start();

$code = md5($nick.$password);
$sess_time=date('ymdHis');
$sess_browser=$_SERVER['HTTP_USER_AGENT'];

$_SESSION['code'] = $code;
$_SESSION['time'] = $sess_time;
$_SESSION['browser'] = $sess_browser;

header("Location: index.php");
}

if($_GET['act'] == 'logout') {
session_start(); // begin session
session_unset();
session_destroy(); // remove the entire session
}
}
?>
<?php echo "$eroras";?>

<html xmlns="http://www.w3.org/1999/xhtml" lang="lt">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="lt"/>
</head>
<body>
<form method='post' action='login[test].php'>
<table align='center'><tr><td> User:</td>
<br />
<td><input type='text' name='nick' size='15'></td>
</tr><tr><td>Password:</td>
<br />
<td><input type='password' name='password' size='15'><input type='submit' name='enter' value=' Enter '></td></tr></table>
<br />
</form>
</body>
</html>

This is just login page. Do I have to validate user in other pages and how?

Thanks for your time spending on this...

Keleth
06-24-2010, 07:46 PM
How I've done it in the past to increase security is I store a cookie with some data (like userID, username, etc) and a session variable that contains an encrypted string of the last login date/time with a seed variable.

Then on each page, I check to see if the data matches up with the encrypted string. So someone trying to sneak their way in would need userID, username, (some other internal data) as well as the extract seed variable I use, where I use it, etc... odds are low.

auriaks
06-24-2010, 08:19 PM
How I've done it in the past to increase security is I store a cookie with some data (like userID, username, etc) and a session variable that contains an encrypted string of the last login date/time with a seed variable.

Then on each page, I check to see if the data matches up with the encrypted string. So someone trying to sneak their way in would need userID, username, (some other internal data) as well as the extract seed variable I use, where I use it, etc... odds are low.

I don't know much about cookies... How make them work with PHP? Could you update my script? I also use md5 code which is stored as $_SESSION['code']

Keleth
06-24-2010, 08:33 PM
Well, its not a case of updating, I wouldn't use your code at all. Cookies are easy to work with in PHP:

http://www.w3schools.com/php/php_cookies.asp

auriaks
06-24-2010, 08:39 PM
I wouldn't use your code at all

Why you wouldn't?

Keleth
06-24-2010, 09:12 PM
Well... the code I use has its own security features, why use the second set of security features you're using? The method I proposed would be instead of the code you're looking at.

auriaks
06-24-2010, 09:36 PM
What I have to do is?:
0. Do I have to FORCE Cookies?
1. Create a cookie like

<?php
$hash = md5($nick.$password.$time);
setcookie("hash", "$hash");
?>
2. Use it as $_COOKIE['hash'] in PHP?
3. Where I should put this code?

The part of session which I am trying to create is:

session_start();

$code = md5($nick.$password);
$sess_time=date('ymdHis');
$sess_browser=$_SERVER['HTTP_USER_AGENT'];

$_SESSION['code'] = $code;
$_SESSION['time'] = $sess_time;
$_SESSION['browser'] = $sess_browser;

For now, I am not looking further(checking and regenerating the session_id or other encrypted codes). Now, I want to change this to create powerful session...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum